Markdown code blocks migration part 7 (#20547)

This commit is contained in:
Andrey Makarov 2022-10-12 17:13:43 +03:00 • committed by GitHub
commit 19ff746916
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 426 additions and 411 deletions

View file

@ -26,8 +26,9 @@
## That is, using the `?` (question mark) to signify the place where a ## That is, using the `?` (question mark) to signify the place where a
## value should be placed. For example: ## value should be placed. For example:
## ##
## .. code-block:: Nim ## ```Nim
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)" ## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
## ```
## ##
## ##
## Examples ## Examples
@ -36,32 +37,34 @@
## Opening a connection to a database ## Opening a connection to a database
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## ```Nim
## import std/db_odbc ## import std/db_odbc
## var db = open("localhost", "user", "password", "dbname") ## var db = open("localhost", "user", "password", "dbname")
## db.close() ## db.close()
## ```
## ##
## Creating a table ## Creating a table
## ---------------- ## ----------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"DROP TABLE IF EXISTS myTable") ## db.exec(sql"DROP TABLE IF EXISTS myTable")
## db.exec(sql("""CREATE TABLE myTable ( ## db.exec(sql("""CREATE TABLE myTable (
## id integer, ## id integer,
## name varchar(50) not null)""")) ## name varchar(50) not null)"""))
## ```
## ##
## Inserting data ## Inserting data
## -------------- ## --------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
## "Andreas") ## "Andreas")
## ```
## ##
## Large example ## Large example
## ------------- ## -------------
## ##
## .. code-block:: Nim ## ```Nim
##
## import std/[db_odbc, math] ## import std/[db_odbc, math]
## ##
## var theDb = open("localhost", "nim", "nim", "test") ## var theDb = open("localhost", "nim", "nim", "test")
@ -87,6 +90,7 @@
## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id) ## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id)
## ##
## theDb.close() ## theDb.close()
## ```
import strutils, odbcsql import strutils, odbcsql
import db_common import db_common

View file

