raindown 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: baf58826a9f492870795c2cfb36104ffb214b7494c0b14a2b11aa5f5a7711c64
4
- data.tar.gz: 136d56da8dd7574698769f971bcce51662c89f29b28e2b87acb758017f9ee708
3
+ metadata.gz: 9b5aafde0e04b0aa360b2dbafc68d924cdbf5675e3e80728219166c03c3a8ad4
4
+ data.tar.gz: 04a815c2fb42f8b756aadab2a183789b53258727900fd44636b602aaa394931f
5
5
  SHA512:
6
- metadata.gz: 2ceb319ab5a5c1482a6d09f98b75e95bf22ece5ca8477b54621ee542691c6de3ee243dc0ef3f580971167cb116990a89a28ae5a4012b50c16ec659a8fcdf5cfa
7
- data.tar.gz: 411f712343878e32a1efc7d99932254984e3f0dc45ba91a8b41316fcbf61e9aa0c404ea7d66fc75e0293975d60632e28bde04adcd044d8e3dc36c02ddf9390c2
6
+ metadata.gz: fdb94e3edf51cd99ad3e6dd24f376f420d44c0e17eb5af90f56a2a5809a9da4962cfc72f5759dc30cc2050f76b6c70739726f0e4de598edaaab48a452c9eaac3
7
+ data.tar.gz: 51225830c8c64cd5dfb8bde92e2e9244db0a8d2418deaa167c437c0ddc16a4534ca91af90cc8b919dd963fb37040f0a781543d688d8068e447f676aaea177198
@@ -31,9 +31,12 @@ module Raindown
31
31
  @tail = tail
32
32
  end
33
33
 
34
- # The data is read every time, so the chart follows changes to its file.
34
+ # The data is read every time, so the chart follows changes to its file. A chart with points of its own, like a
35
+ # project's chart of its commits, needs no file.
35
36
  def rewrite(metadata: NoMetadata)
36
- return Problem.alert('Needs a file path to a CSV, TSV, JSON or YAML file') if ['', nil].include?(@data)
37
+ if ['', nil].include?(@data) && method(:points).owner == Chart
38
+ return Problem.alert('Needs a file path to a CSV, TSV, JSON or YAML file')
39
+ end
37
40
 
38
41
  points = points(metadata:)
39
42
  return '' if points.empty?
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'csv'
3
+ # Loaded when first used, as it loads strscan, a native extension, which slows a packed executable's start.
4
+ autoload :CSV, 'csv'
4
5
  require 'json'
5
6
  require 'yaml'
6
7
 
data/lib/raindown/code.rb CHANGED
@@ -1,24 +1,56 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'commonmarker'
3
+ require_relative 'code_blocks'
4
4
 
5
5
  module Raindown
6
6
  # Finds code in Markdown the way Commonmarker reads it: code spans and fenced, indented or quoted code blocks.
7
7
  module Code
