Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: function to add line numbers to block #220

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
14 changes: 11 additions & 3 deletions docsrc/allblocks.nim
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ template nbCodeBlock(name:string) =
nbToc.output.add "1. <a href=\"#" & anchorName & "\">" & name & "</a>\n"

nbText: """
> This nimib document provides a brief description and example for
> This nimib document provides a brief description and example for
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sorry, the diff contains a lot of line changes because of some automatic tool in my Vim editor to remove whitespaces at the end of lines.

> all blocks in nimib.
""".emojize

Expand All @@ -32,7 +32,7 @@ The markdown syntax is explained in the [Markdown Cheatsheet](https://pietroppet
nimibCode:
nbText: """
#### Markdown Example
My **text** is *formatted* with the
My **text** is *formatted* with the
[Markdown](https://pietroppeter.github.io/nimib/cheatsheet.html) syntax.
"""

Expand All @@ -46,10 +46,18 @@ nimibCode:
nbCode:
echo "Hello World!"

nbText: """
You can also display the line numbers on the left thanks to the global document switch:
"""

nimibCode:
enableLineNumbersDoc()
nbCode:
echo "Hello World!"

nbCodeBlock: "nbCodeSkip"
nbText: """
Similar to `nbCode`, `nbCodeSkip` is a block that displays
Similar to `nbCode`, `nbCodeSkip` is a block that displays
highlighted code but does not run it.
It is useful to show erroneous code or code that takes too long to run.
> :warning: `nbCodeSkip` does not guarantee that the code you show will compile nor run.
Expand Down
6 changes: 3 additions & 3 deletions nimib.nimble
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ task docsdeps, "install dependendencies required for doc building":
exec "nimble -y install [email protected] [email protected] nimoji nimpy [email protected]"

task test, "General tests":
for file in ["tsources.nim", "tblocks.nim", "tnimib.nim", "trenders.nim"]:
for file in ["tsources.nim", "tblocks.nim", "tnimib.nim", "trenders.nim", "tcodeLines.nim"]:
exec "nim r --hints:off tests/" & file
for file in ["tblocks.nim", "tnimib.nim", "trenders.nim"]:
exec "nim r --hints:off -d:nimibCodeFromAst tests/" & file

task readme, "update readme":
exec "nim -d:mdOutput r docsrc/index.nim"
exec "nim -d:mdOutput r docsrc/index.nim"

task docs, "Build documentation":
for file in ["allblocks", "hello", "mostaccio", "numerical", "nolan",
Expand All @@ -34,4 +34,4 @@ task docs, "Build documentation":
exec "nim r --hints:off docsrc/" & file & ".nim"
when not defined(nimibDocsSkipPenguins):
exec "nim r --hints:off docsrc/penguins.nim"
exec "nimble readme"
exec "nimble readme"
21 changes: 16 additions & 5 deletions src/nimib.nim
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ template nbInit*(theme = themes.useDefault, backend = renders.useHtmlBackend, th
# apply theme
theme nb

template nbInitMd*(thisFileRel = "") =
template nbInitMd*(thisFileRel = "") =
var tfr = if thisFileRel == "":
instantiationInfo(-1).filename
else:
Expand All @@ -69,6 +69,12 @@ template nbInitMd*(thisFileRel = "") =
if nb.options.filename == "":
nb.filename = nb.filename.splitFile.name & ".md"

template enableLineNumbersDoc* =
nb.context["enableLineNumbers"] = true

template enableLineNumbersBlock* =
nb.blk.context["enableLineNumbers"] = true

# block generation templates
template newNbCodeBlock*(cmd: string, body, blockImpl: untyped) =
newNbBlock(cmd, true, nb, nb.blk, body, blockImpl)
Expand All @@ -87,6 +93,11 @@ template nbCodeSkip*(body: untyped) =
newNbCodeBlock("nbCodeSkip", body):
discard

template nbCodeWithNumbers*(body: untyped) =
newNbCodeBlock("nbCode", body):
captureStdout(nb.blk.output):
body

template nbCapture*(body: untyped) =
newNbCodeBlock("nbCapture", body):
captureStdout(nb.blk.output):
Expand Down Expand Up @@ -117,13 +128,13 @@ template nbImage*(url: string, caption = "", alt = "") =
url
else:
nb.context["path_to_root"].vString / url
nb.blk.context["alt_text"] =

nb.blk.context["alt_text"] =
if alt == "":
caption
else:
alt

nb.blk.context["caption"] = caption

template nbFile*(name: string, content: string) =
Expand Down Expand Up @@ -155,7 +166,7 @@ when moduleAvailable(nimpy):
template nbShow*(obj: untyped) =
nbRawHtml(obj.toHtml())

template nbRawOutput*(content: string) {.deprecated: "Use nbRawHtml instead".} =
template nbRawOutput*(content: string) {.deprecated: "Use nbRawHtml instead".} =
nbRawHtml(content)

template nbRawHtml*(content: string) =
Expand Down
24 changes: 21 additions & 3 deletions src/nimib/renders.nim
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import std / [strutils, tables, sugar, os, strformat, sequtils]
import std / [strutils, tables, sugar, sequtils]
import ./types, ./jsutils, markdown, mustache
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are unused imports.


import highlight
Expand All @@ -10,6 +10,23 @@ proc mdOutputToHtml(doc: var NbDoc, blk: var NbBlock) =
proc highlightCode(doc: var NbDoc, blk: var NbBlock) =
blk.context["codeHighlighted"] = highlightNim(blk.code)

proc addLineNumbersToHighlightedCode(code: string): string =
let nlines = code.splitLines().len
# var lineNumbers: seq[string] = @[] # newSeqOfCap(nlines)
for i in 1..nlines:
## We have line numbers in the same line than code
result.add("""<span class="hljs-comment"> """ & $i & "</span> " & code.splitlines()[i-1] & "\n")
## but we can not copy-paste code without the numbers
# The following separates line numbers from code, but display is wrong
# result = """ <div>
# <code>""" & lineNumbers.join("") & """</code>
# <code>""" & code & """</code>
# </div>
# """

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should wrap the code in a table or a div container so that we can copy-paste code without the numbers.

proc addLineNumbers(doc: var NbDoc, blk: var NbBlock) =
if blk.context["enableLineNumbers"].castBool or doc.context["enableLineNumbers"].castBool:
blk.context["codeHighlighted"] = addLineNumbersToHighlightedCode(blk.context["codeHighlighted"].castStr)

proc useHtmlBackend*(doc: var NbDoc) =
doc.partials["nbText"] = "{{&outputToHtml}}"
Expand Down Expand Up @@ -45,14 +62,15 @@ proc useHtmlBackend*(doc: var NbDoc) =
# I prefer to initialize here instead of in nimib (each backend should re-initialize)
doc.renderPlans = initTable[string, seq[string]]()
doc.renderPlans["nbText"] = @["mdOutputToHtml"]
doc.renderPlans["nbCode"] = @["highlightCode"] # default partial automatically escapes output (code is escaped when highlighting)
doc.renderPlans["nbCodeSkip"] = @["highlightCode"]
doc.renderPlans["nbCode"] = @["highlightCode", "addLineNumbers"] # default partial automatically escapes output (code is escaped when highlighting)
doc.renderPlans["nbCodeSkip"] = @["highlightCode", "addLineNumbers"]
doc.renderPlans["nbJsFromCodeOwnFile"] = @["compileNimToJs", "highlightCode"]
doc.renderPlans["nbJsFromCode"] = @["highlightCode"]
doc.renderPlans["nimibCode"] = doc.renderPlans["nbCode"]

doc.renderProcs = initTable[string, NbRenderProc]()
doc.renderProcs["mdOutputToHtml"] = mdOutputToHtml
doc.renderProcs["addLineNumbers"] = addLineNumbers
doc.renderProcs["highlightCode"] = highlightCode
doc.renderProcs["compileNimToJs"] = compileNimToJs

Expand Down
11 changes: 11 additions & 0 deletions tests/tcodeLines.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import nimib
import unittest

suite "test sources":
nbInit()
enableLineNumbersDoc()
nbCode:
# a comment
let
x = 1
nbSave()
Loading