summary refs log tree commit diff stats
path: root/nimdoc
Commit message (Collapse)AuthorAgeFilesLines
* docgen: move to shared RST state (fix #16990) (#18256)Andrey Makarov2021-06-201-5/+5
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * docgen: move to shared RST state (fix #16990) * Update lib/packages/docutils/rst.nim Co-authored-by: Andreas Rumpf <rumpf_a@web.de> * Update lib/packages/docutils/rst.nim Co-authored-by: Andreas Rumpf <rumpf_a@web.de> * Update lib/packages/docutils/rst.nim Co-authored-by: Andreas Rumpf <rumpf_a@web.de> * Update compiler/docgen.nim Co-authored-by: Timothee Cour <timothee.cour2@gmail.com> * Update compiler/docgen.nim Co-authored-by: Timothee Cour <timothee.cour2@gmail.com> * Update compiler/docgen.nim Co-authored-by: Timothee Cour <timothee.cour2@gmail.com> * Update lib/packages/docutils/rst.nim Co-authored-by: Timothee Cour <timothee.cour2@gmail.com> * rename `cmdDoc2` to `cmdDoc` * fix (P)RstSharedState convention * new style of initialization * misc suggestions * 1 more rename * fix a regression Co-authored-by: Andreas Rumpf <rumpf_a@web.de> Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>
* Fix JS error on index page and detect dark mode (#18191)drtheuns2021-06-076-24/+54
| | | | | | | | | | | | | | | | * Fix JS error on index page and detect dark mode The theindex.html page doesn't have a dark mode switch so the main function will error because `toggleSwitch` is not defined. Checks have been added to prevent this from happening. Also add automatic detection of system settings for dark-mode. This could also be done with pure css, but then the dark mode variable declarations would have to be duplicated to work with the switch so I went with this approach. * Fix nimdoc tests * Fix rst2html tests
* fix #16993, #18054, #17835 runnableExamples now works with templates and ↵Timothee Cour2021-06-023-10/+15
| | | | nested templates (#18082)
* fix warnings/hints in nimdoc/tester.nim (#18083)Timothee Cour2021-05-303-13/+16
| | | | | | | * fix warnings/hints in nimdoc/tester.nim * improve err msg for nimdoc/tester.nim and change flag from fixup to nimTestsNimdocFixup * address comment: put back quit instead of doAssert
* `doc2tex`: generate docs to Latex (#17997)Andrey Makarov2021-05-142-90/+90
| | | | | * `doc2tex`: generate docs to Latex * address some comments
* follow-up #17837: add `Console` for interactive sessions (#17930)Andrey Makarov2021-05-061-0/+8
| | | | | * follow-up #17837: add `Console` for interactive sessions * fix Latex
* typo: nonexistant => nonexistent (#17918)Timothee Cour2021-05-024-11/+11
| | | | | * typo: nonexistant => nonexistent * fix test (ordering differs because of https://github.com/nim-lang/Nim/issues/17910)
* gitutils: add diffStrings, diffFiles, and use it in testament to compare ↵Timothee Cour2021-04-302-2/+4
| | | | | | | | | | | | | expected vs gotten (#17892) * gitutils: add diffStrings, diffFiles, and use it in testament to compare expected vs gotten * refactor with createTempDir * cleanup * refacotr * PRTEMP fake test spec changes to show effect of diffStrings * add runnableExamples for experimental/diff + cross-reference with gitutils * Revert "PRTEMP fake test spec changes to show effect of diffStrings" This reverts commit 57dc8d642dce6c1127c98b7cbc9edbfe747d4047.
* improve nimsuggest/tester, minor improvements to koch.nim (#17879)Timothee Cour2021-04-291-1/+1
| | | | | * improve nimsuggest/tester * koch improvements
* add RST highlighting for command line / shells (also fixes #16858) (#17789)Andrey Makarov2021-04-211-5/+26
|
* rst indentation fixes (ref #17340) (#17715)Andrey Makarov2021-04-151-2/+2
|
* restyle RST option lists (#17637)Andrey Makarov2021-04-101-0/+27
| | | | | | | | | | | | | * WIP: restyle RST option lists * apply similar style to Latex * fix tests * minor visual tweaks * update tests * remove leftover comments
* fix #17615(runnableExamples silently ignored if placed after some code) (#17619)flywind2021-04-022-4/+4
| | | Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>
* enable syntax highlighting for inline code (#17585)Andrey Makarov2021-04-023-7/+11
| | | | | | | | | | | | | | | | | | | | | | | | | * enable syntax highlighting for inline code * finish '.. default-role' and preliminary '.. role' implementation * more compact check in dirRole * set :literal: as default role for *.rst * Update lib/packages/docutils/rst.nim Co-authored-by: Timothee Cour <timothee.cour2@gmail.com> * use whichRole for setting currRoleKind * Update lib/packages/docutils/rst.nim Co-authored-by: Timothee Cour <timothee.cour2@gmail.com> * rename rnGeneralRole -> rnUnknownRole Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>
* docgen: render pragmas by default except for a select list (and fix #9074) ↵Timothee Cour2021-04-013-43/+43
| | | | (#17054)
* fix https://github.com/nim-lang/RFCs/issues/352: show top-level import for ↵Timothee Cour2021-03-291-4/+8
| | | | | | | | | top-level runnableExamples in generated docs (#17542) * fix https://github.com/nim-lang/RFCs/issues/352: show top-level import for top-level runnableExamples in generated docs * use canonical imoprt * fix test
* fix #17260 render `\` properly in nim doc, rst2html (#17315)Timothee Cour2021-03-241-1/+1
|
* fix #16973 ; nim doc now shows correct, canonical import name in title (#16999)Timothee Cour2021-03-231-2/+2
| | | | * nim doc now shows correct import name in title
* fix #16901: sidebar groups now works with all routines, not just proc,func ↵Timothee Cour2021-03-192-33/+90
| | | | | | | (#17416) * fix #16901: sidebar groups now works with all routines, not just proc,func * fix tests
* RST heading improvements (fix #17091) (#17195)Andrey Makarov2021-03-021-0/+1
|
* RST: implement footnotes and citations (#16960)Andrey Makarov2021-02-151-0/+13
| | | | | | | | | * RST: implement footnotes and citations * manual fixup of nimdoc.out.css * remove unused code * shorter printing code * Update lib/packages/docutils/rst.nim Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
* fix #16885: nimdoc css warning (#16893)zetashift2021-02-011-0/+2
| | | | | | | | | | | | | | | | | | | * fix #16885 * Fixup nimdoc for the CSS filter change * Use the same Nim devel versions * Revert "Use the same Nim devel versions" This reverts commit 8559308f9be54a674f3ac3893efe16e03ecf4d38. * Revert "Fixup nimdoc for the CSS filter change" This reverts commit 99ec00a4bd7c448763b2073a7c6f1332bbab924b. * Fixup nimdoc.out.css Co-authored-by: zetashift <rishi2@laptop.localdomain>
* fix #9102 docgen: sidebar now shows proc signatures instead of encoding (#16857)Timothee Cour2021-01-295-35/+973
|
* conservative approach to fix #15184 (#16723)Andrey Makarov2021-01-154-0/+23
|
* RST: improve line blocks (#16518)Andrey Makarov2020-12-311-1/+1
|
* doc/rst2html: some few fixes for enumerated and bullet lists (#16295)Andrey Makarov2020-12-141-6/+8
| | | | | | | | | | | | * fix bullet/enumarated lists with many blank lines * fix enumerated list parsing * fix parse failure when next line after list empty * implement arbitrary start of enumerator * check that enumerators are in order * remove redundant start=x if x=1 or a * add some doc on implemented features * update start in rst_examples.rst * allow upper-case letters + more docs
* put both funcs and procs under the same section in the documentation (#16301)Miran2020-12-091-23/+12
| | | | | * both funcs and procs are under the same section in the documentation * update the test
* nimdoc: Initialize theme switch and pragma dots on DOMContentLoaded (#16247)Sebastian Reinhard2020-12-066-6/+18
| | | | | | | | | The default HTML template for nimdoc currently initializes the dark mode switch and pragma dots when the onload event is fired. But since the onload event does not fire until all external resources (images, stylesheets, fonts, etc.) have been loaded, the light theme is shown for a brief moment before the document is fully loaded, and it switches to the dark theme. This is quite jarring, especially on slower internet connections. So let's instead initialize these things on the DOMContentLoaded event, which is fired right after the document has been parsed and the initial DOM structure is ready. This means that we now display the dark mode immediately, without having to wait for external resources to load first. For reference, see: - https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event - https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event I have updated the snapshot tests in `nimdoc/`, and done some manual testing of both the theme switch and the pragma dots, to confirm that this does not break anything. Please let me know if I've missed anything.
* RST tables: fix latex col number; allow less than three of `=` (#16040)Andrey Makarov2020-12-041-2/+2
|
* fix #16164, render doc comments (#16230)Miran2020-12-024-1/+18
| | | | | * fix #16164, render doc comments * add a test
* add a tester for rst2html (#15936)Miran2020-11-123-0/+863
|
* Correct all eggs (#15906)Miran2020-11-101-1/+1
| | | | * "eg" is a misspelled "egg", "e.g." is "exempli gratia" * Also, "ie" is "i.e.".
* fix #15702, show enum fields documentation (#15792)Miran2020-10-304-1/+44
|
* [backport: 1.4] Better linebreaks (#15658)Miran2020-10-223-61/+61
|
* add Source+Edit links on top of every docgend file (#15642)Timothee Cour2020-10-223-0/+3
|
* docgen: improve alignment of comments (still not perfect) (#15506)Andreas Rumpf2020-10-071-5/+6
| | | | | | | * docgen: improve alignment of comments (still not perfect) * fix error message text in `tunknown_named_parameter` Co-authored-by: narimiran <narimiran@disroot.org>
* group procs of the same name in TOC (#15487)Miran2020-10-053-61/+157
| | | | | | | | | | | * group procs of the same name in TOC * correctly show `sink` parameters in TOC * no need to reinvent the wheel - `mgetorPut` exists * better setting of text color [ci skip] * fix CSS for better alignment
* Fix theme switch load from local storage (#14897)Manuel Bojato2020-07-105-70/+25
| | | | | | | * fix theme switch load from local storage * Fix tests Co-authored-by: Clyybber <darkmine956@gmail.com>
* cleanup comment now that #14434 was fixed (#14874)Timothee Cour2020-07-011-2/+0
|
* fix #14846; add macros.extractDocCommentsAndRunnables (#14849)Timothee Cour2020-07-014-0/+58
| | | | | | | | | * fix #14846; add macros.extractDocCommentsAndRunnables * fixup * update tests * address comment
* fix #14691 docgen works again for methods (#14701)Timothee Cour2020-06-184-0/+105
| | | | | * fix #14691 docgen methods * fixup
* runnableExamples: correctly handle multiline string litterals (#14492)Timothee Cour2020-06-014-0/+90
| | | | | * runnableExamples: correctly handle multiline string litterals * address comments: improve doc comments + variable namings
* hotfix doc comments for procs without body (#14494)Timothee Cour2020-05-294-0/+98
|
* fix #14485 (#14487)Timothee Cour2020-05-284-0/+42
|
* fix #8871 runnableExamples now preserves source code comments, litterals, ↵Timothee Cour2020-05-288-19/+722
| | | | | | | | | | | and all formatting; other bug fix (#14439) * fix #8871 runnableExamples now preserves source code comments, litterals, and all formatting * remove orig deadcode from getAllRunnableExamplesImpl * fix expected examples * add test to close https://github.com/nim-lang/Nim/issues/14473 * correctly handle regular comments before 1st token inside runnableExamples * add test to answer https://github.com/nim-lang/Nim/pull/14439#discussion_r431829199 * update tests
* Propagate the outDir to rstgen to fix hrefs for modules in subdirs (#14479)Kaushal Modi2020-05-283-1/+27
|
* fix #6583, fix #14376, index+search now generated for all projects, many bug ↵Timothee Cour2020-05-253-1/+10
| | | | | | | | | fixes with nim doc (#14324) * refs #6583 fix nim doc output * changelog * change default for outDir when unspecified * cleanups * --project implies --index
* fix #10731 ; `runnableExamples "-b:cpp --run:off": code` works (#14384)Timothee Cour2020-05-202-3/+4
| | | | * runnableExamples "-b:cpp -r:off": code
* fix #13150 `nim doc --project` now works reliably (#13223)Timothee Cour2020-02-061-2/+2
| | | | | | | | | | * fix #13150 `nim doc --project` works with duplicate names and with imports below main project file * add to help; fixup after #13212 isRelativeTo got merged * fix test tests/compilerapi/tcompilerapi.nim * remove nimblePkg field; compute on the fly instead * kochdocs: compiler docs now under compiler/ * --docRoot now has smart default: best among @pkg, @path
* Fix docs for subdirs too (#13180)Clyybber2020-01-171-1/+1
| | | | | * Fix doc subdirs * Extract to helper proc, and fix on windows
pan class="s">``try`` are executed unless an exception is raised. Then the appropriate ``except`` part is executed. The empty ``except`` part is executed if there is an exception that is not explicitly listed. It is similar to an ``else`` part in ``if`` statements. If there is a ``finally`` part, it is always executed after the exception handlers. The exception is *consumed* in an ``except`` part. If an exception is not handled, it is propagated through the call stack. This means that often the rest of the procedure - that is not within a ``finally`` clause - is not executed (if an exception occurs). If you need to *access* the actual exception object or message inside an ``except`` branch you can use the `getCurrentException() <system.html#getCurrentException>`_ and `getCurrentExceptionMsg() <system.html#getCurrentExceptionMsg>`_ procs from the `system <system.html>`_ module. Example: .. code-block:: nim try: doSomethingHere() except: let e = getCurrentException() msg = getCurrentExceptionMsg() echo "Got exception ", repr(e), " with message ", msg Annotating procs with raised exceptions --------------------------------------- Through the use of the optional ``{.raises.}`` pragma you can specify that a proc is meant to raise a specific set of exceptions, or none at all. If the ``{.raises.}`` pragma is used, the compiler will verify that this is true. For instance, if you specify that a proc raises ``IOError``, and at some point it (or one of the procs it calls) starts raising a new exception the compiler will prevent that proc from compiling. Usage example: .. code-block:: nim proc complexProc() {.raises: [IOError, ArithmeticDefect].} = ... proc simpleProc() {.raises: [].} = ... Once you have code like this in place, if the list of raised exception changes the compiler will stop with an error specifying the line of the proc which stopped validating the pragma and the raised exception not being caught, along with the file and line where the uncaught exception is being raised, which may help you locate the offending code which has changed. If you want to add the ``{.raises.}`` pragma to existing code, the compiler can also help you. You can add the ``{.effects.}`` pragma statement to your proc and the compiler will output all inferred effects up to that point (exception tracking is part of Nim's effect system). Another more roundabout way to find out the list of exceptions raised by a proc is to use the Nim ``doc2`` command which generates documentation for a whole module and decorates all procs with the list of raised exceptions. You can read more about Nim's `effect system and related pragmas in the manual <manual.html#effect-system>`_. Generics ======== Generics are Nim's means to parametrize procs, iterators or types with `type parameters`:idx:. Generic parameters are written within square brackets, for example ``Foo[T]``. They are most useful for efficient type safe containers: .. code-block:: nim :test: "nim c $1" type BinaryTree*[T] = ref object # BinaryTree is a generic type with # generic param ``T`` le, ri: BinaryTree[T] # left and right subtrees; may be nil data: T # the data stored in a node proc newNode*[T](data: T): BinaryTree[T] = # constructor for a node new(result) result.data = data proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) = # insert a node into the tree if root == nil: root = n else: var it = root while it != nil: # compare the data items; uses the generic ``cmp`` proc # that works for any type that has a ``==`` and ``<`` operator var c = cmp(it.data, n.data) if c < 0: if it.le == nil: it.le = n return it = it.le else: if it.ri == nil: it.ri = n return it = it.ri proc add*[T](root: var BinaryTree[T], data: T) = # convenience proc: add(root, newNode(data)) iterator preorder*[T](root: BinaryTree[T]): T = # Preorder traversal of a binary tree. # Since recursive iterators are not yet implemented, # this uses an explicit stack (which is more efficient anyway): var stack: seq[BinaryTree[T]] = @[root] while stack.len > 0: var n = stack.pop() while n != nil: yield n.data add(stack, n.ri) # push right subtree onto the stack n = n.le # and follow the left pointer var root: BinaryTree[string] # instantiate a BinaryTree with ``string`` add(root, newNode("hello")) # instantiates ``newNode`` and ``add`` add(root, "world") # instantiates the second ``add`` proc for str in preorder(root): stdout.writeLine(str) The example shows a generic binary tree. Depending on context, the brackets are used either to introduce type parameters or to instantiate a generic proc, iterator or type. As the example shows, generics work with overloading: the best match of ``add`` is used. The built-in ``add`` procedure for sequences is not hidden and is used in the ``preorder`` iterator. Templates ========= Templates are a simple substitution mechanism that operates on Nim's abstract syntax trees. Templates are processed in the semantic pass of the compiler. They integrate well with the rest of the language and share none of C's preprocessor macros flaws. To *invoke* a template, call it like a procedure. Example: .. code-block:: nim template `!=` (a, b: untyped): untyped = # this definition exists in the System module not (a == b) assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6)) The ``!=``, ``>``, ``>=``, ``in``, ``notin``, ``isnot`` operators are in fact templates: this has the benefit that if you overload the ``==`` operator, the ``!=`` operator is available automatically and does the right thing. (Except for IEEE floating point numbers - NaN breaks basic boolean logic.) ``a > b`` is transformed into ``b < a``. ``a in b`` is transformed into ``contains(b, a)``. ``notin`` and ``isnot`` have the obvious meanings. Templates are especially useful for lazy evaluation purposes. Consider a simple proc for logging: .. code-block:: nim :test: "nim c $1" const debug = true proc log(msg: string) {.inline.} = if debug: stdout.writeLine(msg) var x = 4 log("x has the value: " & $x) This code has a shortcoming: if ``debug`` is set to false someday, the quite expensive ``$`` and ``&`` operations are still performed! (The argument evaluation for procedures is *eager*). Turning the ``log`` proc into a template solves this problem: .. code-block:: nim :test: "nim c $1" const debug = true template log(msg: string) = if debug: stdout.writeLine(msg) var x = 4 log("x has the value: " & $x) The parameters' types can be ordinary types or the meta types ``untyped``, ``typed``, or ``type``. ``type`` suggests that only a type symbol may be given as an argument, and ``untyped`` means symbol lookups and type resolution is not performed before the expression is passed to the template. If the template has no explicit return type, ``void`` is used for consistency with procs and methods. To pass a block of statements to a template, use ``untyped`` for the last parameter: .. code-block:: nim :test: "nim c $1" template withFile(f: untyped, filename: string, mode: FileMode, body: untyped) = let fn = filename var f: File if open(f, fn, mode): try: body finally: close(f) else: quit("cannot open: " & fn) withFile(txt, "ttempl3.txt", fmWrite): txt.writeLine("line 1") txt.writeLine("line 2") In the example the two ``writeLine`` statements are bound to the ``body`` parameter. The ``withFile`` template contains boilerplate code and helps to avoid a common bug: to forget to close the file. Note how the ``let fn = filename`` statement ensures that ``filename`` is evaluated only once. Example: Lifting Procs ---------------------- .. code-block:: nim :test: "nim c $1" import math template liftScalarProc(fname) = ## Lift a proc taking one scalar parameter and returning a ## scalar value (eg ``proc sssss[T](x: T): float``), ## to provide templated procs that can handle a single ## parameter of seq[T] or nested seq[seq[]] or the same type ## ## .. code-block:: Nim ## liftScalarProc(abs) ## # now abs(@[@[1,-2], @[-2,-3]]) == @[@[1,2], @[2,3]] proc fname[T](x: openarray[T]): auto = var temp: T type outType = typeof(fname(temp)) result = newSeq[outType](x.len) for i in 0..<x.len: result[i] = fname(x[i]) liftScalarProc(sqrt) # make sqrt() work for sequences echo sqrt(@[4.0, 16.0, 25.0, 36.0]) # => @[2.0, 4.0, 5.0, 6.0] Compilation to JavaScript ========================= Nim code can be compiled to JavaScript. However in order to write JavaScript-compatible code you should remember the following: - ``addr`` and ``ptr`` have slightly different semantic meaning in JavaScript. It is recommended to avoid those if you're not sure how they are translated to JavaScript. - ``cast[T](x)`` in JavaScript is translated to ``(x)``, except for casting between signed/unsigned ints, in which case it behaves as static cast in C language. - ``cstring`` in JavaScript means JavaScript string. It is a good practice to use ``cstring`` only when it is semantically appropriate. E.g. don't use ``cstring`` as a binary data buffer. Part 3 ====== The next part is entirely about metaprogramming via macros: `Part III <tut3.html>`_