licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.3.2
96e65755f306264e9cc07e754bb955145c1f7354
code
800
fatalerrors = length(ARGS) > 0 && ARGS[1] == "-f" quiet = length(ARGS) > 0 && ARGS[1] == "-q" anyerrors = 0 using PopGenCore using PopGenSims using Test all_tests = [ "cross.jl", "samples.jl", "utils.jl", "sibship.jl", ] println("Running tests:") @testset "All Tests" begin for a_test in all_tests try include(a_test) println("\t\033[1m\033[32mPASSED\033[0m: $(a_test)") catch e global anyerrors += 1 println("\t\033[1m\033[31mFAILED\033[0m: $(a_test)") if fatalerrors rethrow(e) elseif !quiet showerror(stdout, e, backtrace()) println() end end end end anyerrors > 0 && throw("$anyerrors files of tests failed :(")
PopGenSims
https://github.com/pdimens/PopGenSims.jl.git
[ "MIT" ]
0.3.2
96e65755f306264e9cc07e754bb955145c1f7354
code
1914
module SamplesTest using PopGenCore using PopGenSims using Test cats = @nancycats ; d = Dict("1" => 5, "4" => 7, "11" => 3) @testset "Simulate Samples" begin @testset "sample_locus" begin d = Dict(133 => 0.125, 135 => 0.5625, 143 => 0.25, 137 => 0.0625) @test PopGenSims.sample_locus(d, 3, 2) |> length == 3 @test PopGenSims.sample_locus(d, 3, 2) |> first |> length == 2 @test PopGenSims.sample_locus(d, 3, 3) |> length == 3 @test PopGenSims.sample_locus(d, 3, 3) |> first |> length == 3 end @testset "simulate errors" begin @test_throws ArgumentError simulate(cats) @test_throws ArgumentError simulate(cats, n = 1, scale = 1) @test_throws ArgumentError simulate(cats, n = d, scale = 2) end @testset "simulate flat" begin sims = simulate(cats , n = 100) @test sims isa PopData @test sims.metadata.samples == 1700 @test length(sims.genodata.name) == 15300 end @testset "simulate proportional" begin sims = simulate(cats , scale = 1) @test sims isa PopData @test sims.metadata.populations == cats.metadata.populations @test sims.metadata.samples == cats.metadata.samples @test length(sims.genodata.name) == length(cats.genodata.name) sims = simulate(cats , scale = 4) @test sims isa PopData @test sims.metadata.populations == cats.metadata.populations @test sims.metadata.samples == cats.metadata.samples * 4 @test length(sims.genodata.name) == length(cats.genodata.name) * 4 end @testset "simulate arbitrary" begin sims = simulate(cats , n = d) @test sims isa PopData @test sims.metadata.samples == sum(values(d)) @test length(sims.genodata.name) == sum(values(d)) * cats.metadata.loci @test length(d) == sims.metadata.populations end end end # module
PopGenSims
https://github.com/pdimens/PopGenSims.jl.git
[ "MIT" ]
0.3.2
96e65755f306264e9cc07e754bb955145c1f7354
code
1318
module TestSibship using PopGenCore using PopGenSims using Test cats = @nancycats ; @testset "Sibship Simulations" begin @testset "all sibship" begin sims_all = simulatekin(cats, fullsib = 50, halfsib = 50, unrelated = 50, parentoffspring = 50) @test sims_all isa PopData @test sims_all.metadata.samples == 400 @test length(sims_all.genodata.name) == 3600 end @testset "unrelated" begin sims_un = simulatekin(cats, unrelated = 50) @test sims_un isa PopData @test sims_un.metadata.samples == 100 @test length(sims_un.genodata.name) == 900 end @testset "halfsib" begin sims_hs = simulatekin(cats, halfsib = 50) @test sims_hs isa PopData @test sims_hs.metadata.samples == 100 @test length(sims_hs.genodata.name) == 900 end @testset "fullsib" begin sims_fs = simulatekin(cats, fullsib = 50) @test sims_fs isa PopData @test sims_fs.metadata.samples == 100 @test length(sims_fs.genodata.name) == 900 end @testset "parent offspring" begin sims_po = simulatekin(cats, parentoffspring = 50) @test sims_po isa PopData @test sims_po.metadata.samples == 100 @test length(sims_po.genodata.name) == 900 end end end # module
PopGenSims
https://github.com/pdimens/PopGenSims.jl.git
[ "MIT" ]
0.3.2
96e65755f306264e9cc07e754bb955145c1f7354
code
1097
module TestUtils using PopGenCore using PopGenSims using Test cats = @nancycats ; cats2 = copy(cats) @testset "append PopData" begin tmp = append(cats, cats2) @test tmp.metadata.samples == 2 * cats.metadata.samples @test length(tmp.genodata.name) == 2 * length(cats.genodata.name) @test tmp isa PopData append!(cats2, cats) @test cats2.metadata.samples == 2 * cats.metadata.samples @test length(cats2.genodata.name) == 2 * length(cats.genodata.name) @test cats2 isa PopData end @testset "allele pool" begin @test PopGenSims.allele_pool(cats.genodata.genotype[1:30]) |> length == 56 @test PopGenSims.allele_pool(cats.genodata.genotype[1:30]) |> typeof <: NTuple a,b = PopGenSims.allele_pool(cats) @test eltype(a) == String @test length(a) == 9 @test typeof(b) <: Dict @test length(b) == length(a) c = PopGenSims.simulate_sample(b, a, ploidy = 2) @test length(c) == length(a) == length(b) @test all(length.(c) .== 2) c3 = PopGenSims.simulate_sample(b, a, ploidy = 3) @test all(length.(c3) .== 3) end end # module
PopGenSims
https://github.com/pdimens/PopGenSims.jl.git
[ "MIT" ]
0.3.2
96e65755f306264e9cc07e754bb955145c1f7354
docs
1217
![logo](misc/PopGenSims.png) [![alt text](https://img.shields.io/badge/docs-stable-informational?style=for-the-badge&logo=Read%20The%20Docs&logoColor=white)](https://BioJulia.net/PopGen.jl/docs/simulations/simulate_samples) [![alt text](https://img.shields.io/badge/slack-join%20PopGen.jl-9d72b1?style=for-the-badge&logo=slack)](https://join.slack.com/t/popgenjl/shared_invite/zt-deam65n8-DuBs2z1oDtsbBuRplJW~Pg) [![Cite](https://img.shields.io/badge/Cite-10.5281/zenodo.6077864-e1e1e1?style=for-the-badge)](https://zenodo.org/badge/latestdoi/278944885) ![build_status](https://img.shields.io/github/workflow/status/pdimens/PopGenSims.jl/CI_dev?label=Dev%20Build&logo=GitHub&style=for-the-badge) ## Simulate individuals for population genetics This package builds off of [PopGen.jl](http://github.com/BioJulia/PopGen.jl) and simulates offspring that would be generated under certain conditions. With this package you can simulate the offspring of specific individuals, simulate full-sibs, half-sibs, unrelated individuals, and parent-offspring pairs for use with PopGen.jl. You can also randomly generate samples given population-specific allele frequencies. ### Installation ![installation](misc/install.png)
PopGenSims
https://github.com/pdimens/PopGenSims.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3546
module JuDoc using JuDocTemplates using Markdown using Markdown: htmlesc using Dates # see jd_vars using DelimitedFiles: readdlm using OrderedCollections using Pkg using DocStringExtensions: SIGNATURES, TYPEDEF import Logging import LiveServer import Base.push! import NodeJS import Literate import HTTP export serve, publish, cleanpull, newsite, optimize, jd2html, literate_folder, verify_links export lunr export jdf_empty, jdf_lunr, jdf_literate # ----------------------------------------------------------------------------- # # CONSTANTS # """Big number when we want things to be far.""" const BIG_INT = typemax(Int) const JD_ENV = LittleDict( :DEBUG_MODE => false, :FULL_PASS => true, :FORCE_REEVAL => false, :SUPPRESS_ERR => false, :SILENT_MODE => false, :OFFSET_GLOB_LXDEFS => -BIG_INT, :CUR_PATH => "", :CUR_PATH_WITH_EVAL => "", ) """Dict to keep track of languages and how comments are indicated and their extensions.""" const CODE_LANG = LittleDict{String,NTuple{2,String}}( "c" => (".c", "//"), "cpp" => (".cpp", "//"), "fortran" => (".f90", "!"), "go" => (".go", "//"), "javascript" => (".js", "//"), "julia" => (".jl", "#"), "julia-repl" => (".jl", "#"), "lua" => (".lua", "--"), "matlab" => (".m", "%"), "python" => (".py", "#"), "r" => (".r", "#"), "toml" => (".toml", "#"), ) # copied from Base/path.jl if Sys.isunix() """Indicator for directory separation on the OS.""" const PATH_SEP = "/" elseif Sys.iswindows() const PATH_SEP = "\\" else error("Unhandled OS") end """Type of the containers for page variables (local and global).""" const PageVars = LittleDict{String,Pair{K,NTuple{N, DataType}} where {K, N}} """Shorter name for a type that we use everywhere""" const AS = Union{String,SubString{String}} """Convenience constants for an automatic message to add to code files.""" const MESSAGE_FILE_GEN = "This file was generated, do not modify it." const MESSAGE_FILE_GEN_LIT = "# $MESSAGE_FILE_GEN\n\n" const MESSAGE_FILE_GEN_JMD = "# $MESSAGE_FILE_GEN # hide\n" # ----------------------------------------------------------------------------- include("build.jl") # check if user has Node/minify # PARSING include("parser/tokens.jl") include("parser/indent.jl") include("parser/ocblocks.jl") # > latex include("parser/lx_tokens.jl") include("parser/lx_blocks.jl") # > markdown include("parser/md_tokens.jl") include("parser/md_validate.jl") # > html include("parser/html_tokens.jl") include("parser/html_blocks.jl") # CONVERSION # > markdown include("converter/md_blocks.jl") include("converter/md_utils.jl") include("converter/md.jl") # > latex include("converter/lx.jl") include("converter/lx_simple.jl") # > html include("converter/html_functions.jl") include("converter/html.jl") # > fighting Julia's markdown parser include("converter/html_link_fixer.jl") # > javascript include("converter/js_prerender.jl") # FILE PROCESSING include("jd_paths.jl") include("jd_vars.jl") # FILE AND DIR MANAGEMENT include("manager/rss_generator.jl") include("manager/dir_utils.jl") include("manager/file_utils.jl") include("manager/judoc.jl") include("manager/extras.jl") include("manager/post_processing.jl") # MISC UTILS include("misc_utils.jl") include("misc_html.jl") # ERROR TYPES include("error_types.jl") # INTEGRATION include("integration/literate.jl") end # module
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2806
const PY = begin if "PYTHON3" ∈ keys(ENV) ENV["PYTHON3"] else if Sys.iswindows() "py -3" else "python3" end end end const PIP = begin if "PIP3" ∈ keys(ENV) ENV["PIP3"] else if Sys.iswindows() "py -3 -m pip" else "pip3" end end end const NODE = begin if "NODE" ∈ keys(ENV) ENV["NODE"] else NodeJS.nodejs_cmd() end end #= Pre-rendering - In order to prerender KaTeX, the only thing that is required is `node` and then we can just require `katex.min.js` - For highlights, we need `node` and also to have the `highlight.js` installed via `npm`. =# const JD_CAN_PRERENDER = try success(`$NODE -v`); catch; false; end const JD_CAN_HIGHLIGHT = try success(`$NODE -e "require('highlight.js')"`); catch; false; end #= Minification - We use `css_html_js_minify`. To use it, you need python3 and to install it. - Here we check there is python3, and pip3, and then if we fail to import, we try to use pip3 to install it. =# const JD_HAS_PY3 = try success(`$([e for e in split(PY)]) -V`); catch; false; end const JD_HAS_PIP3 = try success(`$([e for e in split(PIP)]) -V`); catch; false; end const JD_CAN_MINIFY = JD_HAS_PY3 && JD_HAS_PIP3 && try success(`$([e for e in split(PY)]) -m "import css_html_js_minify"`) || success(`$([e for e in split(PIP)]) install css_html_js_minify`); catch; false; end #= Information to the user - what JuDoc couldn't find - that the user should do a `build` step after installing =# JD_CAN_HIGHLIGHT || begin JD_CAN_PRERENDER || begin println("""✘ Couldn't find node.js (`$NODE -v` failed). → It is required for pre-rendering KaTeX and highlight.js but is not necessary to run JuDoc (cf docs).""") end println("""✘ Couldn't find highlight.js (`$NODE -e "require('highlight.js')"` failed). → It is required for pre-rendering highlight.js but is not necessary to run JuDoc (cf docs).""") end JD_CAN_MINIFY || begin if JD_HAS_PY3 println("✘ Couldn't find css_html_js_minify (`$([e for e in split(PY)]) -m \"import css_html_js_minify\"` failed).\n" * """→ It is required for minification but is not necessary to run JuDoc (cf docs).""") else println("""✘ Couldn't find python3 (`$([e for e in split(PY)]) -V` failed). → It is required for minification but not necessary to run JuDoc (cf docs).""") end end all((JD_CAN_HIGHLIGHT, JD_CAN_PRERENDER, JD_CAN_MINIFY, JD_HAS_PY3, JD_HAS_PIP3)) || begin println("→ After installing any missing component, please re-build the package (cf docs).") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
819
# # Parsing related # """An OCBlock was not parsed properly (e.g. the closing token was not found).""" struct OCBlockError <: Exception m::String c::String end function Base.showerror(io::IO, be::OCBlockError) println(io, be.m) print(io, be.c) end """A `\\newcommand` was not parsed properly.""" struct LxDefError <: Exception m::String end """A latex command was found but could not be processed properly.""" struct LxComError <: Exception m::String end """A math block name failed to parse.""" struct MathBlockError <: Exception m::String end # # HTML related # """An HTML block (e.g. [`HCond`](@see)) was erroneous.""" struct HTMLBlockError <: Exception m::String end """An HTML function (e.g. `{{fill ...}}`) failed.""" struct HTMLFunctionError <: Exception m::String end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1773
""" FOLDER_PATH Container to keep track of where JuDoc is being run. """ const FOLDER_PATH = Ref{String}() """ IGNORE_FILES Collection of file names that will be ignored at compile time. """ const IGNORE_FILES = [".DS_Store"] """ INFRA_EXT Collection of file extensions considered as potential infrastructure files. """ const INFRA_FILES = [".html", ".css"] """ PATHS Dictionary for the paths of the input folders and the output folders. The simpler case only requires the main input folder to be defined i.e. `PATHS[:src]` and infers the others via the `set_paths!()` function. """ const PATHS = LittleDict{Symbol,String}() """ $(SIGNATURES) This assigns all the paths where files will be read and written with root the `FOLDER_PATH` which is assigned at runtime. """ function set_paths!()::LittleDict{Symbol,String} @assert isassigned(FOLDER_PATH) "FOLDER_PATH undefined" @assert isdir(FOLDER_PATH[]) "FOLDER_PATH is not a valid path" # NOTE it is recommended not to change the names of those paths. # Particularly for the output dir. If you do, check for example that # functions such as JuDoc.publish point to the right dirs/files. PATHS[:folder] = normpath(FOLDER_PATH[]) PATHS[:src] = joinpath(PATHS[:folder], "src") PATHS[:src_pages] = joinpath(PATHS[:src], "pages") PATHS[:src_css] = joinpath(PATHS[:src], "_css") PATHS[:src_html] = joinpath(PATHS[:src], "_html_parts") PATHS[:pub] = joinpath(PATHS[:folder], "pub") PATHS[:css] = joinpath(PATHS[:folder], "css") PATHS[:libs] = joinpath(PATHS[:folder], "libs") PATHS[:assets] = joinpath(PATHS[:folder], "assets") PATHS[:literate] = joinpath(PATHS[:folder], "scripts") return PATHS end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
12745
""" GLOBAL_PAGE_VARS Dictionary of variables assumed to be set for the entire website. Entries have the format KEY => PAIR where KEY is a string (e.g.: "author") and PAIR is a pair where the first element is the default value for the variable and the second is a tuple of accepted possible (super)types for that value. (e.g.: "THE AUTHOR" => (String, Nothing)) DEVNOTE: marked as constant for perf reasons but can be modified since Dict. """ const GLOBAL_PAGE_VARS = PageVars() """ $(SIGNATURES) Convenience function to allocate default values of the global site variables. This is called once, when JuDoc is started. """ @inline function def_GLOBAL_PAGE_VARS!()::Nothing empty!(GLOBAL_PAGE_VARS) GLOBAL_PAGE_VARS["author"] = Pair("THE AUTHOR", (String, Nothing)) GLOBAL_PAGE_VARS["date_format"] = Pair("U dd, yyyy", (String,)) GLOBAL_PAGE_VARS["prepath"] = Pair("", (String,)) # these must be defined for the RSS file to be generated GLOBAL_PAGE_VARS["website_title"] = Pair("", (String,)) GLOBAL_PAGE_VARS["website_descr"] = Pair("", (String,)) GLOBAL_PAGE_VARS["website_url"] = Pair("", (String,)) # if set to false, nothing rss will be considered GLOBAL_PAGE_VARS["generate_rss"] = Pair(true, (Bool,)) return nothing end """ CODE_SCOPE Page-related struct to keep track of the code blocks that have been evaluated. """ mutable struct CodeScope rpaths::Vector{SubString} codes::Vector{SubString} end CodeScope() = CodeScope(String[], String[]) """Convenience function to add a code block to the code scope.""" function push!(cs::CodeScope, rpath::SubString, code::SubString)::Nothing push!(cs.rpaths, rpath) push!(cs.codes, code) return nothing end """Convenience function to (re)start a code scope.""" function reset!(cs::CodeScope)::Nothing cs.rpaths = [] cs.codes = [] return nothing end """Convenience function to purge code scope from head""" function purgefrom!(cs::CodeScope, head::Int) cs.rpaths = cs.rpaths[1:head-1] cs.codes = cs.codes[1:head-1] return nothing end """ LOCAL_PAGE_VARS Dictionary of variables copied and then set for each page (through definitions). Entries have the same format as for `GLOBAL_PAGE_VARS`. DEVNOTE: marked as constant for perf reasons but can be modified since Dict. """ const LOCAL_PAGE_VARS = PageVars() """ $(SIGNATURES) Convenience function to allocate default values of page variables. This is called every time a page is processed. """ @inline function def_LOCAL_PAGE_VARS!()::Nothing # NOTE `jd_code` is the only page var we KEEP (stays alive) code_scope = get(LOCAL_PAGE_VARS, "jd_code_scope") do Pair(CodeScope(), (CodeScope,)) # the "Any" is lazy but easy end empty!(LOCAL_PAGE_VARS) # Local page vars defaults LOCAL_PAGE_VARS["title"] = Pair(nothing, (String, Nothing)) LOCAL_PAGE_VARS["hasmath"] = Pair(true, (Bool,)) LOCAL_PAGE_VARS["hascode"] = Pair(false, (Bool,)) LOCAL_PAGE_VARS["date"] = Pair(Date(1), (String, Date, Nothing)) LOCAL_PAGE_VARS["lang"] = Pair("julia", (String,)) # default lang for indented code LOCAL_PAGE_VARS["reflinks"] = Pair(true, (Bool,)) # whether there are reflinks or not LOCAL_PAGE_VARS["indented_code"] = Pair(true, (Bool,)) # whether to support indented code # # Table of contents controls LOCAL_PAGE_VARS["mintoclevel"] = Pair(1, (Int,)) # set to 2 to ignore h1 LOCAL_PAGE_VARS["maxtoclevel"] = Pair(100, (Int,)) # # CODE EVALUATION LOCAL_PAGE_VARS["reeval"] = Pair(false, (Bool,)) # whether to always re-evals all on pg LOCAL_PAGE_VARS["freezecode"] = Pair(false, (Bool,)) # no-reevaluation of the code LOCAL_PAGE_VARS["showall"] = Pair(false, (Bool,)) # like a notebook on each cell # NOTE: when using literate, `literate_only` will assume that it's the only source of # code, so if it doesn't see change there, it will freeze the code to avoid an eval, this will # cause problems if there's more code on the page than from just the call to \literate # in such cases set literate_only to false. LOCAL_PAGE_VARS["literate_only"] = Pair(true, (Bool,)) # # the jd_* vars should not be assigned externally LOCAL_PAGE_VARS["jd_code_scope"] = code_scope LOCAL_PAGE_VARS["jd_code_head"] = Pair(Ref(0), (Ref{Int},)) LOCAL_PAGE_VARS["jd_code_eval"] = Pair(Ref(false), (Ref{Bool},)) # toggle reeval LOCAL_PAGE_VARS["jd_code"] = Pair("", (String,)) # just the script # RSS 2.0 item specs: # only title, link and description must be defined # # title -- rss_title // fallback to title # (*) link -- [automatically generated] # description -- rss // rss_description NOTE: if undefined, no item generated # author -- rss_author // fallback to author # category -- rss_category # comments -- rss_comments # enclosure -- rss_enclosure # (*) guid -- [automatically generated from link] # pubDate -- rss_pubdate // fallback date // fallback jd_ctime # (*) source -- [unsupported assumes for now there's only one channel] # LOCAL_PAGE_VARS["rss"] = Pair("", (String,)) LOCAL_PAGE_VARS["rss_description"] = Pair("", (String,)) LOCAL_PAGE_VARS["rss_title"] = Pair("", (String,)) LOCAL_PAGE_VARS["rss_author"] = Pair("", (String,)) LOCAL_PAGE_VARS["rss_category"] = Pair("", (String,)) LOCAL_PAGE_VARS["rss_comments"] = Pair("", (String,)) LOCAL_PAGE_VARS["rss_enclosure"] = Pair("", (String,)) LOCAL_PAGE_VARS["rss_pubdate"] = Pair(Date(1), (Date,)) # page vars used by judoc, should not be accessed or defined LOCAL_PAGE_VARS["jd_ctime"] = Pair(Date(1), (Date,)) # time of creation LOCAL_PAGE_VARS["jd_mtime"] = Pair(Date(1), (Date,)) # time of last modification LOCAL_PAGE_VARS["jd_rpath"] = Pair("", (String,)) # local path to file src/[...]/blah.md # If there are GLOBAL vars that are defined, they take precedence local_keys = keys(LOCAL_PAGE_VARS) for k in keys(GLOBAL_PAGE_VARS) k in local_keys || continue LOCAL_PAGE_VARS[k] = GLOBAL_PAGE_VARS[k] end return nothing end """ PAGE_HEADERS Keep track of seen headers. The key is the refstring, the value contains the title, the occurence number for the first appearance of that title and the level (1, ..., 6). """ const PAGE_HEADERS = LittleDict{AS,Tuple{AS,Int,Int}}() """ $(SIGNATURES) Empties `PAGE_HEADERS`. """ @inline function def_PAGE_HEADERS!()::Nothing empty!(PAGE_HEADERS) return nothing end """ PAGE_FNREFS Keep track of name of seen footnotes; the order is kept as it's a list. """ const PAGE_FNREFS = String[] """ $(SIGNATURES) Empties `PAGE_FNREFS`. """ @inline function def_PAGE_FNREFS!()::Nothing empty!(PAGE_FNREFS) return nothing end """ PAGE_LINK_DEFS Keep track of link def candidates """ const PAGE_LINK_DEFS = LittleDict{String,String}() """ $(SIGNATURES) Empties `PAGE_LINK_DEFS`. """ @inline function def_PAGE_LINK_DEFS!()::Nothing empty!(PAGE_LINK_DEFS) return nothing end """ GLOBAL_LXDEFS List of latex definitions accessible to all pages. This is filled when the config file is read (via manager/file_utils/process_config). """ const GLOBAL_LXDEFS = LittleDict{String, LxDef}() """ EMPTY_SS Convenience constant for an empty substring, used in LXDEFS. """ const EMPTY_SS = SubString("") """ $(SIGNATURES) Convenience function to allocate default values of global latex commands accessible throughout the site. See [`resolve_lxcom`](@ref). """ @inline function def_GLOBAL_LXDEFS!()::Nothing empty!(GLOBAL_LXDEFS) # hyperreferences GLOBAL_LXDEFS["\\eqref"] = LxDef("\\eqref", 1, EMPTY_SS) GLOBAL_LXDEFS["\\cite"] = LxDef("\\cite", 1, EMPTY_SS) GLOBAL_LXDEFS["\\citet"] = LxDef("\\citet", 1, EMPTY_SS) GLOBAL_LXDEFS["\\citep"] = LxDef("\\citep", 1, EMPTY_SS) GLOBAL_LXDEFS["\\label"] = LxDef("\\label", 1, EMPTY_SS) GLOBAL_LXDEFS["\\biblabel"] = LxDef("\\biblabel", 2, EMPTY_SS) GLOBAL_LXDEFS["\\toc"] = LxDef("\\toc", 0, EMPTY_SS) GLOBAL_LXDEFS["\\tableofcontents"] = LxDef("\\tableofcontents", 0, EMPTY_SS) # inclusion GLOBAL_LXDEFS["\\input"] = LxDef("\\input", 2, EMPTY_SS) GLOBAL_LXDEFS["\\output"] = LxDef("\\output", 1, EMPTY_SS) GLOBAL_LXDEFS["\\codeoutput"] = LxDef("\\codeoutput", 1, subs("@@code_output \\output{#1}@@")) GLOBAL_LXDEFS["\\textoutput"] = LxDef("\\textoutput", 1, EMPTY_SS) GLOBAL_LXDEFS["\\textinput"] = LxDef("\\textinput", 1, EMPTY_SS) GLOBAL_LXDEFS["\\show"] = LxDef("\\show", 1, EMPTY_SS) GLOBAL_LXDEFS["\\figalt"] = LxDef("\\figalt", 2, EMPTY_SS) GLOBAL_LXDEFS["\\fig"] = LxDef("\\fig", 1, subs("\\figalt{}{#1}")) GLOBAL_LXDEFS["\\file"] = LxDef("\\file", 2, subs("[#1]()")) GLOBAL_LXDEFS["\\tableinput"] = LxDef("\\tableinput", 2, EMPTY_SS) GLOBAL_LXDEFS["\\literate"] = LxDef("\\literate", 1, EMPTY_SS) # text formatting GLOBAL_LXDEFS["\\underline"] = LxDef("\\underline", 1, subs("~~~<span style=\"text-decoration:underline;\">!#1</span>~~~")) GLOBAL_LXDEFS["\\textcss"] = LxDef("\\underline", 2, subs("~~~<span style=\"!#1\">!#2</span>~~~")) return nothing end #= ========================================== Convenience functions related to the jd_vars ============================================= =# """ $(SIGNATURES) Convenience function taking a `DateTime` object and returning the corresponding formatted string with the format contained in `GLOBAL_PAGE_VARS["date_format"]`. """ jd_date(d::DateTime)::AS = Dates.format(d, GLOBAL_PAGE_VARS["date_format"].first) """ $(SIGNATURES) Checks if a data type `t` is a subtype of a tuple of accepted types `tt`. """ check_type(t::DataType, tt::NTuple{N,DataType} where N)::Bool = any(<:(t, tᵢ) for tᵢ ∈ tt) """ $(SIGNATURES) Take a var dictionary `dict` and update the corresponding pair. This should only be used internally as it does not check the validity of `val`. See [`write_page`](@ref) where it is used to store a file's creation and last modification time. """ set_var!(d::PageVars, k::K, v) where K = (d[k] = Pair(v, d[k].second); nothing) #= ================================================= set_vars, the key function to assign site variables ==================================================== =# """ $(SIGNATURES) Given a set of definitions `assignments`, update the variables dictionary `jd_vars`. Keys in `assignments` that do not match keys in `jd_vars` are ignored (a warning message is displayed). The entries in `assignments` are of the form `KEY => STR` where `KEY` is a string key (e.g.: "hasmath") and `STR` is an assignment to evaluate (e.g.: "=false"). """ function set_vars!(jd_vars::PageVars, assignments::Vector{Pair{String,String}})::PageVars # if there's no assignment, cut it short isempty(assignments) && return jd_vars # process each assignment in turn for (key, assign) ∈ assignments # at this point there may still be a comment in the assignment # string e.g. if it came from @def title = "blah" <!-- ... --> # so let's strip <!-- and everything after. # NOTE This is agressive so if it happened that the user wanted # this in a string it would fail (but come on...) idx = findfirst("<!--", assign) !isnothing(idx) && (assign = assign[1:prevind(assign, idx[1])]) tmp = Meta.parse("__tmp__ = " * assign) # try to evaluate the parsed assignment try tmp = eval(tmp) catch err @error "I got an error (of type '$(typeof(err))') trying to evaluate '$tmp', fix the assignment." break end if haskey(jd_vars, key) # if the retrieved value has the right type, assign it to the corresponding key type_tmp = typeof(tmp) acc_types = jd_vars[key].second if check_type(type_tmp, acc_types) jd_vars[key] = Pair(tmp, acc_types) else @warn "Doc var '$key' (type(s): $acc_types) can't be set to value '$tmp' (type: $type_tmp). Assignment ignored." end else # there is no key, so directly assign, the type is not checked jd_vars[key] = Pair(tmp, (typeof(tmp), )) end end return jd_vars end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3410
""" $(SIGNATURES) Convenience function to add an id attribute to a html element """ attr(name::Symbol, val::AS) = ifelse(isempty(val), "", " $name=\"$val\"") """ $SIGNATURES Convenience function for a sup item """ html_sup(id::String, in::AS) = "<sup id=\"$id\">$in</sup>" """ $(SIGNATURES) Convenience function for a header """ html_hk(hk::String, header::AS; id::String="") = "<$hk$(attr(:id, id))>$header</$hk>" """ $(SIGNATURES) Convenience function to introduce a hyper reference. """ function html_ahref(link::AS, name::Union{Int,AS}; title::AS="", class::AS="") a = "<a href=\"$(htmlesc(link))\"" a *= attr(:title, title) a *= attr(:class, class) a *= ">$name</a>" a end """ $(SIGNATURES) Convenience function to introduce a hyper reference relative to a key (local hyperref). """ function html_ahref_key(key::AS, name::Union{Int,AS}) return html_ahref(url_curpage() * "#$key", name) end """ $(SIGNATURES) Convenience function to introduce a div block. """ html_div(name::AS, in::AS) = "<div class=\"$name\">$in</div>" """ $(SIGNATURES) Convenience function to introduce an image. The alt is escaped just in case the user adds quotation marks in the alt string. """ html_img(src::AS, alt::AS="") = "<img src=\"$src\" alt=\"$(htmlesc(alt))\">" """ $(SIGNATURES) Convenience function to introduce a code block. """ function html_code(c::AS, lang::AS="") isempty(c) && return "" isempty(lang) && return "<pre><code class=\"plaintext\">$c</code></pre>" lang == "html" && !is_html_escaped(c) && (c = htmlesc(c)) return "<pre><code class=\"language-$lang\">$c</code></pre>" end """ $(SIGNATURES) Convenience function to introduce inline code. """ html_code_inline(c::AS) = "<code>$c</code>" """ $(SIGNATURES) Insertion of a visible red message in HTML to show there was a problem. """ html_err(mess::String="") = "<p><span style=\"color:red;\">// $mess //</span></p>" """ $(SIGNATURES) Helper function to get the relative url of the current page. """ function url_curpage() # go from /pages/.../something.md to /pub/.../something.html note that if # on windows then it would be \\ whence the PATH_SEP rp = replace(JD_ENV[:CUR_PATH], Regex("^pages$(escape_string(PATH_SEP))")=>"pub$(PATH_SEP)") rp = unixify(rp) rp = splitext(rp)[1] * ".html" startswith(rp, "/") || (rp = "/" * rp) return rp end # Copied from https://github.com/JuliaLang/julia/blob/acb7bd93fb2d5adbbabeaed9f39ab3c85495b02f/stdlib/Markdown/src/render/html.jl#L25-L31 const _htmlescape_chars = LittleDict( '<' => "&lt;", '>' => "&gt;", '"' => "&quot;", '&' => "&amp;" ) for ch in "'`!\$%()=+{}[]" _htmlescape_chars[ch] = "&#$(Int(ch));" end const _htmlesc_to = values(_htmlescape_chars) |> collect """ $(SIGNATURES) Internal function to check if some html code has been escaped. """ is_html_escaped(cs::AS) = !isnothing(findfirst(ss -> occursin(ss, cs), _htmlesc_to)) """ $(SIGNATURES) Internal function to reverse the escaping of some html code (in order to avoid double escaping when pre-rendering with highlight, see issue 326). """ function html_unescape(cs::String) # this is a bit inefficient but whatever, `cs` shouldn't be very long. for (ssfrom, ssto) in _htmlescape_chars cs = replace(cs, ssto => ssfrom) end return cs end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
8214
""" $SIGNATURES Specify the folder for the Literate scripts, by default this is `scripts/`. """ function literate_folder(rp::String="") isempty(rp) && return PATHS[:literate] path = joinpath(PATHS[:folder], rp) !isdir(path) && error("Specified Literate path not found ($rp -- $path)") PATHS[:literate] = path return path end # # Convenience functions to work with strings and substrings # """ $(SIGNATURES) Returns the string corresponding to `s`: `s` itself if it is a string, or the parent string if `s` is a substring. Do not confuse with `String(s::SubString)` which casts `s` into its own object. # Example ```julia-repl julia> a = SubString("hello JuDoc", 3:8); julia> JuDoc.str(a) "hello JuDoc" julia> String(a) "llo Ju" ``` """ str(s::String)::String = s str(s::SubString)::String = s.string """ subs(s, from, to) subs(s, from) subs(s, range) subs(s) Convenience functions to take a substring of a string. # Example ```julia-repl julia> JuDoc.subs("hello", 2:4) "ell" ``` """ subs(s::AS, from::Int, to::Int)::SubString = SubString(s, from, to) subs(s::AS, from::Int)::SubString = subs(s, from, from) subs(s::AS, range::UnitRange{Int})::SubString = SubString(s, range) subs(s::AS) = SubString(s) """ $(SIGNATURES) Given a substring `ss`, returns the position in the parent string where the substring starts. # Example ```julia-repl julia> ss = SubString("hello", 2:4); JuDoc.from(ss) 2 ``` """ from(ss::SubString)::Int = nextind(str(ss), ss.offset) from(s::String) = 1 """ $(SIGNATURES) Given a substring `ss`, returns the position in the parent string where the substring ends. # Example ```julia-repl julia> ss = SubString("hello", 2:4); JuDoc.to(ss) 4 ``` """ to(ss::SubString)::Int = ss.offset + ss.ncodeunits to(s::String) = lastindex(s) """ $(SIGNATURES) Returns the string span of a regex match. Assumes there is no unicode in the match. # Example ```julia-repl julia> JuDoc.matchrange(match(r"ell", "hello")) 2:4 ``` """ matchrange(m::RegexMatch)::UnitRange{Int} = m.offset .+ (0:(length(m.match)-1)) # Other convenience functions """ $(SIGNATURES) Convenience function to display a time since `start`. """ function time_it_took(start::Float64) comp_time = time() - start mess = comp_time > 60 ? "$(round(comp_time/60; digits=1))m" : comp_time > 1 ? "$(round(comp_time; digits=1))s" : "$(round(comp_time*1000; digits=1))ms" return "[done $(lpad(mess, 6))]" end ``` $(SIGNATURES) Nicer printing of processes. ``` function print_final(startmsg::AS, starttime::Float64)::Nothing tit = time_it_took(starttime) println("\r$startmsg$tit") end """ $(SIGNATURES) Convenience function to denote a string as being in a math context in a recursive parsing situation. These blocks will be processed as math blocks but without adding KaTeX elements to it given that they are part of a larger context that already has KaTeX elements. NOTE: this happens when resolving latex commands in a math environment. So for instance if you have `\$\$ x \\in \\R \$\$` and `\\R` is defined as a command that does `\\mathbb{R}` well that would be an embedded math environment. These environments are marked as such so that we don't add additional KaTeX markers around them. """ mathenv(s::AS)::String = "_\$>_$(s)_\$<_" """ $(SIGNATURES) Takes a string `s` and replace spaces by underscores so that that we can use it for hyper-references. So for instance `"aa bb"` will become `aa_bb`. It also defensively removes any non-word character so for instance `"aa bb !"` will be `"aa_bb"` """ function refstring(s::AS)::String # remove html tags st = replace(s, r"<[a-z\/]+>"=>"") # remove non-word characters st = replace(st, r"&#[0-9]+;" => "") st = replace(st, r"[^a-zA-Z0-9_\-\s]" => "") # replace spaces by dashes st = replace(lowercase(strip(st)), r"\s+" => "_") # to avoid clashes with numbering of repeated headers, replace # double underscores by a single one (see convert_header function) st = replace(st, r"__" => "_") # in the unlikely event we don't have anything here, return the hash # of the original string isempty(st) && return string(hash(s)) return st end """ $(SIGNATURES) Internal function to take a path and return a unix version of the path (if it isn't already). Used in [`resolve_assets_rpath`](@ref). """ function unixify(rp::String)::String cand = Sys.isunix() ? rp : replace(rp, "\\"=>"/") isempty(splitext(cand)[2]) || return cand endswith(cand, "/") || isempty(cand) || return cand * "/" return cand end """ $(SIGNATURES) Internal function to take a unix path, split it along `/` and re-join it (which will lead to the same path on unix but not on windows). Only used in [`resolve_assets_rpath`](@ref). """ joinrp(rpath::AS) = joinpath(split(rpath, '/')...) """ $(SIGNATURES) Internal function to resolve a relative path. See [`convert_code_block`](@ref) and [`resolve_lx_input`](@ref). As an example, let's say you have the path `./blah/blih.txt` somewhere in `src/pages/page1.md`. The `./` indicates that the path should be reproduced in `/assets/` and so it will lead to `/assets/pages/blah/blih.txt`. In the `canonical=false` mode, the returned path is a UNIX path (irrelevant of your platform); these paths can be given to html anchors (refs, img, ...). In the `canonical=true` mode, the path is a valid path on the local system. These paths can be given to Julia to read or write things. """ function resolve_assets_rpath(rpath::AS; canonical::Bool=false, code::Bool=false)::String @assert length(rpath) > 1 "relative path '$rpath' doesn't seem right" if startswith(rpath, "/") # this is a full path starting from the website root folder so for instance # `/assets/blah/img1.png`; just return that canonical || return rpath return normpath(joinpath(PATHS[:folder], joinrp(rpath[2:end]))) elseif startswith(rpath, "./") # this is a path relative to the assets folder with the same path as the calling file so # for instance if calling from `src/pages/pg1.md` with `./im1.png` it would refer to # /assets/pages/pg1/im1.png @assert length(rpath) > 2 "relative path '$rpath' doesn't seem right" canonical || return "/assets/" * unixify(splitext(JD_ENV[:CUR_PATH])[1]) * rpath[3:end] return normpath(joinpath(PATHS[:assets], splitext(JD_ENV[:CUR_PATH])[1], joinrp(rpath[3:end]))) end if code # in the code mode we allow a short, this: `julia:ex` is considered # short for `julia:./code/ex` return resolve_assets_rpath("./code/" * rpath; canonical=canonical) end # this is a full path relative to the assets folder for instance `blah/img1.png` would # correspond to `/assets/blah/img1.png` canonical || return "/assets/" * rpath return normpath(joinpath(PATHS[:assets], joinrp(rpath))) end """ context(parent, position) Return an informative message of the context of a position and where the position is, this is useful when throwing error messages. """ function context(par::AS, pos::Int) # context string lidx = lastindex(par) if pos > 20 head = max(1, prevind(par, pos-20)) else head = 1 end if pos <= lidx-20 tail = min(lidx, nextind(par, pos+20)) else tail = lidx end prepend = ifelse(head > 1, "...", "") postpend = ifelse(tail < lidx, "...", "") ctxt = prepend * subs(par, head, tail) * postpend # line number lines = split(par, "\n", keepempty=false) nlines = length(lines) ranges = zeros(Int, nlines, 2) cs = 0 for (i, l) in enumerate(lines[1:end-1]) tmp = [nextind(par, cs), nextind(par, lastindex(l) + cs)] ranges[i, :] .= tmp cs = tmp[2] end ranges[end, :] = [nextind(par, cs), lidx] lno = findfirst(i -> ranges[i,1] <= pos <= ranges[i,2], 1:nlines) # Assemble to form a message mess = """ Context: \t$(strip(ctxt)) (near line $lno) \t$(" "^(pos-head+length(prepend)))^--- """ return mess end context(t::Token) = context(str(t), from(t))
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
8808
""" $(SIGNATURES) Convert a judoc html string into a html string (i.e. replace `{{ ... }}` blocks). """ function convert_html(hs::AS, allvars::PageVars; isoptim::Bool=false)::String isempty(hs) && return hs # Tokenize tokens = find_tokens(hs, HTML_TOKENS, HTML_1C_TOKENS) # Find hblocks ({{ ... }}) hblocks, tokens = find_all_ocblocks(tokens, HTML_OCB) filter!(hb -> hb.name != :COMMENT, hblocks) # Find qblocks (qualify the hblocks) qblocks = qualify_html_hblocks(hblocks) fhs = process_html_qblocks(hs, allvars, qblocks) # See issue #204, basically not all markdown links are processed as # per common mark with the JuliaMarkdown, so this is a patch that kind # of does if haskey(allvars, "reflinks") && allvars["reflinks"].first fhs = find_and_fix_md_links(fhs) end # if it ends with </p>\n but doesn't start with <p>, chop it off # this may happen if the first element parsed is an ocblock (not text) δ = ifelse(endswith(fhs, "</p>\n") && !startswith(fhs, "<p>"), 5, 0) isempty(fhs) && return "" if !isempty(GLOBAL_PAGE_VARS["prepath"].first) && isoptim fhs = fix_links(fhs) end return String(chop(fhs, tail=δ)) end """ $SIGNATURES Return the HTML corresponding to a JuDoc-Markdown string as well as all the page variables. See also [`jd2html`](@ref) which only returns the html. """ function jd2html_v(st::AbstractString; internal::Bool=false, dir::String="")::Tuple{String,Dict} isempty(st) && return st if !internal FOLDER_PATH[] = isempty(dir) ? mktempdir() : dir set_paths!() JD_ENV[:CUR_PATH] = "index.md" def_GLOBAL_LXDEFS!() def_GLOBAL_PAGE_VARS!() end m, v = convert_md(st, collect(values(GLOBAL_LXDEFS)); isinternal=internal) h = convert_html(m, v) return h, v end jd2html(a...; k...)::String = jd2html_v(a...; k...)[1] """ $SIGNATURES Take a qualified html block stack and go through it, with recursive calling. """ function process_html_qblocks(hs::AS, allvars::PageVars, qblocks::Vector{AbstractBlock}, head::Int=1, tail::Int=lastindex(hs))::String htmls = IOBuffer() head = head # (sub)string index i = 1 # qualified block index while i ≤ length(qblocks) β = qblocks[i] # write what's before the block fromβ = from(β) (head < fromβ) && write(htmls, subs(hs, head, prevind(hs, fromβ))) if β isa HTML_OPEN_COND content, head, i = process_html_cond(hs, allvars, qblocks, i) write(htmls, content) # should not see an HEnd by itself --> error elseif β isa HEnd throw(HTMLBlockError("I found a lonely {{end}}.")) # it's a function block, process it else write(htmls, convert_html_fblock(β, allvars)) head = nextind(hs, to(β)) end i += 1 end # write whatever is left after the last block head ≤ tail && write(htmls, subs(hs, head, tail)) return String(take!(htmls)) end function match_url(base::AS, cand::AS) endswith(cand, "/*") && return startswith(base, cand[1:prevind(cand, lastindex(cand))]) return splitext(cand)[1] == base end """ $SIGNATURES Recursively process a conditional block from an opening HTML_COND_OPEN to a {{end}}. """ function process_html_cond(hs::AS, allvars::PageVars, qblocks::Vector{AbstractBlock}, i::Int)::Tuple{String,Int,Int} if i == length(qblocks) throw(HTMLBlockError("Could not close the conditional block " * "starting with '$(qblocks[i].ss)'.")) end init_idx = i else_idx = 0 elseif_idx = Vector{Int}() accept_elseif = true # false as soon as we see an else block content = "" # inbalance keeps track of whether we've managed to find a # matching {{end}}. It increases if it sees other opening {{if..}} # and decreases if it sees a {{end}} inbalance = 1 probe = qblocks[i] # just for allocation while i < length(qblocks) && inbalance > 0 i += 1 probe = qblocks[i] # if we have a {{elseif ...}} or {{else}} with the right level, # keep track of them if inbalance == 1 if probe isa HElseIf accept_elseif || throw(HTMLBlockError("Saw a {{elseif ...}} after a "* "{{else}} block.")) push!(elseif_idx, i) elseif probe isa HElse else_idx = i accept_elseif = false end end inbalance += hbalance(probe) end # we've exhausted the candidate qblocks and not found an appropriate {{end}} if inbalance > 0 throw(HTMLBlockError("Could not close the conditional block " * "starting with '$(qblocks[init_idx].ss)'.")) end # we've found the closing {{end}} at index `i` β_close = probe i_close = i # We now have a complete conditional block with possibly # several else-if blocks and possibly an else block. # Check which one applies and discard the rest k = 0 # index of the first verified condition lag = 0 # aux var to distinguish 1st block case # initial block may be {{if..}} or {{isdef..}} or... # if its not just a {{if...}}, need to act appropriately # and if the condition is verified then k=1 βi = qblocks[init_idx] if βi isa Union{HIsDef,HIsNotDef,HIsPage,HIsNotPage} lag = 1 if βi isa HIsDef k = Int(haskey(allvars, βi.vname)) elseif βi isa HIsNotDef k = Int(!haskey(allvars, βi.vname)) else # HIsPage//HIsNotPage # # current path is relative to /src/ for instance # /src/pages/blah.md -> pages/blah # if starts with `pages/`, replaces by `pub/`: pages/blah => pub/blah rpath = splitext(unixify(JD_ENV[:CUR_PATH]))[1] rpath = replace(rpath, Regex("^pages") => "pub") # compare with β.pages inpage = any(p -> match_url(rpath, p), βi.pages) if βi isa HIsPage k = Int(inpage) else k = Int(!inpage) end end end # If we've not yet found a verified condition, keep looking # Now all cond blocks ahead are {{if ...}} {{elseif ...}} if iszero(k) if lag == 0 conds = [βi.vname, (qblocks[c].vname for c in elseif_idx)...] else conds = [qblocks[c].vname for c in elseif_idx] end known = [haskey(allvars, c) for c in conds] if !all(known) idx = findfirst(.!known) throw(HTMLBlockError("At least one of the condition variable could not be found: " * "couldn't find '$(conds[idx])'.")) end # check that all these variables are bool bools = [isa(allvars[c].first, Bool) for c in conds] if !all(bools) idx = findfirst(.!bools) throw(HTMLBlockError("At least one of the condition variable is not a Bool: " * "'$(conds[idx])' is not a bool.")) end # which one is verified? u = findfirst(c -> allvars[c].first, conds) k = isnothing(u) ? 0 : u + lag end if iszero(k) # if we still haven't found a verified condition, use the else if there is one if !iszero(else_idx) # use elseblock, the content is from it to the β_close head = nextind(hs, to(qblocks[else_idx])) tail = prevind(hs, from(β_close)) # get the stack of blocks in there action_qblocks = qblocks[else_idx+1:i_close-1] # process content = process_html_qblocks(hs, allvars, action_qblocks, head, tail) end else # determine the span of blocks oidx = 0 # opening conditional cidx = 0 # closing conditional if k == 1 oidx = init_idx else oidx = elseif_idx[k-1] end if k ≤ length(elseif_idx) cidx = elseif_idx[k] else cidx = ifelse(iszero(else_idx), i_close, else_idx) end # Get the content head = nextind(hs, to(qblocks[oidx])) tail = prevind(hs, from(qblocks[cidx])) # Get the stack of blocks in there action_qblocks = qblocks[oidx+1:cidx-1] # process content = process_html_qblocks(hs, allvars, action_qblocks, head, tail) end # move the head after the final {{end}} head = nextind(hs, to(β_close)) return content, head, i_close end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
5451
""" $(SIGNATURES) Helper function to process an individual block when it's a `HFun` such as `{{ fill author }}`. Dev Note: `fpath` is (currently) unused but is passed to all `convert_html_block` functions. See [`convert_html`](@ref). """ function convert_html_fblock(β::HFun, allvars::PageVars, ::AS="")::String # normalise function name and apply the function fn = lowercase(β.fname) haskey(HTML_FUNCTIONS, fn) && return HTML_FUNCTIONS[fn](β.params, allvars) # if we get here, then the function name is unknown, warn and ignore @warn "I found a function block '{{$fn ...}}' but don't recognise the function name. Ignoring." return "" end """ $(SIGNATURES) H-Function of the form `{{ fill vname }}` to plug in the content of a jd-var `vname` (assuming it can be represented as a string). """ function hfun_fill(params::Vector{String}, allvars::PageVars)::String # check params if length(params) != 1 throw(HTMLFunctionError("I found a {{fill ...}} with more than one parameter. Verify.")) end # form the fill replacement = "" vname = params[1] if haskey(allvars, vname) # retrieve the value stored tmp_repl = allvars[vname].first isnothing(tmp_repl) || (replacement = string(tmp_repl)) else @warn "I found a '{{fill $vname}}' but I do not know the variable '$vname'. Ignoring." end return replacement end """ $(SIGNATURES) H-Function of the form `{{ insert fpath }}` to plug in the content of a file at `fpath`. Note that the base path is assumed to be `PATHS[:src_html]` so paths have to be expressed relative to that. """ function hfun_insert(params::Vector{String})::String # check params if length(params) != 1 throw(HTMLFunctionError("I found a {{insert ...}} with more than one parameter. Verify.")) end # apply replacement = "" fpath = joinpath(PATHS[:src_html], split(params[1], "/")...) if isfile(fpath) replacement = convert_html(read(fpath, String), merge(GLOBAL_PAGE_VARS, LOCAL_PAGE_VARS)) else @warn "I found an {{insert ...}} block and tried to insert '$fpath' but I couldn't find the file. Ignoring." end return replacement end """ $(SIGNATURES) H-Function of the form `{{href ... }}`. """ function hfun_href(params::Vector{String})::String # check params if length(params) != 2 throw(HTMLFunctionError("I found an {{href ...}} block and expected 2 parameters" * "but got $(length(params)). Verify.")) end # apply replacement = "<b>??</b>" dname, hkey = params[1], params[2] if params[1] == "EQR" haskey(PAGE_EQREFS, hkey) || return replacement replacement = html_ahref_key(hkey, PAGE_EQREFS[hkey]) elseif params[1] == "BIBR" haskey(PAGE_BIBREFS, hkey) || return replacement replacement = html_ahref_key(hkey, PAGE_BIBREFS[hkey]) else @warn "Unknown dictionary name $dname in {{href ...}}. Ignoring" end return replacement end """ $(SIGNATURES) H-Function of the form `{{toc min max}}` (table of contents). Where `min` and `max` control the minimum level and maximum level of the table of content. The split is as follows: * key is the refstring * f[1] is the title (header text) * f[2] is irrelevant (occurence, used for numbering) * f[3] is the level """ function hfun_toc(params::Vector{String})::String if length(params) != 2 throw(HTMLFunctionError("I found a {{toc ...}} block and expected 2 parameters" * "but got $(length(params)). Verify.")) end isempty(PAGE_HEADERS) && return "" # try to parse min-max level min = 0 max = 100 try min = parse(Int, params[1]) max = parse(Int, params[2]) catch throw(HTMLFunctionError("I found a {{toc min max}} but couldn't parse min/max. Verify.")) end inner = "" headers = filter(p -> min ≤ p.second[3] ≤ max, PAGE_HEADERS) baselvl = minimum(h[3] for h in values(headers)) - 1 curlvl = baselvl for (rs, h) ∈ headers lvl = h[3] if lvl ≤ curlvl # Close previous list item inner *= "</li>" # Close additional sublists for each level eliminated for i = curlvl-1:-1:lvl inner *= "</ol></li>" end # Reopen for this list item inner *= "<li>" elseif lvl > curlvl # Open additional sublists for each level added for i = curlvl+1:lvl inner *= "<ol><li>" end end inner *= html_ahref_key(rs, h[1]) curlvl = lvl # At this point, number of sublists (<ol><li>) open equals curlvl end # Close remaining lists, as if going down to the base level for i = curlvl-1:-1:baselvl inner *= "</li></ol>" end toc = "<div class=\"jd-toc\">" * inner * "</div>" end """ HTML_FUNCTIONS Dictionary for special html functions. They can take two variables, the first one `π` refers to the arguments passed to the function, the second one `ν` refers to the page variables (i.e. the context) available to the function. """ const HTML_FUNCTIONS = LittleDict{String, Function}( "fill" => ((π, ν) -> hfun_fill(π, ν)), "insert" => ((π, _) -> hfun_insert(π)), "href" => ((π, _) -> hfun_href(π)), "toc" => ((π, _) -> hfun_toc(π)), )
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3055
""" $(SIGNATURES) Direct inline-style links are properly processed by Julia's Markdown processor but not: * `[link title][some reference]` and later `[some reference]: http://www.reddit.com` * `[link title]` and later `[link title]: https://www.mozilla.org` * (we don't either) `[link title](https://www.google.com "Google's Homepage")` """ function find_and_fix_md_links(hs::String)::String # 1. find all occurences of -- [...]: link # here we're looking for [id] or [id][] or [stuff][id] or ![stuff][id] but not [id]: # 1 > (&#33;)? == either ! or nothing # 2 > &#91;(.*?)&#93; == [...] inside of the brackets # 3 > (?:&#91;(.*?)&#93;)? == [...] inside of second brackets if there is such rx = r"(&#33;)?&#91;(.*?)&#93;(?!:)(?:&#91;(.*?)&#93;)?" m_link_refs = collect(eachmatch(rx, hs)) # recuperate the appropriate id which has a chance to match def_names ref_names = [ # no second bracket or empty second bracket ? # >> true then the id is in the first bracket A --> [id] or [id][] # >> false then the id is in the second bracket B --> [...][id] ifelse(isnothing(ref.captures[3]) || isempty(ref.captures[3]), ref.captures[2], # A. first bracket ref.captures[3]) # B. second bracket for ref in m_link_refs] # reconstruct the text h = IOBuffer() head = 1 i = 0 for (m, refn) in zip(m_link_refs, ref_names) # write what's before (head < m.offset) && write(h, subs(hs, head, prevind(hs, m.offset))) # def = get(PAGE_LINK_DEFS, refn) do "" end if isempty(def) # no def found --> just leave it as it was write(h, m.match) else if !isnothing(m.captures[1]) # CASE: ![alt][id] --> image write(h, html_img(def, refn)) else # It's a link if isnothing(m.captures[3]) || isempty(m.captures[3]) # CASE: [id] or [id][] the id is also the link text write(h, html_ahref(def, refn)) else # It's got a second, non-empty bracket # CASE: [name][id] name = m.captures[2] write(h, html_ahref(def, name)) end end end # move the head after the match head = nextind(hs, m.offset + lastindex(m.match) - 1) end strlen = lastindex(hs) (head ≤ strlen) && write(h, subs(hs, head, strlen)) return String(take!(h)) end """ $(SIGNATURES) for a project website, for instance `username.github.io/project/` all paths should eventually be pre-prended with `/project/`. This would happen just before you publish the website. """ function fix_links(pg::String)::String pp = strip(GLOBAL_PAGE_VARS["prepath"].first, '/') ss = SubstitutionString("\\1=\"/$(pp)/") return replace(pg, r"(src|href|formaction)\s*?=\s*?\"\/" => ss) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4714
""" $(SIGNATURES) Takes a html string that may contain inline katex blocks `\\(...\\)` or display katex blocks `\\[ ... \\]` and use node and katex to pre-render them to HTML. """ function js_prerender_katex(hs::String)::String # look for \(, \) and \[, \] (we know they're paired because generated from markdown parsing) matches = collect(eachmatch(r"\\(\(|\[|\]|\))", hs)) isempty(matches) && return hs # buffer to write the JS script jsbuffer = IOBuffer() write(jsbuffer, """ const katex = require("$(escape_string(joinpath(PATHS[:libs], "katex", "katex.min.js")))"); """) # string to separate the output of the different blocks splitter = "_>jdsplit<_" # go over each match and add the content to the jsbuffer for i ∈ 1:2:length(matches)-1 # tokens are paired, no nesting mo, mc = matches[i:i+1] # check if it's a display style display = (mo.match == "\\[") # this is the content without the \( \) or \[ \] ms = subs(hs, nextind(hs, mo.offset + 1), prevind(hs, mc.offset)) # add to content of jsbuffer write(jsbuffer, """ var html = katex.renderToString("$(escape_string(ms))", {displayMode: $display}) console.log(html) """) # in between every block, write $splitter so that output can be split easily i == length(matches)-1 || write(jsbuffer, """\nconsole.log("$splitter")\n""") end return js2html(hs, jsbuffer, matches, splitter) end """ $(SIGNATURES) Takes a html string that may contain `<pre><code ... </code></pre>` blocks and use node and highlight.js to pre-render them to HTML. """ function js_prerender_highlight(hs::String)::String # look for "<pre><code" and "</code></pre>" these will have been automatically generated # and therefore the regex can be fairly strict with spaces etc matches = collect(eachmatch(r"<pre><code\s*(class=\"?(?:language-)?(.*?)\"?)?\s*>|<\/code><\/pre>", hs)) isempty(matches) && return hs # buffer to write the JS script jsbuffer = IOBuffer() write(jsbuffer, """const hljs = require('highlight.js');""") # string to separate the output of the different blocks splitter = "_>jdsplit<_" # go over each match and add the content to the jsbuffer for i ∈ 1:2:length(matches)-1 # tokens are paired, no nesting co, cc = matches[i:i+1] # core code cs = subs(hs, nextind(hs, matchrange(co).stop), prevind(hs, matchrange(cc).start)) cs = escape_string(cs) # lang lang = co.captures[2] if isnothing(lang) write(jsbuffer, """console.log("<pre><code class=hljs>$cs</code></pre>");\n""") else if lang == "html" && is_html_escaped(cs) # corner case, see https://github.com/tlienart/JuDoc.jl/issues/326 # highlight will re-escape the string further. cs = html_unescape(cs) |> escape_string end # add to content of jsbuffer write(jsbuffer, """console.log("<pre><code class=\\"$lang hljs\\">" + hljs.highlight("$lang", "$cs").value + "</code></pre>");""") end # in between every block, write $splitter so that output can be split easily i == length(matches)-1 || write(jsbuffer, """console.log('$splitter');""") end return js2html(hs, jsbuffer, matches, splitter) end """ $(SIGNATURES) Convenience function to run the content of `jsbuffer` with node, and lace the results with `hs`. """ function js2html(hs::String, jsbuffer::IOBuffer, matches::Vector{RegexMatch}, splitter::String)::String # run it redirecting the output to a buffer outbuffer = IOBuffer() run(pipeline(`$NODE -e "$(String(take!(jsbuffer)))"`, stdout=outbuffer)) # read the buffer and split it using $splitter out = String(take!(outbuffer)) parts = split(out, splitter) # lace everything back together htmls = IOBuffer() head, c = 1, 1 for i ∈ 1:2:length(matches)-1 mo, mc = matches[i:i+1] write(htmls, subs(hs, head, prevind(hs, mo.offset))) pp = strip(parts[c]) if startswith(pp, "<pre><code class=\"julia-repl") pp = replace(pp, r"shell&gt;"=>"<span class=hljs-metas>shell&gt;</span>") pp = replace(pp, r"(\(.*?\)) pkg&gt;"=>s"<span class=hljs-metap>\1 pkg&gt;</span>") end write(htmls, pp) head = mc.offset + length(mc.match) c += 1 end # add the rest of the document beyond the last mathblock head < lastindex(hs) && write(htmls, subs(hs, head, lastindex(hs))) return String(take!(htmls)) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
15802
""" $(SIGNATURES) Take a `LxCom` object `lxc` and try to resolve it. Provided a definition exists etc, the definition is plugged in then sent forward to be re-parsed (in case further latex is present). """ function resolve_lxcom(lxc::LxCom, lxdefs::Vector{LxDef}; inmath::Bool=false)::String # try to find where the first argument of the command starts (if any) i = findfirst("{", lxc.ss) # extract the name of the command e.g. \\cite name = isnothing(i) ? lxc.ss : subs(lxc.ss, 1:(first(i)-1)) # sort special commands where the input depends on context (see hyperrefs and inputs) haskey(LXCOM_HREF, name) && return LXCOM_HREF[name](lxc) name == "\\input" && return resolve_lx_input(lxc) name ∈ keys(LXCOM_SIMPLE) && return LXCOM_SIMPLE[name](lxc) # In subsequent case, whatever the command inserts will be re-parsed (in case the insertion # contains further commands or markdown); partial corresponds to what the command corresponds # to before re-processing. partial = "" if name ∈ keys(LXCOM_SIMPLE_REPROCESS) partial = LXCOM_SIMPLE_REPROCESS[name](lxc) else # retrieve the definition attached to the command lxdef = getdef(lxc) # lxdef = nothing means we're inmath & not found -> let KaTeX deal with it isnothing(lxdef) && return lxc.ss # lxdef = something -> maybe inmath + found; retrieve & apply partial = lxdef for (argnum, β) ∈ enumerate(lxc.braces) content_ = strip(content(β)) # space sensitive "unsafe" one # e.g. blah/!#1 --> blah/blah but note that # \command!#1 --> \commandblah and \commandblah would not be found partial = replace(partial, "!#$argnum" => content_) # non-space sensitive "safe" one # e.g. blah/#1 --> blah/ blah but note that # \command#1 --> \command blah and no error. partial = replace(partial, "#$argnum" => " " * content_) end partial = ifelse(inmath, mathenv(partial), partial) end # reprocess (we don't care about jd_vars=nothing) plug, _ = convert_md(partial, lxdefs, isrecursive=true, isconfig=false, has_mddefs=false) return plug end #= =============== Hyper references ================== =# """ PAGE_EQREFS Dictionary to keep track of equations that are labelled on a page to allow references within the page. """ const PAGE_EQREFS = LittleDict{String, Int}() """ PAGE_EQREFS_COUNTER Counter to keep track of equation numbers as they appear along the page, this helps with equation referencing. (The `_XC0q` is just a random string to avoid clashes). """ const PAGE_EQREFS_COUNTER = "COUNTER_XC0q" """ $(SIGNATURES) Reset the PAGE_EQREFS dictionary. """ @inline function def_PAGE_EQREFS!() empty!(PAGE_EQREFS) PAGE_EQREFS[PAGE_EQREFS_COUNTER] = 0 return nothing end """ PAGE_BIBREFS Dictionary to keep track of bibliographical references on a page to allow citation within the page. """ const PAGE_BIBREFS = LittleDict{String, String}() """ $(SIGNATURES) Reset the PAGE_BIBREFS dictionary. """ def_PAGE_BIBREFS!() = (empty!(PAGE_BIBREFS); nothing) """ $(SIGNATURES) Given a `label` command, replace it with an html anchor. """ add_label(λ::LxCom)::String = "<a id=\"$(refstring(strip(content(λ.braces[1]))))\"></a>" """ $(SIGNATURES) Given a `biblabel` command, update `PAGE_BIBREFS` to keep track of the reference so that it can be linked with a hyperreference. """ function add_biblabel(λ::LxCom)::String name = refstring(strip(content(λ.braces[1]))) PAGE_BIBREFS[name] = content(λ.braces[2]) return "<a id=\"$name\"></a>" end """ $(SIGNATURES) Given a latex command such as `\\eqref{abc}`, hash the reference (here `abc`), check if the given dictionary `d` has an entry corresponding to that hash and return the appropriate HTML for it. """ function form_href(lxc::LxCom, dname::String; parens="("=>")", class="href")::String ct = content(lxc.braces[1]) # "r1, r2, r3" refs = strip.(split(ct, ",")) # ["r1", "r2", "r3"] names = refstring.(refs) nkeys = length(names) # construct the partial link with appropriate parens, it will be # resolved at the second pass (HTML pass) whence the introduction of {{..}} # inner will be "{{href $dn $hr1}}, {{href $dn $hr2}}, {{href $dn $hr3}}" # where $hr1 is the hash of r1 etc. in = prod("{{href $dname $name}}$(ifelse(i < nkeys, ", ", ""))" for (i, name) ∈ enumerate(names)) # encapsulate in a span for potential css-styling return "<span class=\"$class\">$(parens.first)$in$(parens.second)</span>" end """ LXCOM_HREF Dictionary for latex commands related to hyperreference for which a specific replacement that depends on context is constructed. """ const LXCOM_HREF = LittleDict{String, Function}( "\\eqref" => (λ -> form_href(λ, "EQR"; class="eqref")), "\\cite" => (λ -> form_href(λ, "BIBR"; parens=""=>"", class="bibref")), "\\citet" => (λ -> form_href(λ, "BIBR"; parens=""=>"", class="bibref")), "\\citep" => (λ -> form_href(λ, "BIBR"; class="bibref")), "\\biblabel" => add_biblabel, "\\label" => add_label, ) """ $(SIGNATURES) Internal function to resolve a relative path to `/assets/` and return the resolved dir as well as the file name; it also checks that the dir exists. It returns the full path to the file, the path of the directory containing the file, and the name of the file without extension. See also [`resolve_lx_input`](@ref). Note: rpath here is always a UNIX path while the output correspond to SYSTEM paths. """ function check_input_rpath(rpath::AS, lang::AS=""; code::Bool=false)::NTuple{3,String} # find the full system path to the asset fpath = resolve_assets_rpath(rpath; canonical=true, code=code) # check if an extension is given, if not, consider it's `.xx` with language `nothing` if isempty(splitext(fpath)[2]) ext, _ = get(CODE_LANG, lang) do (".xx", nothing) end fpath *= ext end dir, fname = splitdir(fpath) # TODO: probably better to not throw an "argumenterror" here but maybe use html_err # (though the return type needs to be adjusted accordingly and it shouldn't be propagated) # see fill_extension, this is the case where nothing came up if endswith(fname, ".xx") # try to find a file with the same root and any extension otherwise throw an error files = readdir(dir) fn = splitext(fname)[1] k = findfirst(e -> splitext(e)[1] == fn, files) if isnothing(k) throw(ArgumentError("Couldn't find a relevant file when trying to " * "resolve an \\input command. (given: $rpath)")) end fname = files[k] fpath = joinpath(dir, fname) elseif !isfile(fpath) throw(ArgumentError("Couldn't find a relevant file when trying to resolve an \\input " * "command. (given: $rpath)")) end return fpath, dir, splitext(fname)[1] end """ $(SIGNATURES) Internal function to read the content of a script file. See also [`resolve_lx_input`](@ref). """ function resolve_lx_input_hlcode(rpath::AS, lang::AS)::String fpath, = check_input_rpath(rpath; code=true) # Read the file while ignoring lines that are flagged with something like `# HIDE` _, comsym = CODE_LANG[lang] hide = Regex(raw"(?:^|[^\S\r\n]*?)#(\s)*?(?i)hide(all)?") lit_hide = Regex(raw"(?:^|[^\S\r\n]*?)#src") hideall = false io_in = IOBuffer() open(fpath, "r") do f for line ∈ readlines(f) # - if there is a \s#\s+HIDE , skip that line m = match(hide, line) ml = match(lit_hide, line) if all(isnothing, (m, ml)) write(io_in, line) write(io_in, "\n") elseif m !== nothing # does it have a "all" or not? (m.captures[2] === nothing) && continue # it does have an "all" hideall = true break end end end hideall && take!(io_in) # discard the content code = String(take!(io_in)) isempty(code) && return "" endswith(code, "\n") && (code = chop(code, tail=1)) html = html_code(code, lang) if LOCAL_PAGE_VARS["showall"].first html *= show_res(rpath) end return html end """ $(SIGNATURES) Internal function to read the content of a script file and highlight it using `highlight.js`. See also [`resolve_lx_input`](@ref). """ function resolve_lx_input_othercode(rpath::AS, lang::AS)::String fpath, = check_input_rpath(rpath, code=true) return html_code(read(fpath, String), lang) end """ $SIGNATURES Internal function to check if a code should suppress the final show. """ function check_suppress_show(code::AS) scode = strip(code) scode[end] == ';' && return true # last line ? lastline = scode i = findlast(e -> e in (';','\n'), scode) if !isnothing(i) lastline = strip(scode[nextind(scode, i):end]) end startswith(lastline, "@show ") && return true startswith(lastline, "println(") && return true startswith(lastline, "print(") && return true return false end """ $SIGNATURES Internal function to read a result file and show it. """ function show_res(rpath::AS)::String fpath, = check_input_rpath(rpath; code=true) fd, fn = splitdir(fpath) stdo = read(joinpath(fd, "output", splitext(fn)[1] * ".out"), String) res = read(joinpath(fd, "output", splitext(fn)[1] * ".res"), String) # check if there's a final `;` or if the last line is a print, println or show # in those cases, ignore the result file code = strip(read(splitext(fpath)[1] * ".jl", String)) check_suppress_show(code) && (res = "") if !isempty(stdo) endswith(stdo, "\n") || (stdo *= "\n") end res == "nothing" && (res = "") isempty(stdo) && isempty(res) && return "" return html_div("code_output", html_code(stdo * res)) end """ $(SIGNATURES) Internal function to read the raw output of the execution of a file and display it in a pre block. See also [`resolve_lx_input`](@ref). """ function resolve_lx_input_plainoutput(rpath::AS, reproc::Bool=false; code::Bool=false)::String # will throw an error if rpath doesn't exist _, dir, fname = check_input_rpath(rpath; code=code) out_file = joinpath(dir, "output", fname * ".out") # check if the output file exists isfile(out_file) || throw(ErrorException("I found an \\input but no relevant output file.")) # return the content in a pre block (if non empty) content = read(out_file, String) isempty(content) && return "" reproc || return html_code(content) return content end """ $(SIGNATURES) Internal function to read a file at a specified path and just plug it in. (Corresponds to what a simple `\\input` command does in LaTeX). See also [`resolve_lx_textinput`](@ref). """ function resolve_lx_input_textfile(rpath::AS)::String # find the full system path to the asset fpath = resolve_assets_rpath(rpath; canonical=true) isempty(splitext(fpath)[2]) && (fpath *= ".md") isfile(fpath) || throw(ErrorException("I found a \\textinput but no relevant file.")) content = read(fpath, String) isempty(content) && return "" return content end """ $(SIGNATURES) Internal function to read a plot outputted by script `rpath`, possibly named with `id`. See also [`resolve_lx_input`](@ref). The commands `\\fig` and `\\figalt` should be preferred. """ function resolve_lx_input_plotoutput(rpath::AS, id::AS="")::String # will throw an error if rpath doesn't exist _, dir, fname = check_input_rpath(rpath, code=true) plt_name = fname * id # find a plt in output that has the same root name out_path = joinpath(dir, "output") isdir(out_path) || throw(ErrorException("I found an input plot but not output dir.")) out_file = "" for (root, _, files) ∈ walkdir(out_path) for (f, e) ∈ splitext.(files) lc_e = lowercase(e) if f == plt_name && lc_e ∈ (".gif", ".jpg", ".jpeg", ".png", ".svg") reldir = dir if startswith(reldir, PATHS[:folder]) # will usually be the case reldir = reldir[length(PATHS[:folder])+1:end] end out_file = unixify(joinpath(reldir, "output", plt_name * lc_e)) break end end out_file == "" || break end # error if no file found out_file != "" || throw(ErrorException("I found an input plot but no relevant output plot.")) # wrap it in img block return html_img(out_file) end """ $(SIGNATURES) Resolve a command of the form `\\input{code:julia}{path_to_script}` where `path_to_script` is a valid subpath of `/assets/`. All paths should be expressed relatively to `/assets/` i.e. `/assets/[subpath]/script.jl`. If things are not in `assets/`, start the path with `../` to go up one level then go down for instance `../src/pages/script1.jl`. Forward slashes should also be used on windows. Different actions can be taken based on the first bracket: 1. `{julia}` or `{code:julia}` will insert the code in the script with appropriate highlighting 2. `{output}` or `{output:plain}` will look for an output file in `/scripts/output/path_to_script` and will just print the content in a non-highlighted code block 3. `{plot}` or `{plot:id}` will look for a displayable image file (gif, png, jp(e)g or svg) in `/assets/[subpath]/script1` and will add an `img` block as a result. If an `id` is specified, it will try to find an image with the same root name ending with `id.ext` where `id` can help identify a specific image if several are generated by the script, typically a number will be used. """ function resolve_lx_input(lxc::LxCom)::String qualifier = lowercase(strip(content(lxc.braces[1]))) # `code:julia` rpath = strip(content(lxc.braces[2])) # [assets]/subpath/script{.jl} if occursin(":", qualifier) p1, p2 = split(qualifier, ":") # code:julia if p1 == "code" if p2 ∈ keys(CODE_LANG) # these are codes for which we know how they're commented and can use the # HIDE trick (see HIGHLIGHT and resolve_lx_input_hlcode) return resolve_lx_input_hlcode(rpath, p2) else # another language descriptor, let the user do that with highlights.js # note that the HIDE trick will not work here. return resolve_lx_input_othercode(rpath, qualifier) end # output:plain elseif p1 == "output" if p2 == "plain" return resolve_lx_input_plainoutput(rpath, code=true) else throw(ArgumentError("I found an \\input but couldn't interpret \"$qualifier\".")) end # plot:id elseif p1 == "plot" return resolve_lx_input_plotoutput(rpath, p2) else throw(ArgumentError("I found an \\input but couldn't interpret \"$qualifier\".")) end else if qualifier == "output" return resolve_lx_input_plainoutput(rpath; code=true) elseif qualifier == "plot" return resolve_lx_input_plotoutput(rpath) elseif qualifier ∈ ("julia", "fortran", "julia-repl", "matlab", "r", "toml") return resolve_lx_input_hlcode(rpath, qualifier) else # assume it's another language descriptor, let the user do that with highlights.js return resolve_lx_input_othercode(rpath, qualifier) end end end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
7843
# See src/jd_vars : def_GLOBAL_LXDEFS """ $SIGNATURES Internal function to resolve a `\\output{rpath}` (finds the output of a code block and shows it). The `reprocess` argument indicates whether the output should be processed as judoc markdown or inserted as is. """ function resolve_lx_output(lxc::LxCom; reprocess::Bool=false)::String rpath = strip(content(lxc.braces[1])) # [assets]/subpath/script{.jl} return resolve_lx_input_plainoutput(rpath, reprocess; code=true) end """ $SIGNATURES Internal function to resolve a `\\show{rpath}` (finds the result of a code block and shows it). No reprocess for this. """ function resolve_lx_show(lxc::LxCom; reprocess::Bool=false)::String rpath = strip(content(lxc.braces[1])) show_res(rpath) end """ $SIGNATURES Internal function to resolve a `\\textoutput{rpath}` (finds the output of a code block and shows after treating it as markdown to be parsed). """ resolve_lx_textoutput(lxc::LxCom) = resolve_lx_output(lxc; reprocess=true) """ $SIGNATURES Internal function to resolve a `\\textinput{rpath}` (reads the file and show it after processing). """ function resolve_lx_textinput(lxc::LxCom)::String rpath = strip(content(lxc.braces[1])) return resolve_lx_input_textfile(rpath) end """ $SIGNATURES Internal function to resolve a `\\literate{rpath}` see [`literate_to_judoc`](@ref). """ function resolve_lx_literate(lxc::LxCom)::String rpath = strip(content(lxc.braces[1])) opath, haschanged = literate_to_judoc(rpath) isempty(opath) && return "~~~"*html_err("Literate file matching '$rpath' not found.")*"~~~" if !haschanged # page has not changed, check if literate is the only source of code # and in that case skip eval of all code blocks via freezecode if LOCAL_PAGE_VARS["literate_only"].first set_var!(LOCAL_PAGE_VARS, "freezecode", true) end end if haschanged && JD_ENV[:FULL_PASS] set_var!(LOCAL_PAGE_VARS, "reeval", true) end # if haschanged=true and not full pass then this will be handled cell by cell # comparing with cell files following `eval_and_resolve_code` return read(opath, String) end """ $SIGNATURES Internal function to resolve a `\\figalt{alt}{rpath}` (finds a plot and includes it with alt). """ function resolve_lx_figalt(lxc::LxCom)::String rpath = strip(content(lxc.braces[2])) alt = strip(content(lxc.braces[1])) path = resolve_assets_rpath(rpath; canonical=false) fdir, fext = splitext(path) # there are several cases # A. a path with no extension --> guess extension # B. a path with extension --> use that # then in both cases there can be a relative path set but the user may mean # that it's in the subfolder /output/ (if generated by code) so should look # both in the relpath and if not found and if /output/ not already the last subdir candext = ifelse(isempty(fext), (".png", ".jpeg", ".jpg", ".svg", ".gif"), (fext,)) for ext ∈ candext candpath = fdir * ext syspath = joinpath(PATHS[:folder], split(candpath, '/')...) isfile(syspath) && return html_img(candpath, alt) end # now try in the output dir just in case (provided we weren't already looking there) p1, p2 = splitdir(fdir) if splitdir(p1)[2] != "output" for ext ∈ candext candpath = joinpath(p1, "output", p2 * ext) syspath = joinpath(PATHS[:folder], split(candpath, '/')...) isfile(syspath) && return html_img(candpath, alt) end end return html_err("image matching '$path' not found") end """ $SIGNATURES Internal function to resolve a `\\tableinput{header}{rpath}` (finds a csv and includes it with header). """ function resolve_lx_tableinput(lxc::LxCom)::String rpath = strip(content(lxc.braces[2])) header = strip(content(lxc.braces[1])) path = resolve_assets_rpath(rpath; canonical=false) fdir, fext = splitext(path) # copy-paste from resolve_lx_figalt() # A. a path with extension --> use that # there can be a relative path set but the user may mean # that it's in the subfolder /output/ (if generated by code) so should look # both in the relpath and if not found and if /output/ not already the last subdir syspath = joinpath(PATHS[:folder], split(path, '/')...) if isfile(syspath) return csv2html(syspath, header) end # now try in the output dir just in case (provided we weren't already looking there) p1, p2 = splitdir(fdir) if splitdir(p1)[2] != "output" candpath = joinpath(p1, "output", p2 * fext) syspath = joinpath(PATHS[:folder], split(candpath, '/')...) isfile(syspath) && return csv2html(syspath, header) end return html_err("table matching '$path' not found") end """ $SIGNATURES Internal function to process an array of strings to markdown table (in one single string). If header is empty, the first row of the file will be used for header. """ function csv2html(path, header)::String csvcontent = readdlm(path, ',', String, header=false) nrows, ncols = size(csvcontent) io = IOBuffer() # writing the header if ! isempty(header) # header provided newheader = split(header, ",") hs = size(newheader,1) hs != ncols && return html_err("header size ($hs) and number of columns ($ncols) do not match") write(io, prod("| " * h * " " for h in newheader)) rowrange = 1:nrows else # header from csv file write(io, prod("| " * csvcontent[1, i] * " " for i in 1:ncols)) rowrange = 2:nrows end # writing end of header & header separator write(io, "|\n|", repeat( " ----- |", ncols), "\n") # writing content for i in rowrange for j in 1:ncols write(io, "| ", csvcontent[i,j], " ") end write(io, "|\n") end return md2html(String(take!(io))) end """ $SIGNATURES Internal function to resolve a `\\file{name}{rpath}` (finds a file and includes it with link name). Note that while `\\figalt` is tolerant to extensions not being specified, this one is not. """ function resolve_lx_file(lxc::LxCom)::String rpath = strip(content(lxc.braces[2])) name = strip(content(lxc.braces[1])) path = resolve_assets_rpath(rpath; canonical=false) syspath = joinpath(PATHS[:folder], split(path, '/')...) isfile(syspath) && return html_ahref(path, name) return html_err("file matching '$path' not found") end """ $SIGNATURES Internal function to resolve a `\\toc` or `\\tableofcontents`. """ function insert_toc(::LxCom)::String minlevel = LOCAL_PAGE_VARS["mintoclevel"].first maxlevel = LOCAL_PAGE_VARS["maxtoclevel"].first return "{{toc $minlevel $maxlevel}}" end """ $SIGNATURES Dictionary of functions to use for different default latex-like commands. The output of these commands is inserted "as-is" (without re-processing) in the HTML. """ const LXCOM_SIMPLE = LittleDict{String, Function}( "\\output" => resolve_lx_output, # include plain output generated by code "\\figalt" => resolve_lx_figalt, # include a figure (may or may not have been generated) "\\file" => resolve_lx_file, # include a file "\\tableinput" => resolve_lx_tableinput, # include table from a csv file "\\show" => resolve_lx_show, # show result of a code block "\\toc" => insert_toc, "\\tableofcontents" => insert_toc, ) """ $SIGNATURES Same as [`LXCOM_SIMPLE`](@ref) except the output is re-processed before being inserted in the HTML. """ const LXCOM_SIMPLE_REPROCESS = LittleDict{String, Function}( "\\textoutput" => resolve_lx_textoutput, # include output generated by code and reproc "\\textinput" => resolve_lx_textinput, "\\literate" => resolve_lx_literate, )
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
15438
""" $(SIGNATURES) Convert a judoc markdown file read as `mds` into a judoc html string. Returns the html string as well as a dictionary of page variables. **Arguments** * `mds`: the markdown string to process * `pre_lxdefs`: a vector of `LxDef` that are already available. **Keyword arguments** * `isrecursive=false`: a bool indicating whether the call is the parent call or a child call * `isinternal=false`: a bool indicating whether the call stems from `jd2html` in internal mode * `isconfig=false`: a bool indicating whether the file to convert is the configuration file * `has_mddefs=true`: a bool indicating whether to look for definitions of page variables """ function convert_md(mds::AS, pre_lxdefs::Vector{LxDef}=Vector{LxDef}(); isrecursive::Bool=false, isinternal::Bool=false, isconfig::Bool=false, has_mddefs::Bool=true )::Tuple{String,Union{Nothing,PageVars}} if !(isrecursive || isinternal) def_LOCAL_PAGE_VARS!() # page-specific variables def_PAGE_HEADERS!() # all the headers def_PAGE_EQREFS!() # page-specific equation dict (hrefs) def_PAGE_BIBREFS!() # page-specific reference dict (hrefs) def_PAGE_FNREFS!() # page-specific footnote dict def_PAGE_LINK_DEFS!() # page-specific link definition candidates [..]: (...) end # if it's a substring, force it to a string mds = String(mds) # # Parsing of the markdown string # (to find latex command, latex definitions, math envs etc.) # # ----------------------------------------------------------------------------------- #> 1. Tokenize tokens = find_tokens(mds, MD_TOKENS, MD_1C_TOKENS) # distinguish fnref/fndef validate_footnotes!(tokens) # ignore header tokens that are not at the start of a line validate_headers!(tokens) #> 1b. Find indented blocks (ONLY if not recursive to avoid ambiguities!) if !isrecursive find_indented_blocks!(tokens, mds) filter_lr_indent!(tokens, mds) end # ----------------------------------------------------------------------------------- #> 2. Open-Close blocks (OCBlocks) #.> 0 #>> a. find them blocks, tokens = find_all_ocblocks(tokens, MD_OCB_ALL) #>> b. merge CODE_BLOCK_IND which are separated by emptyness merge_indented_blocks!(blocks, mds) #>> b'. only keep indented code blocks which are not contained in larger blocks (#285) filter_indented_blocks!(blocks) #>> c. now that blocks have been found, line-returns can be dropped filter!(τ -> τ.name ∉ L_RETURNS, tokens) #>> e. keep track of literal content of possible link definitions to use validate_and_store_link_defs!(blocks) # ----------------------------------------------------------------------------------- #> 3. LaTeX commands #>> a. find "newcommands", update active blocks/braces lxdefs, tokens, braces, blocks = find_md_lxdefs(tokens, blocks) #>> b. if any lxdefs are given in the context, merge them. `pastdef` specifies # that the definitions appeared "earlier" lprelx = length(pre_lxdefs) (lprelx > 0) && (lxdefs = cat(pastdef.(pre_lxdefs), lxdefs, dims=1)) #>> c. find latex commands lxcoms, _ = find_md_lxcoms(tokens, lxdefs, braces) # ----------------------------------------------------------------------------------- #> 4. Page variable definition (mddefs) jd_vars = nothing has_mddefs && (jd_vars = process_md_defs(blocks, isconfig, lxdefs)) isconfig && return "", jd_vars # ----------------------------------------------------------------------------------- #> 5. Process special characters and html entities so that they can be injected # as they are in the HTML later sp_chars = find_special_chars(tokens) # =================================================================================== # # Forming of the html string # # filter out the fnrefs that are left (still active) # and add them to the blocks to insert fnrefs = filter!(τ -> τ.name == :FOOTNOTE_REF, tokens) #> 1. Merge all the blocks that will need further processing before insertion blocks2insert = merge_blocks(lxcoms, deactivate_divs(blocks), sp_chars, fnrefs) #> 2. Form intermediate markdown + html inter_md, mblocks = form_inter_md(mds, blocks2insert, lxdefs) inter_html = md2html(inter_md; stripp=isrecursive) #> 3. Plug resolved blocks in partial html to form the final html lxcontext = LxContext(lxcoms, lxdefs, braces) hstring = convert_inter_html(inter_html, mblocks, lxcontext) # final vars adjustments if !isnothing(jd_vars) #> if there's code, assemble it so that can be shown or loaded in one shot codes = LOCAL_PAGE_VARS["jd_code_scope"].first.codes if !isempty(codes) set_var!(jd_vars, "jd_code", strip(prod(c*"\n" for c in codes))) end #> if no title is specified, grab the first header if there is one if isnothing(LOCAL_PAGE_VARS["title"].first) && !isempty(PAGE_HEADERS) set_var!(jd_vars, "title", first(values(PAGE_HEADERS))[1]) end end # Return the string + judoc variables return hstring, jd_vars end """ $(SIGNATURES) Same as `convert_md` except tailored for conversion of the inside of a math block (no command definitions, restricted tokenisation to latex tokens). The offset keeps track of where the math block was, which is useful to check whether any of the latex command used in the block have not yet been defined. **Arguments** * `ms`: the string to convert * `lxdefs`: existing latex definitions prior to the math block * `offset`: where the mathblock is with respect to the parent string """ function convert_md_math(ms::AS, lxdefs::Vector{LxDef}=Vector{LxDef}(), offset::Int=0)::String # if a substring is given, copy it as string ms = String(ms) # # Parsing of the markdown string # (to find latex command, latex definitions, math envs etc.) # #> 1. Tokenize (with restricted set) tokens = find_tokens(ms, MD_TOKENS_LX, MD_1C_TOKENS_LX) #> 2. Find braces and drop line returns thereafter blocks, tokens = find_all_ocblocks(tokens, MD_OCB_ALL, inmath=true) braces = filter(β -> β.name == :LXB, blocks) #> 3. Find latex commands (indicate we're in a math environment + offset) lxcoms, _ = find_md_lxcoms(tokens, lxdefs, braces, offset; inmath=true) # # Forming of the html string # (see `form_inter_md`, it's similar but simplified since there are fewer conditions) # htmls = IOBuffer() strlen = lastindex(ms) len_lxc = length(lxcoms) next_lxc = iszero(len_lxc) ? BIG_INT : from(lxcoms[1]) # counters to keep track of where we are and which command we're looking at head, lxc_idx = 1, 1 while (next_lxc < BIG_INT) && (head < strlen) # add anything that may occur before the first command (head < next_lxc) && write(htmls, subs(ms, head, prevind(ms, next_lxc))) # add the first command after resolving, bool to indicate that we're in a math env write(htmls, resolve_lxcom(lxcoms[lxc_idx], lxdefs, inmath=true)) # move the head to after the lxcom and increment the com counter head = nextind(ms, to(lxcoms[lxc_idx])) lxc_idx += 1 next_lxc = from_ifsmaller(lxcoms, lxc_idx, len_lxc) end # add anything after the last command (head ≤ strlen) && write(htmls, chop(ms, head=prevind(ms, head), tail=0)) return String(take!(htmls)) end """ INSERT String that is plugged as a placeholder of blocks that need further processing. The spaces allow to handle overzealous inclusion of `<p>...</p>` from the base Markdown to HTML conversion. """ const INSERT = " ##JDINSERT## " const INSERT_ = strip(INSERT) const INSERT_PAT = Regex(INSERT_) const INSERT_LEN = length(INSERT_) """ $(SIGNATURES) Form an intermediate MD file where special blocks are replaced by a marker (`INSERT`) indicating that a piece will need to be plugged in there later. **Arguments** * `mds`: the (sub)string to convert * `blocks`: vector of blocks * `lxdefs`: existing latex definitions prior to the math block """ function form_inter_md(mds::AS, blocks::Vector{<:AbstractBlock}, lxdefs::Vector{LxDef})::Tuple{String, Vector{AbstractBlock}} strlen = lastindex(mds) intermd = IOBuffer() # keep track of the matching blocks for each insert mblocks = Vector{AbstractBlock}() len_b = length(blocks) len_lxd = length(lxdefs) # check when the next block is next_b = iszero(len_b) ? BIG_INT : from(blocks[1]) # check when the next lxblock is, extra work because there may be lxdefs # passed through in *context* (i.e. that do not appear in mds) therefore # search first lxdef actually in mds (nothing if lxdefs is empty) first_lxd = findfirst(δ -> (from(δ) > 0), lxdefs) next_lxd = isnothing(first_lxd) ? BIG_INT : from(lxdefs[first_lxd]) # check what's next: a block or a lxdef b_or_lxd = (next_b < next_lxd) nxtidx = min(next_b, next_lxd) # keep track of a few counters (where we are, which block, which command) head, b_idx, lxd_idx = 1, 1, first_lxd while (nxtidx < BIG_INT) & (head < strlen) # check if there's anything before head and next block and write it (head < nxtidx) && write(intermd, subs(mds, head, prevind(mds, nxtidx))) # check whether it's a block first or a newcommand first if b_or_lxd # it's a block, check if should be written β = blocks[b_idx] # check whether the block should be skipped if isa(β, OCBlock) && β.name ∈ MD_OCB_IGNORE head = nextind(mds, to(β)) else if isa(β, OCBlock) && β.name ∈ MD_HEADER # this is a trick to allow whatever follows the title to be # properly parsed by Markdown.parse; it could otherwise cause # issues for instance if a table starts immediately after the title write(intermd, INSERT * "\n ") else write(intermd, INSERT) end push!(mblocks, β) head = nextind(mds, to(blocks[b_idx])) end b_idx += 1 next_b = from_ifsmaller(blocks, b_idx, len_b) else # newcommand or ignore --> skip, increase counters, move head head = nextind(mds, to(lxdefs[lxd_idx])) lxd_idx += 1 next_lxd = from_ifsmaller(lxdefs, lxd_idx, len_lxd) end # check which block is next b_or_lxd = (next_b < next_lxd) nxtidx = min(next_b, next_lxd) end # add whatever is after the last block (head <= strlen) && write(intermd, subs(mds, head, strlen)) # combine everything and return return String(take!(intermd)), mblocks end """ $(SIGNATURES) Take a partial markdown string with the `INSERT` marker and plug in the appropriately processed block. **Arguments** * `ihtml`: the intermediary html string (with `INSERT`) * `blocks`: vector of blocks * `lxcontext`: latex context """ function convert_inter_html(ihtml::AS, blocks::Vector{<:AbstractBlock}, lxcontext::LxContext)::String # Find the INSERT indicators allmatches = collect(eachmatch(INSERT_PAT, ihtml)) strlen = lastindex(ihtml) # write the pieces of the final html in order, gradually processing the blocks to insert htmls = IOBuffer() head = 1 for (i, m) ∈ enumerate(allmatches) # two cases can happen based on whitespaces around an insertion that we # want to get rid of, potentially both happen simultaneously. # 1. <p>##JDINSERT##... # 2. ...##JDINSERT##</p> # exceptions, # - list items introduce <li><p> and </p>\n</li> which shouldn't remove # - end of doc introduces </p>(\n?) which should not be removed δ1, δ2 = 0, 0 # keep track of the offset at the front / back # => case 1 c10 = prevind(ihtml, m.offset, 7) # *li><p> c1a = prevind(ihtml, m.offset, 3) # *p> c1b = prevind(ihtml, m.offset) # <p* hasli1 = (c10 > 0) && ihtml[c10:c1b] == "<li><p>" !(hasli1) && (c1a > 0) && ihtml[c1a:c1b] == "<p>" && (δ1 = 3) # => case 2 iend = m.offset + INSERT_LEN c2a = nextind(ihtml, iend) c2b = nextind(ihtml, iend, 4) # </p* c20 = nextind(ihtml, iend, 10) # </p>\n</li* hasli2 = (c20 ≤ strlen) && ihtml[c2a:c20] == "</p>\n</li>" !(hasli2) && (c2b ≤ strlen - 4) && ihtml[c2a:c2b] == "</p>" && (δ2 = 4) # write whatever is at the front, skip the extra space if still present prev = prevind(ihtml, m.offset - δ1) if prev > 0 && ihtml[prev] == ' ' prev = prevind(ihtml, prev) end (head ≤ prev) && write(htmls, subs(ihtml, head:prev)) # move head appropriately head = iend + δ2 if head ≤ strlen head = ifelse(ihtml[head] in (' ', '>'), nextind(ihtml, head), head) end # store the resolved block write(htmls, convert_block(blocks[i], lxcontext)) end # store whatever is after the last INSERT if anything (head ≤ strlen) && write(htmls, subs(ihtml, head:strlen)) # return the full string return String(take!(htmls)) end """ $(SIGNATURES) Convenience function to process markdown definitions `@def ...` as appropriate. Return a dictionary of local page variables or nothing in the case of the config file (which updates globally available page variable dictionaries and also the latex definitions). **Arguments** * `blocks`: vector of active docs * `isconfig`: whether the file being processed is the config file (--> global page variables) * `lxdefs`: latex definitions """ function process_md_defs(blocks::Vector{OCBlock}, isconfig::Bool, lxdefs::Vector{LxDef})::Union{Nothing,PageVars} # Find all markdown definitions (MD_DEF) blocks mddefs = filter(β -> (β.name == :MD_DEF), blocks) # empty container for the assignments assignments = Vector{Pair{String, String}}() # go over the blocks, and extract the assignment for (i, mdd) ∈ enumerate(mddefs) matched = match(MD_DEF_PAT, mdd.ss) if isnothing(matched) @warn "Found delimiters for an @def environment but it didn't have the right " * "@def var = ... format. Verify (ignoring for now)." continue end vname, vdef = matched.captures[1:2] push!(assignments, (String(vname) => String(vdef))) end # if we're currently looking at the config file, update the global page var dictionary # GLOBAL_PAGE_VARS and store the latex definition globally as well in GLOBAL_LXDEFS if isconfig isempty(assignments) || set_vars!(GLOBAL_PAGE_VARS, assignments) for lxd ∈ lxdefs GLOBAL_LXDEFS[lxd.name] = pastdef(lxd) end return nothing end isempty(assignments) || set_vars!(LOCAL_PAGE_VARS, assignments) jd_vars = merge(GLOBAL_PAGE_VARS, LOCAL_PAGE_VARS) return jd_vars end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
13582
""" $(SIGNATURES) Helper function for `convert_inter_html` that processes an extracted block given a latex context `lxc` and returns the processed html that needs to be plugged in the final html. """ function convert_block(β::AbstractBlock, lxcontext::LxContext)::AS # case for special characters / html entities β isa HTML_SPCH && return ifelse(isempty(β.r), β.ss, β.r) # Return relevant interpolated string based on case βn = β.name βn ∈ MD_HEADER && return convert_header(β, lxcontext.lxdefs) βn == :CODE_INLINE && return html_code_inline(content(β) |> htmlesc) βn == :CODE_BLOCK_LANG && return convert_code_block(β.ss) βn == :CODE_BLOCK_IND && return convert_indented_code_block(β.ss) βn == :CODE_BLOCK && return html_code(strip(content(β)), "{{fill lang}}") βn == :ESCAPE && return chop(β.ss, head=3, tail=3) βn == :FOOTNOTE_REF && return convert_footnote_ref(β) βn == :FOOTNOTE_DEF && return convert_footnote_def(β, lxcontext.lxdefs) βn == :LINK_DEF && return "" # Math block --> needs to call further processing to resolve possible latex βn ∈ MATH_BLOCKS_NAMES && return convert_math_block(β, lxcontext.lxdefs) # Div block --> need to process the block as a sub-element if βn == :DIV raw_ct = strip(content(β)) ct, _ = convert_md(raw_ct, lxcontext.lxdefs; isrecursive=true, has_mddefs=false) name = chop(otok(β).ss, head=2, tail=0) return html_div(name, ct) end # default case, ignore block (should not happen) return "" end convert_block(β::LxCom, λ::LxContext) = resolve_lxcom(β, λ.lxdefs) """ MATH_BLOCKS_PARENS Dictionary to keep track of how math blocks are fenced in standard LaTeX and how these fences need to be adapted for compatibility with KaTeX. Each tuple contains the number of characters to chop off the front and the back of the maths expression (fences) as well as the KaTeX-compatible replacement. For instance, `\$ ... \$` will become `\\( ... \\)` chopping off 1 character at the front and the back (`\$` sign). """ const MATH_BLOCKS_PARENS = LittleDict{Symbol, Tuple{Int,Int,String,String}}( :MATH_A => ( 1, 1, "\\(", "\\)"), :MATH_B => ( 2, 2, "\\[", "\\]"), :MATH_C => ( 2, 2, "\\[", "\\]"), :MATH_ALIGN => (13, 11, "\\[\\begin{aligned}", "\\end{aligned}\\]"), :MATH_EQA => (16, 14, "\\[\\begin{array}{c}", "\\end{array}\\]"), :MATH_I => ( 4, 4, "", "") ) """ $(SIGNATURES) Helper function for the math block case of `convert_block` taking the inside of a math block, resolving any latex command in it and returning the correct syntax that KaTeX can render. """ function convert_math_block(β::OCBlock, lxdefs::Vector{LxDef})::String # try to find the block out of `MATH_BLOCKS_PARENS`, if not found, error pm = get(MATH_BLOCKS_PARENS, β.name) do throw(MathBlockError("Unrecognised math block name.")) end # convert the inside, decorate with KaTex and return, also act if # if the math block is a "display" one (with a number) inner = chop(β.ss, head=pm[1], tail=pm[2]) htmls = IOBuffer() if β.name ∉ [:MATH_A, :MATH_I] # NOTE: in the future if allow equation tags, then will need an `if` # here and only increment if there's no tag. For now just use numbers. # increment equation counter PAGE_EQREFS[PAGE_EQREFS_COUNTER] += 1 # check if there's a label, if there is, add that to the dictionary matched = match(r"\\label{(.*?)}", inner) if !isnothing(matched) name = refstring(matched.captures[1]) write(htmls, "<a id=\"$name\"></a>") inner = replace(inner, r"\\label{.*?}" => "") # store the label name and associated number PAGE_EQREFS[name] = PAGE_EQREFS[PAGE_EQREFS_COUNTER] end end # assemble the katex decorators, the resolved content etc write(htmls, pm[3], convert_md_math(inner, lxdefs, from(β)), pm[4]) return String(take!(htmls)) end """ $(SIGNATURES) Helper function for the case of a header block (H1, ..., H6). """ function convert_header(β::OCBlock, lxdefs::Vector{LxDef})::String hk = lowercase(string(β.name)) # h1, h2, ... title, _ = convert_md(content(β), lxdefs; isrecursive=true, has_mddefs=false) rstitle = refstring(title) # check if the header has appeared before and if so suggest # an altered refstring; if that altered refstring also exist # (pathological case, see #241), then extend it with a letter # if that also exists (which would be really crazy) add a random # string keys_headers = keys(PAGE_HEADERS) if rstitle in keys_headers title, n, lvl = PAGE_HEADERS[rstitle] # then update the number of occurence PAGE_HEADERS[rstitle] = (title, n+1, lvl) # update the refstring, note the double _ (see refstring) rstitle *= "__$(n+1)" PAGE_HEADERS[rstitle] = (title, 0, parse(Int, hk[2])) else PAGE_HEADERS[rstitle] = (title, 1, parse(Int, hk[2])) end # return the title return html_hk(hk, html_ahref_key(rstitle, title); id=rstitle) end """Convenience function to increment the eval' code block counter""" increment_code_head() = (LOCAL_PAGE_VARS["jd_code_head"].first[] += 1) """Convenience function to mark `jd_code_eval` as true (subsequent blocks will be evaled)""" toggle_jd_code_eval() = (LOCAL_PAGE_VARS["jd_code_eval"].first[] = true) """ $SIGNATURES Helper function to eval a code block, write it where appropriate, and finally return a resolved block that can be displayed in the html. """ function eval_and_resolve_code(code::AS, rpath::AS; eval::Bool=true, nopush::Bool=false)::String # Here we have a julia code block that was provided with a script path # It will consequently be # 1. written to script file unless it's already there # 2. eval with redirect (unless file+output already there) # 3. inserted after cleaning out lines (see resolve_lx_input) # start by adding it to code scope nopush || push!(LOCAL_PAGE_VARS["jd_code_scope"].first, rpath, code) # form the path path = resolve_assets_rpath(rpath; canonical=true, code=true) # lazy names are allowed without extensions, add one if that's the case endswith(path, ".jl") || (path *= ".jl") # output directory etc out_path, fname = splitdir(path) out_path = mkpath(joinpath(out_path, "output")) out_name = splitext(fname)[1] * ".out" res_name = splitext(fname)[1] * ".res" res_path = joinpath(out_path, res_name) out_path = joinpath(out_path, out_name) # if we're in the no-eval case, check that the relevant files are # there otherwise do re-eval with re-write if !eval && isfile(path) && isfile(out_path) && isfile(res_path) # just return the resolved code block return resolve_lx_input_hlcode(rpath, "julia") end write(path, MESSAGE_FILE_GEN_JMD * code) JD_ENV[:SILENT_MODE] || print(rpad("\r→ evaluating code [...] ($(JD_ENV[:CUR_PATH]), $rpath)", 79) * "\r") # - execute the code while redirecting stdout to file Logging.disable_logging(Logging.LogLevel(3_000)) res = nothing open(out_path, "w") do outf # for stdout redirect_stdout(outf) do res = try include(path) catch e print("There was an error running the code:\n$(e.error)") end end end open(res_path, "w") do outf redirect_stdout(outf) do show(stdout, "text/plain", res) end end Logging.disable_logging(Logging.Debug) JD_ENV[:SILENT_MODE] || print(rpad("\r→ evaluating code [✓]", 79) * "\r") # resolve the code block (highlighting) and return it return resolve_lx_input_hlcode(rpath, "julia") end """ $(SIGNATURES) Helper function for the code block case of `convert_block`. """ function convert_code_block(ss::SubString)::String fencer = ifelse(startswith(ss, "`````"), "`````", "```") reg = Regex("$fencer([a-zA-Z][a-zA-Z-]*)(\\:[a-zA-Z\\\\\\/-_\\.]+)?\\s*\\n?((?:.|\\n)*)$fencer") m = match(reg, ss) lang = m.captures[1] rpath = m.captures[2] code = strip(m.captures[3]) # if no rpath is given, the code is not eval' isnothing(rpath) && return html_code(code, lang) # if the code is not in julia, it's not eval'ed if lang!="julia" @warn "Eval of non-julia code blocks is not yet supported." return html_code(code, lang) end # path currently has an indicative `:` we don't care about rpath = rpath[2:end] # extract handles of relevant local page variables reeval = LOCAL_PAGE_VARS["reeval"].first # full page re-eval eval = LOCAL_PAGE_VARS["jd_code_eval"].first[] # eval toggle from given point freeze = LOCAL_PAGE_VARS["freezecode"].first scope = LOCAL_PAGE_VARS["jd_code_scope"].first head = increment_code_head() # In the case of forced re-eval, we don't care about the # code scope just force-reeval everything sequentially if JD_ENV[:FORCE_REEVAL] || reeval || eval length(scope.codes) ≥ head && purgefrom!(scope, head) return eval_and_resolve_code(code, rpath) end # Now we have Julia code with a path; check briefly if there # are explicit flags indicating we should not eval; if that's # the case then there will be a check to see if the relevant # files exist, if they don't exist the code *will* be eval'ed # (see `eval_and_resolve_code`) if JD_ENV[:FULL_PASS] || freeze length(scope.codes) ≥ head && purgefrom!(scope, head) return eval_and_resolve_code(code, rpath, eval=false) end # Here we're either in # A. full pass but with forced-reeval # B. local pass with non-frozen code # check if the page we're looking at is in scope if JD_ENV[:CUR_PATH] != JD_ENV[:CUR_PATH_WITH_EVAL] # we're necessarily at the first code block of the page. # need to re-instantiate a code scope; note that if we # are here then necessarily a def_LOCAL_PAGE_VARS was # called, so LOCAL_PAGE_VARS["jd_code_head"] points to 1 reset!(scope) # keep track that the page is now in scope JD_ENV[:CUR_PATH_WITH_EVAL] = JD_ENV[:CUR_PATH] # flag rest of page as to be eval-ed (might be stale) toggle_jd_code_eval() # eval and resolve code return eval_and_resolve_code(code, rpath) end # we're in scope, compare the code block with the # current code scope and act appropriately ncodes = length(scope.codes) # there is only one case where we might not add and eval # --> if c ≤ length(code_dict) -- code block may be among seen ones # --> code == code_dict[rpath] -- the content matches exactly if (head ≤ ncodes) if (scope.rpaths[head] == rpath && code == scope.codes[head]) # resolve with no eval (the function will check if the files are # present and if they're not, there will be an evaluation) return eval_and_resolve_code(code, rpath; eval=false, nopush=true) else # purge subsequent code blocks as stale purgefrom!(scope, head) # flag rest of page as to be eval-ed (stale) toggle_jd_code_eval() end end return eval_and_resolve_code(code, rpath) end """ $(SIGNATURES) Helper function for the indented code block case of `convert_block`. """ function convert_indented_code_block(ss::SubString)::String # 1. decrease indentation of all lines (either frontal \n\t or \n⎵⎵⎵⎵) code = replace(ss, r"\n(?:\t| {4})" => "\n") # 2. return; lang is a LOCAL_PAGE_VARS that is julia by default and can be set sc = strip(code) isempty(sc) && return "" return html_code(sc, "{{fill lang}}") end """ $(SIGNATURES) Helper function to convert a `[^1]` into a html sup object with appropriate ref and backref. """ function convert_footnote_ref(β::Token)::String # β.ss is [^id]; extract id id = string(match(r"\[\^(.*?)\]", β.ss).captures[1]) # add it to the list of refs unless it's been seen before pos = 0 for (i, pri) in enumerate(PAGE_FNREFS) if pri == id pos = i break end end if pos == 0 push!(PAGE_FNREFS, id) pos = length(PAGE_FNREFS) end return html_sup("fnref:$id", html_ahref(url_curpage() * "#fndef:$id", "[$pos]"; class="fnref")) end """ $(SIGNATURES) Helper function to convert a `[^1]: ...` into a html table for the def. """ function convert_footnote_def(β::OCBlock, lxdefs::Vector{LxDef})::String # otok(β) is [^id]: id = match(r"\[\^(.*?)\]:", otok(β).ss).captures[1] pos = 0 for (i, pri) in enumerate(PAGE_FNREFS) if pri == id pos = i break end end if pos == 0 # this was never referenced before, so probably best not to show it return "" end # need to process the content which could contain stuff ct, _ = convert_md(content(β), lxdefs; isrecursive=true, has_mddefs=false) """ <table class="fndef" id="fndef:$id"> <tr> <td class=\"fndef-backref\">$(html_ahref(url_curpage() * "#fnref:$id", "[$pos]"))</td> <td class=\"fndef-content\">$(ct)</td> </tr> </table> """ end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2407
""" $(SIGNATURES) Convenience function to call the base markdown to html converter on "simple" strings (i.e. strings that don't need to be further considered and don't contain anything else than markdown tokens). The boolean `stripp` indicates whether to remove the inserted `<p>` and `</p>` by the base markdown processor, this is relevant for things that are parsed within latex commands etc. """ function md2html(ss::AS; stripp::Bool=false)::AS # if there's nothing, return that... isempty(ss) && return ss # Use Julia's Markdown parser followed by Julia's MD->HTML conversion partial = ss |> fix_inserts |> Markdown.parse |> Markdown.html # In some cases, base converter adds <p>...</p>\n which we might not want stripp || return partial startswith(partial, "<p>") && (partial = chop(partial, head=3)) endswith(partial, "</p>") && return chop(partial, tail=4) endswith(partial, "</p>\n") && return chop(partial, tail=5) return partial end """ $(SIGNATURES) Convenience function to check if `idx` is smaller than the length of `v`, if it is, then return the starting point of `v[idx]` (via `from`), otherwise return `BIG_INT`. """ from_ifsmaller(v::Vector, idx::Int, len::Int)::Int = (idx > len) ? BIG_INT : from(v[idx]) """ $(SIGNATURES) Since divs are recursively processed, once they've been found, everything inside them needs to be deactivated and left for further re-processing to avoid double inclusion. """ function deactivate_divs(blocks::Vector{OCBlock})::Vector{OCBlock} active_blocks = ones(Bool, length(blocks)) for (i, β) ∈ enumerate(blocks) fromβ, toβ = from(β), to(β) active_blocks[i] || continue if β.name == :DIV innerblocks = findall(b -> (fromβ < from(b) < toβ), blocks) active_blocks[innerblocks] .= false end end return blocks[active_blocks] end """ $(SIGNATURES) The insertion token have whitespaces around them: ` ##JDINSERT## `, this mostly helps but causes a problem when combined with italic or bold markdown mode since `_blah_` works but not `_ blah _`. This function looks for any occurrence of `[\\*_] ##JDINSERT##` or the opposite and removes the extraneous whitespace. """ fix_inserts(s::AS)::String = replace(replace(s, r"([\*_]) ##JDINSERT##" => s"\1##JDINSERT##"), r"##JDINSERT## ([\*_])" => s"##JDINSERT##\1")
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2542
const LITERATE_JULIA_FENCE = "```julia" const LITERATE_JULIA_FENCE_L = length(LITERATE_JULIA_FENCE) const LITERATE_JULIA_FENCE_R = Regex(LITERATE_JULIA_FENCE) """ $SIGNATURES Take a markdown string generated by literate and post-process it to number each code block and mark them as eval-ed ones. """ function literate_post_process(s::String)::String isempty(s) && return s em = eachmatch(LITERATE_JULIA_FENCE_R, s) buf = IOBuffer() write(buf, "<!--$MESSAGE_FILE_GEN-->\n") head = 1 c = 1 for m in em write(buf, SubString(s, head, prevind(s, m.offset))) write(buf, "```julia:ex$c\n") head = nextind(s, m.offset + LITERATE_JULIA_FENCE_L) c += 1 end lis = lastindex(s) head < lis && write(buf, SubString(s, head, lis)) return String(take!(buf)) end """ $SIGNATURES Take a Literate.jl script and transform it into a JuDoc-markdown file. """ function literate_to_judoc(rpath::AS)::Tuple{String,Bool} startswith(rpath, "/") || error("Literate expects a paths starting with '/'") # rpath is of the form "/scripts/[path/]tutorial[.jl]" # split it so that when recombining it will lead to valid path inc windows srpath = split(rpath, '/')[2:end] # discard empty first since starts with "/" fpath = joinpath(PATHS[:folder], srpath...) endswith(fpath, ".jl") || (fpath *= ".jl") if !isfile(fpath) @warn "File not found when trying to convert a literate file ($fpath)." return "", true end outpath = joinpath(PATHS[:assets], "literate", srpath[2:end-1]...) isdir(outpath) || mkdir(outpath) # retrieve the file name fname = splitext(splitdir(fpath)[2])[1] spath = joinpath(outpath, fname * "_script.jl") prev = "" if isfile(spath) prev = read(spath, String) end # don't show Literate's infos Logging.disable_logging(Logging.LogLevel(Logging.Info)) # >> output the markdown Literate.markdown(fpath, outpath; documenter=false, postprocess=literate_post_process, credit=false) # >> output the script Literate.script(fpath, outpath; documenter=false, postprocess=s->(MESSAGE_FILE_GEN_LIT * s), name=fname * "_script", credit=false) # bring back logging Logging.disable_logging(Logging.LogLevel(Logging.Debug)) # see if things have changed haschanged = (read(spath, String) != prev) # return path to md file return joinpath(outpath, fname * ".md"), haschanged end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4201
""" TrackedFiles Convenience type to keep track of files to watch. """ const TrackedFiles = Dict{Pair{String, String}, Float64} """ $(SIGNATURES) Prepare the output directory `PATHS[:pub]`. * `clear=true` removes the content of the output directory if it exists to start from a blank slate """ function prepare_output_dir(clear::Bool=true)::Nothing # if required to start from a blank slate -> remove the output dir (clear & isdir(PATHS[:pub])) && rm(PATHS[:pub], recursive=true) # create the output dir and the css dir if necessary !isdir(PATHS[:pub]) && mkdir(PATHS[:pub]) !isdir(PATHS[:css]) && mkdir(PATHS[:css]) return nothing end """ $(SIGNATURES) Take a `root` path to an input file and convert to output path. If the output path does not exist, create it. """ function out_path(root::String)::String len_in = lastindex(joinpath(PATHS[:src], "")) length(root) <= len_in && return PATHS[:folder] dpath = root[nextind(root, len_in):end] # construct the out path f_out_path = joinpath(PATHS[:folder], dpath) f_out_path = replace(f_out_path, r"([^a-zA-Z\d\s_:])pages" => s"\1pub") # if it doesn't exist, make the path !ispath(f_out_path) && mkpath(f_out_path) return f_out_path end """ $(SIGNATURES) Update the dictionaries referring to input files and their time of last change. The variable `verb` propagates verbosity. """ function scan_input_dir!(md_files::TrackedFiles, html_files::TrackedFiles, other_files::TrackedFiles, infra_files::TrackedFiles, literate_files::TrackedFiles, verb::Bool=false)::Nothing # top level files (src/*) for file ∈ readdir(PATHS[:src]) isfile(joinpath(PATHS[:src], file)) || continue # skip if it has to be ignored file ∈ IGNORE_FILES && continue fname, fext = splitext(file) fpair = (PATHS[:src] => file) if file == "config.md" add_if_new_file!(infra_files, fpair, verb) elseif fext == ".md" add_if_new_file!(md_files, fpair, verb) else add_if_new_file!(html_files, fpair, verb) end end # pages files (src/pages/*) for (root, _, files) ∈ walkdir(PATHS[:src_pages]) for file ∈ files isfile(joinpath(root, file)) || continue # skip if it has to be ignored file ∈ IGNORE_FILES && continue fname, fext = splitext(file) fpair = (root => file) if fext == ".md" add_if_new_file!(md_files, fpair, verb) elseif fext == ".html" add_if_new_file!(html_files, fpair, verb) else add_if_new_file!(other_files, fpair, verb) end end end # infastructure files (src/_css/* and src/_html_parts/*) for d ∈ (:src_css, :src_html), (root, _, files) ∈ walkdir(PATHS[d]) for file ∈ files isfile(joinpath(root, file)) || continue fname, fext = splitext(file) # skipping files that are not of the type INFRA_FILES fext ∉ INFRA_FILES && continue add_if_new_file!(infra_files, root=>file, verb) end end # literate script files if any, note that the folder may not exist if isdir(PATHS[:literate]) for (root, _, files) ∈ walkdir(PATHS[:literate]) for file ∈ files isfile(joinpath(root, file)) || continue fname, fext = splitext(file) # skipping files that are not script file fext != ".jl" && continue add_if_new_file!(literate_files, root=>file, verb) end end end return nothing end """ $(SIGNATURES) Helper function, if `fpair` is not referenced in the dictionary (new file) add the entry to the dictionary with the time of last modification as val. """ function add_if_new_file!(dict::TrackedFiles, fpair::Pair{String,String}, verb::Bool)::Nothing haskey(dict, fpair) && return nothing # it's a new file verb && println("tracking new file '$(fpair.second)'.") dict[fpair] = mtime(joinpath(fpair...)) return nothing end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1230
function lunr() prepath = get(GLOBAL_PAGE_VARS, "prepath", ""=>0).first isempty(JuDoc.PATHS) && (FOLDER_PATH[] = pwd(); set_paths!()) bkdir = pwd() lunr = joinpath(PATHS[:libs], "lunr") # is there a lunr folder in /libs/ isdir(lunr) || (@warn "No `lunr` folder found in the `/libs/` folder."; return) # are there the relevant files in /libs/lunr/ buildindex = joinpath(lunr, "build_index.js") isfile(buildindex) || (@warn "No `build_index.js` file found in the `/libs/lunr/` folder."; return) # overwrite PATH_PREPEND = ".."; if !isempty(prepath) f = String(read(buildindex)) f = replace(f, r"const\s+PATH_PREPEND\s*?=\s*?\".*?\"\;" => "const PATH_PREPEND = \"$(prepath)\";"; count=1) buildindex = replace(buildindex, r".js$" => ".tmp.js") write(buildindex, f) end cd(lunr) try start = time() msg = rpad("→ Building the Lunr index...", 35) print(msg) run(`$NODE $(splitdir(buildindex)[2])`) print_final(msg, start) catch e @warn "There was an error building the Lunr index." finally isempty(prepath) || rm(buildindex) cd(bkdir) end return end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
6147
""" $(SIGNATURES) Checks for a `config.md` file in `PATHS[:src]` and uses it to set the global variables referenced in `GLOBAL_PAGE_VARS` it also sets the global latex commands via `GLOBAL_LXDEFS`. If the configuration file is not found a warning is shown. """ function process_config()::Nothing # read the config.md file if it is present config_path = joinpath(PATHS[:src], "config.md") if isfile(config_path) convert_md(read(config_path, String); isconfig=true) else @warn "I didn't find a config file. Ignoring." end return nothing end """ $(SIGNATURES) Take a path to an input markdown file (via `root` and `file`), then construct the appropriate HTML page (inserting `head`, `pg_foot` and `foot`) and finally write it at the appropriate place. """ function write_page(root::String, file::String, head::String, pg_foot::String, foot::String; prerender::Bool=false, isoptim::Bool=false)::Nothing # 1. read the markdown into string, convert it and extract definitions # 2. eval the definitions and update the variable dictionary, also retrieve # document variables (time of creation, time of last modif) and add those # to the dictionary. fpath = joinpath(root, file) # The curpath is the relative path starting after /src/ so for instance: # f1/blah/page1.md or index.md etc... this is useful in the code evaluation and management # of paths JD_ENV[:CUR_PATH] = fpath[lastindex(PATHS[:src])+length(PATH_SEP)+1:end] (content, jd_vars) = convert_md(read(fpath, String), collect(values(GLOBAL_LXDEFS))) # Check for RSS elements if GLOBAL_PAGE_VARS["generate_rss"].first && JD_ENV[:FULL_PASS] && !all(e -> e |> first |> isempty, (jd_vars["rss"], jd_vars["rss_description"])) # add item to RSSDICT add_rss_item(jd_vars) end # adding document variables to the dictionary # note that some won't change and so it's not necessary to do this every time # but it takes negligible time to do this so ¯\_(ツ)_/¯ (and it's less annoying # than keeping tabs on which file has already been treated etc). s = stat(fpath) set_var!(jd_vars, "jd_ctime", jd_date(unix2datetime(s.ctime))) set_var!(jd_vars, "jd_mtime", jd_date(unix2datetime(s.mtime))) set_var!(jd_vars, "jd_rpath", JD_ENV[:CUR_PATH]) # 3. process blocks in the html infra elements based on `jd_vars` # (e.g.: add the date in the footer) content = convert_html(str(content), jd_vars) head, pg_foot, foot = (e->convert_html(e, jd_vars)).([head, pg_foot, foot]) # 4. construct the page proper & prerender if needed pg = build_page(head, content, pg_foot, foot) if prerender # KATEX pg = js_prerender_katex(pg) # HIGHLIGHT if JD_CAN_HIGHLIGHT pg = js_prerender_highlight(pg) # remove script pg = replace(pg, r"<script.*?(?:highlight\.pack\.js|initHighlightingOnLoad).*?<\/script>"=>"") end # remove katex scripts pg = replace(pg, r"<script.*?(?:katex\.min\.js|auto-render\.min\.js|renderMathInElement).*?<\/script>"=>"") end # append pre-path if required (see optimize) if !isempty(GLOBAL_PAGE_VARS["prepath"].first) && isoptim pg = fix_links(pg) end # 5. write the html file where appropriate write(joinpath(out_path(root), change_ext(file)), pg) return nothing end """ $(SIGNATURES) See [`process_file_err`](@ref). """ function process_file(case::Symbol, fpair::Pair{String,String}, args...; kwargs...)::Int try process_file_err(case, fpair, args...; kwargs...) catch err JD_ENV[:DEBUG_MODE] && throw(err) rp = fpair.first rp = rp[end-min(20, length(rp))+1 : end] println("\n... encountered an issue processing '$(fpair.second)' in ...$rp.") println("Verify, then start judoc again...\n") JD_ENV[:SUPPRESS_ERR] || @show err return -1 end return 0 end """ $(SIGNATURES) Considers a source file which, depending on `case` could be a html file or a file in judoc markdown etc, located in a place described by `fpair`, processes it by converting it and adding appropriate header and footer and writes it to the appropriate place. It can throw an error which will be caught in `process_file(args...)`. """ function process_file_err(case::Symbol, fpair::Pair{String, String}, head::AS="", pg_foot::AS="", foot::AS="", t::Float64=0.; clear::Bool=false, prerender::Bool=false, isoptim::Bool=false)::Nothing if case == :md write_page(fpair..., head, pg_foot, foot; prerender=prerender, isoptim=isoptim) elseif case == :html fpath = joinpath(fpair...) raw_html = read(fpath, String) proc_html = convert_html(raw_html, GLOBAL_PAGE_VARS; isoptim=isoptim) write(joinpath(out_path(fpair.first), fpair.second), proc_html) elseif case == :other opath = joinpath(out_path(fpair.first), fpair.second) # only copy it again if necessary (particularly relevant when the asset # files take quite a bit of space. if clear || !isfile(opath) || mtime(opath) < t cp(joinpath(fpair...), opath, force=true) end else # case == :infra # copy over css files # NOTE some processing may be further added here later on. if splitext(fpair.second)[2] == ".css" cp(joinpath(fpair...), joinpath(PATHS[:css], fpair.second), force=true) end end JD_ENV[:FULL_PASS] || JD_ENV[:SILENT_MODE] || print(rpad("\r→ page updated [✓]", 79)*"\r") return nothing end """ $(SIGNATURES) Convenience function to replace the extension of a filename with another. """ change_ext(fname::AS, ext=".html")::String = splitext(fname)[1] * ext """ $(SIGNATURES) Convenience function to assemble the html out of its parts. """ build_page(head::String, content::String, pg_foot::String, foot::String)::String = "$head\n<div class=\"jd-content\">\n$content\n$pg_foot\n</div>\n$foot"
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
12505
""" $SIGNATURES Clear the environment dictionaries. """ clear_dicts() = empty!.((GLOBAL_LXDEFS, GLOBAL_PAGE_VARS, LOCAL_PAGE_VARS)) """ $(SIGNATURES) Runs JuDoc in the current directory. Keyword arguments: * `clear=false`: whether to remove any existing output directory * `verb=false`: whether to display messages * `port=8000`: the port to use for the local server (should pick a number between 8000 and 9000) * `single=false`: whether to run a single pass or run continuously * `prerender=false`: whether to pre-render javascript (KaTeX and highlight.js) * `nomess=false`: suppresses all messages (internal use). * `isoptim=false`: whether we're in an optimisation phase or not (if so, links are fixed in case of a project website, see [`write_page`](@ref). * `no_fail_prerender=true`: whether, in a prerendering phase, ignore errors and try to produce an output * `eval_all=false`: whether to force re-evaluation of all code blocks * `silent=false`: switch this on to suppress all output (including eval statements). * `cleanup=true`: whether to clear environment dictionatires, see [`cleanup`](@ref). """ function serve(; clear::Bool=true, verb::Bool=false, port::Int=8000, single::Bool=false, prerender::Bool=false, nomess::Bool=false, isoptim::Bool=false, no_fail_prerender::Bool=true, eval_all::Bool=false, silent::Bool=false, cleanup::Bool=true)::Union{Nothing,Int} # set the global path FOLDER_PATH[] = pwd() println("-----------------------------------------------------------") println("⚠️ JuDoc.jl is being renamed to Franklin.jl ⚠️") println("For future updates (>0.4.3), you will need to add Franklin.") println("See also https://github.com/tlienart/JuDoc.jl/issues/338.") println("-----------------------------------------------------------\n") # silent mode? silent && (JD_ENV[:SILENT_MODE] = true; verb = false) # brief check to see if we're in a folder that looks promising, otherwise stop # and tell the user to check (#155) if !isdir(joinpath(FOLDER_PATH[], "src")) throw(ArgumentError("The current directory doesn't have a src/ folder. " * "Please change directory to a valid JuDoc folder.")) end # check if a Project.toml file is available, if so activate the folder flag_env = false if isfile(joinpath(FOLDER_PATH[], "Project.toml")) Pkg.activate(".") flag_env = true end # construct the set of files to watch watched_files = jd_setup(clear=clear) nomess && (verb = false) # do a first full pass nomess || println("→ Initial full pass...") start = time() JD_ENV[:FORCE_REEVAL] = eval_all sig = jd_fullpass(watched_files; clear=clear, verb=verb, prerender=prerender, isoptim=isoptim, no_fail_prerender=no_fail_prerender) JD_ENV[:FORCE_REEVAL] = false sig < 0 && return sig fmsg = rpad("✔ full pass...", 40) verb && (println(""); print(fmsg); print_final(fmsg, start); println("")) # start the continuous loop if !single nomess || println("→ Starting the server...") coreloopfun = (cntr, fw) -> jd_loop(cntr, fw, watched_files; clear=clear, verb=verb) # start the liveserver in the current directory LiveServer.setverbose(verb) LiveServer.serve(port=port, coreloopfun=coreloopfun) end flag_env && println("→ Use Pkg.activate() to go back to your main environment.") cleanup && clear_dicts() return nothing end """ $(SIGNATURES) Sets up the collection of watched files by doing an initial scan of the input directory. It also sets the paths variables and prepares the output directory. **Keyword argument** * `clear=false`: whether to remove any existing output directory See also [`serve`](@ref). """ function jd_setup(; clear::Bool=true)::NamedTuple # . setting up: # -- reading and storing the path variables # -- setting up the output directory (see `clear`) set_paths!() prepare_output_dir(clear) # . recovering the list of files in the input dir we care about # -- these are stored in dictionaries, the key is the full path and the value is the time of # last change (useful for continuous monitoring) md_files = TrackedFiles() html_files = TrackedFiles() other_files = TrackedFiles() infra_files = TrackedFiles() literate_files = TrackedFiles() # named tuples of all the watched files watched_files = (md=md_files, html=html_files, other=other_files, infra=infra_files, literate=literate_files) # fill the dictionaries scan_input_dir!(watched_files...) return watched_files end """ $(SIGNATURES) A single full pass of judoc looking at all watched files and processing them as appropriate. **Keyword arguments** * `clear=false`: whether to remove any existing output directory * `verb=false`: whether to display messages * `prerender=false`: whether to prerender katex and code blocks * `isoptim=false` : whether it's an optimization pass * `no_fail_prerender=true`: whether to skip if a prerendering goes wrong in which case don't prerender See also [`jd_loop`](@ref), [`serve`](@ref) and [`publish`](@ref). """ function jd_fullpass(watched_files::NamedTuple; clear::Bool=false, verb::Bool=false, prerender::Bool=false, isoptim::Bool=false, no_fail_prerender::Bool=true)::Int JD_ENV[:FULL_PASS] = true # initiate page segments head = read(joinpath(PATHS[:src_html], "head.html"), String) pg_foot = read(joinpath(PATHS[:src_html], "page_foot.html"), String) foot = read(joinpath(PATHS[:src_html], "foot.html"), String) # reset global page variables and latex definitions # NOTE: need to keep track of pre-path if specified, see optimize prepath = get(GLOBAL_PAGE_VARS, "prepath", nothing) def_GLOBAL_PAGE_VARS!() def_GLOBAL_LXDEFS!() empty!(RSS_DICT) # reinsert prepath if specified isnothing(prepath) || (GLOBAL_PAGE_VARS["prepath"] = prepath) # process configuration file (see also `process_md_defs`) process_config() # looking for an index file to process indexmd = PATHS[:src] => "index.md" indexhtml = PATHS[:src] => "index.html" # rest of the pages s = 0 begin if isfile(joinpath(indexmd...)) a = process_file(:md, indexmd, head, pg_foot, foot; clear=clear, prerender=prerender, isoptim=isoptim) if a < 0 && prerender && no_fail_prerender process_file(:md, indexmd, head, pg_foot, foot; clear=clear, prerender=false, isoptim=isoptim) end s += a elseif isfile(joinpath(indexhtml...)) a = process_file(:html, indexhtml, head, pg_foot, foot; clear=clear, prerender=prerender, isoptim=isoptim) if a < 0 && prerender && no_fail_prerender process_file(:html, indexhtml, head, pg_foot, foot; clear=clear, prerender=false, isoptim=isoptim) end s += a else @warn "I didn't find an index.[md|html], there should be one. Ignoring." end # process rest of the files for (case, dict) ∈ pairs(watched_files), (fpair, t) ∈ dict occursin("index.", fpair.second) && continue a = process_file(case, fpair, head, pg_foot, foot, t; clear=clear, prerender=prerender, isoptim=isoptim) if a < 0 && prerender && no_fail_prerender process_file(case, fpair, head, pg_foot, foot, t; clear=clear, prerender=false, isoptim=isoptim) end s += a end end # generate RSS if appropriate GLOBAL_PAGE_VARS["generate_rss"].first && rss_generator() JD_ENV[:FULL_PASS] = false # return -1 if any page return ifelse(s<0, -1, 0) end """ $(SIGNATURES) This is the function that is continuously run, checks if files have been modified and if so, processes them. Every 30 cycles, it checks whether any file was added or deleted and consequently updates the `watched_files`. **Keyword arguments** * `clear=false`: whether to remove any existing output directory * `verb=false`: whether to display messages """ function jd_loop(cycle_counter::Int, ::LiveServer.FileWatcher, watched_files::NamedTuple; clear::Bool=false, verb::Bool=false)::Nothing # every 30 cycles (3 seconds), scan directory to check for new or deleted files and # update dicts accordingly if mod(cycle_counter, 30) == 0 # 1) check if some files have been deleted; note that we don't do anything, # we just remove the file reference from the corresponding dictionary. for d ∈ watched_files, (fpair, _) ∈ d isfile(joinpath(fpair...)) || delete!(d, fpair) end # 2) scan the input folder, if new files have been added then this will update # the dictionaries scan_input_dir!(watched_files..., verb) else # do a pass over the files, check if one has changed and if so trigger # the appropriate file processing mechanism for (case, dict) ∈ pairs(watched_files), (fpair, t) ∈ dict # check if there was a modification to the file fpath = joinpath(fpair...) cur_t = mtime(fpath) cur_t <= t && continue # if there was then the file has been modified and should be re-processed + copied fmsg = rpad("→ file $(fpath[length(FOLDER_PATH[])+1:end]) was modified ", 30) verb && print(fmsg) dict[fpair] = cur_t # if it's an infra_file if haskey(watched_files[:infra], fpair) verb && println("→ full pass...") start = time() jd_fullpass(watched_files; clear=false, verb=false, prerender=false) verb && (print_final(rpad("✔ full pass...", 15), start); println("")) # if it's a literate file elseif haskey(watched_files[:literate], fpair) fmsg = fmsg * rpad("→ updating... ", 15) verb && print("\r" * fmsg) start = time() # literate_path = splitext(unixify(joinpath(fpair...)))[1] # head = read(joinpath(PATHS[:src_html], "head.html"), String) pg_foot = read(joinpath(PATHS[:src_html], "page_foot.html"), String) foot = read(joinpath(PATHS[:src_html], "foot.html"), String) # process all md files that have `\literate` with something that matches for mdfpair in keys(watched_files.md) mdfpath = joinpath(mdfpair...) # read the content and look for `{...}` that may refer # to that script. content = read(mdfpath, String) for m in eachmatch(r"\{(.*?)(\.jl)?\}", content) if endswith(literate_path, m.captures[1]) process_file(:md, mdfpair, head, pg_foot, foot, cur_t; clear=false, prerender=false) break end end end verb && print_final(fmsg, start) else fmsg = fmsg * rpad("→ updating... ", 15) verb && print("\r" * fmsg) start = time() # head = read(joinpath(PATHS[:src_html], "head.html"), String) pg_foot = read(joinpath(PATHS[:src_html], "page_foot.html"), String) foot = read(joinpath(PATHS[:src_html], "foot.html"), String) # if it's the first time we modify this file then all blocks need # to be evaluated so that everything is in scope process_file(case, fpair, head, pg_foot, foot, cur_t; clear=false, prerender=false) verb && print_final(fmsg, start) end end end return nothing end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
9284
""" $SIGNATURES Take a page (in HTML) and check all `href` on it to see if they lead somewhere. """ function verify_links_page(path::AS, online::Bool) shortpath = replace(path, PATHS[:folder] => "") mdpath = replace(shortpath, Regex("^pub$(escape_string(PATH_SEP))")=>"pages$(PATH_SEP)") mdpath = splitext(mdpath)[1] * ".md" shortpath = replace(shortpath, r"^\/"=>"") mdpath = replace(mdpath, r"^\/"=>"") allok = true page = read(path, String) for m in eachmatch(r"\shref=\"(https?://)?(.*?)(?:#(.*?))?\"", page) if m.captures[1] === nothing # internal link, remove the front / otherwise it fails with joinpath link = replace(m.captures[2], r"^\/"=>"") # if it's empty it's `href="/"` which is always ok isempty(link) && continue anchor = m.captures[3] full_link = joinpath(PATHS[:folder], link) if !isfile(full_link) allok && println("") println("- internal link issue on page $mdpath: $link.") allok = false else if !isnothing(anchor) if full_link != path rpage = read(full_link, String) else rpage = page end # look for `id=...` either with or without quotation marks if match(Regex("id=(?:\")?$anchor(?:\")?"), rpage) === nothing allok && println("") println("- internal link issue on page $mdpath: $link.") allok = false end end end else online || continue # external link link = m.captures[1] * m.captures[2] try HTTP.request("HEAD", link).status == 200 || throw() catch allok && println("") println("- external link issue on page $mdpath: $link") allok = false end end end return allok end """ $SIGNATURES Verify all links in generated HTML. """ function verify_links()::Nothing # check that the user is online (otherwise only verify internal links) online = try HTTP.request("HEAD", "https://discourse.julialang.org/", readtimeout=10).status == 200 catch # might fail with DNSError false end print("Verifying links...") if online print(" [you seem online ✓]") else print(" [you don't seem online ✗]") end # go over `index.html` then everything in `pub/` overallok = verify_links_page(joinpath(PATHS[:folder], "index.html"), online) for (root, _, files) ∈ walkdir(PATHS[:pub]) for file ∈ files splitext(file)[2] == ".html" && continue path = joinpath(root, file) allok = verify_links_page(path) overallok = overallok && allok end end overallok && println("\rAll internal $(ifelse(online,"and external ",""))links verified ✓. ") return nothing end const JD_PY_MIN_NAME = ".__py_tmp_minscript.py" """ $(SIGNATURES) Does a full pass followed by a pre-rendering and minification step. * `prerender=true`: whether to pre-render katex and highlight.js (requires `node.js`) * `minify=true`: whether to minify output (requires `python3` and `css_html_js_minify`) * `sig=false`: whether to return an integer indicating success (see [`publish`](@ref)) * `prepath=""`: set this to something like "project-name" if it's a project page * `no_fail_prerender=true`: whether to ignore errors during the pre-rendering process * `suppress_errors=true`: whether to suppress errors * `cleanup=true`: whether to empty environment dictionaries Note: if the prerendering is set to `true`, the minification will take longer as the HTML files will be larger (especially if you have lots of maths on pages). """ function optimize(; prerender::Bool=true, minify::Bool=true, sig::Bool=false, prepath::String="", no_fail_prerender::Bool=true, suppress_errors::Bool=true, cleanup::Bool=true)::Union{Nothing,Bool} suppress_errors && (JD_ENV[:SUPPRESS_ERR] = true) # # Prerendering # if prerender && !JD_CAN_PRERENDER @warn "I couldn't find node and so will not be able to pre-render javascript." prerender = false end if prerender && !JD_CAN_HIGHLIGHT @warn "I couldn't load 'highlight.js' so will not be able to pre-render code blocks. " * "You can install it with `npm install highlight.js`." end if !isempty(prepath) GLOBAL_PAGE_VARS["prepath"] = prepath => (String,) end # re-do a (silent) full pass start = time() fmsg = "\r→ Full pass" print(fmsg) withpre = fmsg * ifelse(prerender, rpad(" (with pre-rendering)", 24), rpad(" (no pre-rendering)", 24)) print(withpre) succ = nothing === serve(single=true, prerender=prerender, nomess=true, isoptim=true, no_fail_prerender=no_fail_prerender, cleanup=cleanup) print_final(withpre, start) # # Minification # if minify && (succ || no_fail_prerender) if JD_CAN_MINIFY start = time() mmsg = rpad("→ Minifying *.[html|css] files...", 35) print(mmsg) # copy the script to the current dir cp(joinpath(dirname(pathof(JuDoc)), "scripts", "minify.py"), JD_PY_MIN_NAME; force=true) # run it succ = success(`$([e for e in split(PY)]) $JD_PY_MIN_NAME`) # remove the script file rm(JD_PY_MIN_NAME) print_final(mmsg, start) else @warn "I didn't find css_html_js_minify, you can install it via pip."* "The output will not be minified." end end JD_ENV[:SUPPRESS_ERR] = false return ifelse(sig, succ, nothing) end """ $(SIGNATURES) This is a simple wrapper doing a git commit and git push without much fanciness. It assumes the current directory is a git folder. It also fixes all links if you specify `prepath` (or if it's set in `config.md`). **Keyword arguments** * `prerender=true`: prerender javascript before pushing see [`optimize`](@ref) * `minify=true`: minify output before pushing see [`optimize`](@ref) * `nopass=false`: set this to true if you have already run `optimize` manually. * `prepath=""`: set this to something like "project-name" if it's a project page * `message="jd-update"`: add commit message. * `cleanup=true`: whether to cleanup environment dictionaries (should stay true). * `final=nothing`: a function `()->nothing` to execute last, before doing the git push. It can be used to refresh a Lunr index, generate notebook files with Literate, etc, ... You might want to compose `jdf_*` functions that are exported by JuDoc (or imitate those). It can access GLOBAL_PAGE_VARS. """ function publish(; prerender::Bool=true, minify::Bool=true, nopass::Bool=false, prepath::String="", message::String="jd-update", cleanup::Bool=true, final::Union{Nothing,Function}=nothing)::Nothing succ = true if !isempty(prepath) || !nopass # no cleanup so that can access global page variables in final step succ = optimize(prerender=prerender, minify=minify, sig=true, prepath=prepath, cleanup=false) end if succ # final hook final === nothing || final() # -------------------------- # Push to git (publication) start = time() pubmsg = rpad("→ Pushing updates with git...", 35) print(pubmsg) try run(`git add -A `) run(`git commit -m "$message" --quiet`) run(`git push --quiet`) print_final(pubmsg, start) catch e println("✘ Could not push updates, verify your connection and try manually.\n") @show e end else println("✘ Something went wrong in the optimisation step. Not pushing updates.") end return nothing end """ $(SIGNATURES) Cleanpull allows you to pull from your remote git repository after having removed the local output directory. This will help avoid merge clashes. """ function cleanpull()::Nothing FOLDER_PATH[] = pwd() set_paths!() if isdir(PATHS[:pub]) rmmsg = rpad("→ Removing local output dir...", 35) print(rmmsg) rm(PATHS[:pub], force=true, recursive=true) println("\r" * rmmsg * " [done ✔ ]") end try pmsg = rpad("→ Retrieving updates from the repository...", 35) print(pmsg) run(`git pull --quiet`) println("\r" * pmsg * " [done ✔ ]") catch e println("✘ Could not pull updates, verify your connection and try manually.\n") @show e end return nothing end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
5319
# TODO: could also expose the channel options if someone wanted # to define those; can probably leave for later until feedback has # been received. # Specifications: RSS 2.0 -- https://cyber.harvard.edu/rss/rss.html#sampleFiles # steps: # 0. check if the relevant variables are defined otherwise don't generate the RSS # 1. is there an RSS file? # --> remove it and create a new one (bc items may have been updated) # 2. go over all pages # --> is there a rss var? # NO --> skip # YES --> recuperate the `jd_ctime` and `jd_mtime` and add a RSS channel object # 3. save the file struct RSSItem # -- required fields title::String link::String description::String # note: should not contain <p> # -- optional fields author::String # note: should be a valid email category::String comments::String # note: should be a valid URL enclosure::String # guid == link pubDate::Date # note: should respect RFC822 (https://www.w3.org/Protocols/rfc822/) end const RSS_DICT = LittleDict{String,RSSItem}() """Convenience function for fallback fields""" jor(v::PageVars, a::String, b::String) = ifelse(isempty(first(v[a])), first(v[b]), first(v[a])) """Convenience function to remove <p> and </p> in RSS description (not supposed to happen)""" remove_html_ps(s::String)::String = replace(s, r"</?p>" => "") """ $SIGNATURES RSS should not contain relative links so this finds relative links and prepends them with the canonical link. """ fix_relative_links(s::String, link::String) = replace(s, r"(href|src)\s*?=\s*?\"\/" => SubstitutionString("\\1=\"$link")) """ $SIGNATURES Create an `RSSItem` out of the provided fields defined in the page vars. """ function add_rss_item(jdv::PageVars)::RSSItem link = url_curpage() title = jor(jdv, "rss_title", "title") descr = jor(jdv, "rss", "rss_description") descr = jd2html(descr; internal=true) |> remove_html_ps author = jdv["rss_author"] |> first category = jdv["rss_category"] |> first comments = jdv["rss_comments"] |> first enclosure = jdv["rss_enclosure"] |> first pubDate = jdv["rss_pubdate"] |> first if pubDate == Date(1) pubDate = jdv["date"] |> first if !isa(pubDate, Date) || pubDate == Date(1) pubDate = jdv["jd_mtime"] |> first end end # warning for title which should really be defined isnothing(title) && (title = "") isempty(title) && @warn "Found an RSS description but no title for page $link." RSS_DICT[link] = RSSItem(title, link, descr, author, category, comments, enclosure, pubDate) end """ $SIGNATURES Extract the entries from RSS_DICT and assemble the RSS. If the dictionary is empty, nothing is generated. """ function rss_generator()::Nothing # is there anything to go in the RSS feed? isempty(RSS_DICT) && return nothing # are the basic defs there? otherwise warn and break rss_title = GLOBAL_PAGE_VARS["website_title"] |> first rss_descr = GLOBAL_PAGE_VARS["website_descr"] |> first rss_link = GLOBAL_PAGE_VARS["website_url"] |> first if any(isempty, (rss_title, rss_descr, rss_link)) @warn """I found RSS items but the RSS feed is not properly described: at least one of the following variables has not been defined in your config.md: `website_title`, `website_descr`, `website_url`. The feed will not be (re)generated.""" return nothing end endswith(rss_link, "/") || (rss_link *= "/") rss_descr = jd2html(rss_descr; internal=true) |> remove_html_ps # is there an RSS file already? if so remove it rss_path = joinpath(PATHS[:folder], "feed.xml") isfile(rss_path) && rm(rss_path) # create a buffer which will correspond to the output rss_buff = IOBuffer() write(rss_buff, """ <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>$rss_title</title> <description><![CDATA[$(fix_relative_links(rss_descr, rss_link))]]></description> <link>$rss_link</link> <atom:link href="$(rss_link)feed.xml" rel="self" type="application/rss+xml" /> """) # loop over items for (k, v) in RSS_DICT full_link = rss_link if startswith(v.link, "/") full_link *= v.link[2:end] else full_link *= v.link end write(rss_buff, """ <item> <title>$(v.title)</title> <link>$(full_link)</link> <description><![CDATA[$(fix_relative_links(v.description, rss_link))</br><a href=\"$full_link\">Read more</a>]]></description> """) for elem in (:author, :category, :comments, :enclosure) e = getproperty(v, elem) isempty(e) || write(rss_buff, """ <$elem>$e</$elem> """) end write(rss_buff, """ <guid>$(full_link)</guid> <pubDate>$(Dates.format(v.pubDate, "e, d u Y")) 00:00:00 UT</pubDate> </item> """) end # finalize write(rss_buff, """ </channel> </rss> """) write(rss_path, take!(rss_buff)) return nothing end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2364
""" $(SIGNATURES) Given `{{ ... }}` blocks, identify what kind of blocks they are and return a vector of qualified blocks of type `AbstractBlock`. """ function qualify_html_hblocks(blocks::Vector{OCBlock})::Vector{AbstractBlock} qb = Vector{AbstractBlock}(undef, length(blocks)) # TODO improve this (if there are many blocks this would be slow) for (i, β) ∈ enumerate(blocks) # if block {{ if v }} m = match(HBLOCK_IF_PAT, β.ss) isnothing(m) || (qb[i] = HIf(β.ss, m.captures[1]); continue) # else block {{ else }} m = match(HBLOCK_ELSE_PAT, β.ss) isnothing(m) || (qb[i] = HElse(β.ss); continue) # else if block {{ elseif v }} m = match(HBLOCK_ELSEIF_PAT, β.ss) isnothing(m) || (qb[i] = HElseIf(β.ss, m.captures[1]); continue) # end block {{ end }} m = match(HBLOCK_END_PAT, β.ss) isnothing(m) || (qb[i] = HEnd(β.ss); continue) # --- # isdef block m = match(HBLOCK_ISDEF_PAT, β.ss) isnothing(m) || (qb[i] = HIsDef(β.ss, m.captures[1]); continue) # ifndef block m = match(HBLOCK_ISNOTDEF_PAT, β.ss) isnothing(m) || (qb[i] = HIsNotDef(β.ss, m.captures[1]); continue) # --- # ispage block m = match(HBLOCK_ISPAGE_PAT, β.ss) isnothing(m) || (qb[i] = HIsPage(β.ss, split(m.captures[1])); continue) # isnotpage block m = match(HBLOCK_ISNOTPAGE_PAT, β.ss) isnothing(m) || (qb[i] = HIsNotPage(β.ss, split(m.captures[1])); continue) # --- # function block {{ fname v1 v2 ... }} m = match(HBLOCK_FUN_PAT, β.ss) isnothing(m) || (qb[i] = HFun(β.ss, m.captures[1], split(m.captures[2])); continue) # --- # function toc {{toc}} m = match(HBLOCK_TOC_PAT, β.ss) isnothing(m) || (qb[i] = HFun(β.ss, "toc", String[]); continue) throw(HTMLBlockError("I found a HBlock that did not match anything, " * "verify '$(β.ss)'")) end return qb end """Blocks that can open a conditional block.""" const HTML_OPEN_COND = Union{HIf,HIsDef,HIsNotDef,HIsPage,HIsNotPage} """ $SIGNATURES Internal function to balance conditional blocks. See [`process_html_qblocks`](@ref). """ hbalance(::HTML_OPEN_COND) = 1 hbalance(::HEnd) = -1 hbalance(::AbstractBlock) = 0
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
5329
""" HTML_1C_TOKENS Dictionary of single-char tokens for HTML. Note that these characters are exclusive, they cannot appear again in a larger token. """ const HTML_1C_TOKENS = LittleDict{Char, Symbol}() """ HTML_TOKENS Dictionary of tokens for HTML. Note that for each, there may be several possibilities to consider in which case the order is important: the first case that works will be taken. """ const HTML_TOKENS = LittleDict{Char, Vector{TokenFinder}}( '<' => [ isexactly("<!--") => :COMMENT_OPEN ], # <!-- ... '-' => [ isexactly("-->") => :COMMENT_CLOSE ], # ... --> '{' => [ isexactly("{{") => :H_BLOCK_OPEN ], # {{ '}' => [ isexactly("}}") => :H_BLOCK_CLOSE ], # }} ) # end dict """ HTML_OCB List of HTML Open-Close blocks. """ const HTML_OCB = [ # name opening token closing token(s) nestable # ---------------------------------------------------------- OCProto(:COMMENT, :COMMENT_OPEN, (:COMMENT_CLOSE,), false), OCProto(:H_BLOCK, :H_BLOCK_OPEN, (:H_BLOCK_CLOSE,), true) ] #= =============== CONDITIONAL BLOCKS ================== =# #= NOTE / TODO * in a conditional block, should make sure else is not followed by elseif * no nesting of conditional blocks is allowed at the moment. This could be done at later stage (needs balancing) or something but seems a bit overkill at this point. This second point might fix the first one by making sure that HIf -> HElseIf / HElse / HEnd HElseIf -> HElseIf / HElse / HEnd HElse -> HEnd =# """ HBLOCK_IF_PAT HBLOCK_ELSE_PAT HBLOCK_ELSEIF_PAT HBLOCK_END_PAT HBLOCK_ISDEF_PAT HBLOCK_ISNOTDEF_PAT HBLOCK_ISPAGE_PAT HBLOCK_ISNOTPAGE_PAT Regex for the different HTML tokens. """ const HBLOCK_IF_PAT = r"{{\s*if\s+([a-zA-Z]\S*)\s*}}" # {{if v1}} const HBLOCK_ELSE_PAT = r"{{\s*else\s*}}" # {{else}} const HBLOCK_ELSEIF_PAT = r"{{\s*else\s*if\s+([a-zA-Z]\S*)\s*}}" # {{elseif v1}} const HBLOCK_END_PAT = r"{{\s*end\s*}}" # {{end}} const HBLOCK_ISDEF_PAT = r"{{\s*isdef\s+([a-zA-Z]\S*)\s*}}" # {{isdef v1}} const HBLOCK_ISNOTDEF_PAT = r"{{\s*isnotdef\s+([a-zA-Z]\S*)\s*}}" # {{isnotdef v1}} const HBLOCK_ISPAGE_PAT = r"{{\s*ispage\s+((.|\n)+?)}}" # {{ispage p1 p2}} const HBLOCK_ISNOTPAGE_PAT = r"{{\s*isnotpage\s+((.|\n)+?)}}" # {{isnotpage p1 p2}} """ $(TYPEDEF) HTML token corresponding to `{{if var}}`. """ struct HIf <: AbstractBlock ss::SubString vname::String end """ $(TYPEDEF) HTML token corresponding to `{{else}}`. """ struct HElse <: AbstractBlock ss::SubString end """ $(TYPEDEF) HTML token corresponding to `{{elseif var}}`. """ struct HElseIf <: AbstractBlock ss::SubString vname::String end """ $(TYPEDEF) HTML token corresponding to `{{end}}`. """ struct HEnd <: AbstractBlock ss::SubString end # ----------------------------------------------------- # General conditional block based on a boolean variable # ----------------------------------------------------- """ $(TYPEDEF) HTML conditional block corresponding to `{{if var}} ... {{else}} ... {{end}}`. """ struct HCond <: AbstractBlock ss::SubString # full block init_cond::String # initial condition (has to exist) sec_conds::Vector{String} # secondary conditions (can be empty) actions::Vector{SubString} # what to do when conditions are met end # ------------------------------------------------------------ # Specific conditional block based on whether a var is defined # ------------------------------------------------------------ """ $(TYPEDEF) HTML token corresponding to `{{isdef var}}`. """ struct HIsDef <: AbstractBlock ss::SubString vname::String end """ $(TYPEDEF) HTML token corresponding to `{{isnotdef var}}`. """ struct HIsNotDef <: AbstractBlock ss::SubString vname::String end # ------------------------------------------------------------ # Specific conditional block based on whether the current page # is or isn't in a group of given pages # ------------------------------------------------------------ """ $(TYPEDEF) HTML token corresponding to `{{ispage path/page}}`. """ struct HIsPage <: AbstractBlock ss::SubString pages::Vector{<:AS} # one or several pages end """ $(TYPEDEF) HTML token corresponding to `{{isnotpage path/page}}`. """ struct HIsNotPage <: AbstractBlock ss::SubString pages::Vector{<:AS} end #= ============ FUNCTION BLOCKS =============== =# """ HBLOCK_FUN_PAT Regex to match `{{ fname param₁ param₂ }}` where `fname` is a html processing function and `paramᵢ` should refer to appropriate variables in the current scope. Available functions are: * `{{ fill vname }}`: to plug a variable (e.g.: a date, author name) * `{{ insert fpath }}`: to plug in a file referred to by the `fpath` (e.g.: a html header) """ const HBLOCK_FUN_PAT = r"{{\s*([a-z]\S+)\s+((.|\n)+?)}}" """ $(TYPEDEF) HTML function block corresponding to `{{ fname p1 p2 ...}}`. """ struct HFun <: AbstractBlock ss::SubString fname::String params::Vector{String} end """ HBLOCK_TOC_PAT Insertion for a table of contents. """ const HBLOCK_TOC_PAT = r"{{\s*toc\s*}}" """ $(TYPEDEF) Empty struct to keep the same taxonomy. """ struct HToc <: AbstractBlock end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
6872
""" $(SIGNATURES) In initial phase, discard all `:LR_INDENT` that don't meet the requirements for an indented code block. I.e.: where the first line is not preceded by a blank line and then subsequently followed by indented lines. """ function filter_lr_indent!(vt::Vector{Token}, s::String)::Nothing tind_idx = [i for i in eachindex(vt) if vt[i].name == :LR_INDENT] isempty(tind_idx) && return nothing disable = zeros(Bool, length(tind_idx)) open = false i = 1 while i <= length(tind_idx) t = vt[tind_idx[i]] if !open # check if previous line is blank prev_idx = prevind(s, from(t)) if prev_idx < 1 || s[prev_idx] != '\n' disable[i] = true else open = true end i += 1 else # if touching previous line, keep open and go to next prev = vt[tind_idx[i-1]] if prev.lno + 1 == t.lno i += 1 else # otherwise close, and continue (will go to !open) open = false continue end end end for i in eachindex(disable) disable[i] || continue vt[tind_idx[i]] = Token(:LINE_RETURN, subs(vt[tind_idx[i]].ss, 1)) end return nothing end """ $(SIGNATURES) Find markers for indented lines (i.e. a line return followed by a tab or 4 spaces). """ function find_indented_blocks!(tokens::Vector{Token}, st::String)::Nothing # index of the line return tokens lr_idx = [j for j in eachindex(tokens) if tokens[j].name == :LINE_RETURN] remove = Int[] # go over all line return tokens; if they are followed by either four spaces # or by a tab, then check if the line is empty or looks like a list, otherwise # change the token for a LR_INDENT token which will be captured as part of code # blocks. for i in 1:length(lr_idx)-1 # capture start and finish of the line (from line return to line return) start = from(tokens[lr_idx[i]]) # first :LINE_RETURN finish = from(tokens[lr_idx[i+1]]) # next :LINE_RETURN line = subs(st, start, finish) indent = "" if startswith(line, "\n ") indent = " " elseif startswith(line, "\n\t") indent = "\t" else continue end # is there something on that line? if so, does it start with a list indicator # like `*`, `-`, `+` or [0-9](.|\)) ? in which case this takes precedence (commonmark) # TODO: document clearly that with fenced code blocks there are far fewer cases for issues code_line = subs(st, nextind(st, start+length(indent)), prevind(st, finish)) scl = strip(code_line) isempty(scl) && continue # list takes precedence (this may cause clash but then just use fenced code blocks...) looks_like_a_list = scl[1] ∈ ('*', '-', '+') || (length(scl) ≥ 2 && scl[1] ∈ ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') && scl[2] ∈ ('.', ')')) looks_like_a_list && continue # if here, it looks like a code line (and will be considered as such) tokens[lr_idx[i]] = Token(:LR_INDENT, subs(st, start, start+length(indent)), i+1) end return nothing end """ $SIGNATURES When two indented code blocks follow each other and there's nothing in between (empty line(s)), merge them into a super block. """ function merge_indented_blocks!(blocks::Vector{OCBlock}, mds::AS)::Nothing # indices of CODE_BLOCK_IND idx = [i for i in eachindex(blocks) if blocks[i].name == :CODE_BLOCK_IND] isempty(idx) && return # check if they're separated by something or nothing inter_space = [(subs(mds, to(blocks[idx[i]]), from(blocks[idx[i+1]])) |> strip |> length) > 0 for i in 1:length(idx)-1] curseq = Int[] # to keep track of current list of blocks to merge del_blocks = Int[] # to keep track of blocks that will be removed afterwards # if there's no inter_space, add to the list, if there is, close and merge for i in eachindex(inter_space) if inter_space[i] && !isempty(curseq) # close and merge all in curseq and empty curseq form_super_block!(blocks, idx, curseq, del_blocks) elseif !inter_space[i] push!(curseq, i) end end !isempty(curseq) && form_super_block!(blocks, idx, curseq, del_blocks) # remove the blocks that have been merged deleteat!(blocks, del_blocks) return end """ $SIGNATURES Helper function to [`merge_indented_blocks`](@ref). """ function form_super_block!(blocks::Vector{OCBlock}, idx::Vector{Int}, curseq::Vector{Int}, del_blocks::Vector{Int})::Nothing push!(curseq, curseq[end]+1) first_block = blocks[idx[curseq[1]]] last_block = blocks[idx[curseq[end]]] # replace the first block with the super block blocks[idx[curseq[1]]] = OCBlock(:CODE_BLOCK_IND, (otok(first_block) => ctok(last_block))) # append all blocks but the first to the delete list append!(del_blocks, curseq[2:end]) empty!(curseq) return end """ $SIGNATURES Discard any indented block that is within a larger block to avoid ambiguities (see #285). """ function filter_indented_blocks!(blocks::Vector{OCBlock})::Nothing\ # retrieve the indices of the indented blocks idx = [i for i in eachindex(blocks) if blocks[i].name == :CODE_BLOCK_IND] isempty(idx) && return nothing # keep track of the ones that are active active = ones(Bool, length(idx)) # retrieve their span indblocks = blocks[idx] froms = indblocks .|> from tos = indblocks .|> to # retrieve the max/min span for faster processing minfrom = froms |> minimum maxto = tos |> maximum update = false # go over all blocks and check if they contain an indented block for block in blocks # discard if the block is before or after all indented blocks from_, to_ = from(block), to(block) (to_ < minfrom || from_ > maxto) && continue # otherwise check and deactivate if it's contained for k in eachindex(active) active[k] || continue indblock = blocks[idx[k]] if from_ < from(indblock) && to_ > to(indblock) active[k] = false update = true end end if update froms[.!active] .= typemax(Int) tos[.!active] .= 0 minfrom = froms |> minimum maxto = tos |> maximum update = false end end deleteat!(blocks, idx[.!active]) return nothing end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
7656
""" $(SIGNATURES) Find `\\newcommand` elements and try to parse what follows to form a proper Latex command. Return a list of such elements. The format is: \\newcommand{NAMING}[NARG]{DEFINING} where [NARG] is optional (see `LX_NARG_PAT`). """ function find_md_lxdefs(tokens::Vector{Token}, blocks::Vector{OCBlock}) # container for the definitions lxdefs = Vector{LxDef}() # find braces `{` and `}` braces = filter(β -> β.name == :LXB, blocks) nbraces = length(braces) # keep track of active tokens active_tokens = ones(Bool, length(tokens)) active_blocks = ones(Bool, length(blocks)) # go over active tokens, stop over the ones that indicate a newcommand # deactivate the tokens that are within the scope of a newcommand for (i, τ) ∈ enumerate(tokens) # skip inactive tokens active_tokens[i] || continue # look for tokens that indicate a newcommand (τ.name == :LX_NEWCOMMAND) || continue # find first brace blocks after the newcommand (naming) fromτ = from(τ) k = findfirst(β -> (fromτ < from(β)), braces) # there must be two brace blocks after the newcommand (name, def) if isnothing(k) || !(1 <= k < nbraces) throw(LxDefError("Ill formed newcommand (needs two {...})")) end # try to find a number of arg between these two first {...} to see # if it may contain something which we'll try to interpret as [.d.] rge = (to(braces[k])+1):(from(braces[k+1])-1) lxnarg = 0 # it found something between the naming brace and the def brace # check if it looks like [.d.] where d is a number and . are # optional spaces (specification of the number of arguments) if !isempty(rge) lxnarg = match(LX_NARG_PAT, subs(str(braces[k]), rge)) if isnothing(lxnarg) throw(LxDefError("Ill formed newcommand (where I expected the "* "specification of the number of arguments).")) end matched = lxnarg.captures[2] lxnarg = isnothing(matched) ? 0 : parse(Int, matched) end # assign naming / def naming_braces = braces[k] defining_braces = braces[k+1] # try to find a valid command name in the first set of braces matched = match(LX_NAME_PAT, content(naming_braces)) if isnothing(matched) throw(LxDefError("Invalid definition of a new command expected a command name " * "of the form `\\command`.")) end # keep track of the command name, definition and where it stops lxname = matched.captures[1] lxdef = strip(content(defining_braces)) todef = to(defining_braces) # store the new latex command push!(lxdefs, LxDef(lxname, lxnarg, lxdef, fromτ, todef)) # mark newcommand token as processed as well as the next token # which is necessarily the command name (brace token is inactive here) active_tokens[i] = false # mark any block (inc. braces!) starting in the scope as inactive for (i, isactive) ∈ enumerate(active_blocks) isactive || continue (fromτ ≤ from(blocks[i]) ≤ todef) && (active_blocks[i] = false) end end # of enumeration of tokens # filter out the stuff that's now marked as inactive by virtue of being # part of a newcommand definition (these things will be inspected later) tokens = tokens[active_tokens] blocks = blocks[active_blocks] # separate the braces from the rest of the blocks, they will be used # to define the lxcoms braces_mask = map(β -> β.name == :LXB, blocks) braces = blocks[braces_mask] blocks = blocks[@. ~braces_mask] return lxdefs, tokens, braces, blocks end """ $(SIGNATURES) Retrieve the reference pointing to a `LxDef` corresponding to a given `lxname`. If no reference is found but `inmath=true`, we propagate and let KaTeX deal with it. If something is found, the reference is returned and will be accessed further down. """ function retrieve_lxdefref(lxname::SubString, lxdefs::Vector{LxDef}, inmath::Bool=false, offset::Int=0)::Ref # find lxdefs with matching name ks = findall(δ -> (δ.name == lxname), lxdefs) # check that the def is before the usage fromlx = from(lxname) + offset filter!(k -> (fromlx > from(lxdefs[k])), ks) if isempty(ks) if !inmath throw(LxComError("Command '$lxname' was used before it was defined.")) end # not found but inmath --> let KaTex deal with it return Ref(nothing) end return Ref(lxdefs, ks[end]) end """ $(SIGNATURES) Find `\\command{arg1}{arg2}...` outside of `xblocks` and `lxdefs`. """ function find_md_lxcoms(tokens::Vector{Token}, lxdefs::Vector{LxDef}, braces::Vector{OCBlock}, offset::Int=0; inmath::Bool=false)::Tuple{Vector{LxCom},Vector{Token}} # containers for the lxcoms lxcoms = Vector{LxCom}() active_τ = ones(Bool, length(tokens)) nbraces = length(braces) # go over tokens, stop over the ones that indicate a command for (i, τ) ∈ enumerate(tokens) active_τ[i] || continue (τ.name == :LX_COMMAND) || continue # 1. look for the definition given the command name lxname = τ.ss lxdefref = retrieve_lxdefref(lxname, lxdefs, inmath, offset) # will only be nothing in a 'inmath' --> no failure, just ignore token isnothing(lxdefref[]) && continue # 2. retrieve number of arguments lxnarg = getindex(lxdefref).narg # 2.a there are none if lxnarg == 0 push!(lxcoms, LxCom(lxname, lxdefref)) active_τ[i] = false # >> there is at least one argument --> find all of them else # spot where an opening brace is expected nxtidx = to(τ) + 1 b1_idx = findfirst(β -> (from(β) == nxtidx), braces) # --> it needs to exist + there should be enough braces left if isnothing(b1_idx) || (b1_idx + lxnarg - 1 > nbraces) throw(LxComError("Command '$lxname' expects $lxnarg argument(s) and there " * "should be no space(s) between the command name and the first " * "brace: \\com{arg1}...")) end # --> examine candidate braces, there should be no spaces between # braces to avoid ambiguities cand_braces = braces[b1_idx:b1_idx+lxnarg-1] for bidx ∈ 1:lxnarg-1 if (to(cand_braces[bidx]) + 1 != from(cand_braces[bidx+1])) throw(LxComError("Argument braces should not be separated by space(s): " * "\\com{arg1}{arg2}... Verify a '$lxname' command.")) end end # all good, can push it from_c = from(τ) to_c = to(cand_braces[end]) str_c = subs(str(τ), from_c, to_c) push!(lxcoms, LxCom(str_c, lxdefref, cand_braces)) # deactivate tokens in the span of the command (will be # reparsed later) first_active = findfirst(τ -> (from(τ) > to_c), tokens[i+1:end]) if isnothing(first_active) active_τ[i+1:end] .= false elseif first_active > 1 active_τ[i+1:(i+first_active-1)] .= false end end end return lxcoms, tokens[active_τ] end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2469
""" LX_NAME_PAT Regex to find the name in a new command within a brace block. For example: \\newcommand{\\com}[2]{def} will give as first capture group `\\com`. """ const LX_NAME_PAT = r"^\s*(\\[a-zA-Z]+)\s*$" """ LX_NARG_PAT Regex to find the number of argument in a new command (if it is given). For example: \\newcommand{\\com}[2]{def} will give as second capture group `2`. If there are no number of arguments, the second capturing group will be `nothing`. """ const LX_NARG_PAT = r"\s*(\[\s*(\d)\s*\])?\s*" """ LX_TOKENS List of names of latex tokens. (See markdown tokens) """ const LX_TOKENS = (:LX_BRACE_OPEN, :LX_BRACE_CLOSE, :LX_COMMAND) """ $(TYPEDEF) Structure to keep track of the definition of a latex command declared via a `\newcommand{\name}[narg]{def}`. NOTE: mutable so that we can modify the `from` element to mark it as zero when the command has been defined in the context of what we're currently parsing. """ mutable struct LxDef name::String narg::Int def ::AS # location of the definition > only things that can be mutated via pastdef! from::Int to ::Int end # if offset unspecified, start from basically -∞ (configs etc) function LxDef(name::String, narg::Int, def::AS) o = JD_ENV[:OFFSET_GLOB_LXDEFS] += 5 # we don't care just fwd a bit LxDef(name, narg, def, o, o + 3) # we also don't care YOLO end from(lxd::LxDef) = lxd.from to(lxd::LxDef) = lxd.to """ pastdef(λ) Convenience function to mark a definition as having been defined in the context i.e.: earlier than any other definition appearing in the current page. """ pastdef(λ::LxDef) = LxDef(λ.name, λ.narg, λ.def) """ $(TYPEDEF) A `LxCom` has a similar content as a `Block`, with the addition of the definition and a vector of brace blocks. """ struct LxCom <: AbstractBlock ss ::SubString # \\command lxdef ::Ref{LxDef} # definition of the command braces::Vector{OCBlock} # relevant {...} associated with the command end LxCom(ss, def) = LxCom(ss, def, Vector{OCBlock}()) from(lxc::LxCom) = from(lxc.ss) to(lxc::LxCom) = to(lxc.ss) """ $(SIGNATURES) For a given `LxCom`, retrieve the definition attached to the corresponding `LxDef` via the reference. """ getdef(lxc::LxCom) = getindex(lxc.lxdef).def """ $(TYPEDEF) Convenience structure to keep track of the latex commands and braces. """ struct LxContext lxcoms::Vector{LxCom} lxdefs::Vector{LxDef} bblocks::Vector{OCBlock} end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
9480
""" MD_1C_TOKENS Dictionary of single-char tokens for Markdown. Note that these characters are exclusive, they cannot appear again in a larger token. """ const MD_1C_TOKENS = LittleDict{Char, Symbol}( '{' => :LXB_OPEN, '}' => :LXB_CLOSE, '\n' => :LINE_RETURN, ) """ MD_TOKENS_LX Subset of `MD_1C_TOKENS` with only the latex tokens (for parsing what's in a math environment). """ const MD_1C_TOKENS_LX = LittleDict{Char, Symbol}( '{' => :LXB_OPEN, '}' => :LXB_CLOSE ) """ MD_TOKENS Dictionary of tokens for Markdown. Note that for each, there may be several possibilities to consider in which case the order is important: the first case that works will be taken. """ const MD_TOKENS = LittleDict{Char, Vector{TokenFinder}}( '<' => [ isexactly("<!--") => :COMMENT_OPEN, # <!-- ... ], '-' => [ isexactly("-->") => :COMMENT_CLOSE, # ... --> ], '~' => [ isexactly("~~~") => :ESCAPE, # ~~~ ... ~~~ ], '[' => [ incrlook(is_footnote) => :FOOTNOTE_REF, # [^...](:)? defs will be separated after ], ']' => [ isexactly("]: ") => :LINK_DEF, ], '\\' => [ # -- special characters, see `find_special_chars` in ocblocks isexactly("\\\\") => :CHAR_LINEBREAK, # --> <br/> isexactly("\\", (' ',)) => :CHAR_BACKSPACE, # --> &#92; isexactly("\\*") => :CHAR_ASTERISK, # --> &#42; isexactly("\\_") => :CHAR_UNDERSCORE,# --> &#95; isexactly("\\`") => :CHAR_BACKTICK, # --> &#96; isexactly("\\@") => :CHAR_ATSIGN, # --> &#64; # -- maths isexactly("\\{") => :INACTIVE, # See note [^1] isexactly("\\}") => :INACTIVE, # See note [^1] isexactly("\\\$") => :INACTIVE, # See note [^1] isexactly("\\[") => :MATH_C_OPEN, # \[ ... isexactly("\\]") => :MATH_C_CLOSE, # ... \] isexactly("\\begin{align}") => :MATH_ALIGN_OPEN, isexactly("\\end{align}") => :MATH_ALIGN_CLOSE, isexactly("\\begin{equation}") => :MATH_D_OPEN, isexactly("\\end{equation}") => :MATH_D_CLOSE, isexactly("\\begin{eqnarray}") => :MATH_EQA_OPEN, isexactly("\\end{eqnarray}") => :MATH_EQA_CLOSE, # -- latex isexactly("\\newcommand") => :LX_NEWCOMMAND, incrlook((_, c) -> α(c)) => :LX_COMMAND, # \command⎵* ], '@' => [ isexactly("@def", (' ',)) => :MD_DEF_OPEN, # @def var = ... isexactly("@@", SPACE_CHAR) => :DIV_CLOSE, # @@⎵* incrlook(is_div_open) => :DIV_OPEN, # @@dname ], '#' => [ isexactly("#", (' ',)) => :H1_OPEN, # see note [^2] isexactly("##", (' ',)) => :H2_OPEN, isexactly("###", (' ',)) => :H3_OPEN, isexactly("####", (' ',)) => :H4_OPEN, isexactly("#####", (' ',)) => :H5_OPEN, isexactly("######", (' ',)) => :H6_OPEN, ], '&' => [ incrlook(is_html_entity) => :CHAR_HTML_ENTITY, ], '$' => [ isexactly("\$", ('$',), false) => :MATH_A, # $⎵* isexactly("\$\$") => :MATH_B, # $$⎵* ], '_' => [ isexactly("_\$>_") => :MATH_I_OPEN, # internal use when resolving a latex command isexactly("_\$<_") => :MATH_I_CLOSE, # within mathenv (e.g. \R <> \mathbb R) ], '`' => [ isexactly("`", ('`',), false) => :CODE_SINGLE, # `⎵ isexactly("``",('`',), false) => :CODE_DOUBLE, # ``⎵* isexactly("```", SPACE_CHAR) => :CODE_TRIPLE, # ```⎵* isexactly("`````", SPACE_CHAR) => :CODE_PENTA, # `````⎵* is_language() => :CODE_LANG, # ```lang* is_language2() => :CODE_LANG2, # `````lang* ], ) # end dict #= NOTE [1] capturing \{ here will force the head to move after it thereby not marking it as a potential open brace, same for the close brace. [2] similar to @def except that it must be at the start of the line. =# """ MD_TOKENS_LX Subset of `MD_TOKENS` with only the latex tokens (for parsing what's in a math environment). """ const MD_TOKENS_LX = Dict{Char, Vector{TokenFinder}}( '\\' => [ isexactly("\\{") => :INACTIVE, isexactly("\\}") => :INACTIVE, incrlook((_, c) -> α(c)) => :LX_COMMAND ] ) """ MD_DEF_PAT Regex to match an assignment of the form @def var = value The first group captures the name (`var`), the second the assignment (`value`). """ const MD_DEF_PAT = r"@def\s+(\S+)\s*?=\s*?(\S.*)" """ L_RETURNS Convenience tuple containing the name for standard line returns and line returns followed by an indentation (either a quadruple space or a tab). """ const L_RETURNS = (:LINE_RETURN, :LR_INDENT, :EOS) """ MD_OCB List of Open-Close Blocks whose content should be deactivated (any token within their span should be marked as inactive) until further processing. The keys are identifier for the type of block, the value is a pair with the opening and closing tokens followed by a boolean indicating whether the content of the block should be reprocessed. The only `OCBlock` not in this dictionary is the brace block since it should not deactivate its content which is needed to find latex definitions (see parser/markdown/find_blocks/find_md_lxdefs). """ const MD_OCB = [ # name opening token closing token(s) nestable # --------------------------------------------------------------------- OCProto(:COMMENT, :COMMENT_OPEN, (:COMMENT_CLOSE,), false), OCProto(:CODE_BLOCK_LANG, :CODE_LANG, (:CODE_TRIPLE,), false), OCProto(:CODE_BLOCK_LANG, :CODE_LANG2, (:CODE_PENTA,), false), OCProto(:CODE_BLOCK, :CODE_TRIPLE, (:CODE_TRIPLE,), false), OCProto(:CODE_BLOCK, :CODE_PENTA, (:CODE_PENTA,), false), OCProto(:CODE_BLOCK_IND, :LR_INDENT, (:LINE_RETURN,), false), OCProto(:CODE_INLINE, :CODE_DOUBLE, (:CODE_DOUBLE,), false), OCProto(:CODE_INLINE, :CODE_SINGLE, (:CODE_SINGLE,), false), OCProto(:ESCAPE, :ESCAPE, (:ESCAPE,), false), OCProto(:FOOTNOTE_DEF, :FOOTNOTE_DEF, L_RETURNS, false), OCProto(:LINK_DEF, :LINK_DEF, L_RETURNS, false), # ------------------------------------------------------------------ OCProto(:H1, :H1_OPEN, L_RETURNS, false), # see [^3] OCProto(:H2, :H2_OPEN, L_RETURNS, false), OCProto(:H3, :H3_OPEN, L_RETURNS, false), OCProto(:H4, :H4_OPEN, L_RETURNS, false), OCProto(:H5, :H5_OPEN, L_RETURNS, false), OCProto(:H6, :H6_OPEN, L_RETURNS, false), # ------------------------------------------------------------------ OCProto(:MD_DEF, :MD_DEF_OPEN, L_RETURNS, false), # see [^4] OCProto(:LXB, :LXB_OPEN, (:LXB_CLOSE,), true ), OCProto(:DIV, :DIV_OPEN, (:DIV_CLOSE,), true ), ] #= NOTE: * [3] a header can be closed by either a line return or an end of string (for instance in the case where a user defines a latex command like so: \newcommand{\section}{# blah} (no line return).) * [4] an `MD_DEF` goes from an `@def` to the next `\n` so no multiple-line def are allowed. * ordering matters! =# """ MD_HEADER All header symbols. """ const MD_HEADER = (:H1, :H2, :H3, :H4, :H5, :H6) """ MD_HEADER_OPEN All header symbols (opening). """ const MD_HEADER_OPEN = (:H1_OPEN, :H2_OPEN, :H3_OPEN, :H4_OPEN, :H5_OPEN, :H6_OPEN) """ MD_OCB_ESC Blocks that will be escaped (their content will not be further processed). Corresponds to the "non-reprocess" elements of `MD_OCB`. """ const MD_OCB_ESC = [e.name for e ∈ MD_OCB if !e.nest] """ MD_OCB_MATH Same concept as `MD_OCB` but for math blocks, they can't be nested. Separating them from the other dictionary makes their processing easier. Dev note: order does not matter. """ const MD_OCB_MATH = [ OCProto(:MATH_A, :MATH_A, (:MATH_A,), false), OCProto(:MATH_B, :MATH_B, (:MATH_B,), false), OCProto(:MATH_C, :MATH_C_OPEN, (:MATH_C_CLOSE,), false), OCProto(:MATH_C, :MATH_D_OPEN, (:MATH_D_CLOSE,), false), OCProto(:MATH_I, :MATH_I_OPEN, (:MATH_I_CLOSE,), false), OCProto(:MATH_ALIGN, :MATH_ALIGN_OPEN, (:MATH_ALIGN_CLOSE,), false), OCProto(:MATH_EQA, :MATH_EQA_OPEN, (:MATH_EQA_CLOSE,), false), ] """ MD_OCB_ALL Combination of all `MD_OCB` in order. """ const MD_OCB_ALL = vcat(MD_OCB, MD_OCB_MATH) # order matters """ MD_OCB_IGNORE List of names of blocks that will need to be dropped at compile time. """ const MD_OCB_IGNORE = [:COMMENT, :MD_DEF] """ MATH_BLOCKS_NAMES List of names of maths environments. """ const MATH_BLOCKS_NAMES = [e.name for e ∈ MD_OCB_MATH] """ MD_OCB_NO_INNER List of names of blocks which will deactivate any block contained within them. See [`find_all_ocblocks`](@ref). """ const MD_OCB_NO_INNER = vcat(MD_OCB_ESC, MATH_BLOCKS_NAMES, :LXB)
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4174
""" $SIGNATURES Find footnotes refs and defs and eliminate the ones that don't verify the appropriate regex. For a footnote ref: `\\[\\^[a-zA-Z0-0]+\\]` and `\\[\\^[a-zA-Z0-0]+\\]:` for the def. """ function validate_footnotes!(tokens::Vector{Token}) fn_refs = Vector{Token}() rm = Int[] for (i, τ) in enumerate(tokens) τ.name == :FOOTNOTE_REF || continue # footnote ref [^1]: m = match(r"^\[\^[a-zA-Z0-9]+\](:)?$", τ.ss) if !isnothing(m) if !isnothing(m.captures[1]) # it's a def tokens[i] = Token(:FOOTNOTE_DEF, τ.ss) end # otherwise it's a ref, leave as is else # delete push!(rm, i) end end deleteat!(tokens, rm) return nothing end """ $SIGNATURES Verify that a given string corresponds to a well formed html entity. """ function validate_html_entity(ss::AS) !isnothing(match(r"&(?:[a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});", ss)) end """ $(SIGNATURES) Given a candidate header block, check that the opening `#` is at the start of a line, otherwise ignore the block. """ function validate_headers!(tokens::Vector{Token})::Nothing isempty(tokens) && return s = str(tokens[1].ss) # does not allocate rm = Int[] for (i, τ) in enumerate(tokens) τ.name in MD_HEADER_OPEN || continue # check if it overlaps with the first character fromτ = from(τ) fromτ == 1 && continue # otherwise check if the previous character is a linereturn prevc = s[prevind(s, fromτ)] prevc == '\n' && continue push!(rm, i) end deleteat!(tokens, rm) return end postprocess_link(s::String) = replace(r"") """ $(SIGNATURES) Keep track of link defs. Deactivate any blocks that is within the span of a link definition (see issue #314). """ function validate_and_store_link_defs!(blocks::Vector{OCBlock})::Nothing isempty(blocks) && return rm = Int[] parent = str(blocks[1]) for (i, β) in enumerate(blocks) if β.name == :LINK_DEF # incremental backward look until we find a `[` or a `\n` # if `\n` (or start of string) first, discard ini = prevind(parent, from(β)) k = ini char = '\n' while k ≥ 1 char = parent[k] char ∈ ('[','\n') && break k = prevind(parent, k) end if char == '[' # redefine the full block ftk = Token(:FOO,subs("")) # we have a [id]: lk add it to PAGE_LINK_DEFS id = subs(parent, nextind(parent, k), ini) # issue #266 in case there's formatting in the link id = jd2html(id, internal=true) id = replace(id, r"^<p>"=>"") id = replace(id, r"<\/p>\n$"=>"") lk = β |> content |> strip |> string PAGE_LINK_DEFS[id] = lk # replace the block by a full one so that it can be fully # discarded in the process of md blocks blocks[i] = OCBlock(:LINK_DEF, ftk=>ftk, subs(parent, k, to(β))) else # discard push!(rm, i) end end end isempty(rm) || deleteat!(blocks, rm) # cleanup: deactivate any block that it's in the span of a link def spans = [(from(ld), to(ld)) for ld in blocks if ld.name == :LINK_DEF] if !isempty(spans) for (i, block) in enumerate(blocks) # if it's in one of the span, discard curspan = (from(block), to(block)) # early stopping if before all ld or after all of them curspan[2] < spans[1][1] && continue curspan[1] > spans[end][2] && continue # go over each span break as soon as it's in for span in spans if span[1] < curspan[1] && curspan[2] < span[2] push!(rm, i) break end end end end isempty(rm) || deleteat!(blocks, rm) return nothing end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
5596
""" $(SIGNATURES) Find active blocks between an opening token (`otoken`) and a closing token `ctoken`. These can be nested (e.g. braces). Return the list of such blocks. If `deactivate` is `true`, all the tokens within the block will be marked as inactive (for further, separate processing). """ function find_ocblocks(tokens::Vector{Token}, ocproto::OCProto; inmath=false)::Tuple{Vector{OCBlock}, Vector{Token}} ntokens = length(tokens) active_tokens = ones(Bool, length(tokens)) ocblocks = Vector{OCBlock}() nestable = ocproto.nest # go over active tokens check if there's an opening token # if so look for the closing one and push for (i, τ) ∈ enumerate(tokens) # only consider active and opening tokens (active_tokens[i] & (τ.name == ocproto.otok)) || continue # if nestable, need to keep track of the balance if nestable # inbalance ≥ 0, 0 if all opening tokens are closed inbalance = 1 # we've seen an opening token j = i # index for the closing token while !iszero(inbalance) & (j < ntokens) j += 1 inbalance += ocbalance(tokens[j], ocproto) end if inbalance > 0 throw(OCBlockError("I found at least one opening token " * "'$(ocproto.otok)' that is not closed properly.", context(τ))) end else # seek forward to find the first closing token j = findfirst(cτ -> (cτ.name ∈ ocproto.ctok), tokens[i+1:end]) # error if no closing token is found if isnothing(j) throw(OCBlockError("I found the opening token '$(τ.name)' but not " * "the corresponding closing token.", context(τ))) end j += i end push!(ocblocks, OCBlock(ocproto.name, τ => tokens[j])) # remove processed tokens and tokens within blocks except if # it's a brace block in a math environment. span = ifelse((ocproto.name == :LXB) & inmath, [i, j], i:j) active_tokens[span] .= false end return ocblocks, tokens[active_tokens] end """ $(SIGNATURES) Helper function to update the inbalance counter when looking for the closing token of a block with nesting. Adds 1 if the token corresponds to an opening token, removes 1 if it's a closing token and 0 otherwise. """ function ocbalance(τ::Token, ocp::OCProto)::Int (τ.name == ocp.otok) && return 1 (τ.name ∈ ocp.ctok) && return -1 return 0 end """ $(SIGNATURES) Convenience function to find all ocblocks e.g. such as `MD_OCBLOCKS`. Returns a vector of vectors of ocblocks. """ function find_all_ocblocks(tokens::Vector{Token}, ocplist::Vector{OCProto}; inmath=false) ocbs_all = Vector{OCBlock}() for ocp ∈ ocplist if ocp.name == :CODE_BLOCK_IND && !LOCAL_PAGE_VARS["indented_code"].first continue end ocbs, tokens = find_ocblocks(tokens, ocp; inmath=inmath) append!(ocbs_all, ocbs) end # it may happen that a block is contained in a larger block # there are two situations where we want to do something about it: # Case 1 (solved here) where a block is inside a larger escape block # Case 2 (solved in check_and_merge_indented_blocks!) when an indented # code block is contained inside a larger block # # CASE 1: block inside a larger escape block. # this can happen if there is a code block in an escape block # (see e.g. #151) or if there's indentation in a math block. # To fix this, we browse the escape blocks in backwards order and check if # there is any other block within it. i = length(ocbs_all) active = ones(Bool, i) all_heads = from.(ocbs_all) while i > 1 cur_ocb = ocbs_all[i] if active[i] && cur_ocb.name ∈ MD_OCB_NO_INNER # find all blocks within the span of this block, deactivate all of them cur_head = all_heads[i] cur_tail = to(cur_ocb) mask = filter(j -> active[j] && cur_head < all_heads[j] < cur_tail, 1:i-1) active[mask] .= false end i -= 1 end deleteat!(ocbs_all, map(!, active)) return ocbs_all, tokens end """ $(SIGNATURES) Merge vectors of blocks by order of appearance of the blocks. """ function merge_blocks(lvb::Vector{<:AbstractBlock}...) blocks = vcat(lvb...) sort!(blocks, by=(β->from(β))) return blocks end """ $SIGNATURES Take a list of token and return those corresponding to special characters or html entities wrapped in `HTML_SPCH` types (will be left alone by the markdown conversion and be inserted as is in the HTML). """ function find_special_chars(tokens::Vector{Token}) spch = Vector{HTML_SPCH}() isempty(tokens) && return spch for τ in tokens τ.name == :CHAR_ASTERISK && push!(spch, HTML_SPCH(τ.ss, "&#42;")) τ.name == :CHAR_UNDERSCORE && push!(spch, HTML_SPCH(τ.ss, "&#95;")) τ.name == :CHAR_ATSIGN && push!(spch, HTML_SPCH(τ.ss, "&#64;")) τ.name == :CHAR_BACKSPACE && push!(spch, HTML_SPCH(τ.ss, "&#92;")) τ.name == :CHAR_BACKTICK && push!(spch, HTML_SPCH(τ.ss, "&#96;")) τ.name == :CHAR_LINEBREAK && push!(spch, HTML_SPCH(τ.ss, "<br/>")) τ.name == :CHAR_HTML_ENTITY && validate_html_entity(τ.ss) && push!(spch, HTML_SPCH(τ.ss)) end return spch end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
12905
""" $(TYPEDEF) This is the supertype defining a section of the string into consideration which can be considered as a "block". For instance, `abc { ... } def` contains one braces block corresponding to the substring `{ ... }`. All subtypes of AbstractBlock must have a `ss` field corresponding to the substring associated to the block. See also [`Token`](@ref), [`OCBlock`](@ref). """ abstract type AbstractBlock end # convenience functions to locate the substring associated to a block from(β::AbstractBlock) = from(β.ss) to(β::AbstractBlock) = to(β.ss) str(β::AbstractBlock) = str(β.ss) """ $(TYPEDEF) A token `τ::Token` denotes a part of the source string indicating a region that may need further processing. It is identified by a symbol `τ.name` (e.g.: `:MATH_ALIGN_OPEN`). Tokens are typically used in this code to identify delimiters of environments. For instance, `abc \$ ... \$ def` contains two tokens `:MATH_A` associated with the `\$` sign. Together they delimit here an inline math expression. """ struct Token <: AbstractBlock name::Symbol ss::SubString lno::Int # for LRINDENT it's useful to store line number end Token(n, s) = Token(n, s, 0) to(β::Token) = ifelse(β.name == :EOS, from(β), to(β.ss)) """ $(TYPEDEF) A special block to wrap special characters like like a html entity and have it left unaffected by the Markdown to HTML transformation so that it can be inserted "as is" in the HTML. """ struct HTML_SPCH <: AbstractBlock ss::SubString r::String end HTML_SPCH(ss) = HTML_SPCH(ss, "") """ $(TYPEDEF) Prototype for an open-close block (see [`OCBlock`](@ref)) with the symbol of the opening token (e.g. `:MATH_A`) and a corresponding list of closing tokens (e.g. `(:MATH_A,)`). See also their definitions in `parser/md_tokens.jl`. """ struct OCProto name::Symbol otok::Symbol ctok::NTuple{N, Symbol} where N nest::Bool end """ $(TYPEDEF) Open-Close block, blocks that are defined by an opening `Token` and a closing `Token`, they may be nested. For instance braces block are formed of an opening `{` and a closing `}` and could be nested. """ struct OCBlock <: AbstractBlock name::Symbol ocpair::Pair{Token,Token} ss::SubString end """ $(SIGNATURES) Shorthand constructor to instantiate an `OCBlock` inferring the associated substring from the `ocpair` (since it's the substring in between the tokens). """ OCBlock(η::Symbol, ω::Pair{Token,Token}, nestable::Bool=false) = OCBlock(η, ω, subs(str(ω.first), from(ω.first), to(ω.second))) """ $(SIGNATURES) Convenience function to retrieve the opening token of an `OCBlock`. """ otok(ocb::OCBlock)::Token = ocb.ocpair.first """ $(SIGNATURES) Convenience function to retrieve the closing token of an `OCBlock`. """ ctok(ocb::OCBlock)::Token = ocb.ocpair.second """ $(SIGNATURES) Convenience function to return the content of an open-close block (`OCBlock`), for instance the content of a `{...}` block would be `...`. """ function content(ocb::OCBlock)::SubString s = str(ocb.ss) # this does not allocate cfrom = nextind(s, to(otok(ocb))) c = ctok(ocb) if c.name == :EOS cto = from(c) else cto = prevind(s, from(c)) end return subs(s, cfrom, cto) end #= FUNCTIONS / CONSTANTS THAT HELP DEFINE TOKENS =# """ EOS Convenience symbol to mark the end of the string to parse (helps with corner cases where a token ends a document without being followed by a space). """ const EOS = '\0' """ SPACE_CHARS Convenience list of characters that would correspond to a `\\s` regex. see also https://github.com/JuliaLang/julia/blob/master/base/strings/unicode.jl. """ const SPACE_CHAR = (' ', '\n', '\t', '\v', '\f', '\r', '\u85', '\ua0', EOS) """ SPACER Convenience list of characters corresponding to digits. """ const NUM_CHAR = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0') """ $(SIGNATURES) Forward lookup checking if a sequence of characters matches `refstring` and is followed (or not followed if `isfollowed==false`) by a character out of a list of characters (`follow`). It returns 1. a number of steps indicating the number of characters to check, 2. whether there is an offset or not (if it is required to check a following character or not), 3. a function that can be applied on a sequence of character. # Example ```julia-repl julia> (s, b, f) = isexactly("aabbc", "d", isfollowed=false); julia> f("aabbcd") false julia> f("aabbce") true julia> s 5 ``` """ function isexactly(refstring::AS, follow::NTuple{K,Char} where K = (), isfollowed=true)::Tuple{Int,Bool,Function,Bool} # number of code units from the start character steps = prevind(refstring, lastindex(refstring)) # no offset (don't check next character) isempty(follow) && return (steps, false, (s,_) -> (s == refstring), false) # will include next char for verification (--> offset of 1) steps = lastindex(refstring) nochop = !isfollowed || EOS ∈ follow # verification function; we want either (false false or true true)) # NOTE, chop because we will take the next char with it λ(s, at_eos) = at_eos ? # if at_eos then we don't get an extra char, compare as is # if isfollowed, then check EOS in follow s == refstring && !isfollowed || EOS ∈ follow : # if not, get extra char, compare with chop(s) == refstring && !xor(isfollowed, s[end] ∈ follow) return (steps, true, λ, nochop) end """ $(SIGNATURES) Check whether `c` is a letter or is in a vector of character `ac`. """ α(c::Char, ac::NTuple{K,Char}=()) where K = isletter(c) || (c ∈ ac) """ $(SIGNATURES) Check whether `c` is alpha numeric or in vector of character `ac` """ αη(c::Char, ac::NTuple{K,Char}=()) where K = α(c, tuple(ac..., NUM_CHAR...)) """ $(SIGNATURES) Syntactic sugar for the incremental look case for which `steps=0` as well as the `offset`. This is a case where from a start character we lazily accept the next sequence of characters stopping as soon as a character fails to verify `λ(c)`. See also [`isexactly`](@ref). """ incrlook(λ::Function, validator=nothing) = (0, false, λ, validator) """ $(SIGNATURES) In combination with `incrlook`, checks to see if we have something that looks like a @@div describing the opening of a div block. Triggering char is a first `@`. """ is_div_open(i::Int, c::Char) = (i == 1 && return c == '@'; return α(c, ('-','_'))) """ $(SIGNATURES) In combination with `incrlook`, checks to see if we have something that looks like a triple backtick followed by a valid combination of letter defining a language. Triggering char is a first backtick. """ is_language() = incrlook(_is_language, _validate_language) function _is_language(i::Int, c::Char) i < 3 && return c == '`' # ` followed by `` forms the opening ``` i == 3 && return α(c) # must be a letter return α(c, ('-',)) # can be a letter or a hyphen, for instance ```objective-c end _validate_language(stack::AS) = !isnothing(match(r"^```[a-zA-Z]", stack)) """ $(SIGNATURES) See [`is_language`](@ref) but with 5 ticks. """ is_language2() = incrlook(_is_language2, _validate_language2) function _is_language2(i::Int, c::Char) i < 5 && return c == '`' i == 5 && return α(c) return α(c, ('-',)) end _validate_language2(stack::AS) = !isnothing(match(r"^`````[a-zA-Z]", stack)) """ $(SIGNATURES) In combination with `incrlook`, checks to see if we have something that looks like a html entity. Note that there can be fake matches, so this will need to be validated later on; if validated it will be treated as HTML; otherwise it will be shown as markdown. Triggerin char is a `&`. """ is_html_entity(i::Int, c::Char) = αη(c, ('#',';')) """ $(SIGNATURES) Check if it looks like `\\[\\^[a-zA-Z0-9]+\\]:`. """ function is_footnote(i::Int, c::Char) i == 1 && return c == '^' i == 2 && return αη(c) i > 2 && return αη(c, (']', ':')) end """ TokenFinder Convenience type to define tokens. The Tuple comes from the output of functions such as [`isexactly`](@ref). """ const TokenFinder = Pair{Tuple{Int,Bool,Function,Union{Bool,Nothing,Function}},Symbol} """ $(SIGNATURES) Go through a text left to right, one (valid) char at the time and keep track of sequences of chars that match specific tokens. The list of tokens found is returned. **Arguments** * `str`: the initial text * `dictn`: dictionary of possible tokens (multiple characters long) * `dict1`: dictionaro of possible tokens (single character) """ function find_tokens(str::AS, dictn::AbstractDict{Char,Vector{TokenFinder}}, dict1::AbstractDict{Char,Symbol})::Vector{Token} isempty(str) && return Token[] # storage to keep track of the tokens found tokens = Vector{Token}() head_idx = 1 # valid string index end_idx = lastindex(str) # outer bound while head_idx <= end_idx head_char = str[head_idx] # 1. is it one of the single-char token? if haskey(dict1, head_char) tok = Token(dict1[head_char], subs(str, head_idx)) push!(tokens, tok) # 2. is it one of the multi-char token? elseif haskey(dictn, head_char) for ((steps, offset, λ, ν), case) ∈ dictn[head_char] #= ↪ steps = length of the lookahead, 0 if incremental (greedy) ↪ offset = if we need to check one character 'too much' (e.g. this is the case if we want to check that something is followed by a space) ↪ λ = the checker function * for a fixed lookahead, it returns true if the segment (head_idx → head_idx + steps) matches a condition * for an incremental lookahead, it returns true if chars given meet a condition, chars after head_idx are fed while the condition holds. ↪ ν = the (optional) validator function in the case of a greedy lookahead to check whether the sequence is valid Either way, we push to the 'memory' the exact span (without the potential offset) of the token and a symbol indicating what it is then we move the head at the end of the token (note that it's pushed by 1 again after the if-else-end to start again). =# if steps > 0 # exact match of a given fixed pattern tail_idx = nextind(str, head_idx, steps) # is there space for the fixed pattern? at_eos = false if ν && tail_idx == nextind(str, end_idx) tail_idx = end_idx at_eos = true end tail_idx > end_idx && continue # consider the substring and verify whether it matches cand_seq = subs(str, head_idx, tail_idx) if λ(cand_seq, at_eos) # if offset==True --> looked at 1 extra char (lookahead) back_one = offset & !at_eos head_idx = prevind(str, tail_idx, back_one) tok = Token(case, chop(cand_seq, tail=back_one)) push!(tokens, tok) # token identified, no need to check other cases. break end else # rule-based match: greedy catch until fail nchars = 1 tail_idx = head_idx probe_idx = nextind(str, head_idx) probe_idx > end_idx && continue probe_char = str[probe_idx] while λ(nchars, probe_char) tail_idx = probe_idx probe_idx = nextind(str, probe_idx) probe_idx > end_idx && break probe_char = str[probe_idx] nchars += 1 end if tail_idx > head_idx cand_seq = subs(str, head_idx, tail_idx) # check if the validator is happy otherwise skip isnothing(ν) || ν(cand_seq) || continue # if it's happy push the token & move after the match tok = Token(case, cand_seq) push!(tokens, tok) head_idx = tail_idx end end end end head_idx = nextind(str, head_idx) end # finally push the end token eos = Token(:EOS, subs(str, end_idx)) push!(tokens, eos) return tokens end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1975
const td = mktempdir() flush_td() = (isdir(td) && rm(td; recursive=true); mkdir(td)) J.FOLDER_PATH[] = td jd2html_td(e) = jd2html(e; dir=td) jd2html_tdv(e) = J.jd2html_v(e; dir=td) J.def_GLOBAL_PAGE_VARS!() J.def_GLOBAL_LXDEFS!() @testset "Paths" begin P = J.set_paths!() @test J.PATHS[:folder] == td @test J.PATHS[:src] == joinpath(td, "src") @test J.PATHS[:src_css] == joinpath(td, "src", "_css") @test J.PATHS[:src_html] == joinpath(td, "src", "_html_parts") @test J.PATHS[:libs] == joinpath(td, "libs") @test J.PATHS[:pub] == joinpath(td, "pub") @test J.PATHS[:css] == joinpath(td, "css") @test P == J.PATHS mkdir(J.PATHS[:src]) mkdir(J.PATHS[:src_pages]) mkdir(J.PATHS[:libs]) mkdir(J.PATHS[:src_css]) mkdir(J.PATHS[:src_html]) mkdir(J.PATHS[:assets]) end # copying _libs/katex in the J.PATHS[:libs] so that it can be used in testing # the js_prerender_math cp(joinpath(dirname(dirname(pathof(JuDoc))), "test", "_libs", "katex"), joinpath(J.PATHS[:libs], "katex")) @testset "Set vars" begin d = J.PageVars( "a" => 0.5 => (Real,), "b" => "hello" => (String, Nothing)) J.set_vars!(d, ["a"=>"5", "b"=>"nothing"]) @test d["a"].first == 5 @test d["b"].first === nothing @test_logs (:warn, "Doc var 'a' (type(s): (Real,)) can't be set to value 'blah' (type: String). Assignment ignored.") J.set_vars!(d, ["a"=>"\"blah\""]) @test_logs (:error, "I got an error (of type 'DomainError') trying to evaluate '__tmp__ = sqrt(-1)', fix the assignment.") J.set_vars!(d, ["a"=> "sqrt(-1)"]) # assigning new variables J.set_vars!(d, ["blah"=>"1"]) @test d["blah"].first == 1 end @testset "Def+coms" begin # see #78 st = raw""" @def title = "blah" <!-- comment --> @def hasmath = false etc """ (m, jdv) = J.convert_md(st) @test jdv["title"].first == "blah" @test jdv["hasmath"].first == false end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4224
# This is a test file to make codecov happy, technically all of the # tests here are already done / integrated within other tests. @testset "strings" begin st = "blah" @test J.str(st) == "blah" sst = SubString("blahblah", 1:4) @test sst == "blah" @test J.str(sst) == "blahblah" sst = SubString("blah✅💕and etcσ⭒ but ∃⫙∀ done", 1:27) @test J.to(sst) == 27 s = "aabccabcdefabcg" for m ∈ eachmatch(r"abc", s) @test s[J.matchrange(m)] == "abc" end end @testset "ocblock" begin st = "This is a block <!--comment--> and done" τ = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) ocb = J.OCBlock(:COMMENT, (τ[1]=>τ[2])) @test J.otok(ocb) == τ[1] @test J.ctok(ocb) == τ[2] end @testset "isexactly" begin steps, b, λ = J.isexactly("<!--") @test steps == length("<!--") - 1 # minus start char @test b == false @test λ("<!--",false) == true @test λ("<--",false) == false steps, b, λ, = J.isexactly("\$", ('\$',)) @test steps == 1 @test b == true @test λ("\$\$",false) == true @test λ("\$a",false) == false @test λ("a\$",false) == false rs = "\$" steps, b, λ = J.isexactly(rs, ('\$',), false) @test steps == nextind(rs, prevind(rs, lastindex(rs))) @test b == true @test λ("\$\$",false) == false @test λ("\$a",false) == true @test λ("a\$",false) == false steps, b, λ = J.incrlook(isletter) @test steps == 0 @test b == false @test λ('c') == true @test λ('[') == false end @testset "timeittook" begin start = time() sleep(0.5) d = mktempdir() f = joinpath(d, "a.txt") open(f, "w") do outf redirect_stdout(outf) do J.print_final("elapsing",start) end end r = read(f, String) m = match(r"\[done\s*(.*?)ms\]", r) @test parse(Float64, m.captures[1]) ≥ 500 end @testset "refstring" begin @test J.refstring("aa bb") == "aa_bb" @test J.refstring("aa <code>bb</code>") == "aa_bb" @test J.refstring("aa bb !") == "aa_bb" @test J.refstring("aa-bb-!") == "aa-bb-" @test J.refstring("aa 🔺 bb") == "aa_bb" @test J.refstring("aaa 0 bb s:2 df") == "aaa_0_bb_s2_df" @test J.refstring("🔺🔺") == string(hash("🔺🔺")) @test J.refstring("blah&#33;") == "blah" end @testset "paths" begin @test J.unixify(pwd()) == replace(pwd(), J.PATH_SEP => "/") * "/" # J.JD_ENV[:CUR_PATH] = "cpA/cpB/" # non-canonical mode @test J.resolve_assets_rpath("./hello/goodbye") == "/assets/cpA/cpB/hello/goodbye" @test J.resolve_assets_rpath("/blah/blih.txt") == "/blah/blih.txt" @test J.resolve_assets_rpath("blah/blih.txt") == "/assets/blah/blih.txt" @test J.resolve_assets_rpath("ex"; code=true) == "/assets/cpA/cpB/code/ex" # canonical mode @test J.resolve_assets_rpath("./hello/goodbye"; canonical=true) == joinpath(J.PATHS[:assets], "cpA", "cpB", "hello", "goodbye") @test J.resolve_assets_rpath("/blah/blih.txt"; canonical=true) == joinpath(J.PATHS[:folder], "blah", "blih.txt") @test J.resolve_assets_rpath("blah/blih.txt"; canonical=true) == joinpath(J.PATHS[:assets], "blah", "blih.txt") end @testset "misc-html" begin λ = "blah/blah.ext" J.JD_ENV[:CUR_PATH] = "pages/cpB/blah.md" @test J.html_ahref(λ, 1) == "<a href=\"$λ\">1</a>" @test J.html_ahref(λ, "bb") == "<a href=\"$λ\">bb</a>" @test J.html_ahref_key("cc", "dd") == "<a href=\"/pub/cpB/blah.html#cc\">dd</a>" @test J.html_div("dn","ct") == "<div class=\"dn\">ct</div>" @test J.html_img("src", "alt") == "<img src=\"src\" alt=\"alt\">" @test J.html_code("code") == "<pre><code class=\"plaintext\">code</code></pre>" @test J.html_code("code", "lang") == "<pre><code class=\"language-lang\">code</code></pre>" @test J.html_err("blah") == "<p><span style=\"color:red;\">// blah //</span></p>" end @testset "misc-html 2" begin h = "<div class=\"foo\">blah</div>" @test !J.is_html_escaped(h) @test J.html_code(h, "html") == """<pre><code class="language-html">&lt;div class&#61;&quot;foo&quot;&gt;blah&lt;/div&gt;</code></pre>""" he = Markdown.htmlesc(h) @test J.is_html_escaped(he) @test J.html_code(h, "html") == J.html_code(h, "html") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2366
using JuDoc, Test, Markdown, Dates, Random, Literate const J = JuDoc const R = @__DIR__ const D = joinpath(dirname(dirname(pathof(JuDoc))), "test", "_dummies") # NOTE this first file MUST be included before running the rest of the tests # otherwise you may get an error like "key 0x099191234..." was not found or # saying that the key :in doesn't exist or something along those lines include("jd_paths_vars.jl"); include("test_utils.jl") include("misc.jl") # MANAGER folder include("manager/utils.jl") include("manager/rss.jl") include("manager/config.jl") println("🍺") # PARSER folder println("PARSER/MD+LX") include("parser/1-tokenize.jl") include("parser/2-blocks.jl") include("parser/markdown+latex.jl") include("parser/markdown-extra.jl") include("parser/footnotes+links.jl") println("🍺") # ERRORS println("Errors") include("errors/context.jl") println("🍺") # CONVERTER folder println("CONVERTER/MD") include("converter/markdown.jl") include("converter/markdown2.jl") include("converter/markdown3.jl") include("converter/markdown4.jl") include("converter/hyperref.jl") println("🍺") println("CONVERTER/HTML") include("converter/html.jl") include("converter/html2.jl") println("🍺") println("CONVERTER/EVAL") include("converter/eval.jl") println("🍺") println("CONVERTER/LX") include("converter/lx_input.jl") include("converter/lx_simple.jl") println("🍺") println("GLOBAL") include("global/cases1.jl") include("global/cases2.jl") include("global/ordering.jl") include("global/html_esc.jl") begin # create temp dir to do complete integration testing (has to be here in order # to locally play nice with node variables etc, otherwise it's a big headache) p = joinpath(D, "..", "__tmp"); # after errors, this may not have been deleted properly isdir(p) && rm(p; recursive=true, force=true) # make dir, go in it, do the tests, then get completely out (otherwise windows # can't delete the folder) mkdir(p); cd(p); include("global/postprocess.jl"); include("global/rss.jl") cd(p) include("global/eval.jl") cd(joinpath(D, "..")) # clean up rm(p; recursive=true, force=true) end cd(dirname(dirname(pathof(JuDoc)))) println("INTEGRATION") include("integration/literate.jl") flush_td() cd(joinpath(dirname(dirname(pathof(JuDoc))))) println("COVERAGE") include("coverage/extras1.jl") println("😅 😅 😅 😅")
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4006
import DataStructures: OrderedDict # This set of tests directly uses the high-level `convert` functions # And checks the behaviour is as expected. J.def_GLOBAL_LXDEFS!() cmd = st -> J.convert_md(st, collect(values(J.GLOBAL_LXDEFS))) chtml = t -> J.convert_html(t...) conv = st -> st |> cmd |> chtml # convenience function that squeezes out all whitespaces and line returns out of a string # and checks if the resulting strings are equal. When expecting a specific string +- some # spaces, this is very convenient. Use == if want to check exact strings. isapproxstr(s1::String, s2::String) = isequal(map(s->replace(s, r"\s|\n"=>""), (s1, s2))...) # this is a slightly ridiculous requirement but apparently the `eval` blocks # don't play well with Travis nor windows while testing, so you just need to forcibly # specify that LinearAlgebra and Random are used (even though the included block says # the same thing). if get(ENV, "CI", "false") == "true" || Sys.iswindows() import Pkg; Pkg.add("LinearAlgebra"); Pkg.add("Random"); using LinearAlgebra, Random; end # takes md input and outputs the html (good for integration testing) function seval(st) J.def_GLOBAL_PAGE_VARS!() J.def_GLOBAL_LXDEFS!() m, v = J.convert_md(st, collect(values(J.GLOBAL_LXDEFS))) h = J.convert_html(m, v) return h end function set_globals() J.def_GLOBAL_PAGE_VARS!() J.def_GLOBAL_LXDEFS!() empty!(J.LOCAL_PAGE_VARS) J.def_LOCAL_PAGE_VARS!() J.JD_ENV[:CUR_PATH] = "index.md" J.JD_ENV[:CUR_PATH_WITH_EVAL] = "" end function explore_md_steps(mds) J.def_GLOBAL_PAGE_VARS!() J.def_GLOBAL_LXDEFS!() empty!(J.RSS_DICT) J.def_LOCAL_PAGE_VARS!() J.def_PAGE_HEADERS!() J.def_PAGE_EQREFS!() J.def_PAGE_BIBREFS!() J.def_PAGE_FNREFS!() J.def_PAGE_LINK_DEFS!() steps = OrderedDict{Symbol,NamedTuple}() # tokenize tokens = J.find_tokens(mds, J.MD_TOKENS, J.MD_1C_TOKENS) fn_refs = J.validate_footnotes!(tokens) J.validate_headers!(tokens) J.find_indented_blocks!(tokens, mds) steps[:tokenization] = (tokens=tokens,) steps[:fn_validation] = (fn_refs=fn_refs,) # ocblocks blocks, tokens = J.find_all_ocblocks(tokens, J.MD_OCB_ALL) J.merge_indented_blocks!(blocks, mds) J.filter_indented_blocks!(blocks) steps[:ocblocks] = (blocks=blocks, tokens=tokens) # filter filter!(τ -> τ.name ∉ J.L_RETURNS, tokens) steps[:filter] = (tokens=tokens, blocks=blocks) J.validate_and_store_link_defs!(blocks) # latex commands lxdefs, tokens, braces, blocks = J.find_md_lxdefs(tokens, blocks) lxcoms, _ = J.find_md_lxcoms(tokens, lxdefs, braces) steps[:latex] = (lxdefs=lxdefs, tokens=tokens, braces=braces, blocks=blocks, lxcoms=lxcoms) sp_chars = J.find_special_chars(tokens) steps[:spchars] = (spchars=sp_chars,) blocks2insert = J.merge_blocks(lxcoms, J.deactivate_divs(blocks), sp_chars) steps[:blocks2insert] = (blocks2insert=blocks2insert,) inter_md, mblocks = J.form_inter_md(mds, blocks2insert, lxdefs) steps[:inter_md] = (inter_md=inter_md, mblocks=mblocks) inter_html = J.md2html(inter_md; stripp=false) steps[:inter_html] = (inter_html=inter_html,) lxcontext = J.LxContext(lxcoms, lxdefs, braces) hstring = J.convert_inter_html(inter_html, mblocks, lxcontext) steps[:hstring] = (hstring=hstring,) return steps end function explore_h_steps(hs, allvars=J.PageVars()) steps = OrderedDict{Symbol,NamedTuple}() tokens = J.find_tokens(hs, J.HTML_TOKENS, J.HTML_1C_TOKENS) steps[:tokenization] = (tokens=tokens,) hblocks, tokens = J.find_all_ocblocks(tokens, J.HTML_OCB) filter!(hb -> hb.name != :COMMENT, hblocks) steps[:ocblocks] = (hblocks=hblocks, tokens=tokens) qblocks = J.qualify_html_hblocks(hblocks) steps[:qblocks] = (qblocks=qblocks,) fhs = J.process_html_qblocks(hs, allvars, qblocks) steps[:fhs] = (fhs=fhs,) return steps end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
31
const A = 2 println("A is $A")
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
6538
J.JD_ENV[:CUR_PATH] = "index.md" @testset "Evalcode" begin # see `converter/md_blocks:convert_code_block` # see `converter/lx/resolve_lx_input_*` # -------------------------------------------- h = raw""" Simple code: ```julia:./code/exca1 a = 5 print(a^2) ``` then: \input{output}{./code/exca1} done. """ |> seval h2 = raw""" Simple code: ```julia:excb1 a = 5 print(a^2) ``` then: \input{output}{excb1} done. """ |> seval @test h == h2 spatha = joinpath(J.PATHS[:assets], "index", "code", "exca1.jl") spathb = joinpath(J.PATHS[:assets], "index", "code", "excb1.jl") @test isfile(spatha) @test isfile(spathb) @test isapproxstr(read(spatha, String), """ $(J.MESSAGE_FILE_GEN_JMD) a = 5\nprint(a^2)""") opath = joinpath(J.PATHS[:assets], "index", "code", "output", "exca1.out") @test isfile(opath) @test read(opath, String) == "25" @test isapproxstr(h, raw""" <p>Simple code: <pre><code class="language-julia">a = 5 print(a^2)</code></pre> then: <pre><code class="plaintext">25</code></pre> done.</p>""") end @testset "Eval (errs)" begin # see `converter/md_blocks:convert_code_block` # -------------------------------------------- h = raw""" Simple code: ```python:./scripts/testpy a = 5 print(a**2) ``` done. """ |> seval @test isapproxstr(h, raw""" <p>Simple code: <pre><code class="language-python">a = 5 print(a**2)</code></pre> done.</p>""") end @testset "Eval (rinput)" begin h = raw""" Simple code: ```julia:/assets/scripts/test2 a = 5 print(a^2) ``` then: \input{output}{/assets/scripts/test2} done. """ |> seval spath = joinpath(J.PATHS[:assets], "scripts", "test2.jl") @test isfile(spath) @test occursin("a = 5\nprint(a^2)", read(spath, String)) opath = joinpath(J.PATHS[:assets], "scripts", "output", "test2.out") @test isfile(opath) @test read(opath, String) == "25" @test isapproxstr(h, """ <p>Simple code: <pre><code class="language-julia">a = 5 print(a^2)</code></pre> then: <pre><code class="plaintext">25</code></pre> done.</p>""") # ------------ J.JD_ENV[:CUR_PATH] = "pages/pg1.md" h = raw""" Simple code: ```julia:./code/abc2 a = 5 print(a^2) ``` then: \input{output}{./code/abc2} done. """ |> seval spath = joinpath(J.PATHS[:assets], "pages", "pg1", "code", "abc2.jl") @test isfile(spath) @test occursin("a = 5\nprint(a^2)", read(spath, String)) opath = joinpath(J.PATHS[:assets], "pages", "pg1", "code", "output" ,"abc2.out") @test isfile(opath) @test read(opath, String) == "25" @test isapproxstr(h, """ <p>Simple code: <pre><code class="language-julia">a = 5 print(a^2)</code></pre> then: <pre><code class="plaintext">25</code></pre> done.</p>""") end @testset "Eval (module)" begin h = raw""" Simple code: ```julia:scripts/test1 using LinearAlgebra a = [5, 2, 3, 4] print(dot(a, a)) ``` then: \input{output}{scripts/test1} done. """ |> seval # dot(a, a) == 54 @test occursin("""then: <pre><code class="plaintext">54</code></pre> done.""", h) end @testset "Eval (img)" begin J.JD_ENV[:CUR_PATH] = "index.html" h = raw""" Simple code: ```julia:tv2 write(joinpath(@__DIR__, "output", "tv2.png"), "blah") ``` then: \input{plot}{tv2} done. """ |> seval @test occursin("then: <img src=\"/assets/index/code/output/tv2.png\" alt=\"\"> done.", h) end @testset "Eval (throw)" begin h = raw""" Simple code: ```julia:scripts/test1 sqrt(-1) ``` then: \input{output}{scripts/test1} done. """ |> seval # errors silently @test occursin("then: <pre><code class=\"plaintext\">There was an error running the code:\nDomainError", h) end @testset "Eval (nojl)" begin h = raw""" Simple code: ```python:scripts/test1 sqrt(-1) ``` done. """ @test (@test_logs (:warn, "Eval of non-julia code blocks is not yet supported.") h |> seval) == "<p>Simple code: <pre><code class=\"language-python\">sqrt(-1)</code></pre> done.</p>\n" end # temporary fix for 186: make error appear and also use `abspath` in internal include @testset "eval #186" begin h = raw""" Simple code: ```julia:scripts/test186 fn = "tempf.jl" write(fn, "a = 1+1") println("Is this a file? $(isfile(fn))") include(abspath(fn)) println("Now: $a") rm(fn) ``` done. \output{scripts/test186} """ |> seval @test isapproxstr(h, raw""" <p>Simple code: <pre><code class="language-julia">fn = "tempf.jl" write(fn, "a = 1+1") println("Is this a file? $(isfile(fn))") include(abspath(fn)) println("Now: $a") rm(fn)</code></pre> done. <pre><code class="plaintext">Is this a file? true Now: 2 </code></pre></p> """) end @testset "show" begin h = raw""" @def hascode = true @def reeval = true ```julia:ex a = 5 a *= 2 ``` \show{ex} """ |> jd2html_td @test isapproxstr(h, """ <pre><code class="language-julia">a = 5 a *= 2</code></pre> <div class="code_output"><pre><code class="plaintext">10</code></pre></div> """) # Show with stdout h = raw""" @def hascode = true @def reeval = true ```julia:ex a = 5 println("hello") a *= 2 ``` \show{ex} """ |> jd2html_td @test isapproxstr(h, """ <pre><code class="language-julia">a = 5 println("hello") a *= 2</code></pre> <div class="code_output"><pre><code class="plaintext">hello 10</code></pre></div> """) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4608
@testset "Cblock+h-fill" begin allvars = J.PageVars( "v1" => "INPUT1" => (String,), "b1" => false => (Bool,), "b2" => true => (Bool,)) hs = raw""" Some text then {{ fill v1 }} and {{ if b1 }} show stuff here {{ fill v2 }} {{ else if b2 }} other stuff {{ else }} show other stuff {{ end }} final text """ @test J.convert_html(hs, allvars) == "Some text then INPUT1 and\n\nother stuff\n\nfinal text\n" hs = raw""" abc {{isdef no}}yada{{end}} def """ @test J.convert_html(hs, allvars) == "abc def\n" hs = raw"""abc {{ fill nope }} ... """ @test (@test_logs (:warn, "I found a '{{fill nope}}' but I do not know the variable 'nope'. Ignoring.") J.convert_html(hs, allvars)) == "abc ... " hs = raw"""unknown fun {{ unknown fun }} and see.""" @test (@test_logs (:warn, "I found a function block '{{unknown ...}}' but don't recognise the function name. Ignoring.") J.convert_html(hs, allvars)) == "unknown fun and see." end @testset "h-insert" begin # Julia 0.7 complains if there's no global here. global temp_rnd = joinpath(J.PATHS[:src_html], "temp.rnd") write(temp_rnd, "some random text to insert") hs = raw""" Trying to insert: {{ insert temp.rnd }} and see. """ allvars = J.PageVars() @test J.convert_html(hs, allvars) == "Trying to insert: some random text to insert and see.\n" hs = raw"""Trying to insert: {{ insert nope.rnd }} and see.""" @test (@test_logs (:warn, "I found an {{insert ...}} block and tried to insert '$(joinpath(J.PATHS[:src_html], "nope.rnd"))' but I couldn't find the file. Ignoring.") J.convert_html(hs, allvars)) == "Trying to insert: and see." end @testset "cond-insert" begin allvars = J.PageVars( "author" => "Stefan Zweig" => (String, Nothing), "date_format" => "U dd, yyyy" => (String,), "isnotes" => true => (Bool,)) hs = "foot {{if isnotes}} {{fill author}}{{end}}" rhs = J.convert_html(hs, allvars) @test rhs == "foot Stefan Zweig" end @testset "cond-insert 2" begin allvars = J.PageVars( "author" => "Stefan Zweig" => (String, Nothing), "date_format" => "U dd, yyyy" => (String,), "isnotes" => true => (Bool,)) hs = "foot {{isdef author}} {{fill author}}{{end}}" rhs = J.convert_html(hs, allvars) @test rhs == "foot Stefan Zweig" hs2 = "foot {{isnotdef blogname}}hello{{end}}" rhs = J.convert_html(hs2, allvars) @test rhs == "foot hello" end @testset "escape-coms" begin allvars = J.PageVars( "author" => "Stefan Zweig" => (String, Nothing), "date_format" => "U dd, yyyy" => (String,), "isnotes" => true => (Bool,)) hs = "foot <!-- {{ fill blahblah }} {{ if v1 }} --> {{isdef author}} {{fill author}}{{end}}" rhs = J.convert_html(hs, allvars) @test rhs == "foot <!-- {{ fill blahblah }} {{ if v1 }} --> Stefan Zweig" end @testset "Cblock+empty" begin # refers to #96 allvars = J.PageVars( "b1" => false => (Bool,), "b2" => true => (Bool,)) jdc = x->J.convert_html(x, allvars) # flag b1 is false @test "{{if b1}} blah {{ else }} blih {{ end }}" |> jdc == " blih " # else @test "{{if b1}} {{ else }} blih {{ end }}" |> jdc == " blih " # else # flag b2 is true @test "{{if b2}} blah {{ else }} blih {{ end }}" |> jdc == " blah " # if @test "{{if b2}} blah {{ else }} {{ end }}" |> jdc == " blah " # if @test "{{if b2}} blah {{ end }}" |> jdc == " blah " # if @test "{{if b1}} blah {{ else }} {{ end }}" |> jdc == " " # else, empty @test "{{if b1}} {{ else }} {{ end }}" |> jdc == " " # else, empty @test "{{if b1}} blah {{ end }}" |> jdc == "" # else, empty @test "{{if b2}} {{ else }} {{ end }}" |> jdc == " " # if, empty @test "{{if b2}} {{ else }} blih {{ end }}" |> jdc == " " # if, empty end @testset "Cond ispage" begin allvars = J.PageVars() hs = raw""" Some text then {{ ispage index.html }} blah {{ end }} but {{isnotpage blah.html ya/xx}} blih {{end}} done. """ J.JD_ENV[:CUR_PATH] = "index.md" @test J.convert_html(hs, allvars) == "Some text then blah but\n blih done.\n" J.JD_ENV[:CUR_PATH] = "blah/blih.md" hs = raw""" A then {{ispage blah/*}}yes{{end}} but not {{isnotpage blih/*}}no{{end}} E. """ @test J.convert_html(hs, allvars) == "A then yes but not no E.\n" J.JD_ENV[:CUR_PATH] = "index.md" end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2389
@testset "Non-nested" begin allvars = J.PageVars( "a" => false => (Bool,), "b" => false => (Bool,)) hs = """A{{if a}}B{{elseif b}}C{{else}}D{{end}}E""" tokens = J.find_tokens(hs, J.HTML_TOKENS, J.HTML_1C_TOKENS) hblocks, tokens = J.find_all_ocblocks(tokens, J.HTML_OCB) qblocks = J.qualify_html_hblocks(hblocks) J.set_vars!(allvars, ["a"=>"true","b"=>"false"]) fhs = J.process_html_qblocks(hs, allvars, qblocks) @test isapproxstr(fhs, "ABE") J.set_vars!(allvars, ["a"=>"false","b"=>"true"]) fhs = J.process_html_qblocks(hs, allvars, qblocks) @test isapproxstr(fhs, "ACE") J.set_vars!(allvars, ["a"=>"false","b"=>"false"]) fhs = J.process_html_qblocks(hs, allvars, qblocks) @test isapproxstr(fhs, "ADE") end @testset "Nested" begin allvars = J.PageVars( "a" => false => (Bool,), "b" => false => (Bool,), "c" => false => (Bool,)) hs = """A {{if a}} B {{elseif b}} C {{if c}} D {{end}} {{else}} E {{end}} F""" tokens = J.find_tokens(hs, J.HTML_TOKENS, J.HTML_1C_TOKENS) hblocks, tokens = J.find_all_ocblocks(tokens, J.HTML_OCB) qblocks = J.qualify_html_hblocks(hblocks) J.set_vars!(allvars, ["a"=>"true"]) fhs = J.process_html_qblocks(hs, allvars, qblocks) @test isapproxstr(fhs, "ABF") J.set_vars!(allvars, ["a"=>"false", "b"=>"true", "c"=>"false"]) fhs = J.process_html_qblocks(hs, allvars, qblocks) @test isapproxstr(fhs, "ACF") J.set_vars!(allvars, ["a"=>"false", "b"=>"true", "c"=>"true"]) fhs = J.process_html_qblocks(hs, allvars, qblocks) @test isapproxstr(fhs, "ACDF") J.set_vars!(allvars, ["a"=>"false", "b"=>"false"]) fhs = J.process_html_qblocks(hs, allvars, qblocks) @test isapproxstr(fhs, "AEF") end @testset "Bad cases" begin # Lonely End block s = """A {{end}}""" @test_throws J.HTMLBlockError J.convert_html(s, J.PageVars()) # Inbalanced s = """A {{if a}} B {{if b}} C {{else}} {{end}}""" @test_throws J.HTMLBlockError J.convert_html(s, J.PageVars()) # Some of the conditions are not bools allvars = J.PageVars( "a" => false => (Bool,), "b" => false => (Bool,), "c" => "Hello" => (String,)) s = """A {{if a}} A {{elseif c}} B {{end}}""" @test_throws J.HTMLBlockError J.convert_html(s, allvars) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3794
@testset "Hyperref" begin J.JD_ENV[:CUR_PATH] = "index.md" st = raw""" Some string $$ x = x \label{eq 1}$$ then as per \citet{amari98b} also this \citep{bardenet17} and \cite{amari98b, bardenet17} Reference to equation: \eqref{eq 1}. Then maybe some text etc. * \biblabel{amari98b}{Amari and Douglas., 1998} **Amari** and **Douglas**: *Why Natural Gradient*, 1998. * \biblabel{bardenet17}{Bardenet et al., 2017} **Bardenet**, **Doucet** and **Holmes**: *On Markov Chain Monte Carlo Methods for Tall Data*, 2017. """; J.def_GLOBAL_PAGE_VARS!() J.def_GLOBAL_LXDEFS!() m, _ = J.convert_md(st, collect(values(J.GLOBAL_LXDEFS))) h1 = J.refstring("eq 1") h2 = J.refstring("amari98b") h3 = J.refstring("bardenet17") @test haskey(J.PAGE_EQREFS, h1) @test haskey(J.PAGE_BIBREFS, h2) @test haskey(J.PAGE_BIBREFS, h3) @test J.PAGE_EQREFS[h1] == 1 # first equation @test J.PAGE_BIBREFS[h2] == "Amari and Douglas., 1998" @test J.PAGE_BIBREFS[h3] == "Bardenet et al., 2017" h = J.convert_html(m, J.PageVars()) @test isapproxstr(h, """ <p> Some string <a id="$h1"></a>\\[ x = x \\] then as per <span class="bibref"><a href="/index.html#$h2">Amari and Douglas., 1998</a></span> also this <span class="bibref">(<a href="/index.html#$h3">Bardenet et al., 2017</a>)</span> and <span class="bibref"><a href="/index.html#$h2">Amari and Douglas., 1998</a>, <a href="/index.html#$h3">Bardenet et al., 2017</a></span> Reference to equation: <span class="eqref">(<a href="/index.html#$h1">1</a>)</span> . </p> <p> Then maybe some text etc. </p> <ul> <li><p><a id="$h2"></a> <strong>Amari</strong> and <strong>Douglas</strong>: <em>Why Natural Gradient</em>, 1998.</p></li> <li><p><a id="$h3"></a> <strong>Bardenet</strong>, <strong>Doucet</strong> and <strong>Holmes</strong>: <em>On Markov Chain Monte Carlo Methods for Tall Data</em>, 2017.</p></li> </ul> """) end @testset "Href-space" begin J.JD_ENV[:CUR_PATH] = "index.md" st = raw""" A $$ x = x \label{eq 1}$$ B C \eqref{eq 1}. and *B $E$*. """ h = st |> seval @test occursin(raw"""<a id="eq_1"></a>\[ x = x \]""", h) @test occursin(raw"""<span class="eqref">(<a href="/index.html#eq_1">1</a>)</span>.""", h) @test occursin(raw"""<em>B \(E\)</em>.""", h) end @testset "Eqref" begin st = raw""" \newcommand{\E}[1]{\mathbb E\left[#1\right]} \newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}} \newcommand{\R}{\mathbb R} Then something like \eqa{ \E{f(X)} \in \R &\text{if}& f:\R\maptso\R} and then \eqa{ 1+1 &=& 2 \label{eq:a trivial one}} but further \eqa{ 1 &=& 1 \label{beyond hope}} and finally a \eqref{eq:a trivial one} and maybe \eqref{beyond hope}. """ m, _ = J.convert_md(st, collect(values(J.GLOBAL_LXDEFS))) @test J.PAGE_EQREFS[J.PAGE_EQREFS_COUNTER] == 3 @test J.PAGE_EQREFS[J.refstring("eq:a trivial one")] == 2 @test J.PAGE_EQREFS[J.refstring("beyond hope")] == 3 h1 = J.refstring("eq:a trivial one") h2 = J.refstring("beyond hope") m == "<p>Then something like \$\$\\begin{array}{c} \\mathbb E\\left[ f(X)\\right] \\in \\mathbb R &\\text{if}& f:\\mathbb R\\maptso\\mathbb R\\end{array}\$\$ and then <a id=\"$h1\"></a>\$\$\\begin{array}{c} 1+1 &=&2 \\end{array}\$\$ but further <a id=\"$h2\"></a>\$\$\\begin{array}{c} 1 &=& 1 \\end{array}\$\$ and finally a <span class=\"eqref)\">({{href EQR $h1}})</span> and maybe <span class=\"eqref)\">({{href EQR $h2}})</span>.</p>\n" end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2420
@testset "Input" begin # # check_input_fname # J.JD_ENV[:CUR_PATH] = "index.html" script1 = joinpath(J.PATHS[:assets], "index", "code", "script1.jl") write(script1, "1+1") fp, d, fn = J.check_input_rpath("script1.jl", code=true) @test fp == script1 @test d == joinpath(J.PATHS[:assets], "index", "code") @test fn == "script1" @test_throws ArgumentError J.check_input_rpath("script2.jl") # # resolve_lx_input_hlcode # r = J.resolve_lx_input_hlcode("script1.jl", "julia") r2 = J.resolve_lx_input_othercode("script1.jl", "julia") @test r == "<pre><code class=\"language-julia\">1+1</code></pre>" @test r2 == r # # resolve_lx_input_plainoutput # mkpath(joinpath(J.PATHS[:assets], "index", "code", "output")) plain1 = joinpath(J.PATHS[:assets], "index", "code", "output", "script1.out") write(plain1, "2") r = J.resolve_lx_input_plainoutput("script1.jl", code=true) @test r == "<pre><code class=\"plaintext\">2</code></pre>" end @testset "LX input" begin write(joinpath(J.PATHS[:assets], "index", "code", "s1.jl"), "println(1+1)") write(joinpath(J.PATHS[:assets], "index", "code", "output", "s1a.png"), "blah") write(joinpath(J.PATHS[:assets], "index", "code", "output", "s1.out"), "blih") st = raw""" Some string \input{julia}{s1.jl} Then maybe \input{output:plain}{s1.jl} Finally img: \input{plot:a}{s1.jl} done. """; J.def_GLOBAL_PAGE_VARS!() J.def_GLOBAL_LXDEFS!() m, _ = J.convert_md(st, collect(values(J.GLOBAL_LXDEFS))) h = J.convert_html(m, J.PageVars()) @test occursin("<p>Some string <pre><code class=\"language-julia\">$(read(joinpath(J.PATHS[:assets], "index", "code", "s1.jl"), String))</code></pre>", h) @test occursin("Then maybe <pre><code class=\"plaintext\">$(read(joinpath(J.PATHS[:assets], "index", "code", "output", "s1.out"), String))</code></pre>", h) @test occursin("Finally img: <img src=\"/assets/index/code/output/s1a.png\" alt=\"\"> done.", h) end @testset "Input MD" begin mkpath(joinpath(J.PATHS[:assets], "ccc")) fp = joinpath(J.PATHS[:assets], "ccc", "asset1.md") write(fp, "blah **blih**") st = raw""" Some string \textinput{ccc/asset1} """; @test isapproxstr(st |> conv, "<p>Some string blah <strong>blih</strong></p>") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
7094
@testset "figalt, fig" begin write(joinpath(J.PATHS[:assets], "testimg.png"), "png code") h = raw""" A figure: \figalt{fig 1}{/assets/testimg.png} \fig{/assets/testimg.png} \fig{/assets/testimg} Done. """ |> seval @test isapproxstr(h, """ <p>A figure: <img src=\"/assets/testimg.png\" alt=\"fig 1\"> <img src=\"/assets/testimg.png\" alt=\"\"> <img src=\"/assets/testimg.png\" alt=\"\"> Done.</p> """) p = mkpath(joinpath(J.PATHS[:assets], "output")) write(joinpath(p, "testimg_2.png"), "png code") h = raw""" Another figure: \figalt{fig blah "hello!"}{/assets/testimg_2.png} """ |> seval @test isapproxstr(h, """ <p>Another figure: <img src=\"/assets/output/testimg_2.png\" alt=\"fig blah $(Markdown.htmlesc("\"hello!\""))\"> </p> """) h = raw""" No fig: \fig{/assets/testimg_3.png} """ |> seval @test isapproxstr(h, """ <p>No fig: $(J.html_err("image matching '/assets/testimg_3.png' not found"))</p> """) end @testset "file" begin write(joinpath(J.PATHS[:assets], "blah.pdf"), "pdf code") h = raw""" View \file{the file}{/assets/blah.pdf} here. """ |> seval @test isapproxstr(h, """ <p>View <a href=\"/assets/blah.pdf\">the file</a> here.</p> """) h = raw""" View \file{no file}{/assets/blih.pdf} here. """ |> seval @test isapproxstr(h, """ <p>View $(J.html_err("file matching '/assets/blih.pdf' not found")) here.</p> """) end @testset "table" begin # # has header in source # testcsv = "h1,h2,h3\nstring1, 1.567, 0\n,,\n l i n e ,.158,99999999" write(joinpath(J.PATHS[:assets], "testcsv.csv"), testcsv) # no header specified h = raw""" A table: \tableinput{}{/assets/testcsv.csv} Done. """ |> seval # NOTE: in VERSION > 1.4, Markdown has alignment for tables: # -- https://github.com/JuliaLang/julia/pull/33849 if VERSION >= v"1.4.0-" shouldbe = """ <p>A table: <table> <tr><th align="right">h1</th><th align="right">h2</th><th align="right">h3</th></tr> <tr><td align="right">string1</td><td align="right">1.567</td><td align="right">0</td></tr> <tr><td align="right"></td><td align="right"></td><td align="right"></td></tr> <tr><td align="right">l i n e</td><td align="right">.158</td><td align="right">99999999</td></tr> </table> Done.</p>""" else shouldbe = """ <p>A table: <table> <tr><th>h1</th><th>h2</th><th>h3</th></tr> <tr><td>string1</td><td>1.567</td><td>0</td></tr> <tr><td></td><td></td><td></td></tr> <tr><td>l i n e</td><td>.158</td><td>99999999</td></tr> </table> Done.</p>""" end @test isapproxstr(h, shouldbe) # header specified h = raw""" A table: \tableinput{A,B,C}{/assets/testcsv.csv} Done. """ |> seval if VERSION >= v"1.4.0-" shouldbe = """ <p>A table: <table> <tr><th align="right">A</th><th align="right">B</th><th align="right">C</th></tr> <tr><td align="right">h1</td><td align="right">h2</td><td align="right">h3</td></tr> <tr><td align="right">string1</td><td align="right">1.567</td><td align="right">0</td></tr> <tr><td align="right"></td><td align="right"></td><td align="right"></td></tr> <tr><td align="right">l i n e</td><td align="right">.158</td><td align="right">99999999</td></tr> </table> Done.</p>""" else shouldbe = """ <p>A table: <table> <tr><th>A</th><th>B</th><th>C</th></tr> <tr><td>h1</td><td>h2</td><td>h3</td></tr> <tr><td>string1</td><td>1.567</td><td>0</td></tr> <tr><td></td><td></td><td></td></tr> <tr><td>l i n e</td><td>.158</td><td>99999999</td></tr> </table> Done.</p>""" end @test isapproxstr(h, shouldbe) # wrong header h = raw""" A table: \tableinput{,}{/assets/testcsv.csv} Done. """ |> seval shouldbe = """<p>A table: <p><span style=\"color:red;\">// header size (2) and number of columns (3) do not match //</span></p> Done.</p>""" @test isapproxstr(h, shouldbe) # # does not have header in source # testcsv = "string1, 1.567, 0\n,,\n l i n e ,.158,99999999" write(joinpath(J.PATHS[:assets], "testcsv.csv"), testcsv) # no header specified h = raw""" A table: \tableinput{}{/assets/testcsv.csv} Done. """ |> seval if VERSION >= v"1.4.0-" shouldbe = """ <p>A table: <table> <tr><th align="right">string1</th><th align="right">1.567</th><th align="right">0</th></tr> <tr><td align="right"></td><td align="right"></td><td align="right"></td></tr> <tr><td align="right">l i n e</td><td align="right">.158</td><td align="right">99999999</td></tr> </table> Done.</p>""" else shouldbe = """ <p>A table: <table> <tr><th>string1</th><th>1.567</th><th>0</th></tr> <tr><td></td><td></td><td></td></tr> <tr><td>l i n e</td><td>.158</td><td>99999999</td></tr> </table> Done.</p>""" end @test isapproxstr(h, shouldbe) # header specified h = raw""" A table: \tableinput{A,B,C}{/assets/testcsv.csv} Done. """ |> seval if VERSION >= v"1.4.0-" shouldbe = """ <p>A table: <table><tr><th align="right">A</th><th align="right">B</th><th align="right">C</th></tr><tr><td align="right">string1</td><td align="right">1.567</td><td align="right">0</td></tr><tr><td align="right"></td><td align="right"></td><td align="right"></td></tr><tr><td align="right">l i n e</td><td align="right">.158</td><td align="right">99999999</td></tr></table> Done.</p>""" else shouldbe = """<p>A table: <table><tr><th>A</th><th>B</th><th>C</th></tr> <tr><td>string1</td><td>1.567</td><td>0</td></tr> <tr><td></td><td></td><td></td></tr> <tr><td>l i n e</td><td>.158</td><td>99999999</td></tr></table> Done.</p>""" end @test isapproxstr(h, shouldbe) # wrong header h = raw""" A table: \tableinput{A,B}{/assets/testcsv.csv} Done. """ |> seval shouldbe = """<p>A table: <p><span style=\"color:red;\">// header size (2) and number of columns (3) do not match //</span></p> Done.</p>""" @test isapproxstr(h, shouldbe) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4330
@testset "Partial MD" begin st = raw""" \newcommand{\com}{HH} \newcommand{\comb}[1]{HH#1HH} A list * \com and \comb{blah} * $f$ is a function * a last element """ steps = explore_md_steps(st) lxdefs, tokens, braces, blocks, lxcoms = steps[:latex] @test length(braces) == 1 @test J.content(braces[1]) == "blah" @test length(blocks) == 1 @test blocks[1].name == :MATH_A @test J.content(blocks[1]) == "f" blocks2insert, = steps[:blocks2insert] inter_md, mblocks = J.form_inter_md(st, blocks2insert, lxdefs) @test inter_md == "\n\nA list\n* ##JDINSERT## and ##JDINSERT## \n* ##JDINSERT## is a function\n* a last element\n" inter_html = J.md2html(inter_md) @test inter_html == "<p>A list</p>\n<ul>\n<li><p>##JDINSERT## and ##JDINSERT## </p>\n</li>\n<li><p>##JDINSERT## is a function</p>\n</li>\n<li><p>a last element</p>\n</li>\n</ul>\n" end # index arithmetic over a string is a bit trickier when using all symbols # we can use `prevind` and `nextind` to make sure it works properly @testset "Inter Md 2" begin st = raw""" ~~~ this⊙ then ⊙ ⊙ and ~~~ finally ⊙⊙𝛴⊙ and ~~~ escape ∀⊙∀ ~~~ done """ inter_md, = explore_md_steps(st)[:inter_md] @test inter_md == " ##JDINSERT## \nfinally ⊙⊙𝛴⊙ and\n ##JDINSERT## \ndone\n" end @testset "Latex eqa" begin st = raw""" a\newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}}b@@d .@@ \eqa{\sin^2(x)+\cos^2(x) &=& 1} """ steps = explore_md_steps(st) lxdefs, tokens, braces, blocks, lxcoms = steps[:latex] blocks2insert, = steps[:blocks2insert] inter_md, mblocks = steps[:inter_md] @test inter_md == "ab ##JDINSERT## \n ##JDINSERT## \n" inter_html, = steps[:inter_html] lxcontext = J.LxContext(lxcoms, lxdefs, braces) @test J.convert_block(blocks2insert[1], lxcontext) == "<div class=\"d\">.</div>" @test isapproxstr(J.convert_block(blocks2insert[2], lxcontext), "\\[\\begin{array}{c} \\sin^2(x)+\\cos^2(x) &=& 1\\end{array}\\]") hstring = J.convert_inter_html(inter_html, blocks2insert, lxcontext) @test isapproxstr(hstring, raw""" <p> ab<div class="d">.</div> \[\begin{array}{c} \sin^2(x)+\cos^2(x) &=& 1 \end{array}\] </p>""") end @testset "MD>HTML" begin st = raw""" text A1 \newcommand{\com}{blah}text A2 \com and ~~~ escape B1 ~~~ \newcommand{\comb}[ 1]{\mathrm{#1}} text C1 $\comb{b}$ text C2 \newcommand{\comc}[ 2]{part1:#1 and part2:#2} then \comc{AA}{BB}. """ steps = explore_md_steps(st) lxdefs, tokens, braces, blocks, lxcoms = steps[:latex] blocks2insert, = steps[:blocks2insert] inter_md, mblocks = steps[:inter_md] inter_html, = steps[:inter_html] @test isapproxstr(inter_md, """ text A1 text A2 ##JDINSERT## and ##JDINSERT## text C1 ##JDINSERT## text C2 then ##JDINSERT## .""") @test isapproxstr(inter_html, """<p>text A1 text A2 ##JDINSERT## and ##JDINSERT## text C1 ##JDINSERT## text C2 then ##JDINSERT## .</p>""") lxcontext = J.LxContext(lxcoms, lxdefs, braces) hstring = J.convert_inter_html(inter_html, blocks2insert, lxcontext) @test isapproxstr(hstring, """ <p>text A1 text A2 blah and escape B1 text C1 \\(\\mathrm{ b}\\) text C2 then part1: AA and part2: BB.</p>""") end @testset "headers" begin J.JD_ENV[:CUR_PATH] = "index.md" h = """ # Title and then ## Subtitle cool! done """ |> seval @test isapproxstr(h, """ <h1 id="title"><a href="/index.html#title">Title</a></h1> and then <h2 id="subtitle_cool"><a href="/index.html#subtitle_cool">Subtitle cool&#33;</a></h2> done """) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3093
# this follows `markdown.jl` but spurred by bugs/issues function inter(st::String) steps = explore_md_steps(st) return steps[:inter_md].inter_md, steps[:inter_html].inter_html end @testset "issue163" begin st = raw"""A _B `C` D_ E""" imd, ih = inter(st) @test imd == "A _B ##JDINSERT## D_ E" @test ih == "<p>A <em>B ##JDINSERT## D</em> E</p>\n" st = raw"""A _`B` C D_ E""" imd, ih = inter(st) @test imd == "A _ ##JDINSERT## C D_ E" @test ih == "<p>A <em>##JDINSERT## C D</em> E</p>\n" st = raw"""A _B C `D`_ E""" imd, ih = inter(st) @test imd == "A _B C ##JDINSERT## _ E" @test ih == "<p>A <em>B C ##JDINSERT##</em> E</p>\n" st = raw"""A _`B` C `D`_ E""" imd, ih = inter(st) @test imd == "A _ ##JDINSERT## C ##JDINSERT## _ E" @test ih == "<p>A <em>##JDINSERT## C ##JDINSERT##</em> E</p>\n" end @testset "TOC" begin J.JD_ENV[:CUR_PATH] = "pages/ff/aa.md" h = raw""" \toc ## Hello `jd` #### weirdly nested ### Goodbye! ## Done done. """ |> seval @test isapproxstr(h, raw""" <div class="jd-toc"> <ol> <li> <a href="/pub/ff/aa.html#hello_jd">Hello <code>jd</code></a> <ol> <li><ol><li><a href="/pub/ff/aa.html#weirdly_nested">weirdly nested</a></li></ol></li> <li><a href="/pub/ff/aa.html#goodbye">Goodbye&#33;</a></li> </ol> </li> <li><a href="/pub/ff/aa.html#done">Done</a></li> </ol> </div> <h2 id="hello_jd"><a href="/pub/ff/aa.html#hello_jd">Hello <code>jd</code></a></h2> <h4 id="weirdly_nested"><a href="/pub/ff/aa.html#weirdly_nested">weirdly nested</a></h4> <h3 id="goodbye"><a href="/pub/ff/aa.html#goodbye">Goodbye&#33;</a></h3> <h2 id="done"><a href="/pub/ff/aa.html#done">Done</a></h2>done. """) end @testset "TOC" begin J.JD_ENV[:CUR_PATH] = "pages/ff/aa.md" s = raw""" @def mintoclevel = 2 @def maxtoclevel = 3 \toc # A ## B #### C ### D ## E ### F done. """ |> seval @test isapproxstr(s, raw""" <div class="jd-toc"> <ol> <li><a href="/pub/ff/aa.html#b">B</a> <ol> <li><a href="/pub/ff/aa.html#d">D</a></li> </ol> </li> <li><a href="/pub/ff/aa.html#e">E</a> <ol> <li><a href="/pub/ff/aa.html#f">F</a></li> </ol> </li> </ol> </div> <h1 id="a"><a href="/pub/ff/aa.html#a">A</a></h1> <h2 id="b"><a href="/pub/ff/aa.html#b">B</a></h2> <h4 id="c"><a href="/pub/ff/aa.html#c">C</a></h4> <h3 id="d"><a href="/pub/ff/aa.html#d">D</a></h3> <h2 id="e"><a href="/pub/ff/aa.html#e">E</a></h2> <h3 id="f"><a href="/pub/ff/aa.html#f">F</a></h3> done. """) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
10836
# NOTE: theses tests focus on speciall characters, html entities # escaping things etc. @testset "Backslashes" begin # see issue #205 st = raw""" Hello \ blah \ end and `B \ c` end and ``` A \ b ``` done """ steps = explore_md_steps(st) tokens, = steps[:tokenization] # the first two backspaces are detected @test tokens[1].ss == "\\" && tokens[1].name == :CHAR_BACKSPACE @test tokens[2].ss == "\\" && tokens[2].name == :CHAR_BACKSPACE # the third one also @test tokens[5].ss == "\\" && tokens[5].name == :CHAR_BACKSPACE sp_chars, = steps[:spchars] # there's only two tokens left which are the backspaces NOT in the code env sp_chars = J.find_special_chars(tokens) for i in 1:2 @test sp_chars[i] isa J.HTML_SPCH @test sp_chars[i].ss == "\\" @test sp_chars[i].r == "&#92;" end inter_html, = steps[:inter_html] @test isapproxstr(inter_html, "<p>Hello ##JDINSERT## blah ##JDINSERT## end and ##JDINSERT## end and ##JDINSERT## done</p>") @test isapproxstr(st |> seval, raw""" <p>Hello &#92; blah &#92; end and <code>B \ c</code> end and <pre><code class="language-julia">A \ b</code></pre> done</p> """) end @testset "Backslashes2" begin # see issue #205 st = raw""" Hello \ blah \ end and `B \ c` end \\ and ``` A \ b ``` done """ steps = explore_md_steps(st) tokens, = steps[:tokenization] @test tokens[7].name == :CHAR_LINEBREAK h = st |> seval @test isapproxstr(st |> seval, raw""" <p>Hello &#92; blah &#92; end and <code>B \ c</code> end <br/> and <pre><code class="language-julia">A \ b</code></pre> done</p> """) end @testset "Backtick" begin # see issue #205 st = raw"""Blah \` etc""" @test isapproxstr(st |> seval, "<p>Blah &#96; etc</p>") end @testset "HTMLEnts" begin # see issue #206 st = raw"""Blah &pi; etc""" @test isapproxstr(st |> seval, "<p>Blah &pi; etc</p>") # but ill-formed ones (either deliberately or not) will be parsed st = raw"""AT&T""" @test isapproxstr(st |> seval, "<p>AT&amp;T</p>") end @testset "DoubleTicks" begin # see issue #204 st = raw"""A `single` B""" steps = explore_md_steps(st) tokens = steps[:tokenization].tokens @test tokens[1].name == :CODE_SINGLE @test tokens[2].name == :CODE_SINGLE st = raw"""A ``double`` B""" steps = explore_md_steps(st) tokens = steps[:tokenization].tokens @test tokens[1].name == :CODE_DOUBLE @test tokens[2].name == :CODE_DOUBLE st = raw"""A `single` and ``double`` B""" steps = explore_md_steps(st) tokens = steps[:tokenization].tokens @test tokens[1].name == :CODE_SINGLE @test tokens[2].name == :CODE_SINGLE @test tokens[3].name == :CODE_DOUBLE @test tokens[4].name == :CODE_DOUBLE st = raw"""A `single` and ``double ` double`` B""" steps = explore_md_steps(st) blocks, tokens = steps[:ocblocks] @test blocks[1].name == :CODE_INLINE @test J.content(blocks[1]) == "double ` double" @test blocks[2].name == :CODE_INLINE @test J.content(blocks[2]) == "single" st = raw"""A `single` and ``double ` double`` and ``` triple ``` B""" steps = explore_md_steps(st) tokens = steps[:tokenization].tokens @test tokens[1].name == :CODE_SINGLE @test tokens[2].name == :CODE_SINGLE @test tokens[3].name == :CODE_DOUBLE @test tokens[4].name == :CODE_SINGLE @test tokens[5].name == :CODE_DOUBLE @test tokens[6].name == :CODE_TRIPLE @test tokens[7].name == :CODE_TRIPLE blocks, tokens = steps[:ocblocks] @test blocks[1].name == :CODE_BLOCK @test J.content(blocks[1]) == " triple " @test blocks[2].name == :CODE_INLINE @test blocks[3].name == :CODE_INLINE st = raw"""A `single` and ``double ` double`` and ``` triple `` triple``` and ```julia 1+1``` and `single again` done""" steps = explore_md_steps(st) blocks, _ = steps[:ocblocks] @test blocks[1].name == :CODE_BLOCK_LANG @test J.content(blocks[1]) == " 1+1" @test blocks[2].name == :CODE_BLOCK @test J.content(blocks[2]) == " triple `` triple" @test blocks[3].name == :CODE_INLINE @test J.content(blocks[3]) == "double ` double" @test blocks[4].name == :CODE_INLINE @test J.content(blocks[4]) == "single" end @testset "\\ and \`" begin # see issue 203 st = raw"""The `"Hello\n"` after the `readall` command is a returned value, whereas the `Hello` after the `run` command is printed output.""" st |> seval @test isapproxstr(st |> seval, raw""" <p>The <code>&quot;Hello\n&quot;</code> after the <code>readall</code> command is a returned value, whereas the <code>Hello</code> after the <code>run</code> command is printed output.</p>""") end @testset "i198" begin st = raw""" Essentially three things are imitated from LaTeX 1. you can introduce definitions using `\newcommand` 1. you can use hyper-references with `\eqref`, `\cite`, ... 1. you can show nice maths (via KaTeX) """ @test isapproxstr(st |> seval, raw""" <p>Essentially three things are imitated from LaTeX</p> <ol> <li><p>you can introduce definitions using <code>\newcommand</code></p></li> <li><p>you can use hyper-references with <code>\eqref</code>, <code>\cite</code>, ...</p></li> <li><p>you can show nice maths &#40;via KaTeX&#41;</p></li> </ol> """) end @testset "fixlinks" begin st = raw""" A [link] and B [link 2] and C [Python][] and D [a link][1] and blah [link]: https://julialang.org/ [link 2]: https://www.mozilla.org/ [Python]: https://www.python.org/ [1]: http://slashdot.org/ end """ @test isapproxstr(st |> seval, """ <p> A <a href="https://julialang.org/">link</a> and B <a href="https://www.mozilla.org/">link 2</a> and C <a href="https://www.python.org/">Python</a> and D <a href="http://slashdot.org/">a link</a> and blah end</p>""") end @testset "fixlinks2" begin st = raw""" A [link] and B ![link][id] and blah [link]: https://julialang.org/ [id]: ./path/to/img.png """ @test isapproxstr(st |> seval, """ <p> A <a href="https://julialang.org/">link</a> and B <img src="./path/to/img.png" alt="id"> and blah </p>""") end @testset "fixlinks3" begin st = raw""" A [link] and B [unknown] and C ![link][id] and D [link]: https://julialang.org/ [id]: ./path/to/img.png [not]: https://www.mozilla.org/ """ @test isapproxstr(st |> seval, """ <p> A <a href="https://julialang.org/">link</a> and B &#91;unknown&#93; and C <img src="./path/to/img.png" alt="id"> and D </p>""") end @testset "IndCode" begin # issue 207 st = raw""" A a = 1+1 if a > 1 @show a end b = 2 @show a+b end """ @test isapproxstr(st |> seval, raw""" <p> A <pre><code class="language-julia">a = 1+1 if a > 1 @show a end b = 2 @show a+b</code></pre> end </p>""") st = raw""" A `single` and ```python blah``` and a = 1+1 then * blah + blih + bloh end """ @test isapproxstr(st |> seval, raw""" <p> A <code>single</code> and <pre><code class="language-python">blah</code></pre> and<pre><code class="language-julia">a = 1+1</code></pre> then </p> <ul> <li><p>blah</p> <ul> <li><p>blih</p></li> <li><p>bloh</p></li> </ul> </li> </ul> <p>end</p> """) st = raw""" A function foo() return 2 end function bar() return 3 end B function baz() return 5 end C """ isapproxstr(st |> seval, raw""" <p>A <pre><code class="language-julia">function foo() return 2 end function bar() return 3 end</code></pre> B <pre><code class="language-julia">function baz() return 5 end</code></pre> C</p> """) end @testset "More ``" begin st = raw""" A ``blah``. """ @test isapproxstr(st |> seval, """<p>A <code>blah</code>.</p>""") end @testset "Issue 266" begin s = """Blah [`hello`] and later [`hello`]: https://github.com/cormullion/ """ |> jd2html_td @test isapproxstr(s, """ <p>Blah <a href="https://github.com/cormullion/"><code>hello</code></a> and later </p> """) end @testset "TOML lang" begin s = raw""" blah ```TOML socrates ``` end """ @test isapproxstr(s |> jd2html_td, """ <p>blah <pre><code class=\"language-TOML\">socrates</code></pre> end</p>""") s = raw""" blah ```julia-repl socrates ``` end """ @test isapproxstr(s |> jd2html_td, """ <p>blah <pre><code class=\"language-julia-repl\">socrates</code></pre> end</p>""") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1666
@testset "latex-wspace" begin s = raw""" \newcommand{\hello}{hello} A\hello B """ |> jd2html_td @test isapproxstr(s, "<p>Ahello B</p>") s = raw""" \newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}} A\eqa{B}C \eqa{ D }E """ |> jd2html_td @test isapproxstr(s, raw""" <p> A\[\begin{array}{c} B\end{array}\]C \[\begin{array}{c} D\end{array}\]E </p>""") s = raw""" \newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}} \eqa{A\\ D }E """ |> jd2html_td @test isapproxstr(s, raw""" \[\begin{array}{c} A\\ D\end{array}\]E """) s = raw""" @def indented_code = false \newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}} \eqa{A\\ D}E""" |> jd2html_td @test isapproxstr(s, raw""" \[\begin{array}{c} A\\ D\end{array}\]E """) end @testset "latex-wspmath" begin s = raw""" \newcommand{\esp}{\quad\!\!} $$A\esp=B$$ """ |> jd2html_td @test isapproxstr(s, raw"\[A\quad\!\!=B\]") end @testset "code-wspace" begin s = raw""" A ``` C B E D ``` """ |> jd2html_td @test isapproxstr(s, """<p>A <pre><code class="language-julia">C\n B\n E\nD</code></pre></p>\n""") end @testset "auto html esc" begin s = raw""" Blah ```html <div class="foo">Blah</div> ``` End """ |> jd2html_td @test isapproxstr(s, """ <p> Blah <pre><code class="language-html">&lt;div class&#61;&quot;foo&quot;&gt;Blah&lt;/div&gt;</code></pre> End</p>""") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2496
@testset "Conv-lx" begin cd(td) # Exception instead of ArgumentError as may fail with system error @test_throws Exception J.check_input_rpath("aldjfk") end @testset "Conv-html" begin @test_throws J.HTMLFunctionError J.convert_html("{{fill bb cc}}", J.PageVars()) @test_throws J.HTMLFunctionError J.convert_html("{{insert bb cc}}", J.PageVars()) @test_throws J.HTMLFunctionError J.convert_html("{{href aa}}", J.PageVars()) @test (@test_logs (:warn, "Unknown dictionary name aa in {{href ...}}. Ignoring") J.convert_html("{{href aa bb}}", J.PageVars())) == "<b>??</b>" @test_throws J.HTMLBlockError J.convert_html("{{if asdf}}{{end}}", J.PageVars()) @test_throws J.HTMLBlockError J.convert_html("{{if asdf}}", J.PageVars()) @test_throws J.HTMLBlockError J.convert_html("{{isdef asdf}}", J.PageVars()) @test_throws J.HTMLBlockError J.convert_html("{{ispage asdf}}", J.PageVars()) end @testset "Conv-md" begin s = """ @def blah """ @test (@test_logs (:warn, "Found delimiters for an @def environment but it didn't have the right @def var = ... format. Verify (ignoring for now).") (s |> jd2html_td)) == "" s = """ Blah [^1]: hello """ |> jd2html_td @test isapproxstr(s, "<p>Blah </p>") end @testset "Judoc" begin cd(td); mkpath("foo"); cd("foo"); @test_throws ArgumentError serve(single=true) cd(td) end @testset "RSS" begin J.set_var!(J.GLOBAL_PAGE_VARS, "website_descr", "") J.RSS_DICT["hello"] = J.RSSItem("","","","","","","",Date(1)) @test (@test_logs (:warn, """ I found RSS items but the RSS feed is not properly described: at least one of the following variables has not been defined in your config.md: `website_title`, `website_descr`, `website_url`. The feed will not be (re)generated.""") J.rss_generator()) === nothing end @testset "parser-lx" begin s = raw""" \newcommand{hello}{hello} """ @test_throws J.LxDefError (s |> jd2html) s = raw""" \foo """ @test_throws J.LxComError (s |> jd2html) s = raw""" \newcommand{\foo}[2]{hello #1 #2} \foo{a} {} """ @test_throws J.LxComError (s |> jd2html) end @testset "ocblocks" begin s = raw""" @@foo """ @test_throws J.OCBlockError (s |> jd2html) end @testset "tofrom" begin s = "jμΛΙα" @test J.from(s) == 1 @test J.to(s) == lastindex(s) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1646
s = """Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini. Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke. """ @testset "context" begin mess = J.context(s, 101) @test s[101] == 't' # println(mess) @test mess == "Context:\n\t...ikon amaranth tatsoi tomatillo melon azuki ... (near line 1)\n ^---\n" mess = J.context(s, 211) @test s[211] == 't' # println(mess) @test mess == "Context:\n\t...ey shallot courgette tatsoi pea sprouts fav... (near line 2)\n ^---\n" mess = J.context(s, 10) # println(mess) @test mess == "Context:\n\tVeggies es bonus vobis, proinde... (near line 1)\n ^---\n" mess = J.context(s, 880) # println(mess) @test mess == "Context:\n\t... potato bell pepper artichoke. (near line 5)\n ^---\n" end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
5172
@testset "∫ newcom" begin st = raw""" \newcommand{ \coma }[ 1]{hello #1} \newcommand{ \comb} [2 ]{\coma{#1}, goodbye #1, #2!} Then \comb{auth1}{auth2}. """ @test isapproxstr(st |> conv, """<p> Then hello auth1, goodbye auth1, auth2$(Markdown.htmlesc("!")). </p>""") end @testset "∫ math" begin st = raw""" \newcommand{\E}[1]{\mathbb E\left[#1\right]} \newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}} \newcommand{\R}{\mathbb R} Then something like \eqa{ \E{f(X)} \in \R &\text{if}& f:\R\maptso\R } """ @test isapproxstr(st |> conv, """<p> Then something like \\[\\begin{array}{c} \\mathbb E\\left[ f(X)\\right] \\in \\mathbb R &\\text{if}& f:\\mathbb R\\maptso\\mathbb R \\end{array}\\] </p>""") end @testset "∫ re-com" begin # see #36 st = raw""" \newcommand{\com}[1]{⭒!#1⭒} \com{A} \newcommand{\com}[1]{◲!#1◲} \com{A} """ steps = st |> explore_md_steps @test steps[:inter_md].inter_md == "\n ##JDINSERT## \n\n ##JDINSERT## \n" @test st |> conv == "⭒A⭒\n◲A◲" end @testset "∫ div" begin # see #74 st = raw""" Etc and `~~~` but hey. @@dd but `x` and `y`? @@ done """ @test isapproxstr(st |> conv, """<p> Etc and <code>~~~</code> but hey. <div class=\"dd\">but <code>x</code> and <code>y</code>? </div> done </p>""") end @testset "∫ code-l" begin st = raw""" Some code ```julia struct P x::Real end ``` done """ @test isapproxstr(st |> conv, """<p> Some code <pre><code class=\"language-julia\"> struct P x::Real end </code></pre> done</p>""") end @testset "∫ math-br" begin # see #73 st = raw""" \newcommand{\R}{\mathbb R} $$ \min_{x\in \R^n} \quad f(x)+i_C(x). $$ """ @test isapproxstr(st |> conv, """\\[ \\min_{x\\in \\mathbb R^n} \\quad f(x)+i_C(x). \\]""") end @testset "∫ insert" begin # see also #65 st = raw""" \newcommand{\com}[1]{⭒!#1⭒} abc\com{A}\com{B}def. """ @test st |> conv == "<p>abc⭒A⭒⭒B⭒def.</p>\n" st = raw""" \newcommand{\com}[1]{⭒!#1⭒} abc \com{A}\com{B} def. """ @test st |> conv == "<p>abc</p>\n⭒A⭒⭒B⭒\n<p>def.</p>\n" st = raw""" \newcommand{\com}[1]{⭒!#1⭒} abc \com{A} def. """ @test st |> conv == "<p>abc</p>\n⭒A⭒\n<p>def.</p>\n" st = raw""" \newcommand{\com}[1]{†!#1†} blah \com{a} * \com{aaa} tt * ss \com{bbb} """ @test isapproxstr(st |> conv, """<p>blah †a† <ul> <li><p>†aaa† tt</p></li> <li><p>ss †bbb†</p></li> </ul>""") end @testset "∫ br-rge" begin # see #70 st = raw""" \newcommand{\scal}[1]{\left\langle#1\right\rangle} \newcommand{\E}{\mathbb E} exhibit A $\scal{\mu, \nu} = \E[X]$ exhibit B $\E[X] = \scal{\mu, \nu}$ end.""" @test isapproxstr(st |> conv, """<p>exhibit A \\(\\left\\langle \\mu, \\nu\\right\\rangle = \\mathbb E[X]\\) exhibit B \\(\\mathbb E[X] = \\left\\langle \\mu, \\nu\\right\\rangle\\) end.</p>""") end @testset "∫ cond" begin stv(var1, var2) = """ @def var1 = $var1 @def var2 = $var2 start ~~~ {{ if var1 }} targ1 {{ else if var2 }} targ2 {{ else }} targ3 {{ end }} ~~~ done """ @test stv(true, true) |> conv == "<p>start \n targ1 \n done</p>\n" @test stv(false, true) |> conv == "<p>start \n targ2 \n done</p>\n" @test stv(false, false) |> conv == "<p>start \n targ3 \n done</p>\n" end @testset "∫ recurs" begin # see #97 st = raw""" | A | B | | :---: | :---: | | C | D | """ if VERSION >= v"1.4.0-" @test isapproxstr(st |> conv, """<table><tr><th align="center">A</th><th align="center">B</th></tr><tr><td align="center">C</td><td align="center">D</td></tr></table>""") else @test isapproxstr(st |> conv, """<table> <tr><th>A</th><th>B</th></tr> <tr><td>C</td><td>D</td></tr> </table>""") end @test J.convert_md(st, isrecursive=true) |> chtml == st |> conv st = raw""" @@emptydiv @@emptycore @@ @@ """ st |> conv == "<div class=\"emptydiv\"><div class=\"emptycore\"></div>\n</div>\n" end @testset "∫ label" begin st = raw""" Blah blah ## some title and then an anchor here \label{anchor} done. """ J.def_GLOBAL_LXDEFS!() r = st |> conv @test occursin("here <a id=\"anchor\"></a> done.", r) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3783
# see issue #151 @testset "HTML escape" begin st = read(joinpath(D, "151.md"), String) @test isapproxstr(st |> conv, """<pre><code class=\"language-julia\"> add OhMyREPL#master </code></pre> <p>AAA</p> <pre><code class=\"language-julia\"> \"\"\" bar(x[, y]) BBB # Examples ```jldoctest D ``` \"\"\" function bar(x, y) ... end </code></pre> <p>For complex functions with multiple arguments use a argument list, also if there are many keyword arguments use <code>&lt;keyword arguments&gt;</code>:</p> <pre><code class=\"language-julia\"> \"\"\" matdiag(diag, nr, nc; &ltkeyword arguments&gt) Create Matrix with number `vdiag` on the super- or subdiagonals and `vndiag` in the rest. # Arguments - `diag::Number`: `Number` to write into created super- or subdiagonal # Examples ```jldoctest julia> matdiag(true, 5, 5, sr=2, ec=3) ``` \"\"\" function matdiag(diag::Number, nr::Integer, nc::Integer;) ... end </code></pre>""") end # see issue #182 @testset "Code blocks" begin st = read(joinpath(D, "182.md"), String) @test isapproxstr(st |> conv, """ <p>Code block:</p> The <em>average</em> temperature is <strong>19.5°C</strong>. <p>The end.</p> """) end @testset "Table" begin J.JD_ENV[:CUR_PATH] = "pages/pg1.html" st = """ A ### Title No. | Graph | Vertices | Edges :---: | :---------: | :------------: | :-----------------: 1 | Twitter Social Circles | 81,306 | 1,342,310 2 | Astro-Physics Collaboration | 17,903 | 197,031 3 | Facebook Social Circles | 4,039 | 88,234 C """ if VERSION >= v"1.4.0-" @test isapproxstr(st |> seval, raw"""<p>A</p> <h3 id="title"><a href="/pub/pg1.html#title">Title</a></h3> <table><tr><th align="center">No.</th><th align="center">Graph</th><th align="center">Vertices</th><th align="center">Edges</th></tr><tr><td align="center">1</td><td align="center">Twitter Social Circles</td><td align="center">81,306</td><td align="center">1,342,310</td></tr><tr><td align="center">2</td><td align="center">Astro-Physics Collaboration</td><td align="center">17,903</td><td align="center">197,031</td></tr><tr><td align="center">3</td><td align="center">Facebook Social Circles</td><td align="center">4,039</td><td align="center">88,234</td></tr></table> <p>C</p>""") else @test isapproxstr(st |> seval, raw""" <p>A</p> <h3 id="title"><a href="/pub/pg1.html#title">Title</a></h3> <table> <tr> <th>No.</th><th>Graph</th><th>Vertices</th><th>Edges</th> </tr> <tr> <td>1</td><td>Twitter Social Circles</td><td>81,306</td><td>1,342,310</td> </tr> <tr> <td>2</td><td>Astro-Physics Collaboration</td><td>17,903</td><td>197,031</td> </tr> <tr> <td>3</td><td>Facebook Social Circles</td><td>4,039</td><td>88,234</td> </tr> </table> <p>C</p> """) end end @testset "Auto title" begin # if no title is set, then the first header is used s = raw""" # AAA etc ~~~{{fill title}}~~~ """ |> jd2html_td @test isapproxstr(s, raw"""<h1 id="aaa"><a href="/index.html#aaa">AAA</a></h1> etc AAA""") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
5422
# This set of tests is specifically for the ordering # of operations, when code blocks are eval-ed or re-eval-ed @testset "EvalOrder" begin flush_td(); set_globals() Random.seed!(0) # seed for extra testing of when code is ran # Generate random numbers in a sequence then we'll check # things are done in the same sequence on the page a, b, c, d, e = randn(5) Random.seed!(0) # Create a page "foo.md" which we'll use and abuse foo = raw""" @def hascode = true ```julia:ex println(randn()) ``` \output{ex} """ # FIRST PASS --> EVAL h = foo |> jd2html_td @test isapproxstr(h, """ <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$a</code></pre> """) # TEXT MODIFICATION + IN SCOPE --> NO REEVAL foo *= "etc" h = foo |> jd2html_td @test isapproxstr(h, """ <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$a</code></pre> etc """) # CODE ADDITION + IN SCOPE --> NO REEVAL OF FIRST BLOCK foo *= raw""" ```julia:ex2 println(randn()) ``` \output{ex2} ```julia:ex3 println(randn()) ``` \output{ex3} """ h = foo |> jd2html_td @test isapproxstr(h, """ <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$a</code></pre> etc <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$b</code></pre> <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$c</code></pre> """) # CODE MODIFICATION + IN SCOPE --> REEVAL OF BLOCK AND AFTER foo = raw""" @def hascode = true ```julia:ex println(randn()) ``` \output{ex} ```julia:ex2 # modif println(randn()) ``` \output{ex2} ```julia:ex3 println(randn()) ``` \output{ex3} """ h = foo |> jd2html_td @test isapproxstr(h, """ <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$a</code></pre> <pre><code class="language-julia"># modif println(randn())</code></pre> <pre><code class=\"plaintext\">$d</code></pre> <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$e</code></pre> """) # FROZEN CODE --> WILL USE CODE FROM BEFORE even though we changed it (no re-eval) foo = raw""" @def hascode = true @def freezecode = true ```julia:ex # modif println(randn()) ``` \output{ex} ```julia:ex2 println(randn()) ``` \output{ex2} ```julia:ex3 println(randn()) ``` \output{ex3} """ h = foo |> jd2html_td @test isapproxstr(h, """ <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$a</code></pre> <pre><code class="language-julia"># modif println(randn())</code></pre> <pre><code class=\"plaintext\">$d</code></pre> <pre><code class="language-julia">println(randn())</code></pre> <pre><code class=\"plaintext\">$e</code></pre> """) end @testset "EvalOrder2" begin flush_td(); set_globals() # Inserting new code block h, vars = raw""" @def hascode = true ```julia:ex1 a = 5 println(a) ``` \output{ex1} ```julia:ex2 a += 3 println(a) ``` \output{ex2} """ |> jd2html_tdv @test isapproxstr(h, """ <pre><code class="language-julia">a = 5 println(a)</code></pre> <pre><code class=\"plaintext\">5</code></pre> <pre><code class="language-julia">a += 3 println(a)</code></pre> <pre><code class=\"plaintext\">8</code></pre> """) @test isapproxstr(J.str(vars["jd_code"].first), """ a = 5 println(a) a += 3 println(a)""") h, vars = raw""" @def hascode = true @def reeval = true ```julia:ex1 a = 5 println(a) ``` \output{ex1} ```julia:ex1b a += 1 println(a) ``` \output{ex1b} ```julia:ex2 a += 3 println(a) ``` \output{ex2} """ |> jd2html_tdv @test isapproxstr(h, """ <pre><code class="language-julia">a = 5 println(a)</code></pre> <pre><code class=\"plaintext\">5</code></pre> <pre><code class="language-julia">a += 1 println(a)</code></pre> <pre><code class=\"plaintext\">6</code></pre> <pre><code class="language-julia">a += 3 println(a)</code></pre> <pre><code class=\"plaintext\">9</code></pre> """) @test isapproxstr(J.str(vars["jd_code"].first), """ a = 5 println(a) a += 1 println(a) a += 3 println(a)""") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
230
# See https://github.com/tlienart/JuDoc.jl/issues/326 @testset "Issue 326" begin h1 = "<div class=\"hello\">Blah</div>" h1e = Markdown.htmlesc(h1) @test J.is_html_escaped(h1e) @test J.html_unescape(h1e) == h1 end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2786
# Following multiple issues over time with ordering, this attempts to have # bunch of test cases where it's clear in what order things are tokenized / found @testset "Ordering-1" begin st = raw""" A <!-- C indent D --> B """ steps = st |> explore_md_steps blocks, = steps[:ocblocks] @test length(blocks) == 1 @test blocks[1].name == :COMMENT @test isapproxstr(st |> seval, """ <p>A</p> <p>B</p> """) end @testset "Ordering-2" begin st = raw""" A \begin{eqnarray} 1 + 1 &=& 2 \end{eqnarray} B """ steps = st |> explore_md_steps blocks, = steps[:ocblocks] @test length(blocks) == 1 @test blocks[1].name == :MATH_EQA @test isapproxstr(st |> seval, raw""" <p>A \[\begin{array}{c} 1 + 1 &=& 2 \end{array}\] B</p>""") end @testset "Ordering-3" begin st = raw""" A \begin{eqnarray} 1 + 1 &=& 2 \end{eqnarray} B <!-- blah \begin{eqnarray} 1 + 1 &=& 2 \end{eqnarray} [blah](hello) --> C """ steps = st |> explore_md_steps blocks, = steps[:ocblocks] @test length(blocks) == 2 @test blocks[1].name == :COMMENT @test blocks[2].name == :MATH_EQA @test isapproxstr(st |> seval, raw""" <p>A \[\begin{array}{c} 1 + 1 &=& 2 \end{array}\] B</p> <p>C</p>""") end @testset "Ordering-4" begin st = raw""" \newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}} A \eqa{ B } C """ steps = st |> explore_md_steps blocks, = steps[:ocblocks] @test length(blocks) == 3 @test all(getproperty.(blocks, :name) .== :LXB) @test isapproxstr(st |> seval, raw""" <p>A \[\begin{array}{c} B \end{array}\] C</p>""") end @testset "Ordering-5" begin st = raw""" A [❗️_ongoing_ ] C """ @test isapproxstr(st |> seval, raw""" <p>A &#91;❗️<em>ongoing</em> &#93; C</p> """) st = raw""" 0 * A * B [❗️_ongoing_ ]<!--(ongoing) ref: >> url --> C """ @test isapproxstr(st |> seval, raw""" <p>0</p> <ul> <li><p>A</p> <ul> <li><p>B &#91;❗️<em>ongoing</em> &#93;</p></li> </ul> </li> </ul> <p>C</p> """) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3344
@testset "Gen&Opt" begin isdir("basic") && rm("basic", recursive=true, force=true) newsite("basic") serve(single=true) # --------------- @test all(isdir, ("assets", "css", "libs", "pub", "src")) @test all(isfile, ("index.html", map(e->joinpath("pub", "menu$e.html"), 1:3)..., map(e->joinpath("css", e), ("basic.css", "judoc.css"))..., ) ) # --------------- if JuDoc.JD_CAN_MINIFY presize1 = stat(joinpath("css", "basic.css")).size presize2 = stat("index.html").size optimize(prerender=false) @test stat(joinpath("css", "basic.css")).size < presize1 @test stat("index.html").size < presize2 end # --------------- # verify all links JuDoc.verify_links() # --------------- # change the prepath index = read("index.html", String) @test occursin("=\"/css/basic.css", index) @test occursin("=\"/css/judoc.css", index) @test occursin("=\"/libs/highlight/github.min.css", index) @test occursin("=\"/libs/katex/katex.min.css", index) optimize(minify=false, prerender=false, prepath="prependme") index = read("index.html", String) @test occursin("=\"/prependme/css/basic.css", index) @test occursin("=\"/prependme/css/judoc.css", index) @test occursin("=\"/prependme/libs/highlight/github.min.css", index) @test occursin("=\"/prependme/libs/katex/katex.min.css", index) end if J.JD_CAN_PRERENDER; @testset "prerender" begin @testset "katex" begin hs = raw""" <!doctype html> <html lang=en> <meta charset=UTF-8> <div class=jd-content> <p>range is \(10\sqrt{3}\)–\(20\sqrt{2}\) <!-- non-ascii en dash --></p> <p>Consider an invertible matrix \(M\) made of blocks \(A\), \(B\), \(C\) and \(D\) with</p> \[ M \quad\!\! =\quad\!\! \begin{pmatrix} A & B \\ C & D \end{pmatrix} \] </div> """ jskx = J.js_prerender_katex(hs) # conversion of the non-ascii endash (inline) @test occursin("""–<span class=\"katex\">""", jskx) # conversion of `\(M\)` (inline) @test occursin("""<span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>M</mi></mrow>""", jskx) # conversion of the equation (display) @test occursin("""<span class=\"katex-display\"><span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>M</mi>""", jskx) end if J.JD_CAN_HIGHLIGHT; @testset "highlight" begin hs = raw""" <!doctype html> <html lang=en> <meta charset=UTF-8> <div class=jd-content> <h1>Title</h1> <p>Blah</p> <pre><code class=language-julia >using Test # Woodbury formula b = 2 println("hello $b") </code></pre> </div> """ jshl = J.js_prerender_highlight(hs) # conversion of the code @test occursin("""<pre><code class="julia hljs"><span class="hljs-keyword">using</span>""", jshl) @test occursin(raw"""<span class="hljs-string">"hello <span class="hljs-variable">$b</span>"</span>""", jshl) end; end # if can highlight end; end # if can prerender
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
736
# simple test that things get created @testset "RSS gen" begin f = joinpath(p, "basic", "feed.xml") @test isfile(f) fc = prod(readlines(f, keep=true)) @test occursin(raw"""<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">""", fc) @test occursin(raw"""<title>JuDoc Template</title>""", fc) @test occursin(raw"""<description><![CDATA[Example website using JuDoc ]]></description>""", fc) @test !occursin(raw"""<author>""", fc) @test occursin(raw"""<link>https://tlienart.github.io/JuDocTemplates.jl/pub/menu1.html</link>""", fc) @test occursin(raw"""<description><![CDATA[A short description of the page which would serve as <strong>blurb</strong> in a <code>RSS</code> feed;""", fc) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3288
scripts = joinpath(J.PATHS[:folder], "literate-scripts") cd(td); J.set_paths!(); mkpath(scripts) @testset "Literate-0" begin @test_throws ErrorException literate_folder("foo/") litpath = literate_folder("literate-scripts/") @test litpath == joinpath(J.PATHS[:folder], "literate-scripts/") end @testset "Literate-a" begin # Post processing: numbering of julia blocks s = raw""" A ```julia B ``` C ```julia D ``` """ @test J.literate_post_process(s) == """ <!--This file was generated, do not modify it.--> A ```julia:ex1 B ``` C ```julia:ex2 D ``` """ end @testset "Literate-b" begin # Literate to JuDoc s = raw""" # # Rational numbers # # In julia rational numbers can be constructed with the `//` operator. # Lets define two rational numbers, `x` and `y`: ## Define variable x and y x = 1//3 y = 2//5 # When adding `x` and `y` together we obtain a new rational number: z = x + y """ path = joinpath(scripts, "tutorial.jl") write(path, s) opath, = J.literate_to_judoc("/literate-scripts/tutorial") @test endswith(opath, joinpath(J.PATHS[:assets], "literate", "tutorial.md")) out = read(opath, String) @test out == """ <!--This file was generated, do not modify it.--> # Rational numbers In julia rational numbers can be constructed with the `//` operator. Lets define two rational numbers, `x` and `y`: ```julia:ex1 # Define variable x and y x = 1//3 y = 2//5 ``` When adding `x` and `y` together we obtain a new rational number: ```julia:ex2 z = x + y ``` """ # Use of `\literate` command h = raw""" @def hascode = true @def showall = true @def reeval = true \literate{/literate-scripts/tutorial.jl} """ |> jd2html_td @test isapproxstr(h, """ <h1 id="rational_numbers"><a href="/index.html#rational_numbers">Rational numbers</a></h1> <p>In julia rational numbers can be constructed with the <code>//</code> operator. Lets define two rational numbers, <code>x</code> and <code>y</code>:</p> <pre><code class="language-julia"># Define variable x and y x = 1//3 y = 2//5</code></pre> <div class="code_output"><pre><code class=\"plaintext\">2//5</code></pre></div> <p>When adding <code>x</code> and <code>y</code> together we obtain a new rational number:</p> <pre><code class="language-julia">z = x + y</code></pre> <div class="code_output"><pre><code class=\"plaintext\">11//15</code></pre></div> """) end @testset "Literate-c" begin s = raw""" \literate{foo} """ @test_throws ErrorException (s |> jd2html_td) s = raw""" \literate{/foo} """ @test @test_logs (:warn, "File not found when trying to convert a literate file ($(joinpath(J.PATHS[:folder], "foo.jl"))).") (s |> jd2html_td) == """<p><span style="color:red;">// Literate file matching '/foo' not found. //</span></p></p>\n""" end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1297
# additional tests for config foofig(p, s) = (write(joinpath(p, "src", "config.md"), s); J.process_config()) @testset "config" begin p = joinpath(D, "..", "__tst_config") isdir(p) && rm(p; recursive=true, force=true) mkdir(p); cd(p); J.FOLDER_PATH[] = pwd() J.set_paths!() mkdir(joinpath(p, "src")) # ================================ # asssignments go to GLOBAL foofig(p, raw""" @def var = 5 """) @test haskey(J.GLOBAL_PAGE_VARS, "var") @test J.GLOBAL_PAGE_VARS["var"][1] == 5 # lxdefs go to GLOBAL foofig(p, raw""" \newcommand{\hello}{goodbye} """) @test haskey(J.GLOBAL_LXDEFS, "\\hello") @test J.GLOBAL_LXDEFS["\\hello"].def == "goodbye" # combination of lxdefs foofig(p, raw""" \newcommand{\hello}{goodbye} \newcommand{\hellob}{\hello} \newcommand{\helloc}{\hellob} """) @test J.GLOBAL_LXDEFS["\\hello"].from < J.GLOBAL_LXDEFS["\\hello"].to < J.GLOBAL_LXDEFS["\\hellob"].from < J.GLOBAL_LXDEFS["\\hellob"].to < J.GLOBAL_LXDEFS["\\helloc"].from < J.GLOBAL_LXDEFS["\\helloc"].to @test jd2html(raw"""\helloc"""; dir=p, internal=true) == "goodbye" # ================================ # go back and cleanup cd(R); rm(p; recursive=true, force=true) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1808
@testset "RSSItem" begin rss = J.RSSItem( "title", "www.link.com", "description", "[email protected]", "category", "www.comments.com", "enclosure", Date(2012,12,12)) @test rss.title == "title" @test rss.link == "www.link.com" @test rss.description == "description" @test rss.author == "[email protected]" @test rss.category == "category" @test rss.comments == "www.comments.com" @test rss.enclosure == "enclosure" @test rss.pubDate == Date(2012,12,12) end @testset "RSSbasics" begin empty!(J.RSS_DICT) J.JD_ENV[:CUR_PATH] = "hey/ho.md" J.set_var!(J.GLOBAL_PAGE_VARS, "website_title", "Website title") J.set_var!(J.GLOBAL_PAGE_VARS, "website_descr", "Website descr") J.set_var!(J.GLOBAL_PAGE_VARS, "website_url", "https://github.com/tlienart/JuDoc.jl/") jdv = merge(J.GLOBAL_PAGE_VARS, copy(J.LOCAL_PAGE_VARS)) J.set_var!(jdv, "rss_title", "title") J.set_var!(jdv, "rss", "A **description** done.") J.set_var!(jdv, "rss_author", "[email protected]") item = J.add_rss_item(jdv) @test item.title == "title" @test item.description == "A <strong>description</strong> done.\n" @test item.author == "[email protected]" # unchanged bc all three fallbacks lead to Data(1) @test item.pubDate == Date(1) J.set_var!(jdv, "rss_title", "") @test @test_logs (:warn, "Found an RSS description but no title for page /hey/ho.html.") J.add_rss_item(jdv).title == "" @test J.RSS_DICT["/hey/ho.html"].description == item.description # Generation J.PATHS[:folder] = td J.rss_generator() feed = joinpath(J.PATHS[:folder], "feed.xml") @test isfile(feed) fc = prod(readlines(feed, keep=true)) @test occursin("<description><![CDATA[A <strong>description</strong> done.", fc) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4307
temp_config = joinpath(JuDoc.PATHS[:src], "config.md") write(temp_config, "@def author = \"Stefan Zweig\"\n") temp_index = joinpath(JuDoc.PATHS[:src], "index.md") write(temp_index, "blah blah") temp_index2 = joinpath(JuDoc.PATHS[:src], "index.html") write(temp_index2, "blah blih") temp_blah = joinpath(JuDoc.PATHS[:src_pages], "blah.md") write(temp_blah, "blah blah") temp_html = joinpath(JuDoc.PATHS[:src_pages], "temp.html") write(temp_html, "some html") temp_rnd = joinpath(JuDoc.PATHS[:src_pages], "temp.rnd") write(temp_rnd, "some random") temp_css = joinpath(JuDoc.PATHS[:src_css], "temp.css") write(temp_css, "some css") JuDoc.process_config() @testset "Prep outdir" begin JuDoc.prepare_output_dir() @test isdir(JuDoc.PATHS[:pub]) @test isdir(JuDoc.PATHS[:css]) temp_out = joinpath(JuDoc.PATHS[:pub], "tmp.html") write(temp_out, "This is a test page.\n") # clear is false => file should remain JuDoc.prepare_output_dir(false) @test isfile(temp_out) # clear is true => file should go JuDoc.prepare_output_dir(true) @test !isfile(temp_out) end @testset "Scan dir" begin println("🐝 Testing file tracking...:") # it also tests add_if_new_file and last md_files = Dict{Pair{String, String}, Float64}() html_files = empty(md_files) other_files = empty(md_files) infra_files = empty(md_files) literate_files = empty(md_files) watched_files = [md_files, html_files, other_files, infra_files, literate_files] JuDoc.scan_input_dir!(md_files, html_files, other_files, infra_files, literate_files, true) @test haskey(md_files, JuDoc.PATHS[:src_pages]=>"blah.md") @test md_files[JuDoc.PATHS[:src_pages]=>"blah.md"] == mtime(temp_blah) == stat(temp_blah).mtime @test html_files[JuDoc.PATHS[:src_pages]=>"temp.html"] == mtime(temp_html) @test other_files[JuDoc.PATHS[:src_pages]=>"temp.rnd"] == mtime(temp_rnd) end @testset "Config+write" begin JuDoc.process_config() @test JuDoc.GLOBAL_PAGE_VARS["author"].first == "Stefan Zweig" rm(temp_config) @test_logs (:warn, "I didn't find a config file. Ignoring.") JuDoc.process_config() # testing write head = "head" pg_foot = "\npage_foot" foot = "foot {{if hasmath}} {{fill author}}{{end}}" JuDoc.write_page(JuDoc.PATHS[:src], "index.md", head, pg_foot, foot) out_file = joinpath(JuDoc.out_path(JuDoc.PATHS[:folder]), "index.html") @test isfile(out_file) @test read(out_file, String) == "head\n<div class=\"jd-content\">\n<p>blah blah</p>\n\n\npage_foot\n</div>\nfoot Stefan Zweig" end temp_config = joinpath(JuDoc.PATHS[:src], "config.md") write(temp_config, "@def author = \"Stefan Zweig\"\n") rm(temp_index2) @testset "Part convert" begin # ✅ 16 aug 2018 write(joinpath(JuDoc.PATHS[:src_html], "head.html"), raw""" <!doctype html> <html lang="en-UK"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/css/main.css"> </head> <body>""") write(joinpath(JuDoc.PATHS[:src_html], "page_foot.html"), raw""" <div class="page-foot"> <div class="copyright"> &copy; All rights reserved. </div> </div>""") write(joinpath(JuDoc.PATHS[:src_html], "foot.html"), raw""" </body> </html>""") clear = true watched_files = J.jd_setup(; clear=clear) J.jd_fullpass(watched_files; clear=clear) @test issubset(["css", "libs", "index.html"], readdir(JuDoc.PATHS[:folder])) @test issubset(["temp.html", "temp.rnd"], readdir(JuDoc.PATHS[:pub])) @test all(split(read(joinpath(JuDoc.PATHS[:folder], "index.html"), String)) .== split("<!doctype html>\n<html lang=\"en-UK\">\n\t<head>\n\t\t<meta charset=\"UTF-8\">\n\t\t<link rel=\"stylesheet\" href=\"/css/main.css\">\n\t</head>\n<body>\n<div class=\"jd-content\">\n<p>blah blah</p>\n\n<div class=\"page-foot\">\n\t\t<div class=\"copyright\">\n\t\t\t\t&copy; All rights reserved.\n\t\t</div>\n</div>\n</div>\n </body>\n</html>")) end @testset "Err procfile" begin write(temp_index, "blah blah { blih etc") println("🐝 Testing error message...:") @test_throws J.OCBlockError JuDoc.process_file_err(:md, JuDoc.PATHS[:src] => "index.md"; clear=false) end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3756
tok = s -> J.find_tokens(s, J.MD_TOKENS, J.MD_1C_TOKENS) vfn = s -> (t = tok(s); J.validate_footnotes!(t); t) vh = s -> (t = vfn(s); J.validate_headers!(t); t) fib = s -> (t = vh(s); J.find_indented_blocks!(t, s); t) fib2 = s -> (t = fib(s); J.filter_lr_indent!(t, s); t) islr(t) = t.name == :LINE_RETURN && t.ss == "\n" istok(t, n, s) = t.name == n && t.ss == s isind(t) = t.name == :LR_INDENT && t.ss == "\n " ## ## FIND_TOKENS ## @testset "P:1:find-tok" begin t = raw""" @def v = 5 @@da @@db @@ @@ $A$ and \[B\] and \com{hello} etc """ |> tok @test istok(t[1], :MD_DEF_OPEN, "@def") @test islr(t[2]) @test istok(t[3], :DIV_OPEN, "@@da") @test islr(t[4]) @test istok(t[5], :DIV_OPEN, "@@db") @test islr(t[6]) @test istok(t[7], :DIV_CLOSE, "@@") @test islr(t[8]) @test istok(t[9], :DIV_CLOSE, "@@") @test islr(t[10]) @test istok(t[11], :MATH_A, "\$") @test istok(t[12], :MATH_A, "\$") @test istok(t[13], :MATH_C_OPEN, "\\[") @test istok(t[14], :MATH_C_CLOSE, "\\]") @test istok(t[15], :LX_COMMAND, "\\com") @test istok(t[16], :LXB_OPEN, "{") @test istok(t[17], :LXB_CLOSE, "}") @test islr(t[18]) @test istok(t[19], :EOS, "\n") end @testset "P:1:ctok" begin # check that tokens at EOS close properly # NOTE: this was avoided before by the addition of a special char # to denote the end of the string but we don't do that anymore. # see `isexactly` and `find_tokens` in the fixed pattern case. t = "@@d ... @@" |> tok @test istok(t[1], :DIV_OPEN, "@@d") @test istok(t[2], :DIV_CLOSE, "@@") @test istok(t[3], :EOS, "@") t = "``` ... ```" |> tok @test istok(t[1], :CODE_TRIPLE, "```") @test istok(t[2], :CODE_TRIPLE, "```") @test istok(t[3], :EOS, "`") t = "<!--...-->" |> tok @test istok(t[1], :COMMENT_OPEN, "<!--") @test istok(t[2], :COMMENT_CLOSE, "-->") t = "~~~...~~~" |> tok @test istok(t[1], :ESCAPE, "~~~") @test istok(t[2], :ESCAPE, "~~~") t = "b `j`" |> tok @test istok(t[1], :CODE_SINGLE, "`") @test istok(t[2], :CODE_SINGLE, "`") @test istok(t[3], :EOS, "`") end ## ## VALIDATE_FOOTNOTE! ## @testset "P:1:val-fn" begin t = raw""" A [^B] and [^B]: etc """ |> vfn @test istok(t[1], :FOOTNOTE_REF, "[^B]") @test islr(t[2]) @test istok(t[3], :FOOTNOTE_DEF, "[^B]:") end ## ## VALIDATE_HEADERS! ## @testset "P:1:val-hd" begin t = raw""" # A ## B and # C """ |> vh @test istok(t[1], :H1_OPEN, "#") @test islr(t[2]) @test istok(t[3], :H2_OPEN, "##") @test islr(t[4]) @test islr(t[5]) @test istok(t[6], :EOS, "\n") end ## ## FIND_INDENTED_BLOCKS! ## @testset "P:1:fib" begin s = raw""" A B1 B2 B3 C @@da @@db E @@ @@ E F G """ t = s |> fib @test islr(t[1]) @test isind(t[2]) && t[2].lno == 3 @test isind(t[3]) && t[3].lno == 4 @test isind(t[4]) && t[4].lno == 5 # B3 @test islr(t[5]) @test islr(t[6]) @test istok(t[7], :DIV_OPEN, "@@da") @test isind(t[8]) && t[8].lno == 8 @test istok(t[9], :DIV_OPEN, "@@db") @test isind(t[10]) && t[10].lno == 9 # in front of E @test isind(t[11]) && t[11].lno == 10 # in front of @@ @test istok(t[12], :DIV_CLOSE, "@@") @test islr(t[13]) @test istok(t[14], :DIV_CLOSE, "@@") @test islr(t[15]) @test isind(t[16]) && t[16].lno == 13 # F @test islr(t[17]) @test islr(t[18]) @test istok(t[19], :EOS, "\n") t = s |> fib2 @test length(t) == 19 @test isind.([t[2], t[3], t[4]]) |> all @test islr.([t[8], t[10], t[11], t[16]]) |> all end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
3517
tok = s -> J.find_tokens(s, J.MD_TOKENS, J.MD_1C_TOKENS) vfn = s -> (t = tok(s); J.validate_footnotes!(t); t) vh = s -> (t = vfn(s); J.validate_headers!(t); t) fib = s -> (t = vh(s); J.find_indented_blocks!(t, s); t) fib2 = s -> (t = fib(s); J.filter_lr_indent!(t, s); t) blk = s -> (J.def_LOCAL_PAGE_VARS!(); J.find_all_ocblocks(fib2(s), J.MD_OCB_ALL)) blk2 = s -> ((b, t) = blk(s); J.merge_indented_blocks!(b, s); b) blk3 = s -> (b = blk2(s); J.filter_indented_blocks!(b); b) blk4 = s -> (b = blk3(s); J.validate_and_store_link_defs!(b); b) isblk(b, n, s) = b.name == n && b.ss == s cont(b) = J.content(b) # Basics @testset "P:2:blk" begin b, t = raw""" A <!-- Hello --> Then ```julia 1+5``` and ~~~ ~~~. """ |> blk @test length(b) == 3 @test isblk(b[1], :COMMENT, "<!--\n\n Hello\n-->") @test isblk(b[2], :CODE_BLOCK_LANG, "```julia 1+5```") @test cont(b[2]) == " 1+5" @test isblk(b[3], :ESCAPE, "~~~ ~~~") end # with indentation @testset "P:2:blk-ind" begin b, t = raw""" A B1 B2 B3 @@d1 B @@ """ |> blk @test length(b) == 2 @test isblk(b[1], :CODE_BLOCK_IND, "\n B1\n B2\n B3\n") @test isblk(b[2], :DIV, "@@d1\n B\n@@") b, t = raw""" @@d1 @@d2 B @@ @@ """ |> blk @test length(b) == 1 @test isblk(b[1], :DIV, "@@d1\n @@d2\n B\n @@\n@@") b, t = raw""" @@d1 @@d2 B @@ @@ """ |> blk @test length(b) == 1 @test isblk(b[1], :DIV, "@@d1\n @@d2\n B\n @@\n@@") end # with indentation and grouping and filtering @testset "P:2:blk-indF" begin b = raw""" A B1 B2 B3 C """ |> blk3 @test isblk(b[1], :CODE_BLOCK_IND, "\n B1\n B2\n\n B3\n") b = raw""" A B C D E F G H """ |> blk3 @test length(b) == 2 @test isblk(b[1], :CODE_BLOCK_IND, "\n B\n C\n D\n E\n") @test isblk(b[2], :CODE_BLOCK_IND, "\n G\n\n\n\n H\n") b = raw""" @@d1 A B C @@ """ |> blk3 @test length(b) == 1 @test isblk(b[1], :DIV, "@@d1\n\n A\n B\n C\n@@") b = raw""" @@d1 @@d2 @@d3 B @@ @@ @@ """ |> blk3 @test b[1].name == :DIV end @testset "P:2:blk-{}" begin b = "{ABC}" |> blk3 @test J.content(b[1]) == "ABC" b = "\\begin{eqnarray} \\sin^2(x)+\\cos^2(x) &=& 1\\end{eqnarray}" |> blk3 @test cont(b[1]) == " \\sin^2(x)+\\cos^2(x) &=& 1" b = raw""" a\newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}}b@@d .@@ \eqa{\sin^2(x)+\cos^2(x) &=& 1} """ |> blk3 @test isblk(b[1], :LXB, raw"{\eqa}") @test isblk(b[2], :LXB, raw"{\begin{eqnarray}#1\end{eqnarray}}") @test isblk(b[3], :LXB, raw"{\sin^2(x)+\cos^2(x) &=& 1}") end # links @testset "P:2:blk-[]" begin b = """ A [A] B. [A]: http://example.com""" |> blk4 @test length(b) == 1 @test isblk(b[1], :LINK_DEF, "[A]: http://example.com") b = """ A [A][B] C. [B]: http://example.com""" |> blk4 @test isblk(b[1], :LINK_DEF, "[B]: http://example.com") b = """ A [`B`] C [`B`]: http://example.com""" |> blk4 @test length(b) == 2 @test isblk(b[1], :CODE_INLINE, "`B`") @test isblk(b[2], :LINK_DEF, "[`B`]: http://example.com") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
1655
@testset "footnotes" begin J.JD_ENV[:CUR_PATH] = "index.md" st = """ A[^1] B[^blah] C """ @test isapproxstr(st |> seval, """ <p>A<sup id="fnref:1"><a href="/index.html#fndef:1" class="fnref">[1]</a></sup> B<sup id="fnref:blah"><a href="/index.html#fndef:blah" class="fnref">[2]</a></sup> C</p>""") st = """ A[^1] B[^blah] C [^1]: first footnote [^blah]: second footnote """ @test isapproxstr(st |> seval, """ <p> A <sup id="fnref:1"><a href="/index.html#fndef:1" class="fnref">[1]</a></sup> B<sup id="fnref:blah"><a href="/index.html#fndef:blah" class="fnref">[2]</a></sup> C <table class="fndef" id="fndef:1"> <tr> <td class="fndef-backref"><a href="/index.html#fnref:1">[1]</a></td> <td class="fndef-content">first footnote</td> </tr> </table> <table class="fndef" id="fndef:blah"> <tr> <td class="fndef-backref"><a href="/index.html#fnref:blah">[2]</a></td> <td class="fndef-content">second footnote</td> </tr> </table> </p>""") end @testset "Fn in code" begin s = raw""" ```markdown this has[^1] [^1]: def ``` blah """ @test isapproxstr(s |> jd2html_td, """ <pre><code class="language-markdown">this has[^1] [^1]: def </code></pre> blah""") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
9327
@testset "Find Tokens" begin a = raw"""some markdown then `code` and @@dname block @@""" tokens = J.find_tokens(a, J.MD_TOKENS, J.MD_1C_TOKENS) @test tokens[1].name == :CODE_SINGLE @test tokens[2].name == :CODE_SINGLE @test tokens[3].name == :DIV_OPEN @test tokens[3].ss == "@@dname" @test tokens[4].ss == "@@" @test tokens[5].name == :EOS end @testset "Find blocks" begin st = raw""" some markdown then `code` and @@dname block @@ then maybe an escape ~~~ escape block ~~~ and done {target} done. """ steps = explore_md_steps(st) blocks, tokens = steps[:ocblocks] braces = filter(β -> β.name == :LXB, blocks) # escape block β = blocks[2] @test β.name == :ESCAPE @test β.ss == "~~~\nescape block\n~~~" # inline code block β = blocks[1] @test β.name == :CODE_INLINE @test β.ss == "`code`" # brace block β = braces[1] @test β.name == :LXB @test β.ss == "{target}" # div block β = blocks[4] @test β.name == :DIV @test β.ss == "@@dname block @@" end @testset "Unicode lx" begin st = raw""" Call me “$x$”, not $🍕$. """ steps = explore_md_steps(st) blocks, _ = steps[:ocblocks] # first math block β = blocks[1] @test β.name == :MATH_A @test β.ss == "\$x\$" # second math block β = blocks[2] @test β.name == :MATH_A @test β.ss == "\$🍕\$" end @testset "Lx defs+coms" begin st = raw""" \newcommand{\E}[1]{\mathbb E\left[#1\right]}blah de blah ~~~ escape b1 ~~~ \newcommand{\eqa}[1]{\begin{eqnarray}#1\end{eqnarray}} \newcommand{\R}{\mathbb R} Then something like \eqa{ \E{f(X)} \in \R &\text{if}& f:\R\maptso\R } and we could try to show latex: ```latex \newcommand{\brol}{\mathbb B} ``` """ lxdefs, tokens, braces, blocks = explore_md_steps(st)[:latex] @test lxdefs[1].name == "\\E" @test lxdefs[1].narg == 1 @test lxdefs[1].def == "\\mathbb E\\left[#1\\right]" @test lxdefs[2].name == "\\eqa" @test lxdefs[2].narg == 1 @test lxdefs[2].def == "\\begin{eqnarray}#1\\end{eqnarray}" @test lxdefs[3].name == "\\R" @test lxdefs[3].narg == 0 @test lxdefs[3].def == "\\mathbb R" @test blocks[2].name == :ESCAPE @test blocks[1].name == :CODE_BLOCK_LANG lxcoms, tokens = J.find_md_lxcoms(tokens, lxdefs, braces) @test lxcoms[1].ss == "\\eqa{ \\E{f(X)} \\in \\R &\\text{if}& f:\\R\\maptso\\R }" lxd = getindex(lxcoms[1].lxdef) @test lxd.name == "\\eqa" end @testset "Lxdefs 2" begin st = raw""" \newcommand{\com}{blah} \newcommand{\comb}[ 2]{hello #1 #2} """ lxdefs, tokens, braces, blocks, lxcoms = explore_md_steps(st)[:latex] @test lxdefs[1].name == "\\com" @test lxdefs[1].narg == 0 @test lxdefs[1].def == "blah" @test lxdefs[2].name == "\\comb" @test lxdefs[2].narg == 2 @test lxdefs[2].def == "hello #1 #2" # # Errors # # testing malformed newcommands st = raw"""abc \newcommand abc""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) blocks, tokens = J.find_all_ocblocks(tokens, J.MD_OCB_ALL) # Ill formed newcommand (needs two {...}) @test_throws J.LxDefError J.find_md_lxdefs(tokens, blocks) st = raw"""abc \newcommand{abc} def""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) blocks, tokens = J.find_all_ocblocks(tokens, J.MD_OCB_ALL) # Ill formed newcommand (needs two {...}) @test_throws J.LxDefError J.find_md_lxdefs(tokens, blocks) end @testset "Lxcoms 2" begin st = raw""" \newcommand{\com}{HH} \newcommand{\comb}[1]{HH#1HH} Blah \com and \comb{blah} etc ```julia f(x) = x^2 ``` etc \comb{blah} then maybe @@adiv inner part @@ final. """ lxdefs, tokens, braces, blocks, lxcoms = explore_md_steps(st)[:latex] @test lxcoms[1].ss == "\\com" @test lxcoms[2].ss == "\\comb{blah}" @test blocks[1].name == :CODE_BLOCK_LANG @test blocks[1].ss == "```julia\nf(x) = x^2\n```" @test J.content(blocks[1]) == "\nf(x) = x^2\n" @test blocks[2].name == :DIV @test blocks[2].ss == "@@adiv inner part @@" @test J.content(blocks[2]) == " inner part " # # Errors # st = raw""" \newcommand{\comb}[1]{HH#1HH} etc \comb then. """ tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) blocks, tokens = J.find_all_ocblocks(tokens, J.MD_OCB_ALL) lxdefs, tokens, braces, blocks = J.find_md_lxdefs(tokens, blocks) # Command comb expects 1 argument and there should be no spaces ... @test_throws J.LxComError J.find_md_lxcoms(tokens, lxdefs, braces) end @testset "lxcoms3" begin st = raw""" text A1 \newcommand{\com}{blah}text A2 \com and ~~~ escape B1 ~~~ \newcommand{\comb}[ 1]{\mathrm{#1}} text C1 $\comb{b}$ text C2 \newcommand{\comc}[ 2]{part1:#1 and part2:#2} then \comc{AA}{BB}. """ lxdefs, tokens, braces, blocks, lxcoms = explore_md_steps(st)[:latex] @test lxdefs[1].name == "\\com" && lxdefs[1].narg == 0 && lxdefs[1].def == "blah" @test lxdefs[2].name == "\\comb" && lxdefs[2].narg == 1 && lxdefs[2].def == "\\mathrm{#1}" @test lxdefs[3].name == "\\comc" && lxdefs[3].narg == 2 && lxdefs[3].def == "part1:#1 and part2:#2" @test blocks[1].name == :ESCAPE @test blocks[1].ss == "~~~\nescape B1\n~~~" end @testset "Merge-blocks" begin st = raw""" @def title = "Convex Optimisation I" \newcommand{\com}[1]{⭒!#1⭒} \com{A} <!-- comment --> then some ## blah <!-- ✅ 19/9/999 --> end \com{B}. """ lxdefs, tokens, braces, blocks, lxcoms = explore_md_steps(st)[:latex] @test blocks[1].name == :COMMENT @test J.content(blocks[1]) == " comment " @test blocks[2].name == :H2 @test J.content(blocks[2]) == " blah <!-- ✅ 19/9/999 -->" @test blocks[3].name == :MD_DEF @test J.content(blocks[3]) == " title = \"Convex Optimisation I\"" @test lxcoms[1].ss == "\\com{A}" @test lxcoms[2].ss == "\\com{B}" b2i = J.merge_blocks(lxcoms, blocks) @test b2i[1].ss == "@def title = \"Convex Optimisation I\"\n" @test b2i[2].ss == "\\com{A}" @test b2i[3].ss == "<!-- comment -->" @test b2i[4].ss == "## blah <!-- ✅ 19/9/999 -->\n" @test b2i[5].ss == "\\com{B}" end @testset "Header blocks" begin st = raw""" # t1 1 ## t2 2 ## trick ### t3 3 #### t4 4 ##### t5 5 ###### t6 6 """ tokens, blocks = explore_md_steps(st)[:filter] @test blocks[1].name == :H1 @test blocks[2].name == :H2 @test blocks[3].name == :H3 @test blocks[4].name == :H4 @test blocks[5].name == :H5 @test blocks[6].name == :H6 J.JD_ENV[:CUR_PATH] = "index.md" h = raw""" # t1 1 ## t2 2 ## t3 `blah` etc 3 ### t4 <!-- title --> 4 ### t2 5 ### t2 6 """ |> seval @test isapproxstr(h, """ <h1 id="t1"><a href="/index.html#t1">t1</a></h1> 1 <h2 id="t2"><a href="/index.html#t2">t2</a></h2> 2 <h2 id="t3_blah_etc"><a href="/index.html#t3_blah_etc">t3 <code>blah</code> etc</a></h2> 3 <h3 id="t4"><a href="/index.html#t4">t4 </a></h3> 4 <h3 id="t2__2"><a href="/index.html#t2__2">t2</a></h3> 5 <h3 id="t2__3"><a href="/index.html#t2__3">t2</a></h3> 6 """) # pathological issue 241 h = raw""" ## example A ## example B ## example 2 C """ |> seval @test isapproxstr(h, """ <h2 id="example"><a href="/index.html#example">example</a></h2> A <h2 id="example__2"><a href="/index.html#example__2">example</a></h2> B <h2 id="example_2"><a href="/index.html#example_2">example 2</a></h2> C """) end @testset "Line skip" begin h = raw""" Hello \\ goodbye """ |> seval @test isapproxstr(h, """<p>Hello <br/> goodbye</p>""") end @testset "Header+lx" begin h = "# blah" |> jd2html_td @test h == raw"""<h1 id="blah"><a href="/index.html#blah">blah</a></h1>""" h = raw""" \newcommand{\foo}{foo} \newcommand{\header}{# hello} \foo \header """ |> jd2html_td @test h == raw"""foo <h1 id="hello"><a href="/index.html#hello">hello</a></h1>""" h = raw""" \newcommand{\foo}{foo} \foo hello """ |> jd2html_td @test h == raw"""foo hello""" h = raw""" \newcommand{\foo}{blah} # \foo hello """ |> jd2html_td @test h == raw"""<h1 id="blah_hello"><a href="/index.html#blah_hello">blah hello</a></h1>""" h = raw""" \newcommand{\foo}{foo} \newcommand{\header}[2]{!#1 \foo #2} \header{##}{hello} """ |> jd2html_td @test h == raw"""<h2 id="foo_hello"><a href="/index.html#foo_hello">foo hello</a></h2>""" end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
2737
@testset "Bold x*" begin # issue 223 h = raw"**x\***" |> seval @test h == "<p><strong>x&#42;</strong></p>\n" h = raw"_x\__" |> seval @test h == "<p><em>x&#95;</em></p>\n" end @testset "Bold code" begin # issue 222 h = raw"""A **`master`** B.""" |> seval @test h == "<p>A <strong><code>master</code></strong> B.</p>\n" end @testset "Tickssss" begin # issue 219 st = raw"""A `B` C""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) @test tokens[1].name == :CODE_SINGLE @test tokens[2].name == :CODE_SINGLE st = raw"""A ``B`` C""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) @test tokens[1].name == :CODE_DOUBLE @test tokens[2].name == :CODE_DOUBLE st = raw"""A ``` B ``` C""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) @test tokens[1].name == :CODE_TRIPLE @test tokens[2].name == :CODE_TRIPLE st = raw"""A ````` B ````` C""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) @test tokens[1].name == :CODE_PENTA @test tokens[2].name == :CODE_PENTA st = raw"""A ```b B ``` C""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) @test tokens[1].name == :CODE_LANG @test tokens[2].name == :CODE_TRIPLE st = raw"""A `````b B ````` C""" tokens = J.find_tokens(st, J.MD_TOKENS, J.MD_1C_TOKENS) @test tokens[1].name == :CODE_LANG2 @test tokens[2].name == :CODE_PENTA h = raw""" A `````markdown B ````` C """ |> jd2html_td @test isapproxstr(h, raw""" <p>A <pre><code class="language-markdown">B </code></pre> C</p> """) h = raw""" A `````markdown ```julia B ``` ````` C """ |> jd2html_td @test isapproxstr(h, raw""" <p>A <pre><code class="language-markdown">```julia B ``` </code></pre> C</p> """) end @testset "Nested ind" begin # issue 285 h = raw""" \newcommand{\hello}{ yaya bar bar } \hello """ |> jd2html_td @test isapproxstr(h, raw"""yaya bar bar""") h = raw""" @@da @@db @@dc blah @@ @@ @@ """ |> jd2html_td @test isapproxstr(h, raw""" <div class="da"> <div class="db"> <div class="dc"> blah </div> </div> </div> """) h = raw""" \newcommand{\hello}[1]{#1} \hello{ good lord } """ |> jd2html_td @test isapproxstr(h, "good lord") end
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
code
4913
# NOTE: # - this is an experimental script comparing Common Mark specs # with what JuDoc supports. A lot of things break but not all # of it is a sign of JuDoc doing the wrong thing. For instance: # # --> support for headers in JuDoc is a bit more involved adding links # to headers by default which Common Mark does not do so of course # all examples with headers currently fail. # # --> common mark accepts stray backticks, JuDoc doesn't # # --> double backslash mean something specific in JuDoc # # --> JuDoc doesn't cleanly handle <p> </p> # # Eventually the `similar_enough` function will be adjusted to ignore # those cases. # -------------------------------------------------------------------- dir_jd = dirname(dirname(pathof(JuDoc))) dir_specs = joinpath(dir_jd, "test", "parser", "common_mark") tests = read(joinpath(dir_specs, "spec029.json"), String) md = eachmatch(r"\"markdown\":\s\"(.*?)\",", tests) md = [unescape_string(m.captures[1]) for m in md] html = eachmatch(r"\"html\":\s\"(.*?)\",", tests) html = [unescape_string(h.captures[1]) for h in html] function unwrap_identity(s) rx = r"&#(.*?);" em = eachmatch(rx, s) |> collect head = 1 ss = "" for (i, m) in enumerate(em) pos = prevind(s, m.offset) if pos > head ss *= SubString(s, head, pos) end c = Char(parse(Int,m.captures[1])) ss *= c head = nextind(s, m.offset + ncodeunits(m.match) - 1) end if head < lastindex(s) ss *= SubString(s, head, lastindex(s)) end ss end function similar_enough(s_ref, s) cleanup(s_ref) == cleanup(s) end function cleanup(s) s_ = s s_ = replace(s_, r"<h(.) id.*?><a href.*?>" => s"<h\1>") s_ = replace(s_, "</a></h" => "</h") s_ = replace(s_, r"^<p>" => "") s_ = replace(s_, r"</p>\n$" => "") s_ = replace(s_, "\n</code>" => "</code>") s_ = unwrap_identity(s_) strip(s_) end function preprocess(md) md = replace(md, "\$" => "\\\$") end function check(r) fails = Int[] for i in r mdi = preprocess(md[i]) htmli = html[i] flag = try similar_enough(htmli, mdi |> jd2html_td) catch false end if !flag println("Breaks example $i") push!(fails, i) else println("Example $i successful [$i]") end end println("FAILURE RATE -- $(round(length(fails)/length(r), digits=2)*100)") fails end jdc(i) = cleanup(preprocess(md[i]) |> jd2html_td) htc(i) = cleanup(html[i]) # TABS # NOTE: issue with `\t` # - also thing with first line tab (currently not accepted in JuDoc) check(1:11) # PRECEDENCE (fails because judoc does not support stray `) check(12) check(13:31) # setext headings are not supported check(70) # INDENTED CODE BLOCKS println("\n==Indented code blocks==\n") f = check(77:88) # HTML code blocks (not expected to work in JuDoc) # fail: all # println("HTML code blocks") # check(117:160) ########################## ########################## ### -- ALL OK # Blank Lines println("\n==Blank lines==\n") f = check(197) # textual content println("\n==Textual content==\n") f = check(647:649) ### --- MOST OK # Block quotes println("\n==Block quotes==\n") f = check(198:222) # Autolinks println("\n==Autolinks==\n") f = check(590:608) # XXX XXX XXX XXX XXX XXX XXX ### --- MOST NOK # HEADINGS println("\n==Headers==\n") check(32:49) # FENCED CODE BLOCKS println("\n==Fenced code blocks==\n") f = check(89:116) # LINK REFERENCE DEFINITIONS println("\n==Link references definitions==\n") f = check(161:188) # Paragraphs println("\n==Paragraphs==\n") f = check(189:196) # List items println("\n==List items==\n") f = check(223:270) # Backslash escapes println("\n==Backslash escapes==\n") f = check(298:310) # Entity and numeric chars println("\n==Entity and num char==\n") f = check(311:327) # Code spans println("\n==Code spans==\n") f = check(328:349) # Emphasis println("\n==Emphasis==\n") f = check(350:480) # Links println("\n==Links==\n") f = check(481:567) # Images # NOTE: # - link title not supported println("\n==Images==\n") f = check(568:589) # Raw HTML (XXX should not expect this to work) println("\n==Raw HTML== (EXPECTED TO FAIL)\n") f = check(609:629) # Hard line break # NOTE: fail due to Julia Markdown chomping off `\n` println("\n==Hard line breaks== (JMD CHOMP LR)\n") f = check(630:644) ### -- ALL NOK # Lists # NOTE: fail due to Julia Markdown inserting paragraphs in lists println("\n==List items== (JMD ADDS PARAGRAPH)\n") f = check(271:296) # inline # NOTE: fail due to stray backtick println("\n==Inlines== (STRAY BACKTICK)\n") f = check(297) # soft line break # NOTE: fail due to Julia's Markdown chomping off the `\n` println("\n==Soft line breaks (JMD CHOMP LR)==\n") f = check(645:646) # ---------------------------------------------------------
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
docs
4412
# NEWS ## v0.3 Thanks a lot to [@cserteGT3](https://github.com/cserteGT3) for his input and [@cormullion](https://github.com/cormullion) for great feedback on the markdown parser through extensive testing. **Features** * indented code blocks are now supported (issue #207, PR #217) * reference links and images like `[link][id]` with later `[id]: url` are now supported (issue #201, PR #214) * headers are now links which facilitates internal hyper-references * automatic table of contents via `\toc` or `\tableofcontents` (PR #188) * added `\\` as a way to force the introduction of a line break, this can be useful in the context of inclusions etc (see https://github.com/cserteGT3/JuDocPlottest/issues/1 for context) * html entities are now supported (issue #206, PR #209) * double backticks are now supported for inline code (see issue #204 and PR #210) * added `\textinput` command to display code output as formatted text (PR #194) * added `\tableinput` command to insert and format a table corresponding to a csv file (PR #197, creds to @cserteGT3) **Bug fixes & improvements** * showing error message when an eval'd block fails (PR #187) * issues with backslashes in code environment etc (issue #205, PR #209) * improved status messages for `cleanpull` (PR #190) and adding the possibility to specify a commit message for `publish` (PR #191, creds to @cserteGT3) **Templates** (JuDocTemplates is now `0.2.5`) * update of KaTeX and Highlight.js respectively to `0.11` and `9.15.10` * fixing the default rights of files to `644` **Other** * general cleanup of the code (trying to make naming more consistent and less clunky, general cleaning up etc) ## v0.2 Thanks a lot to [@Invarianz](https://github.com/Invarianz), [@cserteGT3](https://github.com/cserteGT3) and [@mbaz](https://github.com/mbaz) for help and feedback leading to this version. **Features** * [docs](https://tlienart.github.io/JuDoc.jl/dev/man/syntax/#Code-insertions-1) - Julia code blocks can now be evaluated on the fly and their output displayed * [docs](https://tlienart.github.io/JuDoc.jl/dev/man/syntax/#File-insertions-1) - Additional convenience commands for insertions (`\file`, `\figalt`, `\fig`, `\output`, `\textoutput`) * [docs](https://tlienart.github.io/JuDoc.jl/dev/man/syntax/#More-on-paths-1) - More consistent use of relative paths for inserting assets and keeping folders organised * [docs](https://tlienart.github.io/JuDoc.jl/dev/man/syntax/#Hyper-references-1) - `\label` allows to define anchor points for convenient hyper-references, also header sections are now anchor points themselves * [docs](https://tlienart.github.io/JuDoc.jl/dev/#External-dependencies-1) - Users can now specify the paths to the python, pip and node executables via `ENV` if they prefer to do that * [docs](https://tlienart.github.io/JuDoc.jl/dev/man/workflow/#Hosting-the-website-as-a-project-website-1) - Allow a site to be hosted as a project website (where the root is `/project/` instead of just `/`) **Bug fixes** * better error message if starting the server from the wrong dir ([#155](https://github.com/tlienart/JuDoc.jl/issues/155)) * numerous fixes for windows (read-only files, paths errors, installation instructions, ...) ([#179](https://github.com/tlienart/JuDoc.jl/issues/179), [#177](https://github.com/tlienart/JuDoc.jl/issues/177), [#174](https://github.com/tlienart/JuDoc.jl/issues/174), [#167](https://github.com/tlienart/JuDoc.jl/issues/167), [#16](https://github.com/tlienart/JuDoc.jl/issues/16)0) * fix an issue when mixing code, italic/bold (whitespace issue) ([#163](https://github.com/tlienart/JuDoc.jl/issues/163)) * (_in 1.3_) fix an issue with parsing of nested code blocks within an escape block and paths issues ([#151](https://github.com/tlienart/JuDoc.jl/issues/151), [#15](https://github.com/tlienart/JuDoc.jl/issues/15)0) * (_in 1.2_) fix a problem with the use of `@async` which caused hyper references to fail * (_in 1.1_) fix toml issues and bumped KaTeX up to 0.10.2 **Templates** * [docs](https://tlienart.github.io/JuDoc.jl/dev/man/themes/#Adapting-a-theme-to-JuDoc-1) - how to adapt a theme to JuDoc / add a new template * [demo](https://tlienart.github.io/JuDocTemplates.jl/) - a few new template: `template=sandbox`, an ultra bare bone site to just play with the JuDoc syntax and try things out; `template=hyde`, `template=lanyon`, well-known templates adapted from Jekyll.
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
docs
4466
**WARNING**: this package will be renamed soon to `Franklin.jl` (see issue [#338](https://github.com/tlienart/JuDoc.jl/issues/338)); if you're new to the package maybe wait the end of January before giving it a shot as that might help avoid issues. If you're a current user on `<= 0.4.0` the package will keep working as it does; a coming patch release `0.4.1` will add a helper message then `0.5` will effectively be the first release of Franklin. <div align="center"> <a href="https://tlienart.github.io/JuDocWeb/"> <img src="https://tlienart.github.io/JuDocWeb/assets/infra/logo1.svg" alt="JuDoc" width="150"> </a> </div> <h2 align="center">A Static Site Generator in Julia. <p align="center"> <img src="https://img.shields.io/badge/lifecycle-maturing-blue.svg" alt="Lifecycle"> <a href="https://travis-ci.org/tlienart/JuDoc.jl"> <img src="https://travis-ci.org/tlienart/JuDoc.jl.svg?branch=master" alt="Build Status"> </a> <a href="http://codecov.io/github/tlienart/JuDoc.jl?branch=master"> <img src="http://codecov.io/github/tlienart/JuDoc.jl/coverage.svg?branch=master" alt="Coverage"> </a> </p> </h2> JuDoc is a simple **static site generator** (SSG) oriented towards technical blogging (code, maths, ...) and light, fast-loading pages. The base syntax is plain markdown with a few extensions such as the ability to define and use LaTeX-like commands in or outside of maths environments and the possibility to evaluate code blocks on the fly. ## Docs Go to [JuDoc's main website](https://tlienart.github.io/JuDocWeb/). Some examples of websites using JuDoc * the main website is written in JuDoc, [source](https://github.com/tlienart/JuDocWeb), * [@cormullion's website](https://cormullion.github.io), the author of [Luxor.jl](https://github.com/JuliaGraphics/Luxor.jl), * MLJ's [tutorial website](https://alan-turing-institute.github.io/MLJTutorials/) which shows how JuDoc can interact nicely with [Literate.jl](https://github.com/fredrikekre/Literate.jl) * see also [all julia blog posts](https://julialangblogmirror.netlify.com/) rendered with JuDoc thanks to massive help from [@cormullion](https://github.com/cormullion); see also the [source repo](https://github.com/cormullion/julialangblog) * [my website](https://tlienart.github.io). ## Key features * Use standard markdown with the possibility to use LaTeX-style commands, * Simple way to introduce div blocks allowing easy styling on a page (e.g. "Theorem" boxes etc.), * Can execute and show the output of Julia code blocks, * Simple optimisation step to accelerate webpage loading speed: - compression of HTML and CSS of the generated pages, - optional pre-rendering of KaTeX and highlighted code blocks to remove javascript dependency, * Easy HTML templating to define or adapt a given layout. See [the docs](https://tlienart.github.io/JuDocWeb/) for more information and examples. ## Getting started With Julia ≥ 1.1: ```julia pkg> add JuDoc ``` you can then get started with ```julia julia> using JuDoc julia> newsite("MyNewSite") ✔ Website folder generated at "MyNewSite" (now the current directory). → Use serve() from JuDoc to see the website in your browser. julia> serve() → Initial full pass... → Starting the server... ✔ LiveServer listening on http://localhost:8000/ ... (use CTRL+C to shut down) ``` Modify the files in `MyNewSite/src` and see the changes being live-rendered in your browser. Head to [the docs](https://tlienart.github.io/JuDocWeb/) for more information. ## Associated repositories * [LiveServer.jl](https://github.com/asprionj/LiveServer.jl) a package coded with [Jonas Asprion](https://github.com/asprionj) to render and watch the content of a local folder in the browser. * [JuDocTemplates.jl](https://github.com/tlienart/JuDocTemplates.jl) the repositories where JuDoc themes/templates are developed. * [JuDocWeb](https://github.com/tlienart/JuDocWeb) the repository for JuDoc's website. ## Licenses **Core**: * JuDoc, JuDocTemplates and LiveServer are all MIT licensed. **External**: * KaTeX is [MIT licensed](https://github.com/KaTeX/KaTeX/blob/master/LICENSE), * Node's is essentially [MIT licensed](https://github.com/nodejs/node/blob/master/LICENSE), * css-html-js-minify is [LGPL licensed](https://github.com/juancarlospaco/css-html-js-minify/blob/master/LICENCE.lgpl.txt), * highlight.js is [BSD licensed](https://github.com/highlightjs/highlight.js/blob/master/LICENSE).
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
docs
794
@def title = "Julia" @def hascode = true ```julia add OhMyREPL#master ``` AAA ~~~ <pre><code class="language-julia">""" bar(x[, y]) BBB # Examples ```jldoctest D ``` """ function bar(x, y) ... end </code></pre> ~~~ For complex functions with multiple arguments use a argument list, also if there are many keyword arguments use `<keyword arguments>`: ~~~ <pre><code class="language-julia">""" matdiag(diag, nr, nc; &ltkeyword arguments&gt) Create Matrix with number `vdiag` on the super- or subdiagonals and `vndiag` in the rest. # Arguments - `diag::Number`: `Number` to write into created super- or subdiagonal # Examples ```jldoctest julia> matdiag(true, 5, 5, sr=2, ec=3) ``` """ function matdiag(diag::Number, nr::Integer, nc::Integer;) ... end </code></pre> ~~~
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.4.3
f50c0955c34b8125dc2502000e1a3640e271d626
docs
245
@def hascode = true Code block: ```julia:./test #hideall temps = (15, 23, 20, 15, 20, 17, 18, 30, 21, 19, 17) a = sum(temps)/length(temps) println("The _average_ temperature is **$(round(a, digits=1))°C**.") ``` \textoutput{./test} The end.
JuDoc
https://github.com/tlienart/JuDoc.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
635
using RMLImaging using Documenter DocMeta.setdocmeta!(RMLImaging, :DocTestSetup, :(using RMLImaging); recursive=true) makedocs(; modules=[RMLImaging], authors="Kazunori Akiyama", repo="https://github.com/EHTJulia/RMLImaging.jl/blob/{commit}{path}#{line}", sitename="RMLImaging.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://ehtjulia.github.io/RMLImaging.jl", edit_link="main", assets=String[] ), pages=[ "Home" => "index.md", ] ) deploydocs(; repo="github.com/EHTJulia/RMLImaging.jl", devbranch="main" )
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
1107
module RMLImaging using Base using ChainRulesCore using DataFrames using EHTDimensionalData using EHTImages using EHTModels using EHTUtils using EHTUVData using FLoops using NFFT using Optimization using OptimizationOptimJL using OrderedCollections using Statistics using Zygote # common include("./common.jl") # data model include("./datamodels/abstract.jl") include("./datamodels/visibility.jl") # image model include("./imagemodels/abstract.jl") include("./imagemodels/image2dmodels/abstract.jl") include("./imagemodels/image2dmodels/linear2d.jl") include("./imagemodels/image2dmodels/log2d.jl") # uv-coverages include("./uvcoverages/abstract.jl") include("./uvcoverages/unique.jl") include("./uvcoverages/uvcoverage.jl") # Fourier Transforms include("./fouriertransforms/abstract.jl") include("./fouriertransforms/nfft2d.jl") # Regularizers include("./regularizers/abstract.jl") include("./regularizers/l1norm.jl") include("./regularizers/tsv.jl") include("./regularizers/tv.jl") include("./regularizers/klmem.jl") # Imagers include("./imagers/abstract.jl") include("./imagers/imager2D.jl") end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
551
function sum_floop(x::AbstractArray; ex=ThreadedEx()) value = 0.0 @floop ex for i in 1:length(x) @reduce value += x[i] end return value end function sum_floop_grad(x::AbstractArray) return ones(size(x)...) end function ChainRulesCore.rrule(::typeof(sum_floop), x::AbstractArray; ex=ThreadedEx()) y = sum_floop(x; ex=ex) function pullback(Δy) f̄bar = NoTangent() xbar = @thunk(sum_floop_grad(x) .* Δy) exbar = NoTangent() return f̄bar, xbar, exbar end return y, pullback end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
87
abstract type AbstractDataModel end functionlabel(::AbstractDataModel) = :namelessdata
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
3997
export chisquare export evaluate export initialize_datamodels export residual export VisibilityDataModel struct VisibilityDataModel <: AbstractDataModel data σ variance designmatrix weight Ndata end # Function Label functionlabel(::VisibilityDataModel) = :visibility # Evaluate function evaluate(datamodel::VisibilityDataModel, V::Vector{ComplexF64}; keywords...) return @inbounds getindex(V, datamodel.designmatrix) end # residual function residual(datamodel::VisibilityDataModel, V::Vector{ComplexF64}; keywords...) model = evaluate(datamodel, V) @inbounds resid = (model .- datamodel.data) ./ datamodel.σ return resid end # chisquare function chisquare(datamodel::VisibilityDataModel, V::Vector{ComplexF64}; keywords...) model = evaluate(datamodel, V) @inbounds sqresid = abs.(model .- datamodel.data) .^ 2 ./ datamodel.variance return mean(sqresid) end function get_stokesI(visds::DimStack; keywords...) nch, nspw, ndata, npol = size(visds) # new visibility data set v = zeros(ComplexF64, nch, nspw, ndata, 1) σ = zeros(Float64, nch, nspw, ndata, 1) flag = zeros(Float64, nch, nspw, ndata, 1) for idata in 1:ndata, ispw in 1:nspw, ich in 1:nch v1 = visds[:visibility].data[ich, ispw, idata, 1] v2 = visds[:visibility].data[ich, ispw, idata, 2] f1 = visds[:flag].data[ich, ispw, idata, 1] f2 = visds[:flag].data[ich, ispw, idata, 2] σ1 = visds[:sigma].data[ich, ispw, idata, 1] σ2 = visds[:sigma].data[ich, ispw, idata, 2] if f1 <= 0 || f2 <= 0 flag[ich, ispw, idata, 1] = -1 continue else v[ich, ispw, idata, 1] = 0.5 * (v1 + v2) σ[ich, ispw, idata, 1] = 0.5 * √(σ1^2 + σ2^2) flag[ich, ispw, idata, 1] = 1 end end c, s, d, p = dims(visds) newp = Dim{:p}([1]) newplabel = ["I"] v = DimArray(data=v, dims=(c, s, d, newp), name=:visibility) σ = DimArray(data=σ, dims=(c, s, d, newp), name=:sigma) flag = DimArray(data=flag, dims=(c, s, d, newp), name=:flag) newplabel = DimArray(data=newplabel, dims=(newp), name=:polarization) newds = DimStack( v, σ, flag, newplabel, [visds[key] for key in keys(visds) if key ∉ [:visibility, :sigma, :flag, :polarization]]... ) return newds end function visds2df(visds::DimStack; keywords...) # get data size nch, nspw, ndata, npol = size(visds) nvis = nch * nspw * ndata * npol # initialize dataframe df = DataFrame() df[!, :u] = zeros(Float64, nvis) df[!, :v] = zeros(Float64, nvis) df[!, :Vcmp] = zeros(ComplexF64, nvis) df[!, :σ] = zeros(Float64, nvis) df[!, :σ2] = zeros(Float64, nvis) df[!, :flag] = zeros(Float64, nvis) # fill out dataframe i = 1 for ipol in 1:npol, idata in 1:ndata, ispw in 1:nspw, ich in 1:nch idx = (idata, ispw, ich, 1) df[i, :u] = visds[:u].data[ich, ispw, idata] df[i, :v] = visds[:v].data[ich, ispw, idata] df[i, :Vcmp] = visds[:visibility].data[ich, ispw, idata, ipol] df[i, :σ] = visds[:sigma].data[ich, ispw, idata, ipol] df[i, :σ2] = visds[:sigma].data[ich, ispw, idata, ipol]^2 df[i, :flag] = visds[:flag].data[ich, ispw, idata, ipol] i += 1 end # remove flagged data df = df[df.flag.>0, :] df = df[df.σ.>0, :] return df end function initialize_datamodels(df::DataFrame; keywords...) uv = df.u .+ 1im .* df.v uvc, reverse_idx = unique_ids(uv) uvcov = SingleUVCoverage(real(uvc), imag(uvc), reverse_idx) visdatamodel = VisibilityDataModel( df.Vcmp, df.σ, df.σ2, reverse_idx, 1, length(df.Vcmp) ) return uvcov, visdatamodel end function initialize_datamodels(visds::DimStack; keywords...) ds = get_stokesI(visds) df = visds2df(ds) uvcov, visdatamodel = initialize_datamodels(df) return uvcov, visdatamodel end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
127
""" AbstractFourierTransform Abstract type for Fourier Transform Operators. """ abstract type AbstractFourierTransform end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
2737
export SingleNFFT2D export forward export adjoint """ FourierTransform2D <: AbstractFourierTransform Abstract type for Fourier Transform Operators of a single 2D image. """ abstract type FourierTransform2D <: AbstractFourierTransform end """ SingleNFFT2D(nfft_fwd, nfft_adj, vnorm) <: FourierTransform2D A Fourier Transform Operator of a single 2D Image using NFFT. # Fields - `nfft_fwd`: NFFT operator for the forward transform - `nfft_adj`: NFFT operator for the adjoint transform - `Vkernel`: the factor (phase shift, pulse funciton, kernel, etc) to be multipled by the forward-transformed visibilities. """ struct SingleNFFT2D <: FourierTransform2D nfft_forward nfft_adjoint Vkernel end function SingleNFFT2D(imagemodel, uvcoverage::SingleUVCoverage)::SingleNFFT2D # important constant: DO NOT CHANGE ftsign = +1 # Radio Astronomy data assumes the positive exponent in the forward operation V = Σ I exp(+2πux) # image parameters xref, yref = imagemodel.refpixel # reference position in the unit of pixel Δx, Δy = imagemodel.pixelsize # pixel size in radian Nx, Ny = imagemodel.imagesize # number of pixels # uv-coverage (in lambda) u = uvcoverage.u v = uvcoverage.v uΔx = u .* -Δx # Δx in metadata is positive, so flip the sign for the left-handed sky coordinate vΔy = v .* Δy Nuv = size(u)[1] # k-vector for NFFT k = fill(-1.0 * ftsign, (2, Nuv)) # first -1 is to cancel the negative exponent (i.e. -2πfn) in the forward operation for iuv in 1:Nuv @inbounds k[1, iuv] *= uΔx[iuv] @inbounds k[2, iuv] *= vΔy[iuv] end # factor for the phase center @inbounds Vkernel = exp.(1im .* ftsign .* 2π .* (uΔx .* (Nx / 2 + 1 - xref) .+ vΔy .* (Ny / 2 + 1 - yref))) # pulse function will be added here. # initialize NFFT Plan nfft_forward = NFFT.plan_nfft(k, (Nx, Ny)) nfft_adjoint = NFFT.adjoint(nfft_forward) return SingleNFFT2D(nfft_forward, nfft_adjoint, Vkernel) end @inline function forward(ft::SingleNFFT2D, x::Matrix{Float64}) return forward(ft, complex(x)) end @inline function forward(ft::SingleNFFT2D, x::Matrix{ComplexF64}) @inbounds v = ft.nfft_forward * x @inbounds v .*= ft.Vkernel return v end function ChainRulesCore.rrule(::typeof(forward), ft::SingleNFFT2D, x::Matrix{ComplexF64}) y = forward(ft, x) function pullback(Δy) f̄bar = NoTangent() ftbar = NoTangent() xbar = @thunk(adjoint(ft, Δy)) return f̄bar, ftbar, xbar end return y, pullback end @inline function adjoint(ft::SingleNFFT2D, v::Vector) @inbounds vinp = v ./ ft.Vkernel @inbounds xadj = real(ft.nfft_adjoint * vinp) return xadj end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
1155
export transform_linear_forward export transform_linear_inverse """ AbstractImageModel # Mandatory fields # Optional methods # Mandatory methods # Optional methods """ abstract type AbstractImageModel end """ transform_linear_forward(model::AbstractImageModel, x::AbstractArray) Convert the input array of the image model parameters into the corresponding array of the linear-scale intensity map. This is supposed to be the inverse funciton of ``transform_linear_inverse``. # Arguments - `model::AbstractImageModel`: the image model - `x::AbstractArray`: the array of the image model parameters """ transform_linear_forward(::AbstractImageModel, x::AbstractArray) = x """ transform_linear_forward(model::AbstractImageModel, x::AbstractArray) Convert the input array of the linear-scale intensity map into the array of the corresponding model parameters. This is supposed to be the inverse funciton of ``transform_linear_forward``. # Arguments - `model::AbstractImageModel`: the image model - `x::AbstractArray`: the array of the linear-scale intensity map """ transform_linear_inverse(::AbstractImageModel, x::AbstractArray) = x
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
1915
export initialize abstract type AbstractImage2DModel <: AbstractImageModel end struct IS_POSITIVE end struct NOT_POSITIVE end is_positive(::AbstractImage2DModel) = NOT_POSITIVE() struct IS_NONNEGATIVE end struct NOT_NONNEGATIVE end is_nonnegative(::AbstractImage2DModel) = NOT_NONNEGATIVE() function AbstractImage2DModel(Image2DModelType, image::EHTImages.AbstractEHTImage, idx=[1, 1, 1]) nx, ny, _ = size(image) dx = image.metadata[:dx] dy = image.metadata[:dy] ixref = image.metadata[:ixref] iyref = image.metadata[:iyref] orgidx = idx pulsetype = Symbol(image.metadata[:pulsetype]) return Image2DModelType((nx, ny), (dx, dy), (ixref, iyref), pulsetype, orgidx) end function totalflux(imagemodel::AbstractImage2DModel, x::AbstractArray) x_linear = transform_linear_forward(imagemodel, x) return sum(x_linear) end function normalize(imagemodel::AbstractImage2DModel, x::AbstractArray, totalflux=1.0) x_linear = transform_linear_forward(imagemodel, x) x_totalflux = sum(x_linear) x_norm = x_linear * totalflux / x_totalflux return transform_linear_inverse(imagemodel, x_norm) end function Base.map(image::EHTImages.AbstractEHTImage, imagemodel::AbstractImage2DModel, x::AbstractArray) imageout = copy(image) map!(imageout, imagemodel, x) return imageout end function Base.map(image::EHTImages.AbstractEHTImage, imagemodel::AbstractImage2DModel, x::AbstractArray, idx) imageout = copy(image) map!(imageout, imagemodel, x, idx) return imageout end function Base.map!(image::EHTImages.AbstractEHTImage, imagemodel::AbstractImage2DModel, x::AbstractArray) map!(image, imagemodel, x, imagemodel.orgidx) end function Base.map!(image::EHTImages.AbstractEHTImage, imagemodel::AbstractImage2DModel, x::AbstractArray, idx) x_linear = transform_linear_forward(imagemodel, x) setindex!(image.data, x_linear, :, :, idx...) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
1078
export LinearImage2DModel struct LinearImage2DModel <: AbstractImage2DModel imagesize pixelsize refpixel pulsetype orgidx end is_positive(::LinearImage2DModel) = NOT_POSITIVE() is_nonnegative(::LinearImage2DModel) = NOT_NONNEGATIVE() function LinearImage2DModel(image::EHTImages.AbstractEHTImage, idx=[1, 1, 1]) AbstractImage2DModel(LinearImage2DModel, image, idx) end @inline transform_linear_forward(imagemodel::LinearImage2DModel, x::AbstractArray) = x @inline transform_linear_inverse(imagemodel::LinearImage2DModel, x::AbstractArray) = x function initialize(imagemodel::LinearImage2DModel) return zeros(imagemodel.imagesize) end function initialize(imagemodel::LinearImage2DModel, value::Number) return fill(value, imagemodel.imagesize) end function initialize(imagemodel::LinearImage2DModel, image::EHTImages.AbstractEHTImage) return getindex(image.data, :, :, imagemodel.orgidx...) end function initialize(imagemodel::LinearImage2DModel, image::EHTImages.AbstractEHTImage, idx) return getindex(image.data, :, :, idx...) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
1295
export LogImage2DModel # Definition of the model struct LogImage2DModel <: AbstractImage2DModel imagesize pixelsize refpixel pulsetype orgidx end is_positive_image(::LinearImage2DModel) = IS_POSITIVE() is_nonnegative_image(::LinearImage2DModel) = IS_NONNEGATIVE() # Constructors function LogImage2DModel(image::EHTImages.AbstractEHTImage, idx=[1, 1, 1]) AbstractImage2DModel(LogImage2DModel, image, idx) end # Transoformer to linear-scale images @inline transform_linear_forward(::LogImage2DModel, x::AbstractArray) = @inbounds exp.(x) # Transformer from linear-scale images @inline transform_linear_inverse(::LogImage2DModel, x::AbstractArray) = @inbounds log.(abs.(real(x))) # Initialization function initialize(imagemodel::LogImage2DModel, totalflux::Number=1.0) x = zeros(imagemodel.imagesize) return normalize(imagemodel, x, totalflux) end function initialize(imagemodel::LogImage2DModel, image::EHTImages.AbstractEHTImage) x_linear = getindex(image.data, :, :, imagemodel.orgidx...) return transform_linear_inverse(imagemodel, x_linear) end function initialize(imagemodel::LogImage2DModel, image::EHTImages.AbstractEHTImage, idx) x_linear = getindex(image.data, :, :, idx...) return transform_linear_inverse(imagemodel, x_linear) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
32
abstract type AbstractImager end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
4733
export Imager2D export ImagingProblem struct Imager2D <: AbstractImager skymodel::AbstractImage2DModel ft::SingleNFFT2D datamodels regularlizers parallelizer end """ ImagingProblem(imager::Imager2D, x0::AbstractArray) Initialize Optimization.OptimizationProblem for RML Imaging. Returns the initialized Optimization.OptimizationProblem object. # Arguments - `imager::Imager2D`: the imager - `x0::AbstractArray`: the initial image in the parameter domain. """ function ImagingProblem(imager::Imager2D, x0::AbstractArray) # define optimization function optfunc = OptimizationFunction(lossfunc, Optimization.AutoZygote()) # define optimization problem optprob = Optimization.OptimizationProblem(optfunc, x0, imager) return optprob end """ ImagingProblem(imager::Imager2D, initialimage::AbstractEHTImage) Initialize Optimization.OptimizationProblem for RML Imaging. Returns the initialized Optimization.OptimizationProblem object. # Arguments - `imager::Imager2D`: the imager - `x0::AbstractArray`: the initial image in the parameter domain. """ function ImagingProblem(imager::Imager2D, initimage::AbstractEHTImage) x0 = initialize(imager.skymodel, initimage) return ImagingProblem(imager::Imager2D, x0::AbstractArray) end """ lossfunc(x, imager::Imager2D) The Loss function for the basic 2-dimensional RML Imaging problem. Returns the cost function. # Arguments - `x::AbstractArray`: the image parameters - `imager::Imager2D`: RML Imaging Setting """ function lossfunc(x::AbstractArray, imager::Imager2D) # get the linear scale image x_linear = transform_linear_forward(imager.skymodel, x) # Get the Stokes I image V = forward(imager.ft, x_linear) # Initialize cost function c = 0 # Chisquares for datamodel in imager.datamodels c += chisquare(datamodel, V) end # Regularization functions for reg in imager.regularlizers c += cost(reg, imager.skymodel, x) end return c end """ evaluate(imager::Imager2D, image::AbstractEHTImage) Evaluate chisquares and regularizers from the input image # Arguments - `imager::Imager2D`: RML Imaging Setting - `image::AbstractEHTImage`: the image """ function evaluate(imager::Imager2D, image::AbstractEHTImage) return evaluate(imager, initialize(imager.skymodel, image)) end """ evaluate(imager::Imager2D, x::AbstractArray) Evaluate chisquares and regularizers from the input image parameters # Arguments - `imager::Imager2D`: RML Imaging Setting - `x::AbstractArray`: the image parameters """ function evaluate(imager::Imager2D, x::AbstractArray) # Get the Stokes I image V = forward(imager.ft, transform_linear_forward(imager.skymodel, x)) # initialize dict outdict = OrderedDict() # Initialize cost function c = 0 # Chisquares for datamodel in imager.datamodels chisq = chisquare(datamodel, V) outdict[functionlabel(datamodel)] = chisq c += chisq end # Regularization functions for reg in imager.regularlizers regcost = cost(reg, imager.skymodel, x) outdict[functionlabel(reg)] = regcost c += regcost end outdict[:cost] = c return outdict end """ map(image::EHTImages.AbstractEHTImage, imager::Imager2D, x::AbstractArray[, idx]) """ function Base.map(image::EHTImages.AbstractEHTImage, imager::Imager2D, x::AbstractArray) return map(image, imager.skymodel, x) end function Base.map(image::EHTImages.AbstractEHTImage, imager::Imager2D, x::AbstractArray, idx) return map(image, imager.skymodel, x, idx) end function Base.map(image::EHTImages.AbstractEHTImage, imager::Imager2D, solution::Optimization.SciMLBase.OptimizationSolution) return map(image, imager.skymodel, solution.u) end function Base.map(image::EHTImages.AbstractEHTImage, imager::Imager2D, solution::Optimization.SciMLBase.OptimizationSolution, idx) return map(image, imager.skymodel, solution.u, idx) end """ map!(image::EHTImages.AbstractEHTImage, imager::Imager2D, x::AbstractArray[, idx]) """ function Base.map!(image::EHTImages.AbstractEHTImage, imager::Imager2D, x::AbstractArray) map!(image, imager.skymodel, x) end function Base.map!(image::EHTImages.AbstractEHTImage, imager::Imager2D, x::AbstractArray, idx) map!(image, imager.skymodel, x, idx) end function Base.map!(image::EHTImages.AbstractEHTImage, imager::Imager2D, solution::Optimization.SciMLBase.OptimizationSolution) map!(image, imager.skymodel, solution.u) end function Base.map!(image::EHTImages.AbstractEHTImage, imager::Imager2D, solution::Optimization.SciMLBase.OptimizationSolution, idx) map!(image, imager.skymodel, solution.u, idx) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
3615
export domain export evaluate export functionlabel export hyperparameter export LinearDomain export ParameterDomain """ AbstractRegularizer # Mandatory fields - `hyperparameter::Number`: the hyper parameter of the regularization function. In default, it should be a number. - `domain::RegularizerDomain`: the domain of the image space where the regularization function will be computed. # Mandatory methods - `evaluate(::AbstractRegularizerDomain, ::AbstractRegularizer, ::AbstractImageModel, ::AbstractArray)`: Evaluate the regularization function for the given input sky image. - `evaluate(::AbstractRegularizer, ::AbstractImageModel, ::AbstractArray)`: Evaluate the regularization function for the given input sky image. - `cost(::AbstractRegularizer, ::AbstractImageModel, ::AbstractArray)`: Evaluate the cost function for the given input sky image. The cost function is defined by the product of its hyperparameter and regularization function. - `` """ abstract type AbstractRegularizer end # computing domain abstract type AbstractRegularizerDomain end # computing domain struct LinearDomain <: AbstractRegularizerDomain end struct ParameterDomain <: AbstractRegularizerDomain end # function to get the label for regularizer functionlabel(::AbstractRegularizer) = :namelessregularizer # function to get domain and hyper parameter """ domain(reg::AbstractRegularizer) = reg.domain Return the computing domain of the given regularizer. """ domain(reg::AbstractRegularizer) = reg.domain """ hyperparameter(reg::AbstractRegularizer) = reg.hyperparameter Return the hyperparameter of the given regularizer. """ hyperparameter(reg::AbstractRegularizer) = reg.hyperparameter """ evaluate(domain::AbstractRegularizerDomain, reg::AbstractRegularizer, skymodel::AbstractImageModel, x::AbstractArray) Compute the value of the given regularization function for the given image parameters on the given image model. In default, return 0. # Arguments - `domain::AbstractRegularizerDomain`: the domain of the image where the regularization function will be computed. - `reg::AbstractRegularizer`: the regularization function. - `skymodel::AbstractImageModel`: the model of the input image - `x::AbstractArray`: the parameters of the input image """ evaluate(::AbstractRegularizerDomain, ::AbstractRegularizer, ::AbstractImageModel, ::AbstractArray) = 0 """ evaluate(reg::AbstractRegularizer, skymodel::AbstractImageModel, x::AbstractArray) Compute the value of the given regularization function for the given image parameters on the given image model. In default, return evaluate(domain(reg), reg, skymodel, x). # Arguments - `reg::AbstractRegularizer`: the regularization function. - `skymodel::AbstractImageModel`: the model of the input image - `x::AbstractArray`: the parameters of the input image """ evaluate(reg::AbstractRegularizer, skymodel::AbstractImageModel, x::AbstractArray) = evaluate(reg.domain, reg, skymodel, x) """ cost(reg::AbstractRegularizer, skymodel::AbstractImageModel, x::AbstractArray) Compute the cost function of the given regularization function for the given image parameters on the given image model. In default, this should return `reg.hyperparameter .* evaluate(reg, skymodel, x)`. # Arguments - `reg::AbstractRegularizer`: the regularization function. - `skymodel::AbstractImageModel`: the model of the input image - `x::AbstractArray`: the parameters of the input image """ function cost(reg::AbstractRegularizer, skymodel::AbstractImageModel, x::AbstractArray) return reg.hyperparameter .* evaluate(reg, skymodel, x) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
1157
export KLEntropy """ KLEntropy <: AbstractRegularizer Regularizer using the Kullback-Leibler divergence (or a relative entropy). # fields - `hyperparameter::Number`: the hyperparameter of the regularizer - `prior`: the prior image. - `domain::AbstractRegularizerDomain`: the image domain where the regularization funciton will be computed. KLEntropy can be computed only in `LinearDomain()`. """ struct KLEntropy <: AbstractRegularizer hyperparameter::Number prior domain::AbstractRegularizerDomain end functionlabel(::KLEntropy) = :klentropy """ klentropy_base(x::AbstractArray, p::AbstractArray) Base function of the l1norm. # Arguments - `I::AbstractArray`: the image """ @inline function klentropy_base(x::AbstractArray, p::AbstractArray) # compute the total flux totalflux = sum_floop(x, ThreadedEx()) # compute xlogx @inbounds xnorm = x ./ totalflux @inbounds xlogx = xnorm .* log.(xnorm ./ p) return sum(xlogx) end function evaluate(::LinearDomain, reg::KLEntropy, skymodel::AbstractImage2DModel, x::AbstractArray) return klentropy_base(transform_linear_forward(skymodel, x), reg.prior) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
1232
export L1Norm """ L1Norm <: AbstractRegularizer Regularizer using the l1-norm. # fields - `hyperparameter::Number`: the hyperparameter of the regularizer - `weight`: the weight of the regularizer, which could be a number or an array. - `domain::AbstractRegularizerDomain`: the image domain where the regularization funciton will be computed. L1Norm can be computed only in `LinearDomain()`. """ struct L1Norm <: AbstractRegularizer hyperparameter::Number weight domain::AbstractRegularizerDomain end # function label functionlabel(::L1Norm) = :l1norm """ l1norm(I::AbstractArray) Base function of the l1norm. # Arguments - `I::AbstractArray`: the image """ @inline l1norm(x::AbstractArray) = @inbounds sum(abs.(x)) """ l1norm(I::AbstractArray, w::Number) Base function of the l1norm. # Arguments - `I::AbstractArray`: the image - `w::Number`: the regularization weight """ @inline l1norm(x::AbstractArray, w::Number) = w * l1norm(x) """ evaluate(::AbstractRegularizer, skymodel::AbstractImage2DModel, x::AbstractArray) """ function evaluate(::LinearDomain, reg::L1Norm, skymodel::AbstractImage2DModel, x::AbstractArray) return l1norm(transform_linear_forward(skymodel, x), reg.weight) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
3631
export TSV """ TSV <: AbstractRegularizer Regularizer using the Istropic Total Squared Variation # fields - `hyperparameter::Number`: the hyperparameter of the regularizer - `weight`: the weight of the regularizer, which may be used for multi-dimensional images. - `domain::AbstractRegularizerDomain`: the image domain where the regularization funciton will be computed. """ struct TSV <: AbstractRegularizer hyperparameter::Number weight domain::AbstractRegularizerDomain end # function label functionlabel(::TSV) = :tsv """ tsv_base_pixel(I::AbstractArray, ix::Integer, iy::Integer) Return the squared variation for the given pixel. """ @inline function tsv_base_pixel(I::AbstractArray, ix::Integer, iy::Integer) if ix < size(I, 1) @inbounds ΔIx = I[ix+1, iy] - I[ix, iy] else ΔIx = 0 end if iy < size(I, 2) @inbounds ΔIy = I[ix, iy+1] - I[ix, iy] else ΔIy = 0 end return ΔIx^2 + ΔIy^2 end """ tsv_base_grad_pixel(I::AbstractArray, ix::Integer, iy::Integer) Return the gradient of the squared variation for the given pixel. """ @inline function tsv_base_grad_pixel(I::AbstractArray, ix::Integer, iy::Integer) nx = size(I, 1) ny = size(I, 2) i1 = ix j1 = iy i0 = i1 - 1 j0 = j1 - 1 i2 = i1 + 1 j2 = j1 + 1 grad = 0.0 # For ΔIx = I[i+1,j] - I[i,j] if i2 < nx + 1 @inbounds grad += -2 * (I[i2, j1] - I[i1, j1]) end # For ΔIy = I[i,j+1] - I[i,j] if j2 < ny + 1 @inbounds grad += -2 * (I[i1, j2] - I[i1, j1]) end # For ΔIx = I[i,j] - I[i-1,j] if i0 > 0 @inbounds grad += +2 * (I[i1, j1] - I[i0, j1]) end # For ΔIy = I[i,j] - I[i,j-1] if j0 > 0 @inbounds grad += +2 * (I[i1, j1] - I[i1, j0]) end return grad end """ tsv_base(I::AbstractArray; ex::FLoops's Executor) Base function of the istropic total squared Variation. # Arguments - `I::AbstractArray`: the input two dimensional real image """ @inline function tsv_base(I::AbstractArray) value = 0.0 for iy = 1:size(I, 2), ix = 1:size(I, 1) value += tsv_base_pixel(I, ix, iy) end return value end function ChainRulesCore.rrule(::typeof(tsv_base), x::AbstractArray) y = tsv_base(x) function pullback(Δy) f̄bar = NoTangent() xbar = @thunk(tsv_base_grad(x) * Δy) return f̄bar, xbar end return y, pullback end @inline function tsv_base_grad(I::AbstractArray) nx = size(I, 1) ny = size(I, 2) grad = zeros(nx, ny) for iy in 1:ny, ix in 1:nx @inbounds grad[ix, iy] = tsv_base_grad_pixel(I, ix, iy) end return grad end """ tsv_base(I::AbstractArray, w::Number; ex::Floop's Executor) Base function of the istropic total squared Variation. # Arguments - `I::AbstractArray`: the input two dimensional real image - `w::Number`: the regularization weight """ @inline function tsv_base(I::AbstractArray, w::Number) return w * tsv_base(I) end function ChainRulesCore.rrule(::typeof(tsv_base), x::AbstractArray, w::Number) y = tsv_base(x, w) function pullback(Δy) f̄bar = NoTangent() xbar = @thunk(w .* tsv_base_grad(x) .* Δy) wbar = NoTangent() return f̄bar, xbar, wbar end return y, pullback end function evaluate(::LinearDomain, reg::TSV, skymodel::AbstractImage2DModel, x::AbstractArray) return tsv_base(transform_linear_forward(skymodel, x), reg.weight) end function evaluate(::ParameterDomain, reg::TSV, skymodel::AbstractImage2DModel, x::AbstractArray) return tsv_base(x, reg.weight) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
4666
export TV """ TV <: AbstractRegularizer Regularizer using the Istropic Total Variation # fields - `hyperparameter::Number`: the hyperparameter of the regularizer - `weight`: the weight of the regularizer, which may be used for multi-dimensional images. - `domain::AbstractRegularizerDomain`: the image domain where the regularization funciton will be computed. """ struct TV <: AbstractRegularizer hyperparameter::Number weight domain::AbstractRegularizerDomain end # function label functionlabel(::TV) = :tv """ tv_base_pixel(I::AbstractArray, ix::Integer, iy::Integer) Evaluate the istropic variation term for the given pixel. """ @inline function tv_base_pixel(I::AbstractArray, ix::Integer, iy::Integer) nx = size(I, 1) ny = size(I, 2) if ix < nx @inbounds ΔIx = I[ix+1, iy] - I[ix, iy] else ΔIx = 0 end if iy < ny @inbounds ΔIy = I[ix, iy+1] - I[ix, iy] else ΔIy = 0 end return √(ΔIx^2 + ΔIy^2) end """ tv_base_pixel(I::AbstractArray, ix::Integer, iy::Integer) Evaluate the gradient of the istropic variation term for the given pixel. """ @inline function tv_base_grad_pixel(I::AbstractArray, ix::Integer, iy::Integer) nx = size(I, 1) ny = size(I, 2) i1 = ix j1 = iy i0 = i1 - 1 j0 = j1 - 1 i2 = i1 + 1 j2 = j1 + 1 grad = 0.0 # # For ΔIx = I[i+1,j] - I[i,j], ΔIy = I[i,j+1] - I[i,j] # # ΔIx = I[i+1,j] - I[i,j] if i2 > nx ΔIx = 0.0 else @inbounds ΔIx = I[i2, j1] - I[i1, j1] end # ΔIy = I[i,j+1] - I[i,j] if j2 > ny ΔIy = 0.0 else @inbounds ΔIy = I[i1, j2] - I[i1, j1] end # compute variation and its gradient tv = √(ΔIx^2 + ΔIy^2) if tv > 0 grad += -(ΔIx + ΔIy) / tv end # # For ΔIx= I[i,j]-I[i-1,j], ΔIy = I[i-1,j]-I[i-1,j] # if (i0 > 0) # ΔIx = I[i,j] - I[i-1,j] @inbounds ΔIx = I[i1, j1] - I[i0, j1] # ΔIy = I[i-1,j+1] - I[i-,j] if j2 > ny ΔIy = 0 else @inbounds ΔIy = I[i0, j2] - I[i0, j1] end # compute variation and its gradient tv = √(ΔIx^2 + ΔIy^2) if tv > 0 grad += ΔIx / tv end end # # For ΔIx= I[i+1,j-1]-I[i,j-1], ΔIy = I[i,j]-I[i,j-1] # if (j0 > 0) # ΔIx= I[i+1,j-1] - I[i,j-1] if i2 > nx ΔIx = 0 else @inbounds ΔIx = I[i2, j0] - I[i1, j0] end # ΔIy = I[i,j] - I[i,j-1] @inbounds ΔIy = I[i1, j1] - I[i1, j0] # compute variation and its gradient tv = √(ΔIx^2 + ΔIy^2) if tv > 0 grad += ΔIy / tv end end return grad end """ tv_base(I::AbstractArray; ex::FLoops's Executor) Base function of the istropic total variation. # Arguments - `I::AbstractArray`: the input two dimensional real image """ @inline function tv_base(I::AbstractArray) value = 0.0 for iy = 1:size(I, 2), ix = 1:size(I, 1) value += tv_base_pixel(I, ix, iy) end return value end # Gradient for tv_base: Chain Rule function ChainRulesCore.rrule(::typeof(tv_base), x::AbstractArray) y = tv_base(x) function pullback(Δy) f̄bar = NoTangent() xbar = @thunk(tv_base_grad(x) .* Δy) return f̄bar, xbar end return y, pullback end # Gradient for tv_base: Gradient Function @inline function tv_base_grad(I::AbstractArray) nx = size(I, 1) ny = size(I, 2) grad = zeros(nx, ny) for iy = 1:ny, ix = 1:nx @inbounds grad[ix, iy] = tv_base_grad_pixel(I, ix, iy) end return grad end """ tv_base(I::AbstractArray, w::Number; ex::FLoops's Executor) Base function of the istropic total variation. # Arguments - `I::AbstractArray`: the input two dimensional real image - `w::Number`: the regularization weight """ @inline function tv_base(I::AbstractArray, w::Number) return w * tv_base(I) end function ChainRulesCore.rrule(::typeof(tv_base), x::AbstractArray, w::Number) y = tv_base(x, w) function pullback(Δy) f̄bar = NoTangent() xbar = @thunk(w .* tv_base_grad(x) .* Δy) wbar = NoTangent() return f̄bar, xbar, wbar end return y, pullback end # Evaluation functions # LinearDomain function evaluate(::LinearDomain, reg::TV, skymodel::AbstractImage2DModel, x::AbstractArray) return tv_base(transform_linear_forward(skymodel, x), reg.weight) end # ParameteDomain function evaluate(::ParameterDomain, reg::TV, skymodel::AbstractImage2DModel, x::AbstractArray) return tv_base(x, reg.weight) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
76
""" Abstract type for uv-coverages. """ abstract type AbstractUVCoverage end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
354
export unique_ids function unique_ids(itr) v = Vector{eltype(itr)}() d = Dict{eltype(itr),Int}() revid = Vector{Int}() for val in itr if haskey(d, val) push!(revid, d[val]) else push!(v, val) d[val] = length(v) push!(revid, length(v)) end end (v, revid) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
467
export SingleUVCoverage """ SingleUVCoverage(u, v, reverse_idx) <: AbstractUVCoverage A basic type for single uv-coverage. # Arguemnts: - `u::Vector` - `v::Vector` - `reverse_idx::Vector` """ struct SingleUVCoverage <: AbstractUVCoverage u::Vector v::Vector reverse_idx::Vector end function SingleUVCoverage(u::Vector, v::Vector)::SingleUVCoverage uvc, idx = unique_ids(u .+ 1im .* v) return SingleUVCoverage(real(uvc), imag(uvc), idx) end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
code
93
using RMLImaging using Test @testset "RMLImaging.jl" begin # Write your tests here. end
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
docs
3718
# RMLImaging [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://ehtjulia.github.io/RMLImaging.jl/dev/) [![Build Status](https://github.com/EHTJulia/RMLImaging.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/EHTJulia/RMLImaging.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/EHTJulia/RMLImaging.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/EHTJulia/RMLImaging.jl) This module provides radio astornomy tool kits of the Regularized Maximum Likelihood (RML) imaging methods of radio interferometry. The current focus is the implementation of RML imaging methods for high-angular-resolution imaging within a modest field of view where the direction-dependent effects are ignorable. The tool kits and algorithms are designed to meet the need for multi-dimensional imaging with Very Long Baseline Interferometry (e.g. Event Horizon Telescope) and millimeter interferometry (e.g. ALMA). The library aims to provide the following features: - Julia native implementation of the end-to-end RML imaging process: all the codes involved in RML imaging methods are written in Julia. This allows a significant accerelation from popular python implementations of RML imaging methods, with keeping the easiness to install the package and its dependencies. The Julia-native codes allow the utilization of various powerful packages in Julia's ecosystem --- this also offers the potential to scale the entire code to GPU and clusters easily in the future. - A set of data types and functions for the sky intensity distributions, non-uniform fast Fourier transformations (NUFFT), regularization functions, data likelihood functions, and optimization to solve images. Julia's efficient way of abstracting data types and their function allows interested users to implement their imaging methods. - AD-friendly implementation: the relevant functions for imaging (e.g., forward/adjoint transforms from sky images to Fourier-domain visibilities, regularization functions) are compatible with Automatic differentiation (AD) packages in [the Julia's ChainRules ecosystem](https://juliadiff.org/ChainRulesCore.jl/stable/), for instance [Zygote.jl](https://fluxml.ai/Zygote.jl/stable/). This allows the easier implementation of algorithms using complicated sky models or sets of data products. ## Installation Assuming that you already have Julia correctly installed, it suffices to import RMLImaging.jl in the standard way: ```julia using Pkg Pkg.add("RMLImaging") ``` ## Documentation The documentation is in preparation, but docstrings of available functions are listed for the [latest](https://ehtjulia.github.io/RMLImaging.jl/dev) version. The stable version has not been released. ## Acknowledgements The development of this package has been finantially supported by the following programs. - [AST-2107681](https://www.nsf.gov/awardsearch/showAward?AWD_ID=2107681), National Science Foundation, USA: v0.1.2 - present - [AST-2034306](https://www.nsf.gov/awardsearch/showAward?AWD_ID=2034306), National Science Foundation, USA: v0.1.2 - present - [OMA-2029670](https://www.nsf.gov/awardsearch/showAward?AWD_ID=2029670), National Science Foundation, USA: v0.1.2 - present - [AST-1935980](https://www.nsf.gov/awardsearch/showAward?AWD_ID=1935980), National Science Foundation, USA: v0.1.2 - present - [ALMA North American Development Study Cycle 8](https://science.nrao.edu/facilities/alma/science_sustainability/alma-develop-history), National Radio Astronomy Observatory, USA: v0.1.0 - v0.1.2 The National Radio Astronomy Observatory is a facility of the National Science Foundation operated under cooperative agreement by Associated Universities, Inc.
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MIT" ]
0.1.4
03574cb9370b6eba0f3ace63f75b6028b3ba90b3
docs
188
```@meta CurrentModule = RMLImaging ``` # RMLImaging Documentation for [RMLImaging](https://github.com/RMLImaging/RMLImaging.jl). ```@index ``` ```@autodocs Modules = [RMLImaging] ```
RMLImaging
https://github.com/EHTJulia/RMLImaging.jl.git
[ "MPL-2.0" ]
0.2.0
62d32ca894772a549212729e4adba54df7428e06
code
295
using Documenter, DiceRolls makedocs( sitename = "DiceRolls.jl", format = Documenter.HTML( assets = ["assets/style.css"], prettyurls = get(ENV, "CI", nothing) == "true" ) ) deploydocs( repo = "github.com/abelsiqueira/DiceRolls.jl.git", devbranch = "main", )
DiceRolls
https://github.com/abelsiqueira/DiceRolls.jl.git