### Example of installing foreign dependencies Source: https://nim-lang.github.io/Nim/distros.html This example shows how to use `foreignDep` to register dependencies for a specific distribution like Ubuntu. The output demonstrates the commands that would typically be run to install these dependencies. ```text To complete the installation, run: sudo apt-get install libblas-dev sudo apt-get install libvoodoo ``` ```nim if detectOs(Ubuntu): foreignDep "lbiblas-dev" foreignDep "libvoodoo" ``` -------------------------------- ### Nim Documentation Files Example Source: https://nim-lang.github.io/Nim/niminst.html Lists documentation files to be included in the installer, such as HTML overviews. ```niminst [Documentation] ; Files: "doc/*.html" ; Files: "doc/*.cfg" ; Files: "doc/*.pdf" ; Files: "doc/*.ini" Files: "doc/html/overview.html" Start: "doc/html/overview.html" ``` -------------------------------- ### InnoSetup Configuration Example Source: https://nim-lang.github.io/Nim/niminst.html Configures the path to the Inno Setup compiler and specifies flags to be passed to it. ```niminst [InnoSetup] path = r"c:\Program Files (x86)\Inno Setup 5\iscc.exe" flags = "/Q" ``` -------------------------------- ### Example: Get Server Port Source: https://nim-lang.github.io/Nim/asynchttpserver.html Demonstrates how to create a server, listen on port 0 (dynamic assignment), and assert that a valid port was assigned. ```nim from std/nativesockets import Port let server = newAsyncHttpServer() server.listen(Port(0)) assert server.getPort.uint16 > 0 server.close() ``` -------------------------------- ### Nim Unix Installation Script Example Source: https://nim-lang.github.io/Nim/niminst.html Enables the generation of installation and uninstallation scripts for Unix-like systems. ```niminst [Unix] InstallScript: "yes" UninstallScript: "yes" Files: "bin/nim-gdb" Files: "build_all.sh" ``` -------------------------------- ### Full unittest example Source: https://nim-lang.github.io/Nim/unittest.html Demonstrates the structure of a test suite with setup, teardown, and various assertion types like 'require', 'check', and 'expect'. ```nim 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" ``` -------------------------------- ### Nim Windows Executables Example Source: https://nim-lang.github.io/Nim/niminst.html Lists Windows executable files to be installed, including the Nim compiler and related tools. ```niminst [Windows] Files: "bin/nim.exe" Files: "bin/nimgrep.exe" Files: "bin/nimsuggest.exe" Files: "bin/nimble.exe" Files: "bin/vccexe.exe" Files: "bin/nimgrab.exe" Files: "bin/nimpretty.exe" Files: "bin/testament.exe" Files: "bin/nim-gdb.bat" Files: "bin/atlas.exe" Files: "koch.exe" Files: "finish.exe" ; Files: "bin/downloader.exe" ; Files: "dist/mingw" Files: r"tools\start.bat" BinPath: r"bin;dist\mingw\bin;dist" ``` -------------------------------- ### niminst Config File 'files' Key Example Source: https://nim-lang.github.io/Nim/niminst.html Shows how to specify files and directories to be included in the installation using the 'files' key in the niminst configuration file. Supports wildcards and multiple entries. ```nimconfig [Config] Files: "configDir" Files: "otherconfig/*.conf;otherconfig/*.cfg" ``` -------------------------------- ### Nim Downloadable Components Example Source: https://nim-lang.github.io/Nim/niminst.html Defines optional components that can be downloaded during installation, including documentation, MinGW, and DLLs. ```niminst ; Section | dir | zipFile | size hint (in KB) | url | exe start menu entry Download: r"Documentation|doc|docs.zip|13824|https://nim-lang.org/download/docs-${version}.zip|overview.html" Download: r"C Compiler (MingW)|dist|mingw.zip|82944|https://nim-lang.org/download/${mingw}.zip" Download: r"Support DLLs|bin|nim_dlls.zip|479|https://nim-lang.org/download/dlls.zip" Download: r"Aporia Text Editor|dist|aporia.zip|97997|https://nim-lang.org/download/aporia-0.4.0.zip|aporia-0.4.0\bin\aporia.exe" ; for now only NSIS supports optional downloads ``` -------------------------------- ### Nim Library Files Example Source: https://nim-lang.github.io/Nim/niminst.html Specifies the Nim library directory to be included in the installation. ```niminst [Lib] Files: "lib" ``` -------------------------------- ### Setup Program Procedure Source: https://nim-lang.github.io/Nim/compiler/ast.html Initializes the program setup with configuration and an identifier cache. This operation has no specified exceptions or effects. ```nim proc setupProgram(config: ConfigRef; cache: IdentCache) {....raises: [], tags: [], forbids: [].} ``` -------------------------------- ### Initialize RstGenerator Example Source: https://nim-lang.github.io/Nim/rstgen.html Example demonstrating how to initialize the `RstGenerator` with default configuration and output target. ```nim import packages/docutils/rstgen var gen: RstGenerator gen.initRstGenerator(outHtml, defaultConfig(), "filename", {}) ``` -------------------------------- ### Example: Setting and Getting XmlNode Attributes Source: https://nim-lang.github.io/Nim/xmltree.html Demonstrates setting attributes using XmlAttributes and retrieving them using the attr proc. ```nim 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" ``` -------------------------------- ### Runnable Examples for Procedures Source: https://nim-lang.github.io/Nim/contributing.html Use `runnableExamples` for usage examples when possible. Code blocks can be used for examples not suitable for `runnableExamples`. ```nim proc addThree*(x, y, z: int8): int = ## Adds three `int8` values, treating them as unsigned and ## truncating the result. ## ## ``` ## # things that aren't suitable for a `runnableExamples` go in code block: ## echo execCmdEx("git pull") ## drawOnScreen() ## ``` runnableExamples: # `runnableExamples` is usually preferred to code blocks, when possible. doAssert addThree(3, 125, 6) == -122 result = x +% y +% z ``` -------------------------------- ### Asynchronous Content Fetch Example Source: https://nim-lang.github.io/Nim/httpclient.html An example demonstrating how to create an AsyncHttpClient, fetch content from a URL asynchronously, and assert its content. ```nim import std/[asyncdispatch, strutils] proc asyncProc(): Future[string] {.async.} = let client = newAsyncHttpClient() result = await client.getContent("http://example.com") let exampleHtml = waitFor asyncProc() assert "Example Domain" in exampleHtml assert "Pizza" notin exampleHtml ``` -------------------------------- ### Synchronous Content Fetch Example Source: https://nim-lang.github.io/Nim/httpclient.html An example demonstrating how to create an HttpClient, fetch content from a URL synchronously, and assert its content. ```nim import std/strutils let exampleHtml = newHttpClient().getContent("http://example.com") assert "Example Domain" in exampleHtml assert "Pizza" notin exampleHtml ``` -------------------------------- ### Example Configuration File Syntax Source: https://nim-lang.github.io/Nim/parsecfg.html Illustrates the supported syntax for configuration files, including comments, sections, key-value pairs, options, and various string literal formats. ```nim # 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" ``` -------------------------------- ### NSIS Flags Example Source: https://nim-lang.github.io/Nim/niminst.html Sets flags for the NSIS (Nullsoft Scriptable Install System) installer. ```niminst [NSIS] flags = "/V0" ``` -------------------------------- ### Example: Get OS Name Source: https://nim-lang.github.io/Nim/posix_utils.html Demonstrates how to import parsecfg and use osReleaseFile to get the OS name. ```nim import std/parsecfg when defined(linux): let data = osReleaseFile() echo "OS name: ", data.getSectionValue("", "NAME") ## the data is up to each distro. ``` -------------------------------- ### setupVM Source: https://nim-lang.github.io/Nim/compiler/theindex.html Initializes the virtual machine context for script execution. ```APIDOC ## setupVM ### Description Initializes the virtual machine context for script execution. ### Signature `proc setupVM(module: PSym; cache: IdentCache; scriptName: string; graph: ModuleGraph; idgen: IdGenerator): PEvalContext` ### Module scriptconfig ``` -------------------------------- ### Install Atlas and Cache Packages in CI Source: https://nim-lang.github.io/Nim/atlas.html Example snippet for Github Actions to install Atlas, cache the 'deps/' directory, and install project dependencies with features. ```yaml ... Nim setup ... - name: Install Latest Atlas (recommend until Nim's Atlas verision catches up in 2.2.8+) run: | nimble install 'https://github.com/nim-lang/atlas@#head' - name: Cache packages uses: actions/cache@v3 with: path: deps/ key: ${{ runner.os }}-${{ hashFiles('foo.nimble') }} - name: Install Deps run: | atlas install --feature=test --feature=other # etc ``` -------------------------------- ### setupParser Source: https://nim-lang.github.io/Nim/compiler/theindex.html Initializes the parser with the given configuration and file index. ```APIDOC ## setupParser ### Description Initializes the parser with the given configuration and file index. ### Signature `proc setupParser(p: var Parser; fileIdx: FileIndex; cache: IdentCache; config: ConfigRef): bool` ### Module syntaxes ``` -------------------------------- ### Get JavaScript Constructor Name Example Source: https://nim-lang.github.io/Nim/jsutils.html Shows how to get the constructor name for Nim-created JavaScript arrays like Float64Array. ```nim import std/jsffi let a = array[2, float64].default assert jsConstructorName(a) == "Float64Array" assert jsConstructorName(a.toJs) == "Float64Array" ``` -------------------------------- ### Sizeof Examples Source: https://nim-lang.github.io/Nim/system.html Examples demonstrating the usage of the `sizeof` procedure for character literals and integer literals. ```nim sizeof('A') # => 1 sizeof(2) # => 8 ``` -------------------------------- ### Define Runnable Examples in Nim Source: https://nim-lang.github.io/Nim/system.html Use the `runnableExamples` pragma to mark code sections that should be compiled and tested as documentation examples. These examples are ignored in normal builds but are processed by the documentation generator. ```nim proc runnableExamples(rdoccmd = ""; body: untyped) {.magic: "RunnableExamples", ...raises: [], tags: [], forbids: [].} ``` ```nim proc timesTwo*(x: int): int = ## This proc doubles a number. runnableExamples: # at module scope const exported* = 123 assert timesTwo(5) == 10 block: # at block scope defer: echo "done" runnableExamples "-d:foo -b:cpp": import std/compilesettings assert querySetting(backend) == "cpp" assert defined(foo) runnableExamples "-r:off": ## this one is only compiled import std/browsers openDefaultBrowser "https://forum.nim-lang.org/" 2 * x ``` -------------------------------- ### Nim Regex Lookbehind and Start Offset Example Source: https://nim-lang.github.io/Nim/re.html Demonstrates using lookbehind assertions and the `start` parameter in Nim's `find` and `match` functions. Note that output positions are relative to the start of the input string. ```nim import std/re ## 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 ``` -------------------------------- ### Nim Naming Conventions Example Source: https://nim-lang.github.io/Nim/nep1.html Illustrates Nim's naming conventions for constants and variables. Constants can start with either case, while variables must start with a lowercase letter. ```nim # 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. ``` -------------------------------- ### setupEvalGen Source: https://nim-lang.github.io/Nim/compiler/theindex.html Initializes the code generation for evaluation within the virtual machine. ```APIDOC ## setupEvalGen ### Description Initializes the code generation for evaluation within the virtual machine. ### Signature `proc setupEvalGen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext` ### Module vm ``` -------------------------------- ### Example: Getting XmlNode Attribute Count Source: https://nim-lang.github.io/Nim/xmltree.html Shows how to check the attribute count before and after setting attributes. ```nim var j = newElement("myTag") assert j.attrsLen == 0 let att = {"key1": "first value", "key2": "second value"}.toXmlAttributes j.attrs = att assert j.attrsLen == 2 ``` -------------------------------- ### Setup VM Procedure Source: https://nim-lang.github.io/Nim/compiler/scriptconfig.html Defines the procedure for setting up the virtual machine context for script execution. It takes module, cache, script name, graph, and idgen as parameters. ```nim proc setupVM(module: PSym; cache: IdentCache; scriptName: string; graph: ModuleGraph; idgen: IdGenerator): PEvalContext {....raises: [], tags: [], forbids: [].} ``` -------------------------------- ### Basic Atlas Usage Example Source: https://nim-lang.github.io/Nim/atlas.html A step-by-step example of initializing a new project, using Atlas to add a dependency, and compiling a simple Nim file. ```bash mkdir newproject cd newproject git init atlas use lexim # or using a forge alias: atlas use gh:zedeus/nitter # add `import lexim` to your example.nim file nim c example.nim ``` -------------------------------- ### Example: Using toTable Source: https://nim-lang.github.io/Nim/tables.html Demonstrates creating a Table from a sequence of key-value tuples and asserting its contents. ```nim let a = [('a', 5), ('b', 9)] let b = toTable(a) assert b == {'a': 5, 'b': 9}.toTable ``` -------------------------------- ### Asynchronous File Read/Write Example Source: https://nim-lang.github.io/Nim/asyncfile.html Demonstrates opening a file asynchronously, writing data, seeking to the beginning, reading all content, and closing the file. Ensure the 'asyncfile', 'asyncdispatch', and 'os' modules are imported. ```nim import std/[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() ``` -------------------------------- ### Basic Async HTTP Server Example Source: https://nim-lang.github.io/Nim/asynchttpserver.html This example demonstrates how to create an asynchronous HTTP server that listens on a dynamically chosen port. It responds to all requests with a '200 OK' status and 'Hello World' as the body. Ensure `asyncdispatch` is imported for `sleepAsync` and `waitFor`. ```nim import std/asynchttpserver # This example will create an HTTP server on an automatically chosen port. # It will respond to all requests with a `200 OK` response code and "Hello World" # as the response body. import std/asyncdispatch proc main {.async.} = var server = newAsyncHttpServer() proc cb(req: Request) {.async.} = echo (req.reqMethod, req.url, req.headers) let headers = {"Content-type": "text/plain; charset=utf-8"} await req.respond(Http200, "Hello World", headers.newHttpHeaders()) server.listen(Port(0)) # or Port(8080) to hardcode the standard HTTP port. let port = server.getPort echo "test this with: curl localhost:" & $port.uint16 & "/" while true: if server.shouldAcceptRequest(): await server.acceptRequest(cb) else: # too many concurrent connections, `maxFDs` exceeded # wait 500ms for FDs to be closed await sleepAsync(500) waitFor main() ``` -------------------------------- ### Get match bounds from RegexMatch Source: https://nim-lang.github.io/Nim/nre.html Retrieves the start and end indices of the entire match from a `RegexMatch` object as an `HSlice[int, int]`. ```nim func matchBounds(pattern: RegexMatch): HSlice[int, int] { ...raises: [], tags: [], forbids: []. } ``` -------------------------------- ### Show Help Source: https://nim-lang.github.io/Nim/nimc.html Displays a summary of the command-line switches. ```nim -h, --help ``` -------------------------------- ### setupProgram Source: https://nim-lang.github.io/Nim/compiler/theindex.html Initializes the program structure with the given configuration and identifier cache. ```APIDOC ## setupProgram ### Description Initializes the program structure with the given configuration and identifier cache. ### Signature `proc setupProgram(config: ConfigRef; cache: IdentCache)` ### Module ast ``` -------------------------------- ### Get capture bounds from RegexMatch Source: https://nim-lang.github.io/Nim/nre.html Retrieves the start and end indices of captured groups within a `RegexMatch` object as a `CaptureBounds` slice. ```nim func captureBounds(pattern: RegexMatch): CaptureBounds { ...raises: [], tags: [], forbids: []. } ``` -------------------------------- ### Get Lowest Index of Sequence Source: https://nim-lang.github.io/Nim/system.html Returns the lowest possible index of a Nim sequence. The example demonstrates iteration using `low` and `high`. ```nim proc low[T](x: openArray[T]): int {.magic: "Low", noSideEffect, ...raises: [], tags: [], forbids: [].} var s = @[1, 2, 3, 4, 5, 6, 7] low(s) # => 0 for i in low(s)..high(s): echo s[i] ``` -------------------------------- ### Get Lowest Index of Nim String Source: https://nim-lang.github.io/Nim/system.html Returns the lowest possible index of a Nim string. The example demonstrates its usage and expected output. ```nim proc low(x: string): int {.magic: "Low", noSideEffect, ...raises: [], tags: [], forbids: [].} var str = "Hello world!" low(str) # => 0 ``` -------------------------------- ### setupGlobalCtx Source: https://nim-lang.github.io/Nim/compiler/theindex.html Sets up the global context for the virtual machine. ```APIDOC ## setupGlobalCtx ### Description Sets up the global context for the virtual machine. ### Signature `proc setupGlobalCtx(module: PSym; graph: ModuleGraph; idgen: IdGenerator)` ### Module vm ``` -------------------------------- ### Get JavaScript Type of Value Example Source: https://nim-lang.github.io/Nim/jsutils.html Illustrates using jsTypeOf to identify JavaScript types like 'number', 'boolean', 'object', and 'bigint'. ```nim import std/[jsffi, jsbigints] assert jsTypeOf(1.toJs) == "number" assert jsTypeOf(false.toJs) == "boolean" assert [1].toJs.jsTypeOf == "object" # note the difference with `getProtoName` assert big"1".toJs.jsTypeOf == "bigint" ``` -------------------------------- ### Example: Using startsWith with RegExp Source: https://nim-lang.github.io/Nim/jsre.html Illustrates how to use the 'startsWith' procedure to verify if a string begins with a pattern defined by a RegExp. ```nim let jsregex: RegExp = newRegExp(r"abc", r"i") assert "abcd".startsWith jsregex ``` -------------------------------- ### skMacro Example Source: https://nim-lang.github.io/Nim/idetools.html Example output for a macro. The third column is the macro name, and the fourth column is its signature. The docstring is provided if available. ```nim proc testMacro() = expect(EArithmetic): --> col 2: idetools_api.expect col 3: proc (varargs[expr], stmt): stmt col 7: "" ``` -------------------------------- ### niminst Configuration File Example Source: https://nim-lang.github.io/Nim/niminst.html Demonstrates the syntax for niminst configuration files, including comments, key-value pairs, and string literal variations. Supports variables via the `$variable` notation. ```nimconfig # 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" ``` -------------------------------- ### Get JavaScript Object Prototype Name Example Source: https://nim-lang.github.io/Nim/jsutils.html Demonstrates using getProtoName to identify JavaScript types like Number, String, BigInt, and Arrays. ```nim import std/[jsffi, jsbigints] type A = ref object assert 1.toJs.getProtoName == "[object Number]" assert "a".toJs.getProtoName == "[object String]" assert big"1".toJs.getProtoName == "[object BigInt]" assert false.toJs.getProtoName == "[object Boolean]" assert (a: 1).toJs.getProtoName == "[object Object]" assert A.default.toJs.getProtoName == "[object Null]" assert [1].toJs.getProtoName == "[object Int32Array]" # implementation defined assert @[1].toJs.getProtoName == "[object Array]" # ditto ``` -------------------------------- ### Getting the Default Value of a Type Source: https://nim-lang.github.io/Nim/system.html Returns the default value for type `T`. Unlike `zeroDefault`, this procedure considers default fields of objects. Example requires nimPreviewRangeDefault. ```nim proc default[T](_: typedesc[T]): T {.magic: "Default", noSideEffect, ...raises: [], tags: [], forbids: [].} ``` ```nim assert (int, float).default == (0, 0.0) type Foo = object a: range[2..6] var x = Foo.default assert x.a == 2 ``` -------------------------------- ### Object Initialization with Defaults Source: https://nim-lang.github.io/Nim/manual.html Shows how to initialize objects and ref objects using object construction expressions or the `default` procedure, verifying that default values are applied. ```nim type Foo = object a: int = 2 b = 3.0 Bar = ref object a: int = 2 b = 3.0 block: # created with an object construction expression let x = Foo() assert x.a == 2 and x.b == 3.0 let y = Bar() assert y.a == 2 and y.b == 3.0 block: # created with an object construction expression let x = default(Foo) assert x.a == 2 and x.b == 3.0 let y = default(array[1, Foo]) assert y[0].a == 2 and y[0].b == 3.0 let z = default(tuple[x: Foo]) assert z.x.a == 2 and z.x.b == 3.0 block: # created with the procedure `new` let y = new Bar assert y.a == 2 and y.b == 3.0 ``` -------------------------------- ### Get Rune Byte Length for string Source: https://nim-lang.github.io/Nim/unicode.html Returns the number of bytes a rune takes starting at a specific index in a string. Use when working directly with strings. ```nim proc runeLenAt(s: string; i: Natural): int {.inline, ...raises: [], tags: [], forbids: [].} let a = "añyóng" doAssert a.runeLenAt(0) == 1 doAssert a.runeLenAt(1) == 2 ``` -------------------------------- ### NimScript Command-Line Switch Examples Source: https://nim-lang.github.io/Nim/nims.html Demonstrates how to use the `switch` proc in NimScript to map command-line arguments to configuration settings. These examples show direct mapping and handling of values. ```nim # command-line: --opt:size switch("opt", "size") # command-line: --define:release or -d:release switch("define", "release") # command-line: --forceBuild switch("forceBuild") # command-line: --hint[Conf]:off or --hint:Conf:off switch("hint", "[Conf]:off") ``` -------------------------------- ### Nim Regex find Examples Source: https://nim-lang.github.io/Nim/re.html Demonstrates the usage of the `find` procedure for various scenarios, including finding matches, not found cases, and using the `start` parameter. ```nim 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` ``` -------------------------------- ### Nim Compiler AST: Get Symbol From List Source: https://nim-lang.github.io/Nim/compiler/astalgo.html Retrieve a symbol from a node list, optionally starting from a specific index. Used for parameter or argument lists. ```nim proc getSymFromList(list: PNode; ident: PIdent; start: int = 0) {. ...raises: [], tags: [], forbids: [].} ``` -------------------------------- ### Styled Text Output Example Source: https://nim-lang.github.io/Nim/terminal.html Demonstrates various ways to style text output using `styledWriteLine` and `styledEcho`. Shows how to apply styles, colors, and backgrounds, and how to reset them. ```nim import std/terminal stdout.styledWriteLine({styleBright, styleBlink, styleUnderscore}, "styled text ") stdout.styledWriteLine(fgRed, "red text ") stdout.styledWriteLine(fgWhite, bgRed, "white text in red background") stdout.styledWriteLine(" ordinary text without style ") stdout.setBackGroundColor(bgCyan, true) stdout.setForeGroundColor(fgBlue) stdout.write("blue text in cyan background") stdout.resetAttributes() # You can specify multiple text parameters. Style parameters # only affect the text parameter right after them. styledEcho styleBright, fgGreen, "[PASS]", resetStyle, fgGreen, " Yay!" stdout.styledWriteLine(fgRed, "red text ", styleBright, "bold red", fgDefault, " bold text") ``` -------------------------------- ### Example: Get Environment Variable with Default Value Source: https://nim-lang.github.io/Nim/envvars.html Demonstrates retrieving an environment variable, showing the default empty string for a non-existent variable and a custom default value. ```nim assert getEnv("unknownEnv") == "" assert getEnv("unknownEnv", "doesn't exist") == "doesn't exist" ``` -------------------------------- ### Start Serving HTTP Requests with a Callback Source: https://nim-lang.github.io/Nim/asynchttpserver.html Initiates the server to listen for connections and execute a provided callback for each incoming request. Allows control over error handling and file descriptor limits. ```nim proc serve(server: AsyncHttpServer; port: Port; callback: proc (request: Request): Future[void] {.closure, ...gcsafe.}; address = ""; assumedDescriptorsPerRequest = -1; domain = AF_INET): owned(Future[void]) {....stackTrace: false, raises: [Exception, OSError, ValueError, SslError, LibraryError, KeyError], tags: [RootEffect, WriteIOEffect, ReadIOEffect, TimeEffect], forbids: []}. ``` -------------------------------- ### Reverse Split String by Character Source: https://nim-lang.github.io/Nim/strutils.html Splits a string into a sequence of substrings using a character as a delimiter, starting from the end of the string. Useful for path manipulation to get the tail. ```nim func rsplit(s: string; sep: char; maxsplit: int = -1): seq[string] {....gcsafe, extern: "nsuRSplitChar", raises: [], tags: [], forbids: [].} ``` -------------------------------- ### Example: Respond with JSON Source: https://nim-lang.github.io/Nim/asynchttpserver.html Handles a request for '/hello-world' by responding with a JSON object containing a 'message' field. For other paths, it returns a 'Not Found' response. ```nim import std/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") ``` -------------------------------- ### Get Lowest Index of Array Source: https://nim-lang.github.io/Nim/system.html Returns the lowest possible index of an array. For empty arrays, the return type is `int`. The example shows iteration using `low` and `high`. ```nim proc low[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect, ...raises: [], tags: [], forbids: [].} var arr = [1, 2, 3, 4, 5, 6, 7] low(arr) # => 0 for i in low(arr)..high(arr): echo arr[i] ``` -------------------------------- ### Basic inotify Usage Example Source: https://nim-lang.github.io/Nim/inotify.html Demonstrates initializing an inotify file descriptor, adding a watch for create and delete events on a directory, and subsequently removing the watch. Ensure the 'linux' compilation flag is defined. ```nim import std/inotify when defined(linux): let inotifyFd = inotify_init() # create and get new inotify FileHandle doAssert inotifyFd >= 0 # check for errors let wd = inotifyFd.inotify_add_watch("/tmp", IN_CREATE or IN_DELETE) # Add new watch doAssert wd >= 0 # check for errors discard inotifyFd.inotify_rm_watch(wd) # remove watch ``` -------------------------------- ### Get Rune Byte Length for openArray[char] Source: https://nim-lang.github.io/Nim/unicode.html Returns the number of bytes a rune takes starting at a specific index in an openArray of characters. Use when working with character arrays. ```nim proc runeLenAt(s: openArray[char]; i: Natural): int {....raises: [], tags: [], forbids: [].} let a = "añyóng" doAssert a.runeLenAt(0) == 1 doAssert a.runeLenAt(1) == 2 ``` -------------------------------- ### Example: Open Nim Website in Browser Source: https://nim-lang.github.io/Nim/browsers.html Demonstrates how to call the `openDefaultBrowser` procedure to open a specific URL in the default browser. ```nim openDefaultBrowser("https://nim-lang.org") ``` -------------------------------- ### initToJsonOptions Source: https://nim-lang.github.io/Nim/jsonutils.html Initializes `ToJsonOptions` with default, sane options for JSON serialization. This procedure provides a convenient way to get started with JSON serialization without manually configuring all options. ```APIDOC ## proc initToJsonOptions(): ToJsonOptions ### Description Initializes `ToJsonOptions` with sane options. ``` -------------------------------- ### Example: System Information Source: https://nim-lang.github.io/Nim/posix_utils.html Demonstrates how to access and assert system information using the uname procedure. ```nim echo uname().nodename, uname().release, uname().version doAssert uname().sysname.len != 0 ``` -------------------------------- ### Using StdTmpl Filter with Standard Parameters Source: https://nim-lang.github.io/Nim/filters.html An example of using the stdtmpl filter with its default parameters for generating HTML. Lines starting with the meta character '#' are treated as Nim code. ```nim #? stdtmpl | standard #proc generateHTMLPage(title, currentTab, content: string, # tabs: openArray[string]): string = ``` -------------------------------- ### Creating a Configuration File with newConfig and setSectionKey Source: https://nim-lang.github.io/Nim/parsecfg.html Shows how to programmatically create a new configuration object and populate it with sections and key-value pairs using setSectionKey. The resulting configuration can be stringified for verification. ```nim import std/parsecfg var dict = newConfig() dict.setSectionKey("","charset", "utf-8") dict.setSectionKey("Package", "name", "hello") dict.setSectionKey("Package", "--threads", "on") dict.setSectionKey("Author", "name", "nim-lang") dict.setSectionKey("Author", "website", "nim-lang.org") assert $dict == """ charset=utf-8 [Package] name=hello --threads:on [Author] name=nim-lang website=nim-lang.org """ ``` -------------------------------- ### Nim NRE findIter and toSeq Example Source: https://nim-lang.github.io/Nim/nre.html Illustrates using findIter to get matches and then converting them to a sequence using sequtils.toSeq. It also shows how to access capture bounds and the first match. ```nim import std/nre import std/sugar let vowels = re"[aeoui]" let bounds = collect: for match in "moiga".findIter(vowels): match.matchBounds assert bounds == @[1 .. 1, 2 .. 2, 4 .. 4] from std/sequtils import toSeq let s = sequtils.toSeq("moiga".findIter(vowels)) # fully qualified to avoid confusion with nre.toSeq assert s.len == 3 let firstVowel = "foo".find(vowels) let hasVowel = firstVowel.isSome() assert hasVowel let matchBounds = firstVowel.get().captureBounds[-1] assert matchBounds.a == 1 # as with module `re`, 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`: assert find("uxabc", re"(?<=x|y)ab", start = 1).get.captures[-1] == "ab" assert find("uxabc", re"ab", start = 3).isNone ``` -------------------------------- ### Send Email with STARTTLS Source: https://nim-lang.github.io/Nim/smtp.html Example showing how to send an email using STARTTLS for a secure connection. This involves connecting to the SMTP server, initiating STARTTLS, authenticating, and then sending the email. ```nim var msg = createMessage("Hello from Nim's SMTP", "Hello!.\n Is this awesome or what?", @["foo@gmail.com"]) let smtpConn = newSmtp(debug=true) smtpConn.connect("smtp.mailtrap.io", Port 2525) smtpConn.startTls() smtpConn.auth("username", "password") smtpConn.sendmail("username@gmail.com", @["foo@gmail.com"], $msg) ``` -------------------------------- ### Get Specific Parameter Source: https://nim-lang.github.io/Nim/cmdline.html Returns the i-th command line argument. Indexing starts from 1 for parameters, but 0 may return the executable name. Availability depends on the environment; test with declared(). ```nim when declared(paramStr): # Use paramStr() here else: # Do something else! ``` -------------------------------- ### Create and Use a String Table Source: https://nim-lang.github.io/Nim/strtabs.html Demonstrates the basic creation and usage of a string table using `newStringTable` and direct key-value assignments. Asserts the length and checks for key existence. ```nim import std/strtabs var t = newStringTable() t["name"] = "John" t["city"] = "Monaco" doAssert t.len == 2 doAssert t.hasKey "name" doAssert "name" in t ``` -------------------------------- ### Getting Source Language Enum Source: https://nim-lang.github.io/Nim/highlite.html This example shows how to use the `getSourceLanguage` procedure to convert string representations of programming languages into their corresponding `SourceLanguage` enum values. Useful for dynamically setting the language for the highlighter. ```nim for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l) ``` -------------------------------- ### my_init Source: https://nim-lang.github.io/Nim/mysql.html Initializes the MySQL client library. ```APIDOC ## my_init ### Description Initializes the MySQL client library. ### Method Not specified (likely internal or SDK function) ### Returns `my_bool` - Returns true on success, false otherwise. ``` -------------------------------- ### Get MIME Type from File Extension Source: https://nim-lang.github.io/Nim/mimetypes.html Retrieves the MIME type associated with a given file extension. Returns a default MIME type if the extension is not found. The extension can optionally start with a dot, and it is converted to lowercase before lookup. ```nim func getMimetype(mimedb: MimeDB; ext: string; default = "text/plain"): string {.raises: [], tags: [], forbids: [].} 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 Edit ``` -------------------------------- ### InstallExt Variable Source: https://nim-lang.github.io/Nim/nimscript.html A sequence of strings representing file extensions for installation. ```nim installExt: seq[string] = @[] ``` -------------------------------- ### Walk Directory (Non-Recursive) Source: https://nim-lang.github.io/Nim/osdirs.html Use walkDir to iterate over items in a single directory. Set 'relative' to true to get paths relative to the starting directory. 'checkDir' raises an error if the directory does not exist. 'skipSpecial' filters out non-regular files on Unix. ```nim iterator walkDir(dir: string; relative = false; checkDir = false; skipSpecial = false): tuple[kind: PathComponent, path: string] { ...tags: [ReadDirEffect], raises: [OSError], forbids: [].} ``` ```nim import std/[strutils, sugar] # note: order is not guaranteed # this also works at compile time assert collect(for k in walkDir("dirA"): k.path).join(" ") == "dirA/dirB dirA/dirC dirA/fileA2.txt dirA/fileA1.txt" ``` -------------------------------- ### Using Local and Session Storage Source: https://nim-lang.github.io/Nim/dom.html Demonstrates how to use `localStorage` and `sessionStorage` for client-side data persistence. ```nim import js/dom let window = getWindow() let localStorage = window.localStorage let sessionStorage = window.sessionStorage # Local Storage localStorage.setItem("username", "nim_user") let storedUsername = localStorage.getItem("username") echo "Local Storage Username: ", storedUsername localStorage.removeItem("username") # Session Storage sessionStorage.setItem("session_id", "12345") let sessionId = sessionStorage.getItem("session_id") echo "Session Storage ID: ", sessionId sessionStorage.clear() echo "Local Storage length: ", localStorage.length echo "Session Storage length: ", sessionStorage.length ``` -------------------------------- ### Punycode Encoding and Decoding Examples Source: https://nim-lang.github.io/Nim/punycode.html Demonstrates various use cases for the `encode` and `decode` procedures, including empty strings, single characters, mixed ASCII and Unicode, and strings with spaces. Ensure the 'punycode' module is installed via nimble. ```nim import src/punycode static: block: doAssert encode("") == "" doAssert encode("a") == "a-" doAssert encode("A") == "A-" doAssert encode("3") == "3-" doAssert encode("-") == "--" doAssert encode("--") == "---" doAssert encode("abc") == "abc-" doAssert encode("London") == "London-" doAssert encode("Lloyd-Atkinson") == "Lloyd-Atkinson-" doAssert encode("This has spaces") == "This has spaces-" doAssert encode("ü") == "tda" doAssert encode("München") == "Mnchen-3ya" doAssert encode("Mnchen-3ya") == "Mnchen-3ya-" doAssert encode("München-Ost") == "Mnchen-Ost-9db" doAssert encode("Bahnhof München-Ost") == "Bahnhof Mnchen-Ost-u6b" block: doAssert decode("") == "" doAssert decode("a-") == "a" doAssert decode("A-") == "A" doAssert decode("3-") == "3" doAssert decode("--") == "-" doAssert decode("---") == "--" doAssert decode("abc-") == "abc" doAssert decode("London-") == "London" doAssert decode("Lloyd-Atkinson-") == "Lloyd-Atkinson" doAssert decode("This has spaces-") == "This has spaces" doAssert decode("tda") == "ü" doAssert decode("Mnchen-3ya") == "München" doAssert decode("Mnchen-3ya-") == "Mnchen-3ya" doAssert decode("Mnchen-Ost-9db") == "München-Ost" doAssert decode("Bahnhof Mnchen-Ost-u6b") == "Bahnhof München-Ost" ``` -------------------------------- ### Initialize MultipartData with Key-Value Pairs Source: https://nim-lang.github.io/Nim/httpclient.html Example of creating a MultipartData object and populating it with key-value pairs for actions like login. ```nim var data = newMultipartData({"action": "login", "format": "json"}) ``` -------------------------------- ### Example: Open and Close MemFile Source: https://nim-lang.github.io/Nim/memfiles.html Demonstrates creating, reading slices of, and closing a memory-mapped file. ```nim 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) ``` -------------------------------- ### value (get) Source: https://nim-lang.github.io/Nim/dom.html Gets the value of a Node. ```APIDOC ## value (get) ### Description Gets the value of a Node. ### Method importcpp: "#.value", nodecl ### Parameters - **n** (Node) - The node to get the value from. ``` -------------------------------- ### find(str: string; pattern: Regex; start = 0; endpos = int.high): Option[RegexMatch] Source: https://nim-lang.github.io/Nim/nre.html Finds the given pattern in the string between the start and end positions. `start` is the starting index for matching, and `endpos` is the maximum index for a match. ```APIDOC ## find(str: string; pattern: Regex; start = 0; endpos = int.high): Option[RegexMatch] ### Description Finds the given pattern in the string between the start and end positions. `start` is the starting index for matching, and `endpos` is the maximum index for a match. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```nim # Example usage would go here if provided in source ``` ### Response #### Success Response (Option[RegexMatch]) - Returns `Some(RegexMatch)` if the pattern is found, `None` otherwise. #### Response Example ```nim # Example response would go here if provided in source ``` ``` -------------------------------- ### Creating and Populating a Table Source: https://nim-lang.github.io/Nim/tables.html Demonstrates initializing a Table and populating it with key-value pairs from zipped sequences. Asserts the final state of the table. ```nim import std/tables from std/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 assert beatles == {"George": 1943, "Ringo": 1940, "Paul": 1942, "John": 1940}.toTable ``` -------------------------------- ### X509_STORE_new Source: https://nim-lang.github.io/Nim/openssl.html Creates and initializes a new X509_STORE context. ```APIDOC ## X509_STORE_new ### Description Creates and initializes a new X509_STORE context. This is the primary function to obtain a store object. ### Method N/A (Procedure) ### Endpoint N/A (Procedure) ### Parameters None ### Response - **PX509_STORE**: A pointer to the newly created and initialized X509_STORE context. ``` -------------------------------- ### Check if String Starts with Peg Pattern Source: https://nim-lang.github.io/Nim/pegs.html Returns true if the string `s` starts with the pattern `prefix`. The `start` parameter specifies the offset to begin checking. ```nim func startsWith(s: string; prefix: Peg; start = 0): bool {....gcsafe, extern: "npegs$1", gcsafe, gcsafe, raises: [], tags: [RootEffect], forbids: [].} ``` -------------------------------- ### Regex Matching with Start Position Source: https://nim-lang.github.io/Nim/nre2.html Illustrates how the `start` parameter affects regex matching, noting that output positions are relative to the original string start. ```nim # as with module `re`, 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`: assert find("uxabc", re"(?<=x|y)ab", start = 1).get.captures[-1] == "ab" assert find("uxabc", re"ab", start = 3).isNone ```