@ -20,8 +20,9 @@
## That is, using the `?` (question mark) to signify the place where a ## That is, using the `?` (question mark) to signify the place where a
## value should be placed. For example: ## value should be placed. For example:
## ##
## .. code-block:: Nim ## ```Nim
## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)" ## sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
## ```
## ##
## **Note**: There are two approaches to parameter substitution support by ## **Note**: There are two approaches to parameter substitution support by
## this module. ## this module.
@ -30,12 +31,13 @@
## ##
## 2. `SqlPrepared` using `$1, $2, $3, ...` ## 2. `SqlPrepared` using `$1, $2, $3, ...`
## ##
## .. code-block:: Nim ## ```Nim
## prepare(db, "myExampleInsert", ## prepare(db, "myExampleInsert",
## sql"""INSERT INTO myTable ## sql"""INSERT INTO myTable
## (colA, colB, colC) ## (colA, colB, colC)
## VALUES ($1, $2, $3)""", ## VALUES ($1, $2, $3)""",
## 3) ## 3)
## ```
## ##
## ##
## Unix Socket ## Unix Socket
@ -46,11 +48,12 @@
## ##
## To use Unix sockets with `db_postgres`, change the server address to the socket file path: ## To use Unix sockets with `db_postgres`, change the server address to the socket file path:
## ##
## .. code-block:: Nim ## ```Nim
## import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path ## import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path
## let db = db_postgres.open("/run/postgresql", "user", "password", "database") ## let db = db_postgres.open("/run/postgresql", "user", "password", "database")
## echo db.getAllRows(sql"SELECT version();") ## echo db.getAllRows(sql"SELECT version();")
## db.close() ## db.close()
## ```
## ##
## The socket file path is operating system specific and distribution specific, ## The socket file path is operating system specific and distribution specific,
## additional configuration may or may not be needed on your `postgresql.conf`. ## additional configuration may or may not be needed on your `postgresql.conf`.
@ -63,26 +66,29 @@
## Opening a connection to a database ## Opening a connection to a database
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## ```Nim
## import std/db_postgres ## import std/db_postgres
## let db = open("localhost", "user", "password", "dbname") ## let db = open("localhost", "user", "password", "dbname")
## db.close() ## db.close()
## ```
## ##
## Creating a table ## Creating a table
## ---------------- ## ----------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"DROP TABLE IF EXISTS myTable") ## db.exec(sql"DROP TABLE IF EXISTS myTable")
## db.exec(sql("""CREATE TABLE myTable ( ## db.exec(sql("""CREATE TABLE myTable (
## id integer, ## id integer,
## name varchar(50) not null)""")) ## name varchar(50) not null)"""))
## ```
## ##
## Inserting data ## Inserting data
## -------------- ## --------------
## ##
## .. code-block:: Nim ## ```Nim
## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", ## db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
## "Dominik") ## "Dominik")
## ```
import strutils, postgres import strutils, postgres
import db_common import db_common
@ -609,10 +615,9 @@ proc open*(connection, user, password, database: string): DbConn {.
## connect. ## connect.
## ##
## Example: ## Example:
## ## ```nim
## .. code-block:: nim
##
## con = open("", "", "", "host=localhost port=5432 dbname=mydb") ## con = open("", "", "", "host=localhost port=5432 dbname=mydb")
## ```
## ##
## See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING ## See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
## for more information. ## for more information.

View file

@ -26,46 +26,45 @@
## That is, using the `?` (question mark) to signify the place where a ## That is, using the `?` (question mark) to signify the place where a
## value should be placed. For example: ## value should be placed. For example:
## ##
## .. code-block:: Nim ## ```Nim
##
## sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)" ## sql"INSERT INTO my_table (colA, colB, colC) VALUES (?, ?, ?)"
## ```
## ##
## Opening a connection to a database ## Opening a connection to a database
## ---------------------------------- ## ----------------------------------
## ##
## .. code-block:: Nim ## ```Nim
##
## import std/db_sqlite ## import std/db_sqlite
## ##
## # user, password, database name can be empty. ## # user, password, database name can be empty.
## # These params are not used on db_sqlite module. ## # These params are not used on db_sqlite module.
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## db.close() ## db.close()
## ```
## ##
## Creating a table ## Creating a table
## ---------------- ## ----------------
## ##
## .. code-block:: Nim ## ```Nim
##
## db.exec(sql"DROP TABLE IF EXISTS my_table") ## db.exec(sql"DROP TABLE IF EXISTS my_table")
## db.exec(sql"""CREATE TABLE my_table ( ## db.exec(sql"""CREATE TABLE my_table (
## id INTEGER, ## id INTEGER,
## name VARCHAR(50) NOT NULL ## name VARCHAR(50) NOT NULL
## )""") ## )""")
## ```
## ##
## Inserting data ## Inserting data
## -------------- ## --------------
## ##
## .. code-block:: Nim ## ```Nim
##
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)", ## db.exec(sql"INSERT INTO my_table (id, name) VALUES (0, ?)",
## "Jack") ## "Jack")
## ```
## ##
## Larger example ## Larger example
## -------------- ## --------------
## ##
## .. code-block:: nim ## ```Nim
##
## import std/[db_sqlite, math] ## import std/[db_sqlite, math]
## ##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
@ -93,12 +92,12 @@
## echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id) ## echo "Inserted item: ", db.getValue(sql"SELECT name FROM my_table WHERE id=?", id)
## ##
## db.close() ## db.close()
## ```
## ##
## Storing binary data example ## Storing binary data example
##---------------------------- ##----------------------------
## ##
## .. code-block:: nim ## ```nim
##
## import std/random ## import std/random
## ##
## ## Generate random float datas ## ## Generate random float datas
@ -144,6 +143,7 @@
## doAssert res == orig ## doAssert res == orig
## ##
## db.close() ## db.close()
## ```
## ##
## ##
## Note ## Note
@ -187,13 +187,12 @@ proc dbError*(db: DbConn) {.noreturn.} =
## Raises a `DbError` exception. ## Raises a `DbError` exception.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## if not db.tryExec(sql"SELECT * FROM not_exist_table"): ## if not db.tryExec(sql"SELECT * FROM not_exist_table"):
## dbError(db) ## dbError(db)
## db.close() ## db.close()
## ```
var e: ref DbError var e: ref DbError
new(e) new(e)
e.msg = $sqlite3.errmsg(db) e.msg = $sqlite3.errmsg(db)
@ -227,13 +226,12 @@ proc tryExec*(db: DbConn, query: SqlQuery,
## Tries to execute the query and returns `true` if successful, `false` otherwise. ## Tries to execute the query and returns `true` if successful, `false` otherwise.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## if not db.tryExec(sql"SELECT * FROM my_table"): ## if not db.tryExec(sql"SELECT * FROM my_table"):
## dbError(db) ## dbError(db)
## db.close() ## db.close()
## ```
assert(not db.isNil, "Database not connected.") assert(not db.isNil, "Database not connected.")
var q = dbFormat(query, args) var q = dbFormat(query, args)
var stmt: sqlite3.PStmt var stmt: sqlite3.PStmt
@ -259,9 +257,7 @@ proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
## Executes the query and raises a `DbError` exception if not successful. ## Executes the query and raises a `DbError` exception if not successful.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## try: ## try:
## db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)", ## db.exec(sql"INSERT INTO my_table (id, name) VALUES (?, ?)",
@ -270,6 +266,7 @@ proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
## stderr.writeLine(getCurrentExceptionMsg()) ## stderr.writeLine(getCurrentExceptionMsg())
## finally: ## finally:
## db.close() ## db.close()
## ```
if not tryExec(db, query, args): dbError(db) if not tryExec(db, query, args): dbError(db)
proc newRow(L: int): Row = proc newRow(L: int): Row =
@ -310,8 +307,7 @@ iterator fastRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -328,6 +324,7 @@ iterator fastRows*(db: DbConn, query: SqlQuery,
## # @["2", "item#2"] ## # @["2", "item#2"]
## ##
## db.close() ## db.close()
## ```
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
var L = (column_count(stmt)) var L = (column_count(stmt))
var result = newRow(L) var result = newRow(L)
@ -359,8 +356,7 @@ iterator instantRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -383,6 +379,7 @@ iterator instantRows*(db: DbConn, query: SqlQuery,
## # length:2 ## # length:2
## ##
## db.close() ## db.close()
## ```
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
try: try:
while step(stmt) == SQLITE_ROW: while step(stmt) == SQLITE_ROW:
@ -429,8 +426,7 @@ iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -451,6 +447,7 @@ iterator instantRows*(db: DbConn; columns: var DbColumns; query: SqlQuery,
## # foreignKey: false) ## # foreignKey: false)
## ##
## db.close() ## db.close()
## ```
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
setColumns(columns, stmt) setColumns(columns, stmt)
try: try:
@ -490,8 +487,7 @@ proc getRow*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -512,6 +508,7 @@ proc getRow*(db: DbConn, query: SqlQuery,
## doAssert db.getRow(sql"UPDATE my_table SET name = 'ITEM#1' WHERE id = ?", ## doAssert db.getRow(sql"UPDATE my_table SET name = 'ITEM#1' WHERE id = ?",
## 1) == @[] ## 1) == @[]
## db.close() ## db.close()
## ```
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
var L = (column_count(stmt)) var L = (column_count(stmt))
result = newRow(L) result = newRow(L)
@ -525,8 +522,7 @@ proc getAllRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -537,6 +533,7 @@ proc getAllRows*(db: DbConn, query: SqlQuery,
## ##
## doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])] ## doAssert db.getAllRows(sql"SELECT id, name FROM my_table") == @[Row(@["1", "item#1"]), Row(@["2", "item#2"])]
## db.close() ## db.close()
## ```
result = @[] result = @[]
for r in fastRows(db, query, args): for r in fastRows(db, query, args):
result.add(r) result.add(r)
@ -554,8 +551,7 @@ iterator rows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -572,6 +568,7 @@ iterator rows*(db: DbConn, query: SqlQuery,
## ## @["2", "item#2"] ## ## @["2", "item#2"]
## ##
## db.close() ## db.close()
## ```
for r in fastRows(db, query, args): yield r for r in fastRows(db, query, args): yield r
iterator rows*(db: DbConn, stmtName: SqlPrepared): Row iterator rows*(db: DbConn, stmtName: SqlPrepared): Row
@ -586,8 +583,7 @@ proc getValue*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -602,6 +598,7 @@ proc getValue*(db: DbConn, query: SqlQuery,
## doAssert db.getValue(sql"SELECT name, id FROM my_table") == "item#1" ## doAssert db.getValue(sql"SELECT name, id FROM my_table") == "item#1"
## ##
## db.close() ## db.close()
## ```
var stmt = setupQuery(db, query, args) var stmt = setupQuery(db, query, args)
if step(stmt) == SQLITE_ROW: if step(stmt) == SQLITE_ROW:
let cb = column_bytes(stmt, 0) let cb = column_bytes(stmt, 0)
@ -643,14 +640,14 @@ proc tryInsertID*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)") ## 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 (?, ?)", ## doAssert db.tryInsertID(sql"INSERT INTO not_exist_table (id, name) VALUES (?, ?)",
## 1, "item#1") == -1 ## 1, "item#1") == -1
## db.close() ## db.close()
## ```
assert(not db.isNil, "Database not connected.") assert(not db.isNil, "Database not connected.")
var q = dbFormat(query, args) var q = dbFormat(query, args)
var stmt: sqlite3.PStmt var stmt: sqlite3.PStmt
@ -674,8 +671,7 @@ proc insertID*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)") ## db.exec(sql"CREATE TABLE my_table (id INTEGER, name VARCHAR(50) NOT NULL)")
## ##
@ -689,6 +685,7 @@ proc insertID*(db: DbConn, query: SqlQuery,
## # LoopIndex = 2, InsertID = 3 ## # LoopIndex = 2, InsertID = 3
## ##
## db.close() ## db.close()
## ```
result = tryInsertID(db, query, args) result = tryInsertID(db, query, args)
if result < 0: dbError(db) if result < 0: dbError(db)
@ -713,8 +710,7 @@ proc execAffectedRows*(db: DbConn, query: SqlQuery,
## ##
## **Examples:** ## **Examples:**
## ##
## .. code-block:: Nim ## ```Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ##
## # Records of my_table: ## # Records of my_table:
@ -726,6 +722,7 @@ proc execAffectedRows*(db: DbConn, query: SqlQuery,
## doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2 ## doAssert db.execAffectedRows(sql"UPDATE my_table SET name = 'TEST'") == 2
## ##
## db.close() ## db.close()
## ```
exec(db, query, args) exec(db, query, args)
result = changes(db) result = changes(db)
@ -738,11 +735,10 @@ proc close*(db: DbConn) {.tags: [DbEffect].} =
## Closes the database connection. ## Closes the database connection.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim
##
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## db.close() ## db.close()
## ```
if sqlite3.close(db) != SQLITE_OK: dbError(db) if sqlite3.close(db) != SQLITE_OK: dbError(db)
proc open*(connection, user, password, database: string): DbConn {. proc open*(connection, user, password, database: string): DbConn {.
@ -753,9 +749,7 @@ proc open*(connection, user, password, database: string): DbConn {.
## **Note:** Only the `connection` parameter is used for `sqlite`. ## **Note:** Only the `connection` parameter is used for `sqlite`.
## ##
## **Examples:** ## **Examples:**
## ## ```Nim
## .. code-block:: Nim
##
## try: ## try:
## let db = open("mytest.db", "", "", "") ## let db = open("mytest.db", "", "", "")
## ## do something... ## ## do something...
@ -763,6 +757,7 @@ proc open*(connection, user, password, database: string): DbConn {.
## db.close() ## db.close()
## except: ## except:
## stderr.writeLine(getCurrentExceptionMsg()) ## stderr.writeLine(getCurrentExceptionMsg())
## ```
var db: DbConn var db: DbConn
if sqlite3.open(connection, db) == SQLITE_OK: if sqlite3.open(connection, db) == SQLITE_OK:
result = db result = db

View file

@ -17,37 +17,42 @@
## ##
## This is roughly equivalent to the `async` keyword in JavaScript code. ## This is roughly equivalent to the `async` keyword in JavaScript code.
## ##
## .. code-block:: nim ## ```nim
## proc loadGame(name: string): Future[Game] {.async.} = ## proc loadGame(name: string): Future[Game] {.async.} =
## # code ## # code
## ```
## ##
## should be equivalent to ## should be equivalent to
## ##
## .. code-block:: javascript ## ```javascript
## async function loadGame(name) { ## async function loadGame(name) {
## // code ## // code
## } ## }
## ```
## ##
## A call to an asynchronous procedure usually needs `await` to wait for ## A call to an asynchronous procedure usually needs `await` to wait for
## the completion of the `Future`. ## the completion of the `Future`.
## ##
## .. code-block:: nim ## ```nim
## var game = await loadGame(name) ## var game = await loadGame(name)
## ```
## ##
## Often, you might work with callback-based API-s. You can wrap them with ## Often, you might work with callback-based API-s. You can wrap them with
## asynchronous procedures using promises and `newPromise`: ## asynchronous procedures using promises and `newPromise`:
## ##
## .. code-block:: nim ## ```nim
## proc loadGame(name: string): Future[Game] = ## proc loadGame(name: string): Future[Game] =
## var promise = newPromise() do (resolve: proc(response: Game)): ## var promise = newPromise() do (resolve: proc(response: Game)):
## cbBasedLoadGame(name) do (game: Game): ## cbBasedLoadGame(name) do (game: Game):
## resolve(game) ## resolve(game)
## return promise ## return promise
## ```
## ##
## Forward definitions work properly, you just need to always add the `{.async.}` pragma: ## Forward definitions work properly, you just need to always add the `{.async.}` pragma:
## ##
## .. code-block:: nim ## ```nim
## proc loadGame(name: string): Future[Game] {.async.} ## proc loadGame(name: string): Future[Game] {.async.}
## ```
## ##
## JavaScript compatibility ## JavaScript compatibility
## ======================== ## ========================
@ -57,7 +62,7 @@
## If you need to use this module with older versions of JavaScript, you can ## 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. ## use a tool that backports the resulting JavaScript code, as babel.
# xxx code-block:: javascript above gives `LanguageXNotSupported` warning. # xxx code: javascript above gives `LanguageXNotSupported` warning.
when not defined(js) and not defined(nimsuggest): when not defined(js) and not defined(nimsuggest):
{.fatal: "Module asyncjs is designed to be used with the JavaScript backend.".} {.fatal: "Module asyncjs is designed to be used with the JavaScript backend.".}

View file

@ -1335,9 +1335,10 @@ since (1, 3):
## DOM Parser object (defined on browser only, may not be on NodeJS). ## DOM Parser object (defined on browser only, may not be on NodeJS).
## * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser ## * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
## ##
## .. code-block:: nim ## ```nim
## let prsr = newDomParser() ## let prsr = newDomParser()
## discard prsr.parseFromString("<html><marquee>Hello World</marquee></html>".cstring, "text/html".cstring) ## discard prsr.parseFromString("<html><marquee>Hello World</marquee></html>".cstring, "text/html".cstring)
## ```
DomException* = ref DOMExceptionObj DomException* = ref DOMExceptionObj
## The DOMException interface represents an abnormal event (called an exception) ## The DOMException interface represents an abnormal event (called an exception)

View file

@ -268,15 +268,14 @@ macro `.()`*(obj: JsObject,
## so be careful when using this.) ## so be careful when using this.)
## ##
## Example: ## Example:
## ## ```nim
## .. code-block:: nim
##
## # Let's get back to the console example: ## # Let's get back to the console example:
## var console {.importc, nodecl.}: JsObject ## var console {.importc, nodecl.}: JsObject
## let res = console.log("I return undefined!") ## let res = console.log("I return undefined!")
## console.log(res) # This prints undefined, as console.log always returns ## console.log(res) # This prints undefined, as console.log always returns
## # undefined. Thus one has to be careful, when using ## # undefined. Thus one has to be careful, when using
## # JsObject calls. ## # JsObject calls.
## ```
var importString: string var importString: string
if validJsName($field): if validJsName($field):
importString = "#." & $field & "(@)" importString = "#." & $field & "(@)"
@ -407,8 +406,7 @@ macro `{}`*(typ: typedesc, xs: varargs[untyped]): auto =
## ##
## Example: ## Example:
## ##
## .. code-block:: nim ## ```nim
##
## # Let's say we have a type with a ton of fields, where some fields do not ## # 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`: ## # need to be set, and we do not want those fields to be set to `nil`:
## type ## type
@ -421,7 +419,7 @@ macro `{}`*(typ: typedesc, xs: varargs[untyped]): auto =
## ##
## # This generates roughly the same JavaScript as: ## # This generates roughly the same JavaScript as:
## {.emit: "var obj = {a: 1, k: "foo", d: 42};".} ## {.emit: "var obj = {a: 1, k: "foo", d: 42};".}
## ## ```
let a = ident"a" let a = ident"a"
var body = quote do: var body = quote do:
var `a` {.noinit.}: `typ` var `a` {.noinit.}: `typ`
@ -471,16 +469,16 @@ macro bindMethod*(procedure: typed): auto =
## Example: ## Example:
## ##
## We want to generate roughly this JavaScript: ## We want to generate roughly this JavaScript:
## ## ```js
## .. code-block:: js
## var obj = {a: 10}; ## var obj = {a: 10};
## obj.someMethod = function() { ## obj.someMethod = function() {
## return this.a + 42; ## return this.a + 42;
## }; ## };
## ```
## ##
## We can achieve this using the `bindMethod` macro: ## We can achieve this using the `bindMethod` macro:
## ##
## .. code-block:: nim ## ```nim
## let obj = JsObject{ a: 10 } ## let obj = JsObject{ a: 10 }
## proc someMethodImpl(that: JsObject): int = ## proc someMethodImpl(that: JsObject): int =
## that.a.to(int) + 42 ## that.a.to(int) + 42
@ -489,6 +487,7 @@ macro bindMethod*(procedure: typed): auto =
## # Alternatively: ## # Alternatively:
## obj.someMethod = bindMethod ## obj.someMethod = bindMethod
## proc(that: JsObject): int = that.a.to(int) + 42 ## proc(that: JsObject): int = that.a.to(int) + 42
## ```
if not (procedure.kind == nnkSym or procedure.kind == nnkLambda): if not (procedure.kind == nnkSym or procedure.kind == nnkLambda):
error("Argument has to be a proc or a symbol corresponding to a proc.") error("Argument has to be a proc or a symbol corresponding to a proc.")
var var

View file

@ -13,7 +13,7 @@
## ##
## You can use this to build your own syntax highlighting, check this example: ## You can use this to build your own syntax highlighting, check this example:
## ##
## .. code:: Nim ## ```Nim
## let code = """for x in $int.high: echo x.ord mod 2 == 0""" ## let code = """for x in $int.high: echo x.ord mod 2 == 0"""
## var toknizr: GeneralTokenizer ## var toknizr: GeneralTokenizer
## initGeneralTokenizer(toknizr, code) ## initGeneralTokenizer(toknizr, code)
@ -31,19 +31,20 @@
## else: ## else:
## echo toknizr.kind # All the kinds of tokens can be processed here. ## echo toknizr.kind # All the kinds of tokens can be processed here.
## echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1) ## echo substr(code, toknizr.start, toknizr.length + toknizr.start - 1)
## ```
## ##
## The proc `getSourceLanguage` can get the language `enum` from a string: ## The proc `getSourceLanguage` can get the language `enum` from a string:
## ## ```Nim
## .. code:: Nim
## for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l) ## for l in ["C", "c++", "jAvA", "Nim", "c#"]: echo getSourceLanguage(l)
## ```
## ##
## There is also a `Cmd` pseudo-language supported, which is a simple generic ## There is also a `Cmd` pseudo-language supported, which is a simple generic
## shell/cmdline tokenizer (UNIX shell/Powershell/Windows Command): ## shell/cmdline tokenizer (UNIX shell/Powershell/Windows Command):
## no escaping, no programming language constructs besides variable definition ## no escaping, no programming language constructs besides variable definition
## at the beginning of line. It supports these operators: ## at the beginning of line. It supports these operators:
## ## ```Cmd
## .. code:: Cmd
## & && | || ( ) '' "" ; # for comments ## & && | || ( ) '' "" ; # for comments
## ```
## ##
## Instead of escaping always use quotes like here ## Instead of escaping always use quotes like here
## `nimgrep --ext:'nim|nims' file.name`:cmd: shows how to input ``|``. ## `nimgrep --ext:'nim|nims' file.name`:cmd: shows how to input ``|``.

View file

@ -153,12 +153,12 @@ proc initRstGenerator*(g: var RstGenerator, target: OutputTarget,
## ##
## Example: ## Example:
## ##
## .. code-block:: nim ## ```nim
##
## import packages/docutils/rstgen ## import packages/docutils/rstgen
## ##
## var gen: RstGenerator ## var gen: RstGenerator
## gen.initRstGenerator(outHtml, defaultConfig(), "filename", {}) ## gen.initRstGenerator(outHtml, defaultConfig(), "filename", {})
## ```
g.config = config g.config = config
g.target = target g.target = target
g.tocPart = @[] g.tocPart = @[]
@ -289,13 +289,12 @@ proc renderRstToOut*(d: var RstGenerator, n: PRstNode, result: var string) {.gcs
## Before using this proc you need to initialise a ``RstGenerator`` with ## Before using this proc you need to initialise a ``RstGenerator`` with
## ``initRstGenerator`` and parse a rst file with ``rstParse`` from the ## ``initRstGenerator`` and parse a rst file with ``rstParse`` from the
## `packages/docutils/rst module <rst.html>`_. Example: ## `packages/docutils/rst module <rst.html>`_. Example:
## ## ```nim
## .. code-block:: nim
##
## # ...configure gen and rst vars... ## # ...configure gen and rst vars...
## var generatedHtml = "" ## var generatedHtml = ""
## renderRstToOut(gen, rst, generatedHtml) ## renderRstToOut(gen, rst, generatedHtml)
## echo generatedHtml ## echo generatedHtml
## ```
proc renderAux(d: PDoc, n: PRstNode, result: var string) = proc renderAux(d: PDoc, n: PRstNode, result: var string) =
for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result) for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result)
@ -1602,12 +1601,13 @@ proc rstToHtml*(s: string, options: RstParseOptions,
## work. For an explanation of the ``config`` parameter see the ## work. For an explanation of the ``config`` parameter see the
## ``initRstGenerator`` proc. Example: ## ``initRstGenerator`` proc. Example:
## ##
## .. code-block:: nim ## ```nim
## import packages/docutils/rstgen, strtabs ## import packages/docutils/rstgen, strtabs
## ##
## echo rstToHtml("*Hello* **world**!", {}, ## echo rstToHtml("*Hello* **world**!", {},
## newStringTable(modeStyleInsensitive)) ## newStringTable(modeStyleInsensitive))
## # --> <em>Hello</em> <strong>world</strong>! ## # --> <em>Hello</em> <strong>world</strong>!
## ```
## ##
## If you need to allow the rst ``include`` directive or tweak the generated ## If you need to allow the rst ``include`` directive or tweak the generated
## output you have to create your own ``RstGenerator`` with ## output you have to create your own ``RstGenerator`` with

View file

@ -75,11 +75,11 @@ proc inotify_rm_watch*(fd: cint; wd: cint): cint {.cdecl,
iterator inotify_events*(evs: pointer, n: int): ptr InotifyEvent = iterator inotify_events*(evs: pointer, n: int): ptr InotifyEvent =
## Abstract the packed buffer interface to yield event object pointers. ## Abstract the packed buffer interface to yield event object pointers.
## ## ```Nim
## .. code-block:: Nim
## var evs = newSeq[byte](8192) # Already did inotify_init+add_watch ## var evs = newSeq[byte](8192) # Already did inotify_init+add_watch
## while (let n = read(fd, evs[0].addr, 8192); n) > 0: # read forever ## while (let n = read(fd, evs[0].addr, 8192); n) > 0: # read forever
## for e in inotify_events(evs[0].addr, n): echo e[].len # echo name lens ## for e in inotify_events(evs[0].addr, n): echo e[].len # echo name lens
## ```
var ev: ptr InotifyEvent = cast[ptr InotifyEvent](evs) var ev: ptr InotifyEvent = cast[ptr InotifyEvent](evs)
var n = n var n = n
while n > 0: while n > 0:

View file

@ -1093,11 +1093,11 @@ template onSignal*(signals: varargs[cint], body: untyped) =
## scope. ## scope.
## ##
## Example: ## Example:
## ## ```Nim
## .. code-block::
## from std/posix import SIGINT, SIGTERM, onSignal ## from std/posix import SIGINT, SIGTERM, onSignal
## onSignal(SIGINT, SIGTERM): ## onSignal(SIGINT, SIGTERM):
## echo "bye from signal ", sig ## echo "bye from signal ", sig
## ```
for s in signals: for s in signals:
handle_signal(s, handle_signal(s,

View file

@ -379,22 +379,22 @@ func sort*[T](a: var openArray[T],
## `cmp`, you may use `system.cmp` or instead call the overloaded ## `cmp`, you may use `system.cmp` or instead call the overloaded
## version of `sort`, which uses `system.cmp`. ## version of `sort`, which uses `system.cmp`.
## ##
## .. code-block:: nim ## ```nim
##
## sort(myIntArray, system.cmp[int]) ## sort(myIntArray, system.cmp[int])
## # do not use cmp[string] here as we want to use the specialized ## # do not use cmp[string] here as we want to use the specialized
## # overload: ## # overload:
## sort(myStrArray, system.cmp) ## sort(myStrArray, system.cmp)
## ```
## ##
## You can inline adhoc comparison procs with the `do notation ## You can inline adhoc comparison procs with the `do notation
## <manual_experimental.html#do-notation>`_. Example: ## <manual_experimental.html#do-notation>`_. Example:
## ##
## .. code-block:: nim ## ```nim
##
## people.sort do (x, y: Person) -> int: ## people.sort do (x, y: Person) -> int:
## result = cmp(x.surname, y.surname) ## result = cmp(x.surname, y.surname)
## if result == 0: ## if result == 0:
## result = cmp(x.name, y.name) ## result = cmp(x.name, y.name)
## ```
## ##
## **See also:** ## **See also:**
## * `sort proc<#sort,openArray[T]>`_ ## * `sort proc<#sort,openArray[T]>`_

View file

@ -41,13 +41,13 @@
## requested amount of data is read **or** an exception occurs. ## requested amount of data is read **or** an exception occurs.
## ##
## Code to read some data from a socket may look something like this: ## Code to read some data from a socket may look something like this:
## ## ```Nim
## .. code-block:: Nim
## var future = socket.recv(100) ## var future = socket.recv(100)
## future.addCallback( ## future.addCallback(
## proc () = ## proc () =
## echo(future.read) ## echo(future.read)
## ) ## )
## ```
## ##
## All asynchronous functions returning a `Future` will not block. They ## All asynchronous functions returning a `Future` will not block. They
## will not however return immediately. An asynchronous function will have ## will not however return immediately. An asynchronous function will have
@ -108,24 +108,24 @@
## You can handle exceptions in the same way as in ordinary Nim code; ## You can handle exceptions in the same way as in ordinary Nim code;
## by using the try statement: ## by using the try statement:
## ##
## ## ```Nim
## .. code-block:: Nim
## try: ## try:
## let data = await sock.recv(100) ## let data = await sock.recv(100)
## echo("Received ", data) ## echo("Received ", data)
## except: ## except:
## # Handle exception ## # Handle exception
## ## ```
##
## ##
## An alternative approach to handling exceptions is to use `yield` on a future ## An alternative approach to handling exceptions is to use `yield` on a future
## then check the future's `failed` property. For example: ## then check the future's `failed` property. For example:
## ##
## .. code-block:: Nim ## ```Nim
## var future = sock.recv(100) ## var future = sock.recv(100)
## yield future ## yield future
## if future.failed: ## if future.failed:
## # Handle exception ## # Handle exception
## ```
##
## ##
## Discarding futures ## Discarding futures
## ================== ## ==================

View file

@ -9,7 +9,7 @@
## This module implements asynchronous file reading and writing. ## This module implements asynchronous file reading and writing.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncfile, asyncdispatch, os] ## import std/[asyncfile, asyncdispatch, os]
## ##
## proc main() {.async.} = ## proc main() {.async.} =
@ -21,6 +21,7 @@
## file.close() ## file.close()
## ##
## waitFor main() ## waitFor main()
## ```
import asyncdispatch, os import asyncdispatch, os

View file

@ -21,13 +21,14 @@
## In order to begin any sort of transfer of files you must first ## 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. ## connect to an FTP server. You can do so with the `connect` procedure.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncdispatch, asyncftpclient] ## import std/[asyncdispatch, asyncftpclient]
## proc main() {.async.} = ## proc main() {.async.} =
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") ## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
## await ftp.connect() ## await ftp.connect()
## echo("Connected") ## echo("Connected")
## waitFor(main()) ## waitFor(main())
## ```
## ##
## A new `main` async procedure must be declared to allow the use of the ## A new `main` async procedure must be declared to allow the use of the
## `await` keyword. The connection will complete asynchronously and the ## `await` keyword. The connection will complete asynchronously and the
@ -41,7 +42,7 @@
## working directory before you do so with the `pwd` procedure, you can also ## working directory before you do so with the `pwd` procedure, you can also
## instead specify an absolute path. ## instead specify an absolute path.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncdispatch, asyncftpclient] ## import std/[asyncdispatch, asyncftpclient]
## proc main() {.async.} = ## proc main() {.async.} =
## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test") ## var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
@ -51,6 +52,7 @@
## await ftp.store("file.txt", "file.txt") ## await ftp.store("file.txt", "file.txt")
## echo("File finished uploading") ## echo("File finished uploading")
## waitFor(main()) ## waitFor(main())
## ```
## ##
## Checking the progress of a file transfer ## Checking the progress of a file transfer
## ======================================== ## ========================================
@ -62,7 +64,7 @@
## Procs that take an `onProgressChanged` callback will call this every ## Procs that take an `onProgressChanged` callback will call this every
## `progressInterval` milliseconds. ## `progressInterval` milliseconds.
## ##
## .. code-block:: Nim ## ```Nim
## import std/[asyncdispatch, asyncftpclient] ## import std/[asyncdispatch, asyncftpclient]
## ##
## proc onProgressChanged(total, progress: BiggestInt, ## proc onProgressChanged(total, progress: BiggestInt,
@ -76,6 +78,7 @@
## await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged) ## await ftp.store("file.txt", "/home/user/file.txt", onProgressChanged)
## echo("File finished uploading") ## echo("File finished uploading")
## waitFor(main()) ## waitFor(main())
## ```
import asyncdispatch, asyncnet, nativesockets, strutils, parseutils, os, times import asyncdispatch, asyncnet, nativesockets, strutils, parseutils, os, times

View file

@ -65,8 +65,7 @@
## ##
## The following example demonstrates a simple chat server. ## The following example demonstrates a simple chat server.
## ##
## .. code-block:: Nim ## ```Nim
##
## import std/[asyncnet, asyncdispatch] ## import std/[asyncnet, asyncdispatch]
## ##
## var clients {.threadvar.}: seq[AsyncSocket] ## var clients {.threadvar.}: seq[AsyncSocket]
@ -93,7 +92,7 @@
## ##
## asyncCheck serve() ## asyncCheck serve()
## runForever() ## runForever()
## ## ```
import std/private/since import std/private/since

View file

@ -69,8 +69,9 @@ proc openDefaultBrowser*(url: string) =
## ##
## This proc doesn't raise an exception on error, beware. ## This proc doesn't raise an exception on error, beware.
## ##
## .. code-block:: nim ## ```nim
## block: openDefaultBrowser("https://nim-lang.org") ## block: openDefaultBrowser("https://nim-lang.org")
## ```
doAssert url.len > 0, "URL must not be empty string" doAssert url.len > 0, "URL must not be empty string"
openDefaultBrowserImpl(url) openDefaultBrowserImpl(url)
@ -85,10 +86,11 @@ proc openDefaultBrowser*() {.since: (1, 1).} =
## ##
## This proc doesn't raise an exception on error, beware. ## This proc doesn't raise an exception on error, beware.
## ##
## ```nim
## block: openDefaultBrowser()
## ```
##
## **See also:** ## **See also:**
## ##
## * https://tools.ietf.org/html/rfc6694#section-3 ## * https://tools.ietf.org/html/rfc6694#section-3
##
## .. code-block:: nim
## block: openDefaultBrowser()
openDefaultBrowserImpl("http:about:blank") # See IETF RFC-6694 Section 3. openDefaultBrowserImpl("http:about:blank") # See IETF RFC-6694 Section 3.

View file

@ -9,8 +9,7 @@
## This module implements helper procs for CGI applications. Example: ## This module implements helper procs for CGI applications. Example:
## ##
## .. code-block:: Nim ## ```Nim
##
## import std/[strtabs, cgi] ## import std/[strtabs, cgi]
## ##
## # Fill the values when debugging: ## # Fill the values when debugging:
@ -28,6 +27,7 @@
## writeLine(stdout, "your name: " & myData["name"]) ## writeLine(stdout, "your name: " & myData["name"])
## writeLine(stdout, "your password: " & myData["password"]) ## writeLine(stdout, "your password: " & myData["password"])
## writeLine(stdout, "</body></html>") ## writeLine(stdout, "</body></html>")
## ```
import strutils, os, strtabs, cookies, uri import strutils, os, strtabs, cookies, uri
export uri.encodeUrl, uri.decodeUrl export uri.encodeUrl, uri.decodeUrl
@ -252,9 +252,9 @@ proc setTestData*(keysvalues: varargs[string]) =
## Fills the appropriate environment variables to test your CGI application. ## Fills the appropriate environment variables to test your CGI application.
## This can only simulate the 'GET' request method. `keysvalues` should ## This can only simulate the 'GET' request method. `keysvalues` should
## provide embedded (name, value)-pairs. Example: ## provide embedded (name, value)-pairs. Example:
## ## ```Nim
## .. code-block:: Nim
## setTestData("name", "Hanz", "password", "12345") ## setTestData("name", "Hanz", "password", "12345")
## ```
putEnv("REQUEST_METHOD", "GET") putEnv("REQUEST_METHOD", "GET")
var i = 0 var i = 0
var query = "" var query = ""
@ -269,9 +269,9 @@ proc setTestData*(keysvalues: varargs[string]) =
proc writeContentType*() = proc writeContentType*() =
## Calls this before starting to send your HTML data to `stdout`. This ## Calls this before starting to send your HTML data to `stdout`. This
## implements this part of the CGI protocol: ## implements this part of the CGI protocol:
## ## ```Nim
## .. code-block:: Nim
## write(stdout, "Content-type: text/html\n\n") ## write(stdout, "Content-type: text/html\n\n")
## ```
write(stdout, "Content-type: text/html\n\n") write(stdout, "Content-type: text/html\n\n")
proc resetForStacktrace() = proc resetForStacktrace() =