8
+ # A code span on one line, like `{x}`, between runs of the same number of backticks.
9
+ SPAN = /(?<!`)(`+)(?!`).+?(?<!`)\1(?!`)/n
10
+
8
11
  module_function
9
12
 
10
- # Byte ranges of code in the Markdown, from Commonmarker's line and column positions.
13
+ # Byte ranges of code in the Markdown, from Commonmarker's line and column positions, or rendering Markdown, which
14
+ # doesn't load Commonmarker, its fenced blocks and code spans.
11
15
  def ranges(markdown)
12
- line_offsets = markdown.each_line.reduce([0]) { |offsets, line| offsets << (offsets.last + line.bytesize) }
16
+ return scanned_ranges(markdown) unless Raindown.commonmark?
17
+
18
+ offsets = line_offsets(markdown.lines)
13
19
  ranges = []
14
20
 
15
- Commonmarker.parse(markdown, options: MARKDOWN_OPTIONS).walk do |node|
16
- ranges << range(node.source_position, line_offsets) if %i[code code_block].include?(node.type)
21
+ Raindown.parse_markdown(markdown).walk do |node|
22
+ ranges << range(node.source_position, offsets) if %i[code code_block].include?(node.type)
17
23
  end
18
24
 
19
25
  ranges
20
26
  end
21
27
 
28
+ # The byte offset each line starts at, and the end's.
29
+ def line_offsets(lines)
30
+ lines.reduce([0]) { |offsets, line| offsets << (offsets.last + line.bytesize) }
31
+ end
32
+
33
+ def scanned_ranges(markdown)
34
+ lines = markdown.lines
35
+ offsets = line_offsets(lines)
36
+ ranges = []
37
+ index = 0
38
+ while index < lines.length
39
+ if (block = CodeBlocks.at(lines, index))
40
+ ranges << (offsets[index]...offsets[block[:close] + 1])
41
+ index = block[:close]
42
+ else
43
+ ranges.concat(span_ranges(lines[index], offsets[index]))
44
+ end
45
+ index += 1
46
+ end
47
+ ranges
48
+ end
49
+
50
+ def span_ranges(line, start)
51
+ line.b.to_enum(:scan, SPAN).map { (start + ::Regexp.last_match.begin(0))...(start + ::Regexp.last_match.end(0)) }
52
+ end
53
+
22
54
  def range(position, line_offsets)
23
55
  start = line_offsets[position[:start_line] - 1] + position[:start_column] - 1
24
56
  # A block that ends with its last line ends at column 0 of the line after.
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'commonmarker'
4
-
5
3
  require_relative '../raindown'
6
4
  require_relative 'bare_directives'
7
5
  require_relative 'code_blocks'
@@ -72,7 +70,7 @@ module Raindown
72
70
  private
73
71
 
74
72
  def root
75
- @root ||= Commonmarker.parse(@markdown, options: MARKDOWN_OPTIONS)
73
+ @root ||= Raindown.parse_markdown(@markdown)
76
74
  end
77
75
 
78
76
  def text(heading)
@@ -10,9 +10,11 @@ module Raindown
10
10
  module Editing
11
11
  module_function
12
12
 
13
- def render_markdown(markdown, path:, bare: false)
13
+ # Without commonmark, it's Markdown, for the editor to render itself.
14
+ def render_markdown(markdown, path:, bare: false, commonmark: true)
14
15
  Nodes.load(path)
15
- Raindown.render(markdown:, metadata: Pages.for(path), bare: bare || BareDirectives.file?(path), **Config.render_options(path))
16
+ Raindown.render(markdown:, metadata: Pages.for(path), bare: bare || BareDirectives.file?(path), commonmark:,
17
+ **Config.render_options(path))
16
18
  end
17
19
 
18
20
  def rewrite_markdown(markdown, path:, bare: false, execute: false)
@@ -1,10 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'ipaddr'
4
3
  require 'open3'
5
4
  require 'shellwords'
6
- require 'socket'
7
5
  require 'uri'
6
+ require_relative 'curl_request'
8
7
  require_relative 'curl_response'
9
8
 
10
9
  module Raindown
@@ -13,9 +12,14 @@ module Raindown
13
12
  # are allowed: nothing that reads or writes local files, loads a config, or uses another protocol.
14
13
  # Link-local addresses, like the cloud metadata service at 169.254.169.254, are refused, as they can give out
15
14
  # credentials, and redirects aren't followed (no -L), so a URL can't redirect there either.
15
+ # Or, without processes, like in WebAssembly, the request's sent by Curl.fetcher, as the Obsidian plugin sends it with
16
+ # Obsidian's requestUrl, which refuses link-local hosts but can't pin an address or stop redirects as curl does here.
16
17
  module Curl
17
18
  class Error < StandardError; end
18
- Request = Data.define(:method, :url)
19
+ class << self
20
+ # Given a Request, returns its Response, in place of curl.
21
+ attr_accessor :fetcher
22
+ end
19
23
 
20
24
  TIMEOUT = '30'
21
25
  # The variables curl reads a proxy from, which then looks the names up rather than curl.
@@ -54,6 +58,8 @@ module Raindown
54
58
  # Placeholders like {base_url} are replaced from the variables, word by word, so a value can't add options.
55
59
  def run(snippet, variables = nil)
56
60
  args = arguments(snippet, variables)
61
+ return fetch(args) if fetcher
62
+
57
63
  stdout, stderr, status = Open3.capture3('curl', *SAFE_OPTIONS, '--silent', '--show-error', '--max-time', TIMEOUT,
58
64
  *resolve_options(args), *args, '--write-out', Response::WRITE_OUT)
59
65
  raise Error, stderr.strip.empty? ? "curl exited with #{status.exitstatus}" : stderr.strip unless status.success?
@@ -63,22 +69,19 @@ module Raindown
63
69
  raise Error, 'curl is not installed'
64
70
  end
65
71
 
66
- # The snippet's method and URL, like GET https://httpbin.org/uuid, or nil when it can't be read.
72
+ # The snippet's request, like GET https://httpbin.org/uuid, or nil when it can't be read.
67
73
  def request(snippet, variables = nil)
68
- args = arguments(snippet, variables)
69
- Request.new(method: request_method(args), url: args.find { it.match?(URL) })
74
+ Request.from(arguments(snippet, variables))
70
75
  rescue Error
71
76
  nil
72
77
  end
73
78
 
74
- # A snippet that sends data is a POST, unless it says otherwise, as with curl.
75
- def request_method(args)
76
- index = args.index('--request')
77
- return args[index + 1].upcase if index
78
- return 'HEAD' if args.include?('--head')
79
- return 'POST' if args.intersect?(VALUE_CHECKS.keys.grep(/data|json/))
79
+ # With --fail, an error status fails, as curl does.
80
+ def fetch(args)
81
+ response = fetcher.call(Request.from(args))
82
+ raise Error, "The requested URL returned error: #{response.status}" if args.include?('--fail') && response.status >= 400
80
83
 
81
- 'GET'
84
+ response
82
85
  end
83
86
 
84
87
  def arguments(snippet, variables = nil)
@@ -162,7 +165,10 @@ module Raindown
162
165
  # Resolves each URL's host and pins curl to the address it was checked at, like --resolve api.io:443:203.0.113.5,
163
166
  # so the name can't point somewhere else by the time curl looks it up. A host that's already an IP isn't pinned,
164
167
  # and behind a proxy, which looks names up itself, only a host that's an IP is checked.
168
+ # Sockets are loaded only when an endpoint runs, so writing a file back loads none, as WebAssembly has none.
165
169
  def resolve_options(args)
170
+ require 'ipaddr'
171
+ require 'socket'
166
172
  args.grep(URL).flat_map { pin_option(URI.parse(it)) }
167
173
  rescue URI::InvalidURIError => e
168
174
  raise Error, "Can't read the URL: #{e.message}"
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ module Curl
5
+ # The request a snippet makes, with its headers and body, as curl would send it, for Curl.fetcher to send in its place.
6
+ # Data, joined by &, is the body, as a form unless it's --json, or with --get, the URL's query.
7
+ class Request < Data.define(:method, :url, :headers, :body)
8
+ FORM = { 'Content-Type' => 'application/x-www-form-urlencoded' }.freeze
9
+ JSON_HEADERS = { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }.freeze
10
+ HEADER_OPTIONS = { '--user-agent' => 'User-Agent', '--referer' => 'Referer' }.freeze
11
+
12
+ def initialize(method:, url:, headers: {}, body: nil) = super
13
+
14
+ # From curl's checked arguments, with their options spelled long.
15
+ def self.from(args)
16
+ options = options(args)
17
+ url = options.assoc('--url').last
18
+ data = options.filter_map { |option, value| data_value(option, value) }.join('&')
19
+ headers = headers(options)
20
+ return new(method: request_method(args), url:, headers:) if data.empty?
21
+ return new(method: request_method(args), url: with_query(url, data), headers:) if args.include?('--get')
22
+
23
+ new(method: request_method(args), url:, headers: FORM.merge(headers), body: data)
24
+ end
25
+
26
+ # A snippet that sends data is a POST, unless it says otherwise, as with curl.
27
+ def self.request_method(args)
28
+ index = args.index('--request')
29
+ return args[index + 1].upcase if index
30
+ return 'HEAD' if args.include?('--head')
31
+ return 'GET' if args.include?('--get')
32
+ return 'POST' if args.intersect?(VALUE_CHECKS.keys.grep(/data|json/))
33
+
34
+ 'GET'
35
+ end
36
+
37
+ # The options, each with its value or nil, and each URL as a --url, like ['--url', 'https://a.io'].
38
+ def self.options(args)
39
+ words = args.dup
40
+ pairs = []
41
+ until words.empty?
42
+ word = words.shift
43
+ pairs << if VALUE_CHECKS.key?(word) then [word, words.shift]
44
+ elsif word.start_with?('--') then [word, nil]
45
+ else ['--url', word]
46
+ end
47
+ end
48
+ pairs
49
+ end
50
+
51
+ def self.headers(options)
52
+ options.each_with_object({}) do |(option, value), headers|
53
+ case option
54
+ when '--header'
55
+ name, header = value.split(':', 2)
56
+ headers[name.strip] = header.to_s.strip
57
+ when '--user' then headers['Authorization'] = "Basic #{[value].pack('m0')}"
58
+ when '--json' then headers.merge!(JSON_HEADERS)
59
+ else headers[HEADER_OPTIONS[option]] = value if HEADER_OPTIONS.key?(option)
60
+ end
61
+ end
62
+ end
63
+
64
+ # As curl sends it: --data without line breaks, and --data-urlencode encoded.
65
+ def self.data_value(option, value)
66
+ case option
67
+ when '--data', '--data-ascii' then value.delete("\r\n")
68
+ when '--data-raw', '--data-binary', '--json' then value
69
+ when '--data-urlencode' then urlencoded(value)
70
+ end
71
+ end
72
+
73
+ # Like curl's --data-urlencode, with name=content or =content, only the content's encoded.
74
+ def self.urlencoded(value)
75
+ name, equals, content = value.partition('=')
76
+ return URI.encode_uri_component(value) if equals.empty?
77
+
78
+ [name, URI.encode_uri_component(content)].reject(&:empty?).join('=')
79
+ end
80
+
81
+ def self.with_query(url, query)
82
+ return "#{url}&#{query}" if url.include?('?')
83
+
84
+ "#{url}?#{query}"
85
+ end
86
+
87
+ private_class_method :options, :headers, :data_value, :urlencoded, :with_query
88
+ end
89
+ end
90
+ end
@@ -19,10 +19,13 @@ module Raindown
19
19
  def self.parse(stdout)
20
20
  body, _, info = stdout.rpartition(INFO_MARKER)
21
21
  status, seconds, content_type = info.split(' ', 3)
22
- language = LANGUAGES.find { |pattern, _| content_type.to_s.match?(pattern) }&.last || ''
22
+ received(body:, content_type:, status: status.to_i, milliseconds: (seconds.to_f * 1000).round)
23
+ end
23
24
 
24
- new(body: language == 'json' ? pretty_json(body) : body, language:, status: status.to_i,
25
- milliseconds: (seconds.to_f * 1000).round)
25
+ # A response however it was sent, like by Curl.fetcher.
26
+ def self.received(body:, content_type:, status:, milliseconds:)
27
+ language = LANGUAGES.find { |pattern, _| content_type.to_s.match?(pattern) }&.last || ''
28
+ new(body: language == 'json' ? pretty_json(body) : body, language:, status:, milliseconds:)
26
29
  end
27
30
 
28
31
  def self.pretty_json(body)
@@ -33,6 +33,11 @@ module Raindown
33
33
  end
34
34
  end
35
35
 
36
+ class << self
37
+ # A host in place of NodeJS, answering the same requests, like the Obsidian plugin's worker, which runs them itself.
38
+ attr_writer :host
39
+ end
40
+
36
41
  module_function
37
42
 
38
43
  # Loads the JavaScript Components in a .raindown folder, starting NodeJS the first time a folder has any.
@@ -48,7 +48,9 @@ module Raindown
48
48
 
49
49
  def block_lines(lines, block)
50
50
  comment, written = comment_and_written(written_lines(lines, block))
51
- context = { document: @content, metadata: @metadata, bare: @bare, comment:, written: }
51
+ # The document as it's written so far, from the bottom up, so a node sees what the nodes below it just wrote, like
52
+ # the TOC the headings they write.
53
+ context = { document: lines.join, metadata: @metadata, bare: @bare, comment:, written: }
52
54
  written = written_lines_of(node_written(block, context))
53
55
  return [line(lines[block[:open]]), *bare(written, block)] unless block[:close]
54
56
 
@@ -9,7 +9,7 @@ require_relative 'node'
9
9
  require_relative 'problem'
10
10
  require_relative 'stat'
11
11
  require_relative 'table/table'
12
- require_relative 'toc'
12
+ require_relative 'toc/toc'
13
13
 
14
14
  module Raindown
15
15
  # Nodes are LowNodes that a node block writes into the Markdown and renders into the HTML.
@@ -140,8 +140,10 @@ module Raindown
140
140
  end
141
141
  end
142
142
 
143
+ # Rendering Markdown, a node's written as it would be written back.
143
144
  def html(node, context, **keywords)
144
145
  return node.render_template(props: {}).to_s if template?(node.class)
146
+ return call(node, :rewrite, **context.to_h, **keywords).to_s if !Raindown.commonmark? && node.respond_to?(:rewrite)
145
147
 
146
148
  call(node, :render, **context.to_h, **keywords).to_s
147
149
  end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ # What Pages keeps for as long as the process runs, like "raindown server", until it changes: each root's files, and
5
+ # each file's front matter. An editor that's told of every change to the files, like the Obsidian plugin, which knows
6
+ # its vault's, watches them, so their modified times aren't checked each time they're listed, which in WebAssembly takes
7
+ # as long as listing thousands of them.
8
+ module Listings
9
+ # Each file's front matter, by its path, with the time it was modified when it was read.
10
+ def front_matters
11
+ @front_matters ||= {}
12
+ end
13
+
14
+ # Each file's metadata from its path, by its root and path, like order: 1 for docs/_1-setup.md, which only changes
15
+ # with its path.
16
+ def implicit_metadatas
17
+ @implicit_metadatas ||= {}
18
+ end
19
+
20
+ # The front matter the editor's already read, by path, is kept rather than read again.
21
+ def watch(front_matters = {})
22
+ @watched = true
23
+ front_matters.each { |path, front_matter| self.front_matters[path] = [:given, front_matter] }
24
+ end
25
+
26
+ def watched?
27
+ @watched == true
28
+ end
29
+
30
+ # Files or folders added, changed or removed, by path, so their front matter's read again, and each root's listing
31
+ # has the files added and not those removed, rather than listing every file again.
32
+ def changed(paths)
33
+ return if paths.empty?
34
+
35
+ pages.clear
36
+ paths.each do |path|
37
+ front_matters.delete(path)
38
+ listings.each do |root, listing|
39
+ next unless path.start_with?("#{root}/")
40
+
41
+ listing[:file_paths].reject! { it == path || it.start_with?("#{path}/") }
42
+ listing[:file_paths] << path if File.file?(path) && !path.delete_prefix(root).include?('/.')
43
+ end
44
+ end
45
+ end
46
+
47
+ # Each root's Pages, while an editor watching the files says none have changed, so their metadata's worked out once.
48
+ def pages
49
+ @pages ||= {}
50
+ end
51
+
52
+ # The files under the root, outside hidden folders, like Dirload lists them. They're listed again once a folder among
53
+ # them has changed, which adding, removing or renaming a file or folder in it does, or the editor watching says so.
54
+ def file_paths(root)
55
+ listing = listings[root]
56
+ return listing[:file_paths] if listing && (watched? || listing[:folders].all? { |folder, at| modified_at(folder) == at })
57
+
58
+ folders, file_paths = Dir["#{root}/**/*"].partition { File.directory?(it) }
59
+ listings[root] = { file_paths:, folders: [root, *folders].to_h { [it, modified_at(it)] } }
60
+ file_paths
61
+ end
62
+
63
+ def listings
64
+ @listings ||= {}
65
+ end
66
+
67
+ def modified_at(path)
68
+ File.mtime(path) if File.exist?(path)
69
+ end
70
+ end
71
+ end
@@ -1,8 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'front_matter'
3
+ require_relative '../front_matter'
4
+ require_relative 'listings'
4
5
  require_relative 'page'
5
- require_relative 'utils'
6
+ require_relative '../utils'
6
7
 
7
8
  module Raindown
8
9
  # The metadata of a project's Markdown files, which list: lists by tag.
@@ -13,49 +14,31 @@ module Raindown
13
14
  # folder: basics, order: 1, path: docs/_basics/_1-getting-started.md
14
15
  # Folder tags can share a folder name with "&", like docs/_1&_basics/getting-started.md.
15
16
  # An app can add its own metadata by subclassing and overriding implicit_metadata, like Raindeer's URL paths.
16
- # Each file's front matter is only read once something lists the files. The listing and the front matter are kept for
17
- # as long as the process runs, like "raindown server", until they change.
17
+ # Each file's front matter is only read once something lists the files, and kept, with the listing, by Listings.
18
18
  class Pages
19
19
  EXTENSIONS = %w[md rd markdown raindown].freeze
20
20
  SEGMENTS = Regexp.union(['/', '&', '-'])
21
21
 
22
- class << self
23
- # Each file's front matter, by its path, with the time it was modified when it was read.
24
- def front_matters
25
- @front_matters ||= {}
26
- end
22
+ extend Listings
27
23
 
24
+ class << self
28
25
  # The Markdown files under a project's root, the folder with its .raindown folder, or a vault, or else the file's
29
26
  # folder.
30
27
  def for(path)
31
- require_relative 'projects'
28
+ require_relative '../projects'
32
29
  load(root: Projects.content_root(path) || File.dirname(File.expand_path(path)))
33
30
  end
34
31
 
35
- # Lists the files under the root, without loading them, for Dirload.
32
+ # Lists the files under the root, without loading them, for Dirload, once while an editor watching them says none
33
+ # have changed.
36
34
  def load(root:)
35
+ return pages[root] if watched? && pages[root]
36
+
37
37
  require 'dirload'
38
38
  file_types = file_paths(root).group_by { Dirload.extension(file_path: it) }
39
- new(metadata: Dirload::Metadata.new(loaded_paths: {}, missed_paths: [], file_types:), root:)
40
- end
41
-
42
- # The files under the root, outside hidden folders, like Dirload lists them. They're listed again once a folder
43
- # among them has changed, which adding, removing or renaming a file or folder in it does.
44
- def file_paths(root)
45
- listing = listings[root]
46
- return listing[:file_paths] if listing&.dig(:folders)&.all? { |folder, modified| modified_at(folder) == modified }
47
-
48
- folders, file_paths = Dir["#{root}/**/*"].partition { File.directory?(it) }
49
- listings[root] = { file_paths:, folders: [root, *folders].to_h { [it, modified_at(it)] } }
50
- file_paths
51
- end
52
-
53
- def listings
54
- @listings ||= {}
55
- end
56
-
57
- def modified_at(path)
58
- File.mtime(path) if File.exist?(path)
39
+ loaded = new(metadata: Dirload::Metadata.new(loaded_paths: {}, missed_paths: [], file_types:), root:)
40
+ pages[root] = loaded if watched?
41
+ loaded
59
42
  end
60
43
  end
61
44
 
@@ -109,14 +92,18 @@ module Raindown
109
92
  end
110
93
 
111
94
  def process(file_path:)
112
- metadata = @metadata[file_path] = implicit_metadata(file_path:).merge(front_matter(file_path))
95
+ implicit = self.class.implicit_metadatas[[@root, file_path]] ||= implicit_metadata(file_path:)
96
+ metadata = @metadata[file_path] = implicit.merge(front_matter(file_path))
113
97
  metadata.each { |type, tag| Array(tag).each { |item| tag(type:, tag: item, file_path:) } }
114
98
  end
115
99
 
116
- # The file's front matter, read again only when the file's changed since it was last read.
100
+ # The file's front matter, read again only when the file's changed since it was last read, or an editor watching the
101
+ # files says so.
117
102
  def front_matter(file_path)
118
- modified = File.mtime(file_path)
119
103
  modified_then, front_matter = self.class.front_matters[file_path]
104
+ return front_matter if modified_then && self.class.watched?
105
+
106
+ modified = File.mtime(file_path)
120
107
  return front_matter if modified_then == modified
121
108
 
122
109
  FrontMatter.read(file_path).tap { self.class.front_matters[file_path] = [modified, it] }
@@ -3,7 +3,7 @@
3
3
  require 'find'
4
4
  require_relative 'gitignore'
5
5
  require_relative 'nodes'
6
- require_relative 'pages'
6
+ require_relative 'pages/pages'
7
7
 
8
8
  module Raindown
9
9
  # Raindown projects are folders with a .raindown folder, and their Markdown files are watched for changes.
@@ -6,7 +6,7 @@ require_relative 'bare_directives'
6
6
  require_relative 'document'
7
7
  require_relative 'front_matter'
8
8
  require_relative 'nodes'
9
- require_relative 'pages'
9
+ require_relative 'pages/pages'
10
10
  require_relative 'utils'
11
11
 
12
12
  module Raindown
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'csv'
3
+ # Loaded when first used, as it loads strscan, a native extension, which slows a packed executable's start.
4
+ autoload :CSV, 'csv'
4
5
  require 'fileutils'
5
6
 
6
7
  module Raindown
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../front_matter'
4
+ require_relative '../variables'
5
+
6
+ module Raindown
7
+ # The headings of Markdown as it's written, without rendering it, so a table of contents can be written back while
8
+ # it's typed: # headings and underlined ones, outside front matter, code and HTML comments, with their text as it
9
+ # reads, without its links, code or emphasis marks, and ids made the way Commonmarker makes them, numbered when
10
+ # they repeat, like to-read and to-read-1. Variables in them, like {title}, are filled in from the variables given,
11
+ # but headings in if: and for: blocks are as they're written, and headings that components render aren't in it, as
12
+ # they're only in HTML.
13
+ module MarkdownHeadings
14
+ ATX = /\A {0,3}(\#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+\#+)?[ \t]*\z/
15
+ SETEXT = /\A {0,3}(=+|-+)[ \t]*\z/
16
+ FENCE = /\A {0,3}(`{3,}|~{3,})/
17
+ # A line that's a block of its own, rather than a paragraph's, which can't be underlined into a heading.
18
+ BLOCK = /\A {0,3}(?:[|>#<]|[-*+][ \t]|\d+[.)][ \t]|\z)/
19
+ COMMENT = /<!--.*?-->/m
20
+
21
+ module_function
22
+
23
+ def scan(markdown, variables: nil)
24
+ seen = Hash.new(0)
25
+ headings(lines(markdown)).map do |level, written|
26
+ written = filled(written, variables)
27
+ text = plain(written)
28
+ id = anchor(plain(written, images: true))
29
+ count = seen[id]
30
+ seen[id] += 1
31
+ { level:, text:, id: count.zero? ? id : "#{id}-#{count}" }
32
+ end
33
+ end
34
+
35
+ # A heading's id, the way Commonmarker makes it, like to-read for "To read".
36
+ def anchor(heading)
37
+ heading.downcase.gsub(/[^\p{Word}\- ]/, '').tr(' ', '-')
38
+ end
39
+
40
+ # Its lines after its front matter, with its HTML comments blanked out, keeping their lines.
41
+ def lines(markdown)
42
+ _, body = FrontMatter.parse(markdown)
43
+ body.to_s.gsub(COMMENT) { it.gsub(/[^\n]/, '') }.lines(chomp: true)
44
+ end
45
+
46
+ # Each heading's level and text, outside fenced code, in order.
47
+ def headings(lines)
48
+ fence = nil
49
+ lines.each_with_index.filter_map do |line, index|
50
+ marker = line[FENCE, 1]
51
+ if marker || fence
52
+ fence = fence_after(fence, marker)
53
+ next
54
+ end
55
+
56
+ heading(line, index.positive? ? lines[index - 1] : '')
57
+ end
58
+ end
59
+
60
+ # The fence still open after a line with the marker: closed by one like it, at least as long.
61
+ def fence_after(fence, marker)
62
+ return marker unless fence
63
+ return nil if marker&.start_with?(fence[0]) && marker.length >= fence.length
64
+
65
+ fence
66
+ end
67
+
68
+ def heading(line, above)
69
+ if (match = line.match(ATX))
70
+ [match[1].length, match[2].to_s]
71
+ elsif line.match?(SETEXT) && !above.match?(BLOCK) && !above.match?(SETEXT)
72
+ [line.strip.start_with?('=') ? 1 : 2, above]
73
+ end
74
+ end
75
+
76
+ # The heading with its variables filled in, like {title}.
77
+ def filled(text, variables)
78
+ return text unless variables
79
+
80
+ text.gsub(/\{([A-Za-z_][\w.]*)\}/) { Variables.value(variables, ::Regexp.last_match(1)).to_s }
81
+ end
82
+
83
+ # The heading's text as it reads: links as their text, images left out, or as their alt text, as in its id, code
84
+ # without its backticks, emphasis without its marks, but for underscores inside words, HTML without its tags, and
85
+ # escaped characters as themselves.
86
+ def plain(text, images: false)
87
+ text.strip
88
+ .gsub(/!\[([^\]]*)\]\([^)]*\)/) { images ? ::Regexp.last_match(1) : '' }
89
+ .gsub(/\[([^\]]*)\]\([^)]*\)/, '\1')
90
+ .gsub(/(`+)(.+?)\1/) { ::Regexp.last_match(2).strip }
91
+ .gsub(/(\*\*|\*)(?=\S)(.+?)(?<=\S)\1/, '\2')
92
+ .gsub(/(?<![[:alnum:]])(__|_)(?=\S)(.+?)(?<=\S)\1(?![[:alnum:]])/, '\2')
93
+ .gsub(/<[^>]*>/, '')
94
+ .gsub(/\\([[:punct:]])/, '\1')
95
+ .strip
96
+ end
97
+ end
98
+ end
@@ -2,7 +2,8 @@
2
2
 
3
3
  require 'cgi/escape'
4
4
 
5
- require_relative 'node'
5
+ require_relative 'markdown_headings'
6
+ require_relative '../node'
6
7
 
7
8
  module Raindown
8
9
  # The node behind toc: and :toc, a table of contents of the document's headings.
@@ -14,8 +15,10 @@ module Raindown
14
15
  IGNORED = %r{<!--.*?-->|<script\b.*?</script\s*>}mi
15
16
  TAG = /<[^>]*>/
16
17
 
18
+ # From the Markdown as it's written, without rendering it, so it's quick enough to write back as it's typed.
17
19
  def rewrite(document:, metadata: nil, bare: false)
18
- headings = headings_below_title(markdown: document, metadata:, bare:)
20
+ variables = Context.new(document:, metadata: metadata || NoMetadata, bare:).variables
21
+ headings = below_title(MarkdownHeadings.scan(document, variables:))
19
22
  return '' if headings.empty?
20
23
 
21
24
  min_level = headings.map { |heading| heading[:level] }.min
@@ -27,7 +30,7 @@ module Raindown
27
30
 
28
31
  # With the document's final HTML, the headings include ones its components render.
29
32
  def render(document:, html: nil, metadata: nil, bare: false)
30
- items = headings_below_title(markdown: document, html:, metadata:, bare:).map do |heading|
33
+ items = below_title(headings(markdown: document, html:, metadata:, bare:)).map do |heading|
31
34
  "<li class='h#{heading[:level]}'><a href='##{heading[:id]}'>#{CGI.escapeHTML(heading[:text])}</a></li>"
32
35
  end
33
36
 
@@ -44,8 +47,8 @@ module Raindown
44
47
  end
45
48
 
46
49
  # A lone top-level heading that starts the document is its title, so it's left out when there are headings below it.
47
- def headings_below_title(**)
48
- title, *below = headings = headings(**)
50
+ def below_title(headings)
51
+ title, *below = headings
49
52
  return headings if below.empty? || title[:level] != 1 || below.any? { it[:level] == 1 }
50
53
 
51
54
  below
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'csv'
3
+ # Loaded when first used, as it loads strscan, a native extension, which slows a packed executable's start.
4
+ autoload :CSV, 'csv'
4
5
  require 'fileutils'
5
6
  require 'open3'
6
7
  require 'time'
@@ -7,7 +7,7 @@ require_relative '../document'
7
7
  require_relative '../front_matter'
8
8
  require_relative '../node_blocks'
9
9
  require_relative '../nodes'
10
- require_relative '../pages'
10
+ require_relative '../pages/pages'
11
11
  require_relative '../projects'
12
12
  require_relative '../workers/workers'
13
13
  require_relative '../stat'
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative 'code'
4
4
  require_relative 'front_matter'
5
+ require_relative 'toc/markdown_headings'
5
6
 
6
7
  module Raindown
7
8
  # Obsidian's links between notes, which render as Markdown links to the file they name, by its path in the project,
@@ -53,14 +54,9 @@ module Raindown
53
54
  def markdown_link(link, page)
54
55
  name, heading, label = link.captures.map { it&.strip }
55
56
  label ||= [name, heading].compact.join(' > ')
56
- anchor = "##{anchor(heading)}" if heading
57
+ anchor = "##{MarkdownHeadings.anchor(heading)}" if heading
57
58
 
58
59
  "[#{label.gsub(/[\[\]]/) { "\\#{it}" }}](<#{page.path}#{anchor}>)"
59
60
  end
60
-
61
- # A heading's id, the way Commonmarker makes it, like to-read for "To read".
62
- def anchor(heading)
63
- heading.downcase.gsub(/[^\p{Word}\- ]/, '').tr(' ', '-')
64
- end
65
61
  end
66
62
  end
data/lib/raindown.rb CHANGED
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'commonmarker'
4
3
  require 'antlers'
5
4
  require 'antlers/api'
6
5
 
@@ -14,7 +13,7 @@ require_relative 'raindown/fragments'
14
13
  require_relative 'raindown/front_matter'
15
14
  require_relative 'raindown/heading_ids'
16
15
  require_relative 'raindown/node_blocks'
17
- require_relative 'raindown/pages'
16
+ require_relative 'raindown/pages/pages'
18
17
  require_relative 'raindown/pre_renderer'
19
18
  require_relative 'raindown/table/table_formatter'
20
19
  require_relative 'raindown/utils'
@@ -50,31 +49,39 @@ module Raindown
50
49
  # Front matter keys are variables, like {title} or <{ title }>.
51
50
  # Bare directives like "toc:" show in bold in the HTML, and the rest stay hidden, as comments.
52
51
  # Code blocks are highlighted, unless highlight_code is false for a site that highlights code in the browser.
53
- def render(markdown:, metadata: NoMetadata, bare: false, highlight_code: true)
52
+ # Without commonmark, it's Markdown, not HTML, with nodes as they'd be written back, for an app to render itself, like
53
+ # Obsidian's reading view in the plugin, where Commonmarker, which is native, can't run.
54
+ def render(markdown:, metadata: NoMetadata, bare: false, highlight_code: true, commonmark: true)
54
55
  context = Context.new(document: markdown, metadata:, bare: bare || BareDirectives.front_matter?(markdown))
55
56
 
56
- highlighting(highlight_code) do
57
+ rendering(highlight_code:, commonmark:) do
57
58
  Fragments.collect do
58
59
  # Components' HTML goes back in, then their headings get unique ids, before nodes like the TOC see it.
59
60
  html = Nodes.render_placeholders(assembled(context), context)
61
+ output = Directives.render("#{html.chomp}\n")
62
+ next output if commonmark
60
63
 
61
- Directives.render("#{html.chomp}\n")
64
+ output.gsub(/[\u{E000}\u{E001}]/, CODE_BRACES.invert)
62
65
  end
63
66
  end
64
67
  end
65
68
 
66
- # Whether code is highlighted while the block runs, like one document's render,
69
+ # Whether code is highlighted, and Markdown made HTML, while the block runs, like one document's render,
67
70
  # so components and endpoints rendering their own Markdown follow it too.
68
- def highlighting(highlight_code)
69
- outer = Thread.current[:raindown_highlight_code]
70
- Thread.current[:raindown_highlight_code] = highlight_code
71
+ def rendering(highlight_code:, commonmark: true)
72
+ outer = Thread.current[:raindown_rendering]
73
+ Thread.current[:raindown_rendering] = { highlight_code:, commonmark: }
71
74
  yield
72
75
  ensure
73
- Thread.current[:raindown_highlight_code] = outer
76
+ Thread.current[:raindown_rendering] = outer
74
77
  end
75
78
 
76
79
  def highlight_code?
77
- Thread.current[:raindown_highlight_code] != false
80
+ Thread.current[:raindown_rendering]&.fetch(:highlight_code) != false
81
+ end
82
+
83
+ def commonmark?
84
+ Thread.current[:raindown_rendering]&.fetch(:commonmark) != false
78
85
  end
79
86
 
80
87
  # The document's HTML with its components' HTML put back, and unique heading ids.
@@ -88,9 +95,18 @@ module Raindown
88
95
  commonmark(PreRenderer.render(markdown, variables: context.variables, context:))
89
96
  end
90
97
 
91
- # Markdown to HTML, like a document's or a component's slot.
98
+ # Commonmarker's tree of the Markdown. It's only loaded here, as only rendering HTML needs it, so a build without it,
99
+ # like the WebAssembly one, can still write back.
100
+ def parse_markdown(markdown)
101
+ require 'commonmarker'
102
+ Commonmarker.parse(markdown, options: MARKDOWN_OPTIONS)
103
+ end
104
+
105
+ # Markdown to HTML, like a document's or a component's slot, unless it's rendering Markdown.
92
106
  def commonmark(markdown)
93
- doc = Commonmarker.parse(hide_directives(markdown: TableFormatter.gfm(markdown)), options: MARKDOWN_OPTIONS)
107
+ return markdown unless commonmark?
108
+
109
+ doc = parse_markdown(hide_directives(markdown: TableFormatter.gfm(markdown)))
94
110
  preserve_code(doc:)
95
111
 
96
112
  html = highlight_code? ? doc.to_html(options: HTML_OPTIONS) : unhighlighted_html(doc:)
data/lib/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Raindown
4
- VERSION = '0.18.0'
4
+ VERSION = '0.19.0'
5
5
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: raindown
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.18.0
4
+ version: 0.19.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - maedi
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-11-09 00:00:00.000000000 Z
10
+ date: 2026-11-10 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: antlers
@@ -228,6 +228,7 @@ files:
228
228
  - lib/raindown/document.rb
229
229
  - lib/raindown/editing.rb
230
230
  - lib/raindown/endpoint/curl.rb
231
+ - lib/raindown/endpoint/curl_request.rb
231
232
  - lib/raindown/endpoint/curl_response.rb
232
233
  - lib/raindown/endpoint/endpoint_args.rb
233
234
  - lib/raindown/endpoint/endpoint_runner.rb
@@ -245,8 +246,9 @@ files:
245
246
  - lib/raindown/node_blocks.rb
246
247
  - lib/raindown/node_injector.rb
247
248
  - lib/raindown/nodes.rb
248
- - lib/raindown/page.rb
249
- - lib/raindown/pages.rb
249
+ - lib/raindown/pages/listings.rb
250
+ - lib/raindown/pages/page.rb
251
+ - lib/raindown/pages/pages.rb
250
252
  - lib/raindown/pre_renderer.rb
251
253
  - lib/raindown/problem.rb
252
254
  - lib/raindown/projects.rb
@@ -263,7 +265,8 @@ files:
263
265
  - lib/raindown/table/table_formatter.rb
264
266
  - lib/raindown/table/table_formulas.rb
265
267
  - lib/raindown/table/written_table.rb
266
- - lib/raindown/toc.rb
268
+ - lib/raindown/toc/markdown_headings.rb
269
+ - lib/raindown/toc/toc.rb
267
270
  - lib/raindown/tui.rb
268
271
  - lib/raindown/tui/blueprints/blueprints_renderer.rb
269
272
  - lib/raindown/tui/blueprints/blueprints_view.rb
File without changes