DELETED .deepsource.toml
Index: .deepsource.toml
==================================================================
--- .deepsource.toml
+++ /dev/null
@@ -1,8 +0,0 @@
-version = 1
-
-[[analyzers]]
-name = "go"
-enabled = true
-
- [analyzers.meta]
-import_paths = ["github.com/zettelstore/zettelstore"]
Index: LICENSE.txt
==================================================================
--- LICENSE.txt
+++ LICENSE.txt
@@ -1,6 +1,6 @@
-Copyright (c) 2020-2021 Detlef Stern
+Copyright (c) 2020-present Detlef Stern
Licensed under the EUPL
Zettelstore is licensed under the European Union Public License, version 1.2 or
later (EUPL v. 1.2). The license is available in the official languages of the
Index: Makefile
==================================================================
--- Makefile
+++ Makefile
@@ -1,25 +1,31 @@
-## Copyright (c) 2020-2021 Detlef Stern
+## Copyright (c) 2020-present Detlef Stern
##
-## This file is part of zettelstore.
+## This file is part of Zettelstore.
##
## Zettelstore is licensed under the latest version of the EUPL (European Union
## Public License). Please see file LICENSE.txt for your rights and obligations
## under this license.
-.PHONY: check build release clean
+.PHONY: check relcheck api version build release clean
check:
- go run tools/build.go check
+ go run tools/check/check.go
+
+relcheck:
+ go run tools/check/check.go -r
+
+api:
+ go run tools/testapi/testapi.go
version:
- @echo $(shell go run tools/build.go version)
+ @echo $(shell go run tools/build/build.go version)
build:
- go run tools/build.go build
+ go run tools/build/build.go build
release:
- go run tools/build.go release
+ go run tools/build/build.go release
clean:
- go run tools/build.go clean
+ go run tools/clean/clean.go
Index: README.md
==================================================================
--- README.md
+++ README.md
@@ -10,11 +10,17 @@
“Zettelstore”.
To get an initial impression, take a look at the
[manual](https://zettelstore.de/manual/). It is a live example of the
zettelstore software, running in read-only mode.
+
+[Zettelstore Client](https://t73f.de/r/zsc) provides client software to access
+Zettelstore via its API more easily, [Zettelstore
+Contrib](https://zettelstore.de/contrib) contains contributed software, which
+often connects to Zettelstore via its API. Some of the software packages may be
+experimental.
The software, including the manual, is licensed
under the [European Union Public License 1.2 (or
later)](https://zettelstore.de/home/file?name=LICENSE.txt&ci=trunk).
-[Stay tuned](https://twitter.com/zettelstore)…
+[Stay tuned](https://mastodon.social/tags/Zettelstore) …
Index: VERSION
==================================================================
--- VERSION
+++ VERSION
@@ -1,1 +1,1 @@
-0.0.13
+0.22.0-dev
DELETED ast/ast.go
Index: ast/ast.go
==================================================================
--- ast/ast.go
+++ /dev/null
@@ -1,94 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast
-
-import (
- "net/url"
-
- "zettelstore.de/z/domain"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
-)
-
-// ZettelNode is the root node of the abstract syntax tree.
-// It is *not* part of the visitor pattern.
-type ZettelNode struct {
- // Zettel domain.Zettel
- Meta *meta.Meta // Original metadata
- Content domain.Content // Original content
- Zid id.Zid // Zettel identification.
- InhMeta *meta.Meta // Metadata of the zettel, with inherited values.
- Ast BlockSlice // Zettel abstract syntax tree is a sequence of block nodes.
-}
-
-// Node is the interface, all nodes must implement.
-type Node interface {
- Accept(v Visitor)
-}
-
-// BlockNode is the interface that all block nodes must implement.
-type BlockNode interface {
- Node
- blockNode()
-}
-
-// BlockSlice is a slice of BlockNodes.
-type BlockSlice []BlockNode
-
-// ItemNode is a node that can occur as a list item.
-type ItemNode interface {
- BlockNode
- itemNode()
-}
-
-// ItemSlice is a slice of ItemNodes.
-type ItemSlice []ItemNode
-
-// DescriptionNode is a node that contains just textual description.
-type DescriptionNode interface {
- ItemNode
- descriptionNode()
-}
-
-// DescriptionSlice is a slice of DescriptionNodes.
-type DescriptionSlice []DescriptionNode
-
-// InlineNode is the interface that all inline nodes must implement.
-type InlineNode interface {
- Node
- inlineNode()
-}
-
-// InlineSlice is a slice of InlineNodes.
-type InlineSlice []InlineNode
-
-// Reference is a reference to external or internal material.
-type Reference struct {
- URL *url.URL
- Value string
- State RefState
-}
-
-// RefState indicates the state of the reference.
-type RefState int
-
-// Constants for RefState
-const (
- RefStateInvalid RefState = iota // Invalid Reference
- RefStateZettel // Reference to an internal zettel
- RefStateSelf // Reference to same zettel with a fragment
- RefStateFound // Reference to an existing internal zettel
- RefStateBroken // Reference to a non-existing internal zettel
- RefStateHosted // Reference to local hosted non-Zettel, without URL change
- RefStateBased // Reference to local non-Zettel, to be prefixed
- RefStateExternal // Reference to external material
-)
DELETED ast/attr.go
Index: ast/attr.go
==================================================================
--- ast/attr.go
+++ /dev/null
@@ -1,103 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast
-
-import (
- "strings"
-)
-
-// Attributes store additional information about some node types.
-type Attributes struct {
- Attrs map[string]string
-}
-
-// HasDefault returns true, if the default attribute "-" has been set.
-func (a *Attributes) HasDefault() bool {
- if a != nil {
- _, ok := a.Attrs["-"]
- return ok
- }
- return false
-}
-
-// RemoveDefault removes the default attribute
-func (a *Attributes) RemoveDefault() {
- a.Remove("-")
-}
-
-// Get returns the attribute value of the given key and a succes value.
-func (a *Attributes) Get(key string) (string, bool) {
- if a != nil {
- value, ok := a.Attrs[key]
- return value, ok
- }
- return "", false
-}
-
-// Clone returns a duplicate of the attribute.
-func (a *Attributes) Clone() *Attributes {
- if a == nil {
- return nil
- }
- attrs := make(map[string]string, len(a.Attrs))
- for k, v := range a.Attrs {
- attrs[k] = v
- }
- return &Attributes{attrs}
-}
-
-// Set changes the attribute that a given key has now a given value.
-func (a *Attributes) Set(key, value string) *Attributes {
- if a == nil {
- return &Attributes{map[string]string{key: value}}
- }
- if a.Attrs == nil {
- a.Attrs = make(map[string]string)
- }
- a.Attrs[key] = value
- return a
-}
-
-// Remove the key from the attributes.
-func (a *Attributes) Remove(key string) {
- if a != nil {
- delete(a.Attrs, key)
- }
-}
-
-// AddClass adds a value to the class attribute.
-func (a *Attributes) AddClass(class string) *Attributes {
- if a == nil {
- return &Attributes{map[string]string{"class": class}}
- }
- classes := a.GetClasses()
- for _, cls := range classes {
- if cls == class {
- return a
- }
- }
- classes = append(classes, class)
- a.Attrs["class"] = strings.Join(classes, " ")
- return a
-}
-
-// GetClasses returns the class values as a string slice
-func (a *Attributes) GetClasses() []string {
- if a == nil {
- return nil
- }
- classes, ok := a.Attrs["class"]
- if !ok {
- return nil
- }
- return strings.Fields(classes)
-}
DELETED ast/attr_test.go
Index: ast/attr_test.go
==================================================================
--- ast/attr_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast_test
-
-import (
- "testing"
-
- "zettelstore.de/z/ast"
-)
-
-func TestHasDefault(t *testing.T) {
- attr := &ast.Attributes{}
- if attr.HasDefault() {
- t.Error("Should not have default attr")
- }
- attr = &ast.Attributes{Attrs: map[string]string{"-": "value"}}
- if !attr.HasDefault() {
- t.Error("Should have default attr")
- }
-}
-
-func TestAttrClone(t *testing.T) {
- orig := &ast.Attributes{}
- clone := orig.Clone()
- if len(clone.Attrs) > 0 {
- t.Error("Attrs must be empty")
- }
-
- orig = &ast.Attributes{Attrs: map[string]string{"": "0", "-": "1", "a": "b"}}
- clone = orig.Clone()
- m := clone.Attrs
- if m[""] != "0" || m["-"] != "1" || m["a"] != "b" || len(m) != len(orig.Attrs) {
- t.Error("Wrong cloned map")
- }
- m["a"] = "c"
- if orig.Attrs["a"] != "b" {
- t.Error("Aliased map")
- }
-}
DELETED ast/block.go
Index: ast/block.go
==================================================================
--- ast/block.go
+++ /dev/null
@@ -1,204 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast
-
-// Definition of Block nodes.
-
-// ParaNode contains just a sequence of inline elements.
-// Another name is "paragraph".
-type ParaNode struct {
- Inlines InlineSlice
-}
-
-func (pn *ParaNode) blockNode() {}
-func (pn *ParaNode) itemNode() {}
-func (pn *ParaNode) descriptionNode() {}
-
-// Accept a visitor and visit the node.
-func (pn *ParaNode) Accept(v Visitor) { v.VisitPara(pn) }
-
-//--------------------------------------------------------------------------
-
-// VerbatimNode contains lines of uninterpreted text
-type VerbatimNode struct {
- Code VerbatimCode
- Attrs *Attributes
- Lines []string
-}
-
-// VerbatimCode specifies the format that is applied to code inline nodes.
-type VerbatimCode int
-
-// Constants for VerbatimCode
-const (
- _ VerbatimCode = iota
- VerbatimProg // Program code.
- VerbatimComment // Block comment
- VerbatimHTML // Block HTML, e.g. for Markdown
-)
-
-func (vn *VerbatimNode) blockNode() {}
-func (vn *VerbatimNode) itemNode() {}
-
-// Accept a visitor an visit the node.
-func (vn *VerbatimNode) Accept(v Visitor) { v.VisitVerbatim(vn) }
-
-//--------------------------------------------------------------------------
-
-// RegionNode encapsulates a region of block nodes.
-type RegionNode struct {
- Code RegionCode
- Attrs *Attributes
- Blocks BlockSlice
- Inlines InlineSlice // Additional text at the end of the region
-}
-
-// RegionCode specifies the actual region type.
-type RegionCode int
-
-// Values for RegionCode
-const (
- _ RegionCode = iota
- RegionSpan // Just a span of blocks
- RegionQuote // A longer quotation
- RegionVerse // Line breaks matter
-)
-
-func (rn *RegionNode) blockNode() {}
-func (rn *RegionNode) itemNode() {}
-
-// Accept a visitor and visit the node.
-func (rn *RegionNode) Accept(v Visitor) { v.VisitRegion(rn) }
-
-//--------------------------------------------------------------------------
-
-// HeadingNode stores the heading text and level.
-type HeadingNode struct {
- Level int
- Inlines InlineSlice // Heading text, possibly formatted
- Slug string // Heading text, suitable to be used as an URL fragment
- Attrs *Attributes
-}
-
-func (hn *HeadingNode) blockNode() {}
-func (hn *HeadingNode) itemNode() {}
-
-// Accept a visitor and visit the node.
-func (hn *HeadingNode) Accept(v Visitor) { v.VisitHeading(hn) }
-
-//--------------------------------------------------------------------------
-
-// HRuleNode specifies a horizontal rule.
-type HRuleNode struct {
- Attrs *Attributes
-}
-
-func (hn *HRuleNode) blockNode() {}
-func (hn *HRuleNode) itemNode() {}
-
-// Accept a visitor and visit the node.
-func (hn *HRuleNode) Accept(v Visitor) { v.VisitHRule(hn) }
-
-//--------------------------------------------------------------------------
-
-// NestedListNode specifies a nestable list, either ordered or unordered.
-type NestedListNode struct {
- Code NestedListCode
- Items []ItemSlice
- Attrs *Attributes
-}
-
-// NestedListCode specifies the actual list type.
-type NestedListCode int
-
-// Values for ListCode
-const (
- _ NestedListCode = iota
- NestedListOrdered // Ordered list.
- NestedListUnordered // Unordered list.
- NestedListQuote // Quote list.
-)
-
-func (ln *NestedListNode) blockNode() {}
-func (ln *NestedListNode) itemNode() {}
-
-// Accept a visitor and visit the node.
-func (ln *NestedListNode) Accept(v Visitor) { v.VisitNestedList(ln) }
-
-//--------------------------------------------------------------------------
-
-// DescriptionListNode specifies a description list.
-type DescriptionListNode struct {
- Descriptions []Description
-}
-
-// Description is one element of a description list.
-type Description struct {
- Term InlineSlice
- Descriptions []DescriptionSlice
-}
-
-func (dn *DescriptionListNode) blockNode() {}
-
-// Accept a visitor and visit the node.
-func (dn *DescriptionListNode) Accept(v Visitor) { v.VisitDescriptionList(dn) }
-
-//--------------------------------------------------------------------------
-
-// TableNode specifies a full table
-type TableNode struct {
- Header TableRow // The header row
- Align []Alignment // Default column alignment
- Rows []TableRow // The slice of cell rows
-}
-
-// TableCell contains the data for one table cell
-type TableCell struct {
- Align Alignment // Cell alignment
- Inlines InlineSlice // Cell content
-}
-
-// TableRow is a slice of cells.
-type TableRow []*TableCell
-
-// Alignment specifies text alignment.
-// Currently only for tables.
-type Alignment int
-
-// Constants for Alignment.
-const (
- _ Alignment = iota
- AlignDefault // Default alignment, inherited
- AlignLeft // Left alignment
- AlignCenter // Center the content
- AlignRight // Right alignment
-)
-
-func (tn *TableNode) blockNode() {}
-
-// Accept a visitor and visit the node.
-func (tn *TableNode) Accept(v Visitor) { v.VisitTable(tn) }
-
-//--------------------------------------------------------------------------
-
-// BLOBNode contains just binary data that must be interpreted according to
-// a syntax.
-type BLOBNode struct {
- Title string
- Syntax string
- Blob []byte
-}
-
-func (bn *BLOBNode) blockNode() {}
-
-// Accept a visitor and visit the node.
-func (bn *BLOBNode) Accept(v Visitor) { v.VisitBLOB(bn) }
DELETED ast/inline.go
Index: ast/inline.go
==================================================================
--- ast/inline.go
+++ /dev/null
@@ -1,196 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast
-
-// Definitions of inline nodes.
-
-// TextNode just contains some text.
-type TextNode struct {
- Text string // The text itself.
-}
-
-func (tn *TextNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (tn *TextNode) Accept(v Visitor) { v.VisitText(tn) }
-
-// --------------------------------------------------------------------------
-
-// TagNode contains a tag.
-type TagNode struct {
- Tag string // The text itself.
-}
-
-func (tn *TagNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (tn *TagNode) Accept(v Visitor) { v.VisitTag(tn) }
-
-// --------------------------------------------------------------------------
-
-// SpaceNode tracks inter-word space characters.
-type SpaceNode struct {
- Lexeme string
-}
-
-func (sn *SpaceNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (sn *SpaceNode) Accept(v Visitor) { v.VisitSpace(sn) }
-
-// --------------------------------------------------------------------------
-
-// BreakNode signals a new line that must / should be interpreted as a new line break.
-type BreakNode struct {
- Hard bool // Hard line break?
-}
-
-func (bn *BreakNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (bn *BreakNode) Accept(v Visitor) { v.VisitBreak(bn) }
-
-// --------------------------------------------------------------------------
-
-// LinkNode contains the specified link.
-type LinkNode struct {
- Ref *Reference
- Inlines InlineSlice // The text associated with the link.
- OnlyRef bool // True if no text was specified.
- Attrs *Attributes // Optional attributes
-}
-
-func (ln *LinkNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (ln *LinkNode) Accept(v Visitor) { v.VisitLink(ln) }
-
-// --------------------------------------------------------------------------
-
-// ImageNode contains the specified image reference.
-type ImageNode struct {
- Ref *Reference // Reference to image
- Blob []byte // BLOB data of the image, as an alternative to Ref.
- Syntax string // Syntax of Blob
- Inlines InlineSlice // The text associated with the image.
- Attrs *Attributes // Optional attributes
-}
-
-func (in *ImageNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (in *ImageNode) Accept(v Visitor) { v.VisitImage(in) }
-
-// --------------------------------------------------------------------------
-
-// CiteNode contains the specified citation.
-type CiteNode struct {
- Key string // The citation key
- Inlines InlineSlice // The text associated with the citation.
- Attrs *Attributes // Optional attributes
-}
-
-func (cn *CiteNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (cn *CiteNode) Accept(v Visitor) { v.VisitCite(cn) }
-
-// --------------------------------------------------------------------------
-
-// MarkNode contains the specified merked position.
-// It is a BlockNode too, because although it is typically parsed during inline
-// mode, it is moved into block mode afterwards.
-type MarkNode struct {
- Text string
-}
-
-func (mn *MarkNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (mn *MarkNode) Accept(v Visitor) { v.VisitMark(mn) }
-
-// --------------------------------------------------------------------------
-
-// FootnoteNode contains the specified footnote.
-type FootnoteNode struct {
- Inlines InlineSlice // The footnote text.
- Attrs *Attributes // Optional attributes
-}
-
-func (fn *FootnoteNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (fn *FootnoteNode) Accept(v Visitor) { v.VisitFootnote(fn) }
-
-// --------------------------------------------------------------------------
-
-// FormatNode specifies some inline formatting.
-type FormatNode struct {
- Code FormatCode
- Attrs *Attributes // Optional attributes.
- Inlines InlineSlice
-}
-
-// FormatCode specifies the format that is applied to the inline nodes.
-type FormatCode int
-
-// Constants for FormatCode
-const (
- _ FormatCode = iota
- FormatItalic // Italic text.
- FormatEmph // Semantically emphasized text.
- FormatBold // Bold text.
- FormatStrong // Semantically strongly emphasized text.
- FormatUnder // Underlined text.
- FormatInsert // Inserted text.
- FormatStrike // Text that is no longer relevant or no longer accurate.
- FormatDelete // Deleted text.
- FormatSuper // Superscripted text.
- FormatSub // SubscriptedText.
- FormatQuote // Quoted text.
- FormatQuotation // Quotation text.
- FormatSmall // Smaller text.
- FormatSpan // Generic inline container.
- FormatMonospace // Monospaced text.
-)
-
-func (fn *FormatNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (fn *FormatNode) Accept(v Visitor) { v.VisitFormat(fn) }
-
-// --------------------------------------------------------------------------
-
-// LiteralNode specifies some uninterpreted text.
-type LiteralNode struct {
- Code LiteralCode
- Attrs *Attributes // Optional attributes.
- Text string
-}
-
-// LiteralCode specifies the format that is applied to code inline nodes.
-type LiteralCode int
-
-// Constants for LiteralCode
-const (
- _ LiteralCode = iota
- LiteralProg // Inline program code.
- LiteralKeyb // Keyboard strokes.
- LiteralOutput // Sample output.
- LiteralComment // Inline comment
- LiteralHTML // Inline HTML, e.g. for Markdown
-)
-
-func (rn *LiteralNode) inlineNode() {}
-
-// Accept a visitor and visit the node.
-func (rn *LiteralNode) Accept(v Visitor) { v.VisitLiteral(rn) }
DELETED ast/ref.go
Index: ast/ref.go
==================================================================
--- ast/ref.go
+++ /dev/null
@@ -1,92 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast
-
-import (
- "net/url"
-
- "zettelstore.de/z/domain/id"
-)
-
-// ParseReference parses a string and returns a reference.
-func ParseReference(s string) *Reference {
- switch s {
- case "", "00000000000000":
- return &Reference{URL: nil, Value: s, State: RefStateInvalid}
- }
- if state, ok := localState(s); ok {
- if state == RefStateBased {
- s = s[1:]
- }
- u, err := url.Parse(s)
- if err == nil {
- return &Reference{URL: u, Value: s, State: state}
- }
- }
- u, err := url.Parse(s)
- if err != nil {
- return &Reference{URL: nil, Value: s, State: RefStateInvalid}
- }
- if len(u.Scheme)+len(u.Opaque)+len(u.Host) == 0 && u.User == nil {
- if _, err := id.Parse(u.Path); err == nil {
- return &Reference{URL: u, Value: s, State: RefStateZettel}
- }
- if u.Path == "" && u.Fragment != "" {
- return &Reference{URL: u, Value: s, State: RefStateSelf}
- }
- }
- return &Reference{URL: u, Value: s, State: RefStateExternal}
-}
-
-func localState(path string) (RefState, bool) {
- if len(path) > 0 && path[0] == '/' {
- if len(path) > 1 && path[1] == '/' {
- return RefStateBased, true
- }
- return RefStateHosted, true
- }
- if len(path) > 1 && path[0] == '.' {
- if len(path) > 2 && path[1] == '.' && path[2] == '/' {
- return RefStateHosted, true
- }
- return RefStateHosted, path[1] == '/'
- }
- return RefStateInvalid, false
-}
-
-// String returns the string representation of a reference.
-func (r Reference) String() string {
- if r.URL != nil {
- return r.URL.String()
- }
- return r.Value
-}
-
-// IsValid returns true if reference is valid
-func (r *Reference) IsValid() bool { return r.State != RefStateInvalid }
-
-// IsZettel returns true if it is a referencen to a local zettel.
-func (r *Reference) IsZettel() bool {
- switch r.State {
- case RefStateZettel, RefStateSelf, RefStateFound, RefStateBroken:
- return true
- }
- return false
-}
-
-// IsLocal returns true if reference is local
-func (r *Reference) IsLocal() bool {
- return r.State == RefStateHosted || r.State == RefStateBased
-}
-
-// IsExternal returns true if it is a referencen to external material.
-func (r *Reference) IsExternal() bool { return r.State == RefStateExternal }
DELETED ast/ref_test.go
Index: ast/ref_test.go
==================================================================
--- ast/ref_test.go
+++ /dev/null
@@ -1,94 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast_test provides the tests for the abstract syntax tree.
-package ast_test
-
-import (
- "testing"
-
- "zettelstore.de/z/ast"
-)
-
-func TestParseReference(t *testing.T) {
- testcases := []struct {
- link string
- err bool
- exp string
- }{
- {"", true, ""},
- {"123", false, "123"},
- {",://", true, ""},
- }
-
- for i, tc := range testcases {
- got := ast.ParseReference(tc.link)
- if got.IsValid() == tc.err {
- t.Errorf(
- "TC=%d, expected parse error of %q: %v, but got %q", i, tc.link, tc.err, got)
- }
- if got.IsValid() && got.String() != tc.exp {
- t.Errorf("TC=%d, Reference of %q is %q, but got %q", i, tc.link, tc.exp, got)
- }
- }
-}
-
-func TestReferenceIsZettelMaterial(t *testing.T) {
- testcases := []struct {
- link string
- isZettel bool
- isExternal bool
- isLocal bool
- }{
- {"", false, false, false},
- {"00000000000000", false, false, false},
- {"http://zettelstore.de/z/ast", false, true, false},
- {"12345678901234", true, false, false},
- {"12345678901234#local", true, false, false},
- {"http://12345678901234", false, true, false},
- {"http://zettelstore.de/z/12345678901234", false, true, false},
- {"http://zettelstore.de/12345678901234", false, true, false},
- {"/12345678901234", false, false, true},
- {"//12345678901234", false, false, true},
- {"./12345678901234", false, false, true},
- {"../12345678901234", false, false, true},
- {".../12345678901234", false, true, false},
- }
-
- for i, tc := range testcases {
- ref := ast.ParseReference(tc.link)
- isZettel := ref.IsZettel()
- if isZettel != tc.isZettel {
- t.Errorf(
- "TC=%d, Reference %q isZettel=%v expected, but got %v",
- i,
- tc.link,
- tc.isZettel,
- isZettel)
- }
- isLocal := ref.IsLocal()
- if isLocal != tc.isLocal {
- t.Errorf(
- "TC=%d, Reference %q isLocal=%v expected, but got %v",
- i,
- tc.link,
- tc.isLocal, isLocal)
- }
- isExternal := ref.IsExternal()
- if isExternal != tc.isExternal {
- t.Errorf(
- "TC=%d, Reference %q isExternal=%v expected, but got %v",
- i,
- tc.link,
- tc.isExternal,
- isExternal)
- }
- }
-}
DELETED ast/traverser.go
Index: ast/traverser.go
==================================================================
--- ast/traverser.go
+++ /dev/null
@@ -1,161 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast
-
-// A traverser is a Visitor that just traverses the AST and delegates node
-// spacific actions to a Visitor. This Visitor should not traverse the AST.
-
-// TopDownTraverser visits first the node and then the children nodes.
-type TopDownTraverser struct {
- v Visitor
-}
-
-// NewTopDownTraverser creates a new traverser.
-func NewTopDownTraverser(visitor Visitor) TopDownTraverser {
- return TopDownTraverser{visitor}
-}
-
-// VisitVerbatim has nothing to traverse.
-func (t TopDownTraverser) VisitVerbatim(vn *VerbatimNode) { t.v.VisitVerbatim(vn) }
-
-// VisitRegion traverses the content and the additional text.
-func (t TopDownTraverser) VisitRegion(rn *RegionNode) {
- t.v.VisitRegion(rn)
- t.VisitBlockSlice(rn.Blocks)
- t.VisitInlineSlice(rn.Inlines)
-}
-
-// VisitHeading traverses the heading.
-func (t TopDownTraverser) VisitHeading(hn *HeadingNode) {
- t.v.VisitHeading(hn)
- t.VisitInlineSlice(hn.Inlines)
-}
-
-// VisitHRule traverses nothing.
-func (t TopDownTraverser) VisitHRule(hn *HRuleNode) { t.v.VisitHRule(hn) }
-
-// VisitNestedList traverses all nested list elements.
-func (t TopDownTraverser) VisitNestedList(ln *NestedListNode) {
- t.v.VisitNestedList(ln)
- for _, item := range ln.Items {
- t.visitItemSlice(item)
- }
-}
-
-// VisitDescriptionList traverses all description terms and their associated
-// descriptions.
-func (t TopDownTraverser) VisitDescriptionList(dn *DescriptionListNode) {
- t.v.VisitDescriptionList(dn)
- for _, defs := range dn.Descriptions {
- t.VisitInlineSlice(defs.Term)
- for _, descr := range defs.Descriptions {
- t.visitDescriptionSlice(descr)
- }
- }
-}
-
-// VisitPara traverses the inlines of a paragraph.
-func (t TopDownTraverser) VisitPara(pn *ParaNode) {
- t.v.VisitPara(pn)
- t.VisitInlineSlice(pn.Inlines)
-}
-
-// VisitTable traverses all cells of the header and then row-wise all cells of
-// the table body.
-func (t TopDownTraverser) VisitTable(tn *TableNode) {
- t.v.VisitTable(tn)
- for _, col := range tn.Header {
- t.VisitInlineSlice(col.Inlines)
- }
- for _, row := range tn.Rows {
- for _, col := range row {
- t.VisitInlineSlice(col.Inlines)
- }
- }
-}
-
-// VisitBLOB traverses nothing.
-func (t TopDownTraverser) VisitBLOB(bn *BLOBNode) { t.v.VisitBLOB(bn) }
-
-// VisitText traverses nothing.
-func (t TopDownTraverser) VisitText(tn *TextNode) { t.v.VisitText(tn) }
-
-// VisitTag traverses nothing.
-func (t TopDownTraverser) VisitTag(tn *TagNode) { t.v.VisitTag(tn) }
-
-// VisitSpace traverses nothing.
-func (t TopDownTraverser) VisitSpace(sn *SpaceNode) { t.v.VisitSpace(sn) }
-
-// VisitBreak traverses nothing.
-func (t TopDownTraverser) VisitBreak(bn *BreakNode) { t.v.VisitBreak(bn) }
-
-// VisitLink traverses the link text.
-func (t TopDownTraverser) VisitLink(ln *LinkNode) {
- t.v.VisitLink(ln)
- t.VisitInlineSlice(ln.Inlines)
-}
-
-// VisitImage traverses the image text.
-func (t TopDownTraverser) VisitImage(in *ImageNode) {
- t.v.VisitImage(in)
- t.VisitInlineSlice(in.Inlines)
-}
-
-// VisitCite traverses the cite text.
-func (t TopDownTraverser) VisitCite(cn *CiteNode) {
- t.v.VisitCite(cn)
- t.VisitInlineSlice(cn.Inlines)
-}
-
-// VisitFootnote traverses the footnote text.
-func (t TopDownTraverser) VisitFootnote(fn *FootnoteNode) {
- t.v.VisitFootnote(fn)
- t.VisitInlineSlice(fn.Inlines)
-}
-
-// VisitMark traverses nothing.
-func (t TopDownTraverser) VisitMark(mn *MarkNode) { t.v.VisitMark(mn) }
-
-// VisitFormat traverses the formatted text.
-func (t TopDownTraverser) VisitFormat(fn *FormatNode) {
- t.v.VisitFormat(fn)
- t.VisitInlineSlice(fn.Inlines)
-}
-
-// VisitLiteral traverses nothing.
-func (t TopDownTraverser) VisitLiteral(ln *LiteralNode) { t.v.VisitLiteral(ln) }
-
-// VisitBlockSlice traverses a block slice.
-func (t TopDownTraverser) VisitBlockSlice(bns BlockSlice) {
- for _, bn := range bns {
- bn.Accept(t)
- }
-}
-
-func (t TopDownTraverser) visitItemSlice(ins ItemSlice) {
- for _, in := range ins {
- in.Accept(t)
- }
-}
-
-func (t TopDownTraverser) visitDescriptionSlice(dns DescriptionSlice) {
- for _, dn := range dns {
- dn.Accept(t)
- }
-}
-
-// VisitInlineSlice traverses a block slice.
-func (t TopDownTraverser) VisitInlineSlice(ins InlineSlice) {
- for _, in := range ins {
- in.Accept(t)
- }
-}
DELETED ast/visitor.go
Index: ast/visitor.go
==================================================================
--- ast/visitor.go
+++ /dev/null
@@ -1,39 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package ast provides the abstract syntax tree.
-package ast
-
-// Visitor is the interface all visitors must implement.
-type Visitor interface {
- // Block nodes
- VisitVerbatim(vn *VerbatimNode)
- VisitRegion(rn *RegionNode)
- VisitHeading(hn *HeadingNode)
- VisitHRule(hn *HRuleNode)
- VisitNestedList(ln *NestedListNode)
- VisitDescriptionList(dn *DescriptionListNode)
- VisitPara(pn *ParaNode)
- VisitTable(tn *TableNode)
- VisitBLOB(bn *BLOBNode)
-
- // Inline nodes
- VisitText(tn *TextNode)
- VisitTag(tn *TagNode)
- VisitSpace(sn *SpaceNode)
- VisitBreak(bn *BreakNode)
- VisitLink(ln *LinkNode)
- VisitImage(in *ImageNode)
- VisitCite(cn *CiteNode)
- VisitFootnote(fn *FootnoteNode)
- VisitMark(mn *MarkNode)
- VisitFormat(fn *FormatNode)
- VisitLiteral(ln *LiteralNode)
-}
DELETED auth/auth.go
Index: auth/auth.go
==================================================================
--- auth/auth.go
+++ /dev/null
@@ -1,101 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package auth provides services for authentification / authorization.
-package auth
-
-import (
- "time"
-
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/place"
- "zettelstore.de/z/web/server"
-)
-
-// BaseManager allows to check some base auth modes.
-type BaseManager interface {
- // IsReadonly returns true, if the systems is configured to run in read-only-mode.
- IsReadonly() bool
-}
-
-// TokenManager provides methods to create authentication
-type TokenManager interface {
-
- // GetToken produces a authentication token.
- GetToken(ident *meta.Meta, d time.Duration, kind TokenKind) ([]byte, error)
-
- // CheckToken checks the validity of the token and returns relevant data.
- CheckToken(token []byte, k TokenKind) (TokenData, error)
-}
-
-// TokenKind specifies for which application / usage a token is/was requested.
-type TokenKind int
-
-// Allowed values of token kind
-const (
- _ TokenKind = iota
- KindJSON
- KindHTML
-)
-
-// TokenData contains some important elements from a token.
-type TokenData struct {
- Token []byte
- Now time.Time
- Issued time.Time
- Expires time.Time
- Ident string
- Zid id.Zid
-}
-
-// AuthzManager provides methods for authorization.
-type AuthzManager interface {
- BaseManager
-
- // Owner returns the zettel identifier of the owner.
- Owner() id.Zid
-
- // IsOwner returns true, if the given zettel identifier is that of the owner.
- IsOwner(zid id.Zid) bool
-
- // Returns true if authentication is enabled.
- WithAuth() bool
-
- // GetUserRole role returns the user role of the given user zettel.
- GetUserRole(user *meta.Meta) meta.UserRole
-}
-
-// Manager is the main interface for providing the service.
-type Manager interface {
- TokenManager
- AuthzManager
-
- PlaceWithPolicy(auth server.Auth, unprotectedPlace place.Place, rtConfig config.Config) (place.Place, Policy)
-}
-
-// Policy is an interface for checking access authorization.
-type Policy interface {
- // User is allowed to create a new zettel.
- CanCreate(user, newMeta *meta.Meta) bool
-
- // User is allowed to read zettel
- CanRead(user, m *meta.Meta) bool
-
- // User is allowed to write zettel.
- CanWrite(user, oldMeta, newMeta *meta.Meta) bool
-
- // User is allowed to rename zettel
- CanRename(user, m *meta.Meta) bool
-
- // User is allowed to delete zettel
- CanDelete(user, m *meta.Meta) bool
-}
DELETED auth/cred/cred.go
Index: auth/cred/cred.go
==================================================================
--- auth/cred/cred.go
+++ /dev/null
@@ -1,53 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package cred provides some function for handling credentials.
-package cred
-
-import (
- "bytes"
-
- "golang.org/x/crypto/bcrypt"
- "zettelstore.de/z/domain/id"
-)
-
-// HashCredential returns a hashed vesion of the given credential
-func HashCredential(zid id.Zid, ident, credential string) (string, error) {
- fullCredential := createFullCredential(zid, ident, credential)
- res, err := bcrypt.GenerateFromPassword(fullCredential, bcrypt.DefaultCost)
- if err != nil {
- return "", err
- }
- return string(res), nil
-}
-
-// CompareHashAndCredential checks, whether the hashed credential is a possible
-// value when hashing the credential.
-func CompareHashAndCredential(hashed string, zid id.Zid, ident, credential string) (bool, error) {
- fullCredential := createFullCredential(zid, ident, credential)
- err := bcrypt.CompareHashAndPassword([]byte(hashed), fullCredential)
- if err == nil {
- return true, nil
- }
- if err == bcrypt.ErrMismatchedHashAndPassword {
- return false, nil
- }
- return false, err
-}
-
-func createFullCredential(zid id.Zid, ident, credential string) []byte {
- var buf bytes.Buffer
- buf.WriteString(zid.String())
- buf.WriteByte(' ')
- buf.WriteString(ident)
- buf.WriteByte(' ')
- buf.WriteString(credential)
- return buf.Bytes()
-}
DELETED auth/impl/impl.go
Index: auth/impl/impl.go
==================================================================
--- auth/impl/impl.go
+++ /dev/null
@@ -1,184 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package impl provides services for authentification / authorization.
-package impl
-
-import (
- "errors"
- "hash/fnv"
- "io"
- "time"
-
- "github.com/pascaldekloe/jwt"
-
- "zettelstore.de/z/auth"
- "zettelstore.de/z/auth/policy"
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/kernel"
- "zettelstore.de/z/place"
- "zettelstore.de/z/web/server"
-)
-
-type myAuth struct {
- readonly bool
- owner id.Zid
- secret []byte
-}
-
-// New creates a new auth object.
-func New(readonly bool, owner id.Zid, extSecret string) auth.Manager {
- return &myAuth{
- readonly: readonly,
- owner: owner,
- secret: calcSecret(extSecret),
- }
-}
-
-var configKeys = []string{
- kernel.CoreProgname,
- kernel.CoreGoVersion,
- kernel.CoreHostname,
- kernel.CoreGoOS,
- kernel.CoreGoArch,
- kernel.CoreVersion,
-}
-
-func calcSecret(extSecret string) []byte {
- h := fnv.New128()
- if extSecret != "" {
- io.WriteString(h, extSecret)
- }
- for _, key := range configKeys {
- io.WriteString(h, kernel.Main.GetConfig(kernel.CoreService, key).(string))
- }
- return h.Sum(nil)
-}
-
-// IsReadonly returns true, if the systems is configured to run in read-only-mode.
-func (a *myAuth) IsReadonly() bool { return a.readonly }
-
-const reqHash = jwt.HS512
-
-// ErrNoUser signals that the meta data has no role value 'user'.
-var ErrNoUser = errors.New("auth: meta is no user")
-
-// ErrNoIdent signals that the 'ident' key is missing.
-var ErrNoIdent = errors.New("auth: missing ident")
-
-// ErrOtherKind signals that the token was defined for another token kind.
-var ErrOtherKind = errors.New("auth: wrong token kind")
-
-// ErrNoZid signals that the 'zid' key is missing.
-var ErrNoZid = errors.New("auth: missing zettel id")
-
-// GetToken returns a token to be used for authentification.
-func (a *myAuth) GetToken(ident *meta.Meta, d time.Duration, kind auth.TokenKind) ([]byte, error) {
- if role, ok := ident.Get(meta.KeyRole); !ok || role != meta.ValueRoleUser {
- return nil, ErrNoUser
- }
- subject, ok := ident.Get(meta.KeyUserID)
- if !ok || subject == "" {
- return nil, ErrNoIdent
- }
-
- now := time.Now().Round(time.Second)
- claims := jwt.Claims{
- Registered: jwt.Registered{
- Subject: subject,
- Expires: jwt.NewNumericTime(now.Add(d)),
- Issued: jwt.NewNumericTime(now),
- },
- Set: map[string]interface{}{
- "zid": ident.Zid.String(),
- "_tk": int(kind),
- },
- }
- token, err := claims.HMACSign(reqHash, a.secret)
- if err != nil {
- return nil, err
- }
- return token, nil
-}
-
-// ErrTokenExpired signals an exired token
-var ErrTokenExpired = errors.New("auth: token expired")
-
-// CheckToken checks the validity of the token and returns relevant data.
-func (a *myAuth) CheckToken(token []byte, k auth.TokenKind) (auth.TokenData, error) {
- h, err := jwt.NewHMAC(reqHash, a.secret)
- if err != nil {
- return auth.TokenData{}, err
- }
- claims, err := h.Check(token)
- if err != nil {
- return auth.TokenData{}, err
- }
- now := time.Now().Round(time.Second)
- expires := claims.Expires.Time()
- if expires.Before(now) {
- return auth.TokenData{}, ErrTokenExpired
- }
- ident := claims.Subject
- if ident == "" {
- return auth.TokenData{}, ErrNoIdent
- }
- if zidS, ok := claims.Set["zid"].(string); ok {
- if zid, err := id.Parse(zidS); err == nil {
- if kind, ok := claims.Set["_tk"].(float64); ok {
- if auth.TokenKind(kind) == k {
- return auth.TokenData{
- Token: token,
- Now: now,
- Issued: claims.Issued.Time(),
- Expires: expires,
- Ident: ident,
- Zid: zid,
- }, nil
- }
- }
- return auth.TokenData{}, ErrOtherKind
- }
- }
- return auth.TokenData{}, ErrNoZid
-}
-
-func (a *myAuth) Owner() id.Zid { return a.owner }
-
-func (a *myAuth) IsOwner(zid id.Zid) bool {
- return zid.IsValid() && zid == a.owner
-}
-
-func (a *myAuth) WithAuth() bool { return a.owner != id.Invalid }
-
-// GetUserRole role returns the user role of the given user zettel.
-func (a *myAuth) GetUserRole(user *meta.Meta) meta.UserRole {
- if user == nil {
- if a.WithAuth() {
- return meta.UserRoleUnknown
- }
- return meta.UserRoleOwner
- }
- if a.IsOwner(user.Zid) {
- return meta.UserRoleOwner
- }
- if val, ok := user.Get(meta.KeyUserRole); ok {
- if ur := meta.GetUserRole(val); ur != meta.UserRoleUnknown {
- return ur
- }
- }
- return meta.UserRoleReader
-}
-
-func (a *myAuth) PlaceWithPolicy(auth server.Auth, unprotectedPlace place.Place, rtConfig config.Config) (place.Place, auth.Policy) {
- return policy.PlaceWithPolicy(auth, a, unprotectedPlace, rtConfig)
-}
DELETED auth/policy/anon.go
Index: auth/policy/anon.go
==================================================================
--- auth/policy/anon.go
+++ /dev/null
@@ -1,50 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package policy provides some interfaces and implementation for authorization policies.
-package policy
-
-import (
- "zettelstore.de/z/auth"
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain/meta"
-)
-
-type anonPolicy struct {
- authConfig config.AuthConfig
- pre auth.Policy
-}
-
-func (ap *anonPolicy) CanCreate(user, newMeta *meta.Meta) bool {
- return ap.pre.CanCreate(user, newMeta)
-}
-
-func (ap *anonPolicy) CanRead(user, m *meta.Meta) bool {
- return ap.pre.CanRead(user, m) && ap.checkVisibility(m)
-}
-
-func (ap *anonPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool {
- return ap.pre.CanWrite(user, oldMeta, newMeta) && ap.checkVisibility(oldMeta)
-}
-
-func (ap *anonPolicy) CanRename(user, m *meta.Meta) bool {
- return ap.pre.CanRename(user, m) && ap.checkVisibility(m)
-}
-
-func (ap *anonPolicy) CanDelete(user, m *meta.Meta) bool {
- return ap.pre.CanDelete(user, m) && ap.checkVisibility(m)
-}
-
-func (ap *anonPolicy) checkVisibility(m *meta.Meta) bool {
- if ap.authConfig.GetVisibility(m) == meta.VisibilityExpert {
- return ap.authConfig.GetExpertMode()
- }
- return true
-}
DELETED auth/policy/default.go
Index: auth/policy/default.go
==================================================================
--- auth/policy/default.go
+++ /dev/null
@@ -1,55 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package policy provides some interfaces and implementation for authorizsation policies.
-package policy
-
-import (
- "zettelstore.de/z/auth"
- "zettelstore.de/z/domain/meta"
-)
-
-type defaultPolicy struct {
- manager auth.AuthzManager
-}
-
-func (d *defaultPolicy) CanCreate(user, newMeta *meta.Meta) bool { return true }
-func (d *defaultPolicy) CanRead(user, m *meta.Meta) bool { return true }
-func (d *defaultPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool {
- return d.canChange(user, oldMeta)
-}
-func (d *defaultPolicy) CanRename(user, m *meta.Meta) bool { return d.canChange(user, m) }
-func (d *defaultPolicy) CanDelete(user, m *meta.Meta) bool { return d.canChange(user, m) }
-
-func (d *defaultPolicy) canChange(user, m *meta.Meta) bool {
- metaRo, ok := m.Get(meta.KeyReadOnly)
- if !ok {
- return true
- }
- if user == nil {
- // If we are here, there is no authentication.
- // See owner.go:CanWrite.
-
- // No authentication: check for owner-like restriction, because the user
- // acts as an owner
- return metaRo != meta.ValueUserRoleOwner && !meta.BoolValue(metaRo)
- }
-
- userRole := d.manager.GetUserRole(user)
- switch metaRo {
- case meta.ValueUserRoleReader:
- return userRole > meta.UserRoleReader
- case meta.ValueUserRoleWriter:
- return userRole > meta.UserRoleWriter
- case meta.ValueUserRoleOwner:
- return userRole > meta.UserRoleOwner
- }
- return !meta.BoolValue(metaRo)
-}
DELETED auth/policy/owner.go
Index: auth/policy/owner.go
==================================================================
--- auth/policy/owner.go
+++ /dev/null
@@ -1,145 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package policy provides some interfaces and implementation for authorizsation policies.
-package policy
-
-import (
- "zettelstore.de/z/auth"
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain/meta"
-)
-
-type ownerPolicy struct {
- manager auth.AuthzManager
- authConfig config.AuthConfig
- pre auth.Policy
-}
-
-func (o *ownerPolicy) CanCreate(user, newMeta *meta.Meta) bool {
- if user == nil || !o.pre.CanCreate(user, newMeta) {
- return false
- }
- return o.userIsOwner(user) || o.userCanCreate(user, newMeta)
-}
-
-func (o *ownerPolicy) userCanCreate(user, newMeta *meta.Meta) bool {
- if o.manager.GetUserRole(user) == meta.UserRoleReader {
- return false
- }
- if role, ok := newMeta.Get(meta.KeyRole); ok && role == meta.ValueRoleUser {
- return false
- }
- return true
-}
-
-func (o *ownerPolicy) CanRead(user, m *meta.Meta) bool {
- // No need to call o.pre.CanRead(user, meta), because it will always return true.
- // Both the default and the readonly policy allow to read a zettel.
- vis := o.authConfig.GetVisibility(m)
- if res, ok := o.checkVisibility(user, vis); ok {
- return res
- }
- return o.userIsOwner(user) || o.userCanRead(user, m, vis)
-}
-
-func (o *ownerPolicy) userCanRead(user, m *meta.Meta, vis meta.Visibility) bool {
- switch vis {
- case meta.VisibilityOwner, meta.VisibilityExpert:
- return false
- case meta.VisibilityPublic:
- return true
- }
- if user == nil {
- return false
- }
- if role, ok := m.Get(meta.KeyRole); ok && role == meta.ValueRoleUser {
- // Only the user can read its own zettel
- return user.Zid == m.Zid
- }
- return true
-}
-
-var noChangeUser = []string{
- meta.KeyID,
- meta.KeyRole,
- meta.KeyUserID,
- meta.KeyUserRole,
-}
-
-func (o *ownerPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool {
- if user == nil || !o.pre.CanWrite(user, oldMeta, newMeta) {
- return false
- }
- vis := o.authConfig.GetVisibility(oldMeta)
- if res, ok := o.checkVisibility(user, vis); ok {
- return res
- }
- if o.userIsOwner(user) {
- return true
- }
- if !o.userCanRead(user, oldMeta, vis) {
- return false
- }
- if role, ok := oldMeta.Get(meta.KeyRole); ok && role == meta.ValueRoleUser {
- // Here we know, that user.Zid == newMeta.Zid (because of userCanRead) and
- // user.Zid == newMeta.Zid (because oldMeta.Zid == newMeta.Zid)
- for _, key := range noChangeUser {
- if oldMeta.GetDefault(key, "") != newMeta.GetDefault(key, "") {
- return false
- }
- }
- return true
- }
- if o.manager.GetUserRole(user) == meta.UserRoleReader {
- return false
- }
- return o.userCanCreate(user, newMeta)
-}
-
-func (o *ownerPolicy) CanRename(user, m *meta.Meta) bool {
- if user == nil || !o.pre.CanRename(user, m) {
- return false
- }
- if res, ok := o.checkVisibility(user, o.authConfig.GetVisibility(m)); ok {
- return res
- }
- return o.userIsOwner(user)
-}
-
-func (o *ownerPolicy) CanDelete(user, m *meta.Meta) bool {
- if user == nil || !o.pre.CanDelete(user, m) {
- return false
- }
- if res, ok := o.checkVisibility(user, o.authConfig.GetVisibility(m)); ok {
- return res
- }
- return o.userIsOwner(user)
-}
-
-func (o *ownerPolicy) checkVisibility(user *meta.Meta, vis meta.Visibility) (bool, bool) {
- if vis == meta.VisibilityExpert {
- return o.userIsOwner(user) && o.authConfig.GetExpertMode(), true
- }
- return false, false
-}
-
-func (o *ownerPolicy) userIsOwner(user *meta.Meta) bool {
- if user == nil {
- return false
- }
- if o.manager.IsOwner(user.Zid) {
- return true
- }
- if val, ok := user.Get(meta.KeyUserRole); ok && val == meta.ValueUserRoleOwner {
- return true
- }
- return false
-}
DELETED auth/policy/place.go
Index: auth/policy/place.go
==================================================================
--- auth/policy/place.go
+++ /dev/null
@@ -1,165 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package policy provides some interfaces and implementation for authorizsation policies.
-package policy
-
-import (
- "context"
- "io"
-
- "zettelstore.de/z/auth"
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/place"
- "zettelstore.de/z/search"
- "zettelstore.de/z/web/server"
-)
-
-// PlaceWithPolicy wraps the given place inside a policy place.
-func PlaceWithPolicy(
- auth server.Auth,
- manager auth.AuthzManager,
- place place.Place,
- authConfig config.AuthConfig,
-) (place.Place, auth.Policy) {
- pol := newPolicy(manager, authConfig)
- return newPlace(auth, place, pol), pol
-}
-
-// polPlace implements a policy place.
-type polPlace struct {
- auth server.Auth
- place place.Place
- policy auth.Policy
-}
-
-// newPlace creates a new policy place.
-func newPlace(auth server.Auth, place place.Place, policy auth.Policy) place.Place {
- return &polPlace{
- auth: auth,
- place: place,
- policy: policy,
- }
-}
-
-func (pp *polPlace) Location() string {
- return pp.place.Location()
-}
-
-func (pp *polPlace) CanCreateZettel(ctx context.Context) bool {
- return pp.place.CanCreateZettel(ctx)
-}
-
-func (pp *polPlace) CreateZettel(ctx context.Context, zettel domain.Zettel) (id.Zid, error) {
- user := pp.auth.GetUser(ctx)
- if pp.policy.CanCreate(user, zettel.Meta) {
- return pp.place.CreateZettel(ctx, zettel)
- }
- return id.Invalid, place.NewErrNotAllowed("Create", user, id.Invalid)
-}
-
-func (pp *polPlace) GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) {
- zettel, err := pp.place.GetZettel(ctx, zid)
- if err != nil {
- return domain.Zettel{}, err
- }
- user := pp.auth.GetUser(ctx)
- if pp.policy.CanRead(user, zettel.Meta) {
- return zettel, nil
- }
- return domain.Zettel{}, place.NewErrNotAllowed("GetZettel", user, zid)
-}
-
-func (pp *polPlace) GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) {
- m, err := pp.place.GetMeta(ctx, zid)
- if err != nil {
- return nil, err
- }
- user := pp.auth.GetUser(ctx)
- if pp.policy.CanRead(user, m) {
- return m, nil
- }
- return nil, place.NewErrNotAllowed("GetMeta", user, zid)
-}
-
-func (pp *polPlace) FetchZids(ctx context.Context) (id.Set, error) {
- return nil, place.NewErrNotAllowed("fetch-zids", pp.auth.GetUser(ctx), id.Invalid)
-}
-
-func (pp *polPlace) SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) {
- user := pp.auth.GetUser(ctx)
- canRead := pp.policy.CanRead
- s = s.AddPreMatch(func(m *meta.Meta) bool { return canRead(user, m) })
- return pp.place.SelectMeta(ctx, s)
-}
-
-func (pp *polPlace) CanUpdateZettel(ctx context.Context, zettel domain.Zettel) bool {
- return pp.place.CanUpdateZettel(ctx, zettel)
-}
-
-func (pp *polPlace) UpdateZettel(ctx context.Context, zettel domain.Zettel) error {
- zid := zettel.Meta.Zid
- user := pp.auth.GetUser(ctx)
- if !zid.IsValid() {
- return &place.ErrInvalidID{Zid: zid}
- }
- // Write existing zettel
- oldMeta, err := pp.place.GetMeta(ctx, zid)
- if err != nil {
- return err
- }
- if pp.policy.CanWrite(user, oldMeta, zettel.Meta) {
- return pp.place.UpdateZettel(ctx, zettel)
- }
- return place.NewErrNotAllowed("Write", user, zid)
-}
-
-func (pp *polPlace) AllowRenameZettel(ctx context.Context, zid id.Zid) bool {
- return pp.place.AllowRenameZettel(ctx, zid)
-}
-
-func (pp *polPlace) RenameZettel(ctx context.Context, curZid, newZid id.Zid) error {
- meta, err := pp.place.GetMeta(ctx, curZid)
- if err != nil {
- return err
- }
- user := pp.auth.GetUser(ctx)
- if pp.policy.CanRename(user, meta) {
- return pp.place.RenameZettel(ctx, curZid, newZid)
- }
- return place.NewErrNotAllowed("Rename", user, curZid)
-}
-
-func (pp *polPlace) CanDeleteZettel(ctx context.Context, zid id.Zid) bool {
- return pp.place.CanDeleteZettel(ctx, zid)
-}
-
-func (pp *polPlace) DeleteZettel(ctx context.Context, zid id.Zid) error {
- meta, err := pp.place.GetMeta(ctx, zid)
- if err != nil {
- return err
- }
- user := pp.auth.GetUser(ctx)
- if pp.policy.CanDelete(user, meta) {
- return pp.place.DeleteZettel(ctx, zid)
- }
- return place.NewErrNotAllowed("Delete", user, zid)
-}
-
-func (pp *polPlace) ReadStats(st *place.Stats) {
- pp.place.ReadStats(st)
-}
-
-func (pp *polPlace) Dump(w io.Writer) {
- pp.place.Dump(w)
-}
DELETED auth/policy/policy.go
Index: auth/policy/policy.go
==================================================================
--- auth/policy/policy.go
+++ /dev/null
@@ -1,66 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package policy provides some interfaces and implementation for authorizsation policies.
-package policy
-
-import (
- "zettelstore.de/z/auth"
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain/meta"
-)
-
-// newPolicy creates a policy based on given constraints.
-func newPolicy(manager auth.AuthzManager, authConfig config.AuthConfig) auth.Policy {
- var pol auth.Policy
- if manager.IsReadonly() {
- pol = &roPolicy{}
- } else {
- pol = &defaultPolicy{manager}
- }
- if manager.WithAuth() {
- pol = &ownerPolicy{
- manager: manager,
- authConfig: authConfig,
- pre: pol,
- }
- } else {
- pol = &anonPolicy{
- authConfig: authConfig,
- pre: pol,
- }
- }
- return &prePolicy{pol}
-}
-
-type prePolicy struct {
- post auth.Policy
-}
-
-func (p *prePolicy) CanCreate(user, newMeta *meta.Meta) bool {
- return newMeta != nil && p.post.CanCreate(user, newMeta)
-}
-
-func (p *prePolicy) CanRead(user, m *meta.Meta) bool {
- return m != nil && p.post.CanRead(user, m)
-}
-
-func (p *prePolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool {
- return oldMeta != nil && newMeta != nil && oldMeta.Zid == newMeta.Zid &&
- p.post.CanWrite(user, oldMeta, newMeta)
-}
-
-func (p *prePolicy) CanRename(user, m *meta.Meta) bool {
- return m != nil && p.post.CanRename(user, m)
-}
-
-func (p *prePolicy) CanDelete(user, m *meta.Meta) bool {
- return m != nil && p.post.CanDelete(user, m)
-}
DELETED auth/policy/policy_test.go
Index: auth/policy/policy_test.go
==================================================================
--- auth/policy/policy_test.go
+++ /dev/null
@@ -1,620 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package policy provides some interfaces and implementation for authorizsation policies.
-package policy
-
-import (
- "fmt"
- "testing"
-
- "zettelstore.de/z/auth"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
-)
-
-func TestPolicies(t *testing.T) {
- testScene := []struct {
- readonly bool
- withAuth bool
- expert bool
- }{
- {true, true, true},
- {true, true, false},
- {true, false, true},
- {true, false, false},
- {false, true, true},
- {false, true, false},
- {false, false, true},
- {false, false, false},
- }
- for _, ts := range testScene {
- authzManager := &testAuthzManager{
- readOnly: ts.readonly,
- withAuth: ts.withAuth,
- }
- pol := newPolicy(authzManager, &authConfig{ts.expert})
- name := fmt.Sprintf("readonly=%v/withauth=%v/expert=%v",
- ts.readonly, ts.withAuth, ts.expert)
- t.Run(name, func(tt *testing.T) {
- testCreate(tt, pol, ts.withAuth, ts.readonly, ts.expert)
- testRead(tt, pol, ts.withAuth, ts.readonly, ts.expert)
- testWrite(tt, pol, ts.withAuth, ts.readonly, ts.expert)
- testRename(tt, pol, ts.withAuth, ts.readonly, ts.expert)
- testDelete(tt, pol, ts.withAuth, ts.readonly, ts.expert)
- })
- }
-}
-
-type testAuthzManager struct {
- readOnly bool
- withAuth bool
-}
-
-func (a *testAuthzManager) IsReadonly() bool { return a.readOnly }
-func (a *testAuthzManager) Owner() id.Zid { return ownerZid }
-func (a *testAuthzManager) IsOwner(zid id.Zid) bool { return zid == ownerZid }
-
-func (a *testAuthzManager) WithAuth() bool { return a.withAuth }
-
-func (a *testAuthzManager) GetUserRole(user *meta.Meta) meta.UserRole {
- if user == nil {
- if a.WithAuth() {
- return meta.UserRoleUnknown
- }
- return meta.UserRoleOwner
- }
- if a.IsOwner(user.Zid) {
- return meta.UserRoleOwner
- }
- if val, ok := user.Get(meta.KeyUserRole); ok {
- if ur := meta.GetUserRole(val); ur != meta.UserRoleUnknown {
- return ur
- }
- }
- return meta.UserRoleReader
-}
-
-type authConfig struct{ expert bool }
-
-func (ac *authConfig) GetExpertMode() bool { return ac.expert }
-
-func (ac *authConfig) GetVisibility(m *meta.Meta) meta.Visibility {
- if vis, ok := m.Get(meta.KeyVisibility); ok {
- switch vis {
- case meta.ValueVisibilityPublic:
- return meta.VisibilityPublic
- case meta.ValueVisibilityOwner:
- return meta.VisibilityOwner
- case meta.ValueVisibilityExpert:
- return meta.VisibilityExpert
- }
- }
- return meta.VisibilityLogin
-}
-
-func testCreate(t *testing.T, pol auth.Policy, withAuth, readonly, isExpert bool) {
- t.Helper()
- anonUser := newAnon()
- reader := newReader()
- writer := newWriter()
- owner := newOwner()
- owner2 := newOwner2()
- zettel := newZettel()
- userZettel := newUserZettel()
- testCases := []struct {
- user *meta.Meta
- meta *meta.Meta
- exp bool
- }{
- // No meta
- {anonUser, nil, false},
- {reader, nil, false},
- {writer, nil, false},
- {owner, nil, false},
- {owner2, nil, false},
- // Ordinary zettel
- {anonUser, zettel, !withAuth && !readonly},
- {reader, zettel, !withAuth && !readonly},
- {writer, zettel, !readonly},
- {owner, zettel, !readonly},
- {owner2, zettel, !readonly},
- // User zettel
- {anonUser, userZettel, !withAuth && !readonly},
- {reader, userZettel, !withAuth && !readonly},
- {writer, userZettel, !withAuth && !readonly},
- {owner, userZettel, !readonly},
- {owner2, userZettel, !readonly},
- }
- for _, tc := range testCases {
- t.Run("Create", func(tt *testing.T) {
- got := pol.CanCreate(tc.user, tc.meta)
- if tc.exp != got {
- tt.Errorf("exp=%v, but got=%v", tc.exp, got)
- }
- })
- }
-}
-
-func testRead(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) {
- t.Helper()
- anonUser := newAnon()
- reader := newReader()
- writer := newWriter()
- owner := newOwner()
- owner2 := newOwner2()
- zettel := newZettel()
- publicZettel := newPublicZettel()
- loginZettel := newLoginZettel()
- ownerZettel := newOwnerZettel()
- expertZettel := newExpertZettel()
- userZettel := newUserZettel()
- testCases := []struct {
- user *meta.Meta
- meta *meta.Meta
- exp bool
- }{
- // No meta
- {anonUser, nil, false},
- {reader, nil, false},
- {writer, nil, false},
- {owner, nil, false},
- {owner2, nil, false},
- // Ordinary zettel
- {anonUser, zettel, !withAuth},
- {reader, zettel, true},
- {writer, zettel, true},
- {owner, zettel, true},
- {owner2, zettel, true},
- // Public zettel
- {anonUser, publicZettel, true},
- {reader, publicZettel, true},
- {writer, publicZettel, true},
- {owner, publicZettel, true},
- {owner2, publicZettel, true},
- // Login zettel
- {anonUser, loginZettel, !withAuth},
- {reader, loginZettel, true},
- {writer, loginZettel, true},
- {owner, loginZettel, true},
- {owner2, loginZettel, true},
- // Owner zettel
- {anonUser, ownerZettel, !withAuth},
- {reader, ownerZettel, !withAuth},
- {writer, ownerZettel, !withAuth},
- {owner, ownerZettel, true},
- {owner2, ownerZettel, true},
- // Expert zettel
- {anonUser, expertZettel, !withAuth && expert},
- {reader, expertZettel, !withAuth && expert},
- {writer, expertZettel, !withAuth && expert},
- {owner, expertZettel, expert},
- {owner2, expertZettel, expert},
- // Other user zettel
- {anonUser, userZettel, !withAuth},
- {reader, userZettel, !withAuth},
- {writer, userZettel, !withAuth},
- {owner, userZettel, true},
- {owner2, userZettel, true},
- // Own user zettel
- {reader, reader, true},
- {writer, writer, true},
- {owner, owner, true},
- {owner, owner2, true},
- {owner2, owner, true},
- {owner2, owner2, true},
- }
- for _, tc := range testCases {
- t.Run("Read", func(tt *testing.T) {
- got := pol.CanRead(tc.user, tc.meta)
- if tc.exp != got {
- tt.Errorf("exp=%v, but got=%v", tc.exp, got)
- }
- })
- }
-}
-
-func testWrite(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) {
- t.Helper()
- anonUser := newAnon()
- reader := newReader()
- writer := newWriter()
- owner := newOwner()
- owner2 := newOwner2()
- zettel := newZettel()
- publicZettel := newPublicZettel()
- loginZettel := newLoginZettel()
- ownerZettel := newOwnerZettel()
- expertZettel := newExpertZettel()
- userZettel := newUserZettel()
- writerNew := writer.Clone()
- writerNew.Set(meta.KeyUserRole, owner.GetDefault(meta.KeyUserRole, ""))
- roFalse := newRoFalseZettel()
- roTrue := newRoTrueZettel()
- roReader := newRoReaderZettel()
- roWriter := newRoWriterZettel()
- roOwner := newRoOwnerZettel()
- notAuthNotReadonly := !withAuth && !readonly
- testCases := []struct {
- user *meta.Meta
- old *meta.Meta
- new *meta.Meta
- exp bool
- }{
- // No old and new meta
- {anonUser, nil, nil, false},
- {reader, nil, nil, false},
- {writer, nil, nil, false},
- {owner, nil, nil, false},
- {owner2, nil, nil, false},
- // No old meta
- {anonUser, nil, zettel, false},
- {reader, nil, zettel, false},
- {writer, nil, zettel, false},
- {owner, nil, zettel, false},
- {owner2, nil, zettel, false},
- // No new meta
- {anonUser, zettel, nil, false},
- {reader, zettel, nil, false},
- {writer, zettel, nil, false},
- {owner, zettel, nil, false},
- {owner2, zettel, nil, false},
- // Old an new zettel have different zettel identifier
- {anonUser, zettel, publicZettel, false},
- {reader, zettel, publicZettel, false},
- {writer, zettel, publicZettel, false},
- {owner, zettel, publicZettel, false},
- {owner2, zettel, publicZettel, false},
- // Overwrite a normal zettel
- {anonUser, zettel, zettel, notAuthNotReadonly},
- {reader, zettel, zettel, notAuthNotReadonly},
- {writer, zettel, zettel, !readonly},
- {owner, zettel, zettel, !readonly},
- {owner2, zettel, zettel, !readonly},
- // Public zettel
- {anonUser, publicZettel, publicZettel, notAuthNotReadonly},
- {reader, publicZettel, publicZettel, notAuthNotReadonly},
- {writer, publicZettel, publicZettel, !readonly},
- {owner, publicZettel, publicZettel, !readonly},
- {owner2, publicZettel, publicZettel, !readonly},
- // Login zettel
- {anonUser, loginZettel, loginZettel, notAuthNotReadonly},
- {reader, loginZettel, loginZettel, notAuthNotReadonly},
- {writer, loginZettel, loginZettel, !readonly},
- {owner, loginZettel, loginZettel, !readonly},
- {owner2, loginZettel, loginZettel, !readonly},
- // Owner zettel
- {anonUser, ownerZettel, ownerZettel, notAuthNotReadonly},
- {reader, ownerZettel, ownerZettel, notAuthNotReadonly},
- {writer, ownerZettel, ownerZettel, notAuthNotReadonly},
- {owner, ownerZettel, ownerZettel, !readonly},
- {owner2, ownerZettel, ownerZettel, !readonly},
- // Expert zettel
- {anonUser, expertZettel, expertZettel, notAuthNotReadonly && expert},
- {reader, expertZettel, expertZettel, notAuthNotReadonly && expert},
- {writer, expertZettel, expertZettel, notAuthNotReadonly && expert},
- {owner, expertZettel, expertZettel, !readonly && expert},
- {owner2, expertZettel, expertZettel, !readonly && expert},
- // Other user zettel
- {anonUser, userZettel, userZettel, notAuthNotReadonly},
- {reader, userZettel, userZettel, notAuthNotReadonly},
- {writer, userZettel, userZettel, notAuthNotReadonly},
- {owner, userZettel, userZettel, !readonly},
- {owner2, userZettel, userZettel, !readonly},
- // Own user zettel
- {reader, reader, reader, !readonly},
- {writer, writer, writer, !readonly},
- {owner, owner, owner, !readonly},
- {owner2, owner2, owner2, !readonly},
- // Writer cannot change importand metadata of its own user zettel
- {writer, writer, writerNew, notAuthNotReadonly},
- // No r/o zettel
- {anonUser, roFalse, roFalse, notAuthNotReadonly},
- {reader, roFalse, roFalse, notAuthNotReadonly},
- {writer, roFalse, roFalse, !readonly},
- {owner, roFalse, roFalse, !readonly},
- {owner2, roFalse, roFalse, !readonly},
- // Reader r/o zettel
- {anonUser, roReader, roReader, false},
- {reader, roReader, roReader, false},
- {writer, roReader, roReader, !readonly},
- {owner, roReader, roReader, !readonly},
- {owner2, roReader, roReader, !readonly},
- // Writer r/o zettel
- {anonUser, roWriter, roWriter, false},
- {reader, roWriter, roWriter, false},
- {writer, roWriter, roWriter, false},
- {owner, roWriter, roWriter, !readonly},
- {owner2, roWriter, roWriter, !readonly},
- // Owner r/o zettel
- {anonUser, roOwner, roOwner, false},
- {reader, roOwner, roOwner, false},
- {writer, roOwner, roOwner, false},
- {owner, roOwner, roOwner, false},
- {owner2, roOwner, roOwner, false},
- // r/o = true zettel
- {anonUser, roTrue, roTrue, false},
- {reader, roTrue, roTrue, false},
- {writer, roTrue, roTrue, false},
- {owner, roTrue, roTrue, false},
- {owner2, roTrue, roTrue, false},
- }
- for _, tc := range testCases {
- t.Run("Write", func(tt *testing.T) {
- got := pol.CanWrite(tc.user, tc.old, tc.new)
- if tc.exp != got {
- tt.Errorf("exp=%v, but got=%v", tc.exp, got)
- }
- })
- }
-}
-
-func testRename(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) {
- t.Helper()
- anonUser := newAnon()
- reader := newReader()
- writer := newWriter()
- owner := newOwner()
- owner2 := newOwner2()
- zettel := newZettel()
- expertZettel := newExpertZettel()
- roFalse := newRoFalseZettel()
- roTrue := newRoTrueZettel()
- roReader := newRoReaderZettel()
- roWriter := newRoWriterZettel()
- roOwner := newRoOwnerZettel()
- notAuthNotReadonly := !withAuth && !readonly
- testCases := []struct {
- user *meta.Meta
- meta *meta.Meta
- exp bool
- }{
- // No meta
- {anonUser, nil, false},
- {reader, nil, false},
- {writer, nil, false},
- {owner, nil, false},
- {owner2, nil, false},
- // Any zettel
- {anonUser, zettel, notAuthNotReadonly},
- {reader, zettel, notAuthNotReadonly},
- {writer, zettel, notAuthNotReadonly},
- {owner, zettel, !readonly},
- {owner2, zettel, !readonly},
- // Expert zettel
- {anonUser, expertZettel, notAuthNotReadonly && expert},
- {reader, expertZettel, notAuthNotReadonly && expert},
- {writer, expertZettel, notAuthNotReadonly && expert},
- {owner, expertZettel, !readonly && expert},
- {owner2, expertZettel, !readonly && expert},
- // No r/o zettel
- {anonUser, roFalse, notAuthNotReadonly},
- {reader, roFalse, notAuthNotReadonly},
- {writer, roFalse, notAuthNotReadonly},
- {owner, roFalse, !readonly},
- {owner2, roFalse, !readonly},
- // Reader r/o zettel
- {anonUser, roReader, false},
- {reader, roReader, false},
- {writer, roReader, notAuthNotReadonly},
- {owner, roReader, !readonly},
- {owner2, roReader, !readonly},
- // Writer r/o zettel
- {anonUser, roWriter, false},
- {reader, roWriter, false},
- {writer, roWriter, false},
- {owner, roWriter, !readonly},
- {owner2, roWriter, !readonly},
- // Owner r/o zettel
- {anonUser, roOwner, false},
- {reader, roOwner, false},
- {writer, roOwner, false},
- {owner, roOwner, false},
- {owner2, roOwner, false},
- // r/o = true zettel
- {anonUser, roTrue, false},
- {reader, roTrue, false},
- {writer, roTrue, false},
- {owner, roTrue, false},
- {owner2, roTrue, false},
- }
- for _, tc := range testCases {
- t.Run("Rename", func(tt *testing.T) {
- got := pol.CanRename(tc.user, tc.meta)
- if tc.exp != got {
- tt.Errorf("exp=%v, but got=%v", tc.exp, got)
- }
- })
- }
-}
-
-func testDelete(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) {
- t.Helper()
- anonUser := newAnon()
- reader := newReader()
- writer := newWriter()
- owner := newOwner()
- owner2 := newOwner2()
- zettel := newZettel()
- expertZettel := newExpertZettel()
- roFalse := newRoFalseZettel()
- roTrue := newRoTrueZettel()
- roReader := newRoReaderZettel()
- roWriter := newRoWriterZettel()
- roOwner := newRoOwnerZettel()
- notAuthNotReadonly := !withAuth && !readonly
- testCases := []struct {
- user *meta.Meta
- meta *meta.Meta
- exp bool
- }{
- // No meta
- {anonUser, nil, false},
- {reader, nil, false},
- {writer, nil, false},
- {owner, nil, false},
- {owner2, nil, false},
- // Any zettel
- {anonUser, zettel, notAuthNotReadonly},
- {reader, zettel, notAuthNotReadonly},
- {writer, zettel, notAuthNotReadonly},
- {owner, zettel, !readonly},
- {owner2, zettel, !readonly},
- // Expert zettel
- {anonUser, expertZettel, notAuthNotReadonly && expert},
- {reader, expertZettel, notAuthNotReadonly && expert},
- {writer, expertZettel, notAuthNotReadonly && expert},
- {owner, expertZettel, !readonly && expert},
- {owner2, expertZettel, !readonly && expert},
- // No r/o zettel
- {anonUser, roFalse, notAuthNotReadonly},
- {reader, roFalse, notAuthNotReadonly},
- {writer, roFalse, notAuthNotReadonly},
- {owner, roFalse, !readonly},
- {owner2, roFalse, !readonly},
- // Reader r/o zettel
- {anonUser, roReader, false},
- {reader, roReader, false},
- {writer, roReader, notAuthNotReadonly},
- {owner, roReader, !readonly},
- {owner2, roReader, !readonly},
- // Writer r/o zettel
- {anonUser, roWriter, false},
- {reader, roWriter, false},
- {writer, roWriter, false},
- {owner, roWriter, !readonly},
- {owner2, roWriter, !readonly},
- // Owner r/o zettel
- {anonUser, roOwner, false},
- {reader, roOwner, false},
- {writer, roOwner, false},
- {owner, roOwner, false},
- {owner2, roOwner, false},
- // r/o = true zettel
- {anonUser, roTrue, false},
- {reader, roTrue, false},
- {writer, roTrue, false},
- {owner, roTrue, false},
- {owner2, roTrue, false},
- }
- for _, tc := range testCases {
- t.Run("Delete", func(tt *testing.T) {
- got := pol.CanDelete(tc.user, tc.meta)
- if tc.exp != got {
- tt.Errorf("exp=%v, but got=%v", tc.exp, got)
- }
- })
- }
-}
-
-const (
- readerZid = id.Zid(1013)
- writerZid = id.Zid(1015)
- ownerZid = id.Zid(1017)
- owner2Zid = id.Zid(1019)
- zettelZid = id.Zid(1021)
- visZid = id.Zid(1023)
- userZid = id.Zid(1025)
-)
-
-func newAnon() *meta.Meta { return nil }
-func newReader() *meta.Meta {
- user := meta.New(readerZid)
- user.Set(meta.KeyTitle, "Reader")
- user.Set(meta.KeyRole, meta.ValueRoleUser)
- user.Set(meta.KeyUserRole, meta.ValueUserRoleReader)
- return user
-}
-func newWriter() *meta.Meta {
- user := meta.New(writerZid)
- user.Set(meta.KeyTitle, "Writer")
- user.Set(meta.KeyRole, meta.ValueRoleUser)
- user.Set(meta.KeyUserRole, meta.ValueUserRoleWriter)
- return user
-}
-func newOwner() *meta.Meta {
- user := meta.New(ownerZid)
- user.Set(meta.KeyTitle, "Owner")
- user.Set(meta.KeyRole, meta.ValueRoleUser)
- user.Set(meta.KeyUserRole, meta.ValueUserRoleOwner)
- return user
-}
-func newOwner2() *meta.Meta {
- user := meta.New(owner2Zid)
- user.Set(meta.KeyTitle, "Owner 2")
- user.Set(meta.KeyRole, meta.ValueRoleUser)
- user.Set(meta.KeyUserRole, meta.ValueUserRoleOwner)
- return user
-}
-func newZettel() *meta.Meta {
- m := meta.New(zettelZid)
- m.Set(meta.KeyTitle, "Any Zettel")
- return m
-}
-func newPublicZettel() *meta.Meta {
- m := meta.New(visZid)
- m.Set(meta.KeyTitle, "Public Zettel")
- m.Set(meta.KeyVisibility, meta.ValueVisibilityPublic)
- return m
-}
-func newLoginZettel() *meta.Meta {
- m := meta.New(visZid)
- m.Set(meta.KeyTitle, "Login Zettel")
- m.Set(meta.KeyVisibility, meta.ValueVisibilityLogin)
- return m
-}
-func newOwnerZettel() *meta.Meta {
- m := meta.New(visZid)
- m.Set(meta.KeyTitle, "Owner Zettel")
- m.Set(meta.KeyVisibility, meta.ValueVisibilityOwner)
- return m
-}
-func newExpertZettel() *meta.Meta {
- m := meta.New(visZid)
- m.Set(meta.KeyTitle, "Expert Zettel")
- m.Set(meta.KeyVisibility, meta.ValueVisibilityExpert)
- return m
-}
-func newRoFalseZettel() *meta.Meta {
- m := meta.New(zettelZid)
- m.Set(meta.KeyTitle, "No r/o Zettel")
- m.Set(meta.KeyReadOnly, "false")
- return m
-}
-func newRoTrueZettel() *meta.Meta {
- m := meta.New(zettelZid)
- m.Set(meta.KeyTitle, "A r/o Zettel")
- m.Set(meta.KeyReadOnly, "true")
- return m
-}
-func newRoReaderZettel() *meta.Meta {
- m := meta.New(zettelZid)
- m.Set(meta.KeyTitle, "Reader r/o Zettel")
- m.Set(meta.KeyReadOnly, meta.ValueUserRoleReader)
- return m
-}
-func newRoWriterZettel() *meta.Meta {
- m := meta.New(zettelZid)
- m.Set(meta.KeyTitle, "Writer r/o Zettel")
- m.Set(meta.KeyReadOnly, meta.ValueUserRoleWriter)
- return m
-}
-func newRoOwnerZettel() *meta.Meta {
- m := meta.New(zettelZid)
- m.Set(meta.KeyTitle, "Owner r/o Zettel")
- m.Set(meta.KeyReadOnly, meta.ValueUserRoleOwner)
- return m
-}
-func newUserZettel() *meta.Meta {
- m := meta.New(userZid)
- m.Set(meta.KeyTitle, "Any User")
- m.Set(meta.KeyRole, meta.ValueRoleUser)
- return m
-}
DELETED auth/policy/readonly.go
Index: auth/policy/readonly.go
==================================================================
--- auth/policy/readonly.go
+++ /dev/null
@@ -1,22 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package policy provides some interfaces and implementation for authorization policies.
-package policy
-
-import "zettelstore.de/z/domain/meta"
-
-type roPolicy struct{}
-
-func (p *roPolicy) CanCreate(user, newMeta *meta.Meta) bool { return false }
-func (p *roPolicy) CanRead(user, m *meta.Meta) bool { return true }
-func (p *roPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool { return false }
-func (p *roPolicy) CanRename(user, m *meta.Meta) bool { return false }
-func (p *roPolicy) CanDelete(user, m *meta.Meta) bool { return false }
Index: cmd/cmd_file.go
==================================================================
--- cmd/cmd_file.go
+++ cmd/cmd_file.go
@@ -1,53 +1,62 @@
//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
+// Copyright (c) 2020-present Detlef Stern
//
-// This file is part of zettelstore.
+// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
//-----------------------------------------------------------------------------
package cmd
import (
+ "context"
"flag"
"fmt"
"io"
"os"
- "zettelstore.de/z/domain"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
- "zettelstore.de/z/input"
- "zettelstore.de/z/parser"
+ "t73f.de/r/zsc/api"
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "t73f.de/r/zsx/input"
+
+ "zettelstore.de/z/internal/encoder"
+ "zettelstore.de/z/internal/parser"
+ "zettelstore.de/z/internal/zettel"
)
// ---------- Subcommand: file -----------------------------------------------
-func cmdFile(fs *flag.FlagSet, cfg *meta.Meta) (int, error) {
- format := fs.Lookup("t").Value.String()
+func cmdFile(fs *flag.FlagSet) (int, error) {
+ enc := fs.Lookup("t").Value.String()
m, inp, err := getInput(fs.Args())
if m == nil {
return 2, err
}
z := parser.ParseZettel(
- domain.Zettel{
+ context.Background(),
+ zettel.Zettel{
Meta: m,
- Content: domain.NewContent(inp.Src[inp.Pos:]),
+ Content: zettel.NewContent(inp.Src[inp.Pos:]),
},
- m.GetDefault(meta.KeySyntax, meta.ValueSyntaxZmk),
+ string(m.GetDefault(meta.KeySyntax, meta.DefaultSyntax)),
nil,
)
- enc := encoder.Create(format, &encoder.Environment{Lang: m.GetDefault(meta.KeyLang, meta.ValueLangEN)})
- if enc == nil {
- fmt.Fprintf(os.Stderr, "Unknown format %q\n", format)
+ encdr := encoder.Create(
+ api.Encoder(enc),
+ &encoder.CreateParameter{Lang: string(m.GetDefault(meta.KeyLang, meta.ValueLangEN))})
+ if encdr == nil {
+ fmt.Fprintf(os.Stderr, "Unknown format %q\n", enc)
return 2, nil
}
- _, err = enc.WriteZettel(os.Stdout, z, format != "raw")
+ _, err = encdr.WriteZettel(os.Stdout, z)
if err != nil {
return 2, err
}
fmt.Println()
@@ -58,26 +67,26 @@
if len(args) < 1 {
src, err := io.ReadAll(os.Stdin)
if err != nil {
return nil, nil, err
}
- inp := input.NewInput(string(src))
+ inp := input.NewInput(src)
m := meta.NewFromInput(id.New(true), inp)
return m, inp, nil
}
src, err := os.ReadFile(args[0])
if err != nil {
return nil, nil, err
}
- inp := input.NewInput(string(src))
+ inp := input.NewInput(src)
m := meta.NewFromInput(id.New(true), inp)
if len(args) > 1 {
- src, err := os.ReadFile(args[1])
+ src, err = os.ReadFile(args[1])
if err != nil {
return nil, nil, err
}
- inp = input.NewInput(string(src))
+ inp = input.NewInput(src)
}
return m, inp, nil
}
Index: cmd/cmd_password.go
==================================================================
--- cmd/cmd_password.go
+++ cmd/cmd_password.go
@@ -1,13 +1,16 @@
//-----------------------------------------------------------------------------
-// Copyright (c) 2020 Detlef Stern
+// Copyright (c) 2020-present Detlef Stern
//
-// This file is part of zettelstore.
+// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
//-----------------------------------------------------------------------------
package cmd
import (
@@ -15,18 +18,19 @@
"fmt"
"os"
"golang.org/x/term"
- "zettelstore.de/z/auth/cred"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth/cred"
)
// ---------- Subcommand: password -------------------------------------------
-func cmdPassword(fs *flag.FlagSet, cfg *meta.Meta) (int, error) {
+func cmdPassword(fs *flag.FlagSet) (int, error) {
if fs.NArg() == 0 {
fmt.Fprintln(os.Stderr, "User name and user zettel identification missing")
return 2, nil
}
if fs.NArg() == 1 {
Index: cmd/cmd_run.go
==================================================================
--- cmd/cmd_run.go
+++ cmd/cmd_run.go
@@ -1,126 +1,140 @@
//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
+// Copyright (c) 2020-present Detlef Stern
//
-// This file is part of zettelstore.
+// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
//-----------------------------------------------------------------------------
package cmd
import (
+ "context"
"flag"
"net/http"
- "zettelstore.de/z/auth"
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/kernel"
- "zettelstore.de/z/place"
- "zettelstore.de/z/usecase"
- "zettelstore.de/z/web/adapter"
- "zettelstore.de/z/web/adapter/api"
- "zettelstore.de/z/web/adapter/webui"
- "zettelstore.de/z/web/server"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/auth/user"
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/config"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/usecase"
+ "zettelstore.de/z/internal/web/adapter/api"
+ "zettelstore.de/z/internal/web/adapter/webui"
+ "zettelstore.de/z/internal/web/server"
)
// ---------- Subcommand: run ------------------------------------------------
func flgRun(fs *flag.FlagSet) {
- fs.String("c", defConfigfile, "configuration file")
+ fs.String("c", "", "configuration file")
fs.Uint("a", 0, "port number kernel service (0=disable)")
fs.Uint("p", 23123, "port number web service")
fs.String("d", "", "zettel directory")
fs.Bool("r", false, "system-wide read-only mode")
fs.Bool("v", false, "verbose mode")
fs.Bool("debug", false, "debug mode")
}
-func withDebug(fs *flag.FlagSet) bool {
- dbg := fs.Lookup("debug")
- return dbg != nil && dbg.Value.String() == "true"
-}
-
-func runFunc(fs *flag.FlagSet, cfg *meta.Meta) (int, error) {
- exitCode, err := doRun(withDebug(fs))
+func runFunc(*flag.FlagSet) (int, error) {
+ var exitCode int
+ err := kernel.Main.StartService(kernel.WebService)
+ if err != nil {
+ exitCode = 1
+ }
kernel.Main.WaitForShutdown()
return exitCode, err
}
-func doRun(debug bool) (int, error) {
- kern := kernel.Main
- kern.SetDebug(debug)
- if err := kern.StartService(kernel.WebService); err != nil {
- return 1, err
- }
- return 0, nil
-}
-
-func setupRouting(webSrv server.Server, placeManager place.Manager, authManager auth.Manager, rtConfig config.Config) {
- protectedPlaceManager, authPolicy := authManager.PlaceWithPolicy(webSrv, placeManager, rtConfig)
- api := api.New(webSrv, authManager, authManager, webSrv, rtConfig)
- wui := webui.New(webSrv, authManager, rtConfig, authManager, placeManager, authPolicy)
-
- ucAuthenticate := usecase.NewAuthenticate(authManager, authManager, placeManager)
- ucCreateZettel := usecase.NewCreateZettel(rtConfig, protectedPlaceManager)
- ucGetMeta := usecase.NewGetMeta(protectedPlaceManager)
- ucGetZettel := usecase.NewGetZettel(protectedPlaceManager)
- ucParseZettel := usecase.NewParseZettel(rtConfig, ucGetZettel)
- ucListMeta := usecase.NewListMeta(protectedPlaceManager)
- ucListRoles := usecase.NewListRole(protectedPlaceManager)
- ucListTags := usecase.NewListTags(protectedPlaceManager)
- ucZettelContext := usecase.NewZettelContext(protectedPlaceManager)
-
- webSrv.Handle("/", wui.MakeGetRootHandler(protectedPlaceManager))
- webSrv.AddListRoute('a', http.MethodGet, wui.MakeGetLoginHandler())
- webSrv.AddListRoute('a', http.MethodPost, adapter.MakePostLoginHandler(
- api.MakePostLoginHandlerAPI(ucAuthenticate),
- wui.MakePostLoginHandlerHTML(ucAuthenticate)))
- webSrv.AddListRoute('a', http.MethodPut, api.MakeRenewAuthHandler())
- webSrv.AddZettelRoute('a', http.MethodGet, wui.MakeGetLogoutHandler())
- if !authManager.IsReadonly() {
- webSrv.AddZettelRoute('b', http.MethodGet, wui.MakeGetRenameZettelHandler(ucGetMeta))
- webSrv.AddZettelRoute('b', http.MethodPost, wui.MakePostRenameZettelHandler(
- usecase.NewRenameZettel(protectedPlaceManager)))
- webSrv.AddZettelRoute('c', http.MethodGet, wui.MakeGetCopyZettelHandler(
- ucGetZettel, usecase.NewCopyZettel()))
- webSrv.AddZettelRoute('c', http.MethodPost, wui.MakePostCreateZettelHandler(ucCreateZettel))
- webSrv.AddZettelRoute('d', http.MethodGet, wui.MakeGetDeleteZettelHandler(ucGetZettel))
- webSrv.AddZettelRoute('d', http.MethodPost, wui.MakePostDeleteZettelHandler(
- usecase.NewDeleteZettel(protectedPlaceManager)))
- webSrv.AddZettelRoute('e', http.MethodGet, wui.MakeEditGetZettelHandler(ucGetZettel))
- webSrv.AddZettelRoute('e', http.MethodPost, wui.MakeEditSetZettelHandler(
- usecase.NewUpdateZettel(protectedPlaceManager)))
- webSrv.AddZettelRoute('f', http.MethodGet, wui.MakeGetFolgeZettelHandler(
- ucGetZettel, usecase.NewFolgeZettel(rtConfig)))
- webSrv.AddZettelRoute('f', http.MethodPost, wui.MakePostCreateZettelHandler(ucCreateZettel))
- webSrv.AddZettelRoute('g', http.MethodGet, wui.MakeGetNewZettelHandler(
- ucGetZettel, usecase.NewNewZettel()))
- webSrv.AddZettelRoute('g', http.MethodPost, wui.MakePostCreateZettelHandler(ucCreateZettel))
- }
- webSrv.AddListRoute('f', http.MethodGet, wui.MakeSearchHandler(
- usecase.NewSearch(protectedPlaceManager), ucGetMeta, ucGetZettel))
- webSrv.AddListRoute('h', http.MethodGet, wui.MakeListHTMLMetaHandler(
- ucListMeta, ucListRoles, ucListTags))
- webSrv.AddZettelRoute('h', http.MethodGet, wui.MakeGetHTMLZettelHandler(
- ucParseZettel, ucGetMeta))
- webSrv.AddZettelRoute('i', http.MethodGet, wui.MakeGetInfoHandler(ucParseZettel, ucGetMeta))
- webSrv.AddZettelRoute('j', http.MethodGet, wui.MakeZettelContextHandler(ucZettelContext))
-
- webSrv.AddZettelRoute('l', http.MethodGet, api.MakeGetLinksHandler(ucParseZettel))
- webSrv.AddZettelRoute('o', http.MethodGet, api.MakeGetOrderHandler(
- usecase.NewZettelOrder(protectedPlaceManager, ucParseZettel)))
- webSrv.AddListRoute('r', http.MethodGet, api.MakeListRoleHandler(ucListRoles))
- webSrv.AddListRoute('t', http.MethodGet, api.MakeListTagsHandler(ucListTags))
- webSrv.AddZettelRoute('y', http.MethodGet, api.MakeZettelContextHandler(ucZettelContext))
- webSrv.AddListRoute('z', http.MethodGet, api.MakeListMetaHandler(
- usecase.NewListMeta(protectedPlaceManager), ucGetMeta, ucParseZettel))
- webSrv.AddZettelRoute('z', http.MethodGet, api.MakeGetZettelHandler(
- ucParseZettel, ucGetMeta))
+func setupRouting(webSrv server.Server, boxManager box.Manager, authManager auth.Manager, rtConfig config.Config) {
+ protectedBoxManager, authPolicy := authManager.BoxWithPolicy(boxManager, rtConfig)
+ kern := kernel.Main
+ webLogger := kern.GetLogger(kernel.WebService)
+
+ var getUser getUserImpl
+ authLogger := kern.GetLogger(kernel.AuthService)
+ ucLogger := kern.GetLogger(kernel.CoreService)
+ ucGetUser := usecase.NewGetUser(authManager, boxManager)
+ ucAuthenticate := usecase.NewAuthenticate(authLogger, authManager, &ucGetUser)
+ ucIsAuth := usecase.NewIsAuthenticated(ucLogger, &getUser, authManager)
+ ucCreateZettel := usecase.NewCreateZettel(ucLogger, rtConfig, protectedBoxManager)
+ ucGetAllZettel := usecase.NewGetAllZettel(protectedBoxManager)
+ ucGetZettel := usecase.NewGetZettel(protectedBoxManager)
+ ucParseZettel := usecase.NewParseZettel(rtConfig, ucGetZettel)
+ ucGetReferences := usecase.NewGetReferences()
+ ucQuery := usecase.NewQuery(protectedBoxManager)
+ ucEvaluate := usecase.NewEvaluate(rtConfig, &ucGetZettel, &ucQuery)
+ ucQuery.SetEvaluate(&ucEvaluate)
+ ucTagZettel := usecase.NewTagZettel(protectedBoxManager, &ucQuery)
+ ucRoleZettel := usecase.NewRoleZettel(protectedBoxManager, &ucQuery)
+ ucListSyntax := usecase.NewListSyntax(protectedBoxManager)
+ ucListRoles := usecase.NewListRoles(protectedBoxManager)
+ ucDelete := usecase.NewDeleteZettel(ucLogger, protectedBoxManager)
+ ucUpdate := usecase.NewUpdateZettel(ucLogger, protectedBoxManager)
+ ucRefresh := usecase.NewRefresh(ucLogger, protectedBoxManager)
+ ucReIndex := usecase.NewReIndex(ucLogger, protectedBoxManager)
+ ucVersion := usecase.NewVersion(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVersion).(string))
+
+ a := api.New(
+ webLogger.With("system", "WEBAPI"),
+ webSrv, authManager, authManager, rtConfig, authPolicy)
+ wui := webui.New(
+ webLogger.With("system", "WEBUI"),
+ webSrv, authManager, rtConfig, authManager, boxManager, authPolicy, &ucEvaluate)
+
+ webSrv.Handle("/", wui.MakeGetRootHandler(protectedBoxManager))
+ if assetDir := kern.GetConfig(kernel.WebService, kernel.WebAssetDir).(string); assetDir != "" {
+ const assetPrefix = "/assets/"
+ webSrv.Handle(assetPrefix, http.StripPrefix(assetPrefix, http.FileServer(http.Dir(assetDir))))
+ webSrv.Handle("/favicon.ico", wui.MakeFaviconHandler(assetDir))
+ }
+
+ // Web user interface
+ if !authManager.IsReadonly() {
+ webSrv.AddListRoute('c', server.MethodGet, wui.MakeGetZettelFromListHandler(&ucQuery, &ucEvaluate, ucListRoles, ucListSyntax))
+ webSrv.AddListRoute('c', server.MethodPost, wui.MakePostCreateZettelHandler(&ucCreateZettel))
+ webSrv.AddZettelRoute('c', server.MethodGet, wui.MakeGetCreateZettelHandler(
+ ucGetZettel, &ucCreateZettel, ucListRoles, ucListSyntax))
+ webSrv.AddZettelRoute('c', server.MethodPost, wui.MakePostCreateZettelHandler(&ucCreateZettel))
+ webSrv.AddZettelRoute('d', server.MethodGet, wui.MakeGetDeleteZettelHandler(ucGetZettel, ucGetAllZettel))
+ webSrv.AddZettelRoute('d', server.MethodPost, wui.MakePostDeleteZettelHandler(&ucDelete))
+ webSrv.AddZettelRoute('e', server.MethodGet, wui.MakeEditGetZettelHandler(ucGetZettel, ucListRoles, ucListSyntax))
+ webSrv.AddZettelRoute('e', server.MethodPost, wui.MakeEditSetZettelHandler(&ucUpdate))
+ }
+ webSrv.AddListRoute('g', server.MethodGet, wui.MakeGetGoActionHandler(&ucRefresh))
+ webSrv.AddListRoute('h', server.MethodGet, wui.MakeListHTMLMetaHandler(&ucQuery, &ucTagZettel, &ucRoleZettel, &ucReIndex))
+ webSrv.AddZettelRoute('h', server.MethodGet, wui.MakeGetHTMLZettelHandler(&ucEvaluate, ucGetZettel))
+ webSrv.AddListRoute('i', server.MethodGet, wui.MakeGetLoginOutHandler())
+ webSrv.AddListRoute('i', server.MethodPost, wui.MakePostLoginHandler(&ucAuthenticate))
+ webSrv.AddZettelRoute('i', server.MethodGet, wui.MakeGetInfoHandler(
+ ucParseZettel, ucGetReferences, &ucEvaluate, ucGetZettel, ucGetAllZettel, &ucQuery))
+
+ // API
+ webSrv.AddListRoute('a', server.MethodPost, a.MakePostLoginHandler(&ucAuthenticate))
+ webSrv.AddListRoute('a', server.MethodPut, a.MakeRenewAuthHandler())
+ webSrv.AddZettelRoute('r', server.MethodGet, a.MakeGetReferencesHandler(ucParseZettel, ucGetReferences))
+ webSrv.AddListRoute('x', server.MethodGet, a.MakeGetDataHandler(ucVersion))
+ webSrv.AddListRoute('x', server.MethodPost, a.MakePostCommandHandler(&ucIsAuth, &ucRefresh))
+ webSrv.AddListRoute('z', server.MethodGet, a.MakeQueryHandler(&ucQuery, &ucTagZettel, &ucRoleZettel, &ucReIndex))
+ webSrv.AddZettelRoute('z', server.MethodGet, a.MakeGetZettelHandler(ucGetZettel, ucParseZettel, ucEvaluate))
+ if !authManager.IsReadonly() {
+ webSrv.AddListRoute('z', server.MethodPost, a.MakePostCreateZettelHandler(&ucCreateZettel))
+ webSrv.AddZettelRoute('z', server.MethodPut, a.MakeUpdateZettelHandler(&ucUpdate))
+ webSrv.AddZettelRoute('z', server.MethodDelete, a.MakeDeleteZettelHandler(&ucDelete))
+ }
if authManager.WithAuth() {
- webSrv.SetUserRetriever(usecase.NewGetUserByZid(placeManager))
+ webSrv.SetUserRetriever(usecase.NewGetUserByZid(boxManager))
}
}
+
+type getUserImpl struct{}
+
+func (*getUserImpl) GetCurrentUser(ctx context.Context) *meta.Meta { return user.GetCurrentUser(ctx) }
DELETED cmd/cmd_run_simple.go
Index: cmd/cmd_run_simple.go
==================================================================
--- cmd/cmd_run_simple.go
+++ /dev/null
@@ -1,52 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-package cmd
-
-import (
- "flag"
- "fmt"
- "os"
- "strings"
-
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/kernel"
-)
-
-func flgSimpleRun(fs *flag.FlagSet) {
- fs.String("d", "", "zettel directory")
-}
-
-func runSimpleFunc(fs *flag.FlagSet, cfg *meta.Meta) (int, error) {
- kern := kernel.Main
- listenAddr := kern.GetConfig(kernel.WebService, kernel.WebListenAddress).(string)
- exitCode, err := doRun(false)
- if idx := strings.LastIndexByte(listenAddr, ':'); idx >= 0 {
- kern.Log()
- kern.Log("--------------------------")
- kern.Log("Open your browser and enter the following URL:")
- kern.Log()
- kern.Log(fmt.Sprintf(" http://localhost%v", listenAddr[idx:]))
- kern.Log()
- }
- kern.WaitForShutdown()
- return exitCode, err
-}
-
-// runSimple is called, when the user just starts the software via a double click
-// or via a simple call ``./zettelstore`` on the command line.
-func runSimple() int {
- dir := "./zettel"
- if err := os.MkdirAll(dir, 0750); err != nil {
- fmt.Fprintf(os.Stderr, "Unable to create zettel directory %q (%s)\n", dir, err)
- os.Exit(1)
- }
- return executeCommand("run-simple", "-d", dir)
-}
Index: cmd/command.go
==================================================================
--- cmd/command.go
+++ cmd/command.go
@@ -1,39 +1,43 @@
//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
+// Copyright (c) 2020-present Detlef Stern
//
-// This file is part of zettelstore.
+// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
//-----------------------------------------------------------------------------
package cmd
import (
"flag"
- "sort"
-
- "zettelstore.de/z/domain/meta"
+ "log/slog"
+ "maps"
+ "slices"
)
// Command stores information about commands / sub-commands.
type Command struct {
- Name string // command name as it appears on the command line
- Func CommandFunc // function that executes a command
- Places bool // if true then places will be set up
- Header bool // Print a heading on startup
- Flags func(*flag.FlagSet) // function to set up flag.FlagSet
- flags *flag.FlagSet // flags that belong to the command
-
+ Name string // command name as it appears on the command line
+ Func CommandFunc // function that executes a command
+ Simple bool // Operate in simple-mode
+ Boxes bool // if true then boxes will be set up
+ Header bool // Print a heading on startup
+ LineServer bool // Start admin line server
+ SetFlags func(*flag.FlagSet) // function to set up flag.FlagSet
+ flags *flag.FlagSet // flags that belong to the command
}
// CommandFunc is the function that executes the command.
// It accepts the parsed command line parameters.
// It returns the exit code and an error.
-type CommandFunc func(*flag.FlagSet, *meta.Meta) (int, error)
+type CommandFunc func(*flag.FlagSet) (int, error)
// GetFlags return the flag.FlagSet defined for the command.
func (c *Command) GetFlags() *flag.FlagSet { return c.flags }
var commands = make(map[string]Command)
@@ -45,12 +49,14 @@
}
if _, ok := commands[cmd.Name]; ok {
panic("Command already registered: " + cmd.Name)
}
cmd.flags = flag.NewFlagSet(cmd.Name, flag.ExitOnError)
- if cmd.Flags != nil {
- cmd.Flags(cmd.flags)
+ cmd.flags.String("l", slog.LevelInfo.String(), "log level specification")
+
+ if cmd.SetFlags != nil {
+ cmd.SetFlags(cmd.flags)
}
commands[cmd.Name] = cmd
}
// Get returns the command identified by the given name and a bool to signal success.
@@ -58,13 +64,6 @@
cmd, ok := commands[name]
return cmd, ok
}
// List returns a sorted list of all registered command names.
-func List() []string {
- result := make([]string, 0, len(commands))
- for name := range commands {
- result = append(result, name)
- }
- sort.Strings(result)
- return result
-}
+func List() []string { return slices.Sorted(maps.Keys(commands)) }
DELETED cmd/fd_limit.go
Index: cmd/fd_limit.go
==================================================================
--- cmd/fd_limit.go
+++ /dev/null
@@ -1,15 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// +build !darwin
-
-package cmd
-
-func raiseFdLimit() error { return nil }
DELETED cmd/fd_limit_raise.go
Index: cmd/fd_limit_raise.go
==================================================================
--- cmd/fd_limit_raise.go
+++ /dev/null
@@ -1,47 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// +build darwin
-
-package cmd
-
-import (
- "log"
- "syscall"
-)
-
-const minFiles = 1048576
-
-func raiseFdLimit() error {
- var rLimit syscall.Rlimit
- err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
- if err != nil {
- return err
- }
- if rLimit.Cur >= minFiles {
- return nil
- }
- rLimit.Cur = minFiles
- if rLimit.Cur > rLimit.Max {
- rLimit.Cur = rLimit.Max
- }
- err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
- if err != nil {
- return err
- }
- err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
- if err != nil {
- return err
- }
- if rLimit.Cur < minFiles {
- log.Printf("Make sure you have no more than %d files in all your places if you enabled notification\n", rLimit.Cur)
- }
- return nil
-}
Index: cmd/main.go
==================================================================
--- cmd/main.go
+++ cmd/main.go
@@ -1,230 +1,263 @@
//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
+// Copyright (c) 2020-present Detlef Stern
//
-// This file is part of zettelstore.
+// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
//-----------------------------------------------------------------------------
+// Package cmd provides the commands to call Zettelstore from the command line.
package cmd
import (
- "errors"
+ "crypto/sha256"
"flag"
"fmt"
+ "log/slog"
"net"
"net/url"
"os"
+ "runtime/debug"
"strconv"
"strings"
-
- "zettelstore.de/z/auth"
- "zettelstore.de/z/auth/impl"
- "zettelstore.de/z/config"
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/input"
- "zettelstore.de/z/kernel"
- "zettelstore.de/z/place"
- "zettelstore.de/z/place/manager"
- "zettelstore.de/z/place/progplace"
- "zettelstore.de/z/web/server"
-)
-
-const (
- defConfigfile = ".zscfg"
-)
+ "time"
+
+ "t73f.de/r/zsc/api"
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "t73f.de/r/zsx/input"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/auth/impl"
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/compbox"
+ "zettelstore.de/z/internal/box/manager"
+ "zettelstore.de/z/internal/config"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/web/server"
+)
+
+const strRunSimple = "run-simple"
func init() {
RegisterCommand(Command{
Name: "help",
- Func: func(*flag.FlagSet, *meta.Meta) (int, error) {
+ Func: func(*flag.FlagSet) (int, error) {
fmt.Println("Available commands:")
for _, name := range List() {
fmt.Printf("- %q\n", name)
}
return 0, nil
},
})
RegisterCommand(Command{
Name: "version",
- Func: func(*flag.FlagSet, *meta.Meta) (int, error) { return 0, nil },
- Header: true,
- })
- RegisterCommand(Command{
- Name: "run",
- Func: runFunc,
- Places: true,
- Header: true,
- Flags: flgRun,
- })
- RegisterCommand(Command{
- Name: "run-simple",
- Func: runSimpleFunc,
- Places: true,
- Header: true,
- Flags: flgSimpleRun,
+ Func: func(*flag.FlagSet) (int, error) { return 0, nil },
+ Header: true,
+ })
+ RegisterCommand(Command{
+ Name: "run",
+ Func: runFunc,
+ Boxes: true,
+ Header: true,
+ LineServer: true,
+ SetFlags: flgRun,
+ })
+ RegisterCommand(Command{
+ Name: strRunSimple,
+ Func: runFunc,
+ Simple: true,
+ Boxes: true,
+ Header: true,
+ // LineServer: true,
+ SetFlags: func(fs *flag.FlagSet) {
+ // fs.Uint("a", 0, "port number kernel service (0=disable)")
+ fs.String("d", "", "zettel directory")
+ },
})
RegisterCommand(Command{
Name: "file",
Func: cmdFile,
- Flags: func(fs *flag.FlagSet) {
- fs.String("t", "html", "target output format")
+ SetFlags: func(fs *flag.FlagSet) {
+ fs.String("t", api.EncoderHTML.String(), "target output encoding")
},
})
RegisterCommand(Command{
Name: "password",
Func: cmdPassword,
})
}
-func readConfig(fs *flag.FlagSet) (cfg *meta.Meta) {
- var configFile string
+func fetchStartupConfiguration(fs *flag.FlagSet) (string, *meta.Meta) {
if configFlag := fs.Lookup("c"); configFlag != nil {
- configFile = configFlag.Value.String()
- } else {
- configFile = defConfigfile
+ if filename := configFlag.Value.String(); filename != "" {
+ content, err := readConfiguration(filename)
+ return filename, createConfiguration(content, err)
+ }
}
- content, err := os.ReadFile(configFile)
+ filename, content, err := searchAndReadConfiguration()
+ return filename, createConfiguration(content, err)
+}
+
+func createConfiguration(content []byte, err error) *meta.Meta {
if err != nil {
return meta.New(id.Invalid)
}
- return meta.NewFromInput(id.Invalid, input.NewInput(string(content)))
+ return meta.NewFromInput(id.Invalid, input.NewInput(content))
+}
+
+func readConfiguration(filename string) ([]byte, error) { return os.ReadFile(filename) }
+
+func searchAndReadConfiguration() (string, []byte, error) {
+ for _, filename := range []string{"zettelstore.cfg", "zsconfig.txt", "zscfg.txt", "_zscfg", ".zscfg"} {
+ if content, err := readConfiguration(filename); err == nil {
+ return filename, content, nil
+ }
+ }
+ return "", nil, os.ErrNotExist
}
-func getConfig(fs *flag.FlagSet) *meta.Meta {
- cfg := readConfig(fs)
+func getConfig(fs *flag.FlagSet) (string, *meta.Meta) {
+ filename, cfg := fetchStartupConfiguration(fs)
fs.Visit(func(flg *flag.Flag) {
switch flg.Name {
case "p":
- if portStr, err := parsePort(flg.Value.String()); err == nil {
- cfg.Set(keyListenAddr, net.JoinHostPort("127.0.0.1", portStr))
- }
+ cfg.Set(keyListenAddr, meta.Value(net.JoinHostPort("127.0.0.1", flg.Value.String())))
case "a":
- if portStr, err := parsePort(flg.Value.String()); err == nil {
- cfg.Set(keyAdminPort, portStr)
- }
+ cfg.Set(keyAdminPort, meta.Value(flg.Value.String()))
case "d":
val := flg.Value.String()
if strings.HasPrefix(val, "/") {
val = "dir://" + val
} else {
val = "dir:" + val
}
- cfg.Set(keyPlaceOneURI, val)
+ deleteConfiguredBoxes(cfg)
+ cfg.Set(keyBoxOneURI, meta.Value(val))
+ case "l":
+ cfg.Set(keyLogLevel, meta.Value(flg.Value.String()))
+ case "debug":
+ cfg.Set(keyDebug, meta.Value(flg.Value.String()))
case "r":
- cfg.Set(keyReadOnly, flg.Value.String())
+ cfg.Set(keyReadOnly, meta.Value(flg.Value.String()))
case "v":
- cfg.Set(keyVerbose, flg.Value.String())
+ cfg.Set(keyVerbose, meta.Value(flg.Value.String()))
}
})
- return cfg
+ return filename, cfg
}
-func parsePort(s string) (string, error) {
- port, err := net.LookupPort("tcp", s)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Wrong port specification: %q", s)
- return "", err
+func deleteConfiguredBoxes(cfg *meta.Meta) {
+ for key := range cfg.Rest() {
+ if strings.HasPrefix(key, kernel.BoxURIs) {
+ cfg.Delete(key)
+ }
}
- return strconv.Itoa(port), nil
}
const (
- keyAdminPort = "admin-port"
- keyDefaultDirPlaceType = "default-dir-place-type"
- keyInsecureCookie = "insecure-cookie"
- keyListenAddr = "listen-addr"
- keyOwner = "owner"
- keyPersistentCookie = "persistent-cookie"
- keyPlaceOneURI = kernel.PlaceURIs + "1"
- keyReadOnly = "read-only-mode"
- keyTokenLifetimeHTML = "token-lifetime-html"
- keyTokenLifetimeAPI = "token-lifetime-api"
- keyURLPrefix = "url-prefix"
- keyVerbose = "verbose"
-)
-
-func setServiceConfig(cfg *meta.Meta) error {
- ok := setConfigValue(true, kernel.CoreService, kernel.CoreVerbose, cfg.GetBool(keyVerbose))
- if val, found := cfg.Get(keyAdminPort); found {
- ok = setConfigValue(ok, kernel.CoreService, kernel.CorePort, val)
- }
-
- ok = setConfigValue(ok, kernel.AuthService, kernel.AuthOwner, cfg.GetDefault(keyOwner, ""))
- ok = setConfigValue(ok, kernel.AuthService, kernel.AuthReadonly, cfg.GetBool(keyReadOnly))
-
- ok = setConfigValue(
- ok, kernel.PlaceService, kernel.PlaceDefaultDirType,
- cfg.GetDefault(keyDefaultDirPlaceType, kernel.PlaceDirTypeNotify))
- ok = setConfigValue(ok, kernel.PlaceService, kernel.PlaceURIs+"1", "dir:./zettel")
- format := kernel.PlaceURIs + "%v"
- for i := 1; ; i++ {
- key := fmt.Sprintf(format, i)
+ keyAdminPort = "admin-port"
+ keyAssetDir = "asset-dir"
+ keyBaseURL = "base-url"
+ keyBoxOneURI = kernel.BoxURIs + "1"
+ keyDebug = "debug-mode"
+ keyDefaultDirBoxType = "default-dir-box-type"
+ keyInsecureCookie = "insecure-cookie"
+ keyInsecureHTML = "insecure-html"
+ keyListenAddr = "listen-addr"
+ keyLogLevel = "log-level"
+ keyLoopbackIdent = "loopback-ident"
+ keyLoopbackZid = "loopback-zid"
+ keyMaxRequestSize = "max-request-size"
+ keyOwner = "owner"
+ keyPersistentCookie = "persistent-cookie"
+ keyReadOnly = "read-only-mode"
+ keyRuntimeProfiling = "runtime-profiling"
+ keySxNesting = "sx-max-nesting"
+ keyTokenLifetimeHTML = "token-lifetime-html"
+ keyTokenLifetimeAPI = "token-lifetime-api"
+ keyURLPrefix = "url-prefix"
+ keyVerbose = "verbose-mode"
+)
+
+func setServiceConfig(cfg *meta.Meta) bool {
+ debugMode := cfg.GetBool(keyDebug)
+ if debugMode && kernel.Main.GetKernelLogLevel() > slog.LevelDebug {
+ kernel.Main.SetLogLevel(logging.LevelString(slog.LevelDebug))
+ }
+ if logLevel, found := cfg.Get(keyLogLevel); found {
+ kernel.Main.SetLogLevel(string(logLevel))
+ }
+ err := setConfigValue(nil, kernel.CoreService, kernel.CoreDebug, debugMode)
+ err = setConfigValue(err, kernel.CoreService, kernel.CoreVerbose, cfg.GetBool(keyVerbose))
+ if val, found := cfg.Get(keyAdminPort); found {
+ err = setConfigValue(err, kernel.CoreService, kernel.CorePort, val)
+ }
+
+ err = setConfigValue(err, kernel.AuthService, kernel.AuthOwner, cfg.GetDefault(keyOwner, ""))
+ err = setConfigValue(err, kernel.AuthService, kernel.AuthReadonly, cfg.GetBool(keyReadOnly))
+
+ err = setConfigValue(
+ err, kernel.BoxService, kernel.BoxDefaultDirType,
+ cfg.GetDefault(keyDefaultDirBoxType, kernel.BoxDirTypeNotify))
+ err = setConfigValue(err, kernel.BoxService, kernel.BoxURIs+"1", "dir:./zettel")
+ for i := 1; ; i++ {
+ key := kernel.BoxURIs + strconv.Itoa(i)
val, found := cfg.Get(key)
if !found {
break
}
- ok = setConfigValue(ok, kernel.PlaceService, key, val)
- }
-
- ok = setConfigValue(
- ok, kernel.WebService, kernel.WebListenAddress,
- cfg.GetDefault(keyListenAddr, "127.0.0.1:23123"))
- ok = setConfigValue(ok, kernel.WebService, kernel.WebURLPrefix, cfg.GetDefault(keyURLPrefix, "/"))
- ok = setConfigValue(ok, kernel.WebService, kernel.WebSecureCookie, !cfg.GetBool(keyInsecureCookie))
- ok = setConfigValue(ok, kernel.WebService, kernel.WebPersistentCookie, cfg.GetBool(keyPersistentCookie))
- ok = setConfigValue(
- ok, kernel.WebService, kernel.WebTokenLifetimeAPI, cfg.GetDefault(keyTokenLifetimeAPI, ""))
- ok = setConfigValue(
- ok, kernel.WebService, kernel.WebTokenLifetimeHTML, cfg.GetDefault(keyTokenLifetimeHTML, ""))
-
- if !ok {
- return errors.New("unable to set configuration")
- }
- return nil
-}
-
-func setConfigValue(ok bool, subsys kernel.Service, key string, val interface{}) bool {
- done := kernel.Main.SetConfig(subsys, key, fmt.Sprintf("%v", val))
- if !done {
- kernel.Main.Log("unable to set configuration:", key, val)
- }
- return ok && done
-}
-
-func setupOperations(cfg *meta.Meta, withPlaces bool) {
- var createManager kernel.CreatePlaceManagerFunc
- if withPlaces {
- err := raiseFdLimit()
- if err != nil {
- srvm := kernel.Main
- srvm.Log("Raising some limitions did not work:", err)
- srvm.Log("Prepare to encounter errors. Most of them can be mitigated. See the manual for details")
- srvm.SetConfig(kernel.PlaceService, kernel.PlaceDefaultDirType, kernel.PlaceDirTypeSimple)
- }
- createManager = func(placeURIs []*url.URL, authManager auth.Manager, rtConfig config.Config) (place.Manager, error) {
- progplace.Setup(cfg)
- return manager.New(placeURIs, authManager, rtConfig)
- }
- } else {
- createManager = func([]*url.URL, auth.Manager, config.Config) (place.Manager, error) { return nil, nil }
- }
-
- kernel.Main.SetCreators(
- func(readonly bool, owner id.Zid) (auth.Manager, error) {
- return impl.New(readonly, owner, cfg.GetDefault("secret", "")), nil
- },
- createManager,
- func(srv server.Server, plMgr place.Manager, authMgr auth.Manager, rtConfig config.Config) error {
- setupRouting(srv, plMgr, authMgr, rtConfig)
- return nil
- },
- )
+ err = setConfigValue(err, kernel.BoxService, key, val)
+ }
+
+ err = setConfigValue(
+ err, kernel.ConfigService, kernel.ConfigInsecureHTML, cfg.GetDefault(keyInsecureHTML, kernel.ConfigSecureHTML))
+
+ err = setConfigValue(
+ err, kernel.WebService, kernel.WebListenAddress, cfg.GetDefault(keyListenAddr, "127.0.0.1:23123"))
+ err = setConfigValue(err, kernel.WebService, kernel.WebLoopbackIdent, cfg.GetDefault(keyLoopbackIdent, ""))
+ err = setConfigValue(err, kernel.WebService, kernel.WebLoopbackZid, cfg.GetDefault(keyLoopbackZid, ""))
+ if val, found := cfg.Get(keyBaseURL); found {
+ err = setConfigValue(err, kernel.WebService, kernel.WebBaseURL, val)
+ }
+ if val, found := cfg.Get(keyURLPrefix); found {
+ err = setConfigValue(err, kernel.WebService, kernel.WebURLPrefix, val)
+ }
+ err = setConfigValue(err, kernel.WebService, kernel.WebSecureCookie, !cfg.GetBool(keyInsecureCookie))
+ err = setConfigValue(err, kernel.WebService, kernel.WebPersistentCookie, cfg.GetBool(keyPersistentCookie))
+ if val, found := cfg.Get(keyMaxRequestSize); found {
+ err = setConfigValue(err, kernel.WebService, kernel.WebMaxRequestSize, val)
+ }
+ err = setConfigValue(
+ err, kernel.WebService, kernel.WebTokenLifetimeAPI, cfg.GetDefault(keyTokenLifetimeAPI, ""))
+ err = setConfigValue(
+ err, kernel.WebService, kernel.WebTokenLifetimeHTML, cfg.GetDefault(keyTokenLifetimeHTML, ""))
+ err = setConfigValue(err, kernel.WebService, kernel.WebProfiling, debugMode || cfg.GetBool(keyRuntimeProfiling))
+ if val, found := cfg.Get(keyAssetDir); found {
+ err = setConfigValue(err, kernel.WebService, kernel.WebAssetDir, val)
+ }
+ if val, found := cfg.Get(keySxNesting); found {
+ err = setConfigValue(err, kernel.WebService, kernel.WebSxMaxNesting, val)
+ }
+ return err == nil
+}
+
+func setConfigValue(err error, subsys kernel.Service, key string, val any) error {
+ if err == nil {
+ if err = kernel.Main.SetConfig(subsys, key, fmt.Sprint(val)); err != nil {
+ kernel.Main.GetKernelLogger().Error("Unable to set configuration",
+ "key", key, "value", val, "err", err)
+ }
+ }
+ return err
}
func executeCommand(name string, args ...string) int {
command, ok := Get(name)
if !ok {
@@ -234,34 +267,139 @@
fs := command.GetFlags()
if err := fs.Parse(args); err != nil {
fmt.Fprintf(os.Stderr, "%s: unable to parse flags: %v %v\n", name, args, err)
return 1
}
- cfg := getConfig(fs)
- if err := setServiceConfig(cfg); err != nil {
- fmt.Fprintf(os.Stderr, "%s: %v\n", name, err)
+ filename, cfg := getConfig(fs)
+ if !setServiceConfig(cfg) {
+ fs.Usage()
+ return 2
+ }
+
+ kern := kernel.Main
+ var createManager kernel.CreateBoxManagerFunc
+ if command.Boxes {
+ createManager = func(boxURIs []*url.URL, authManager auth.Manager, rtConfig config.Config) (box.Manager, error) {
+ compbox.Setup(cfg)
+ return manager.New(boxURIs, authManager, rtConfig)
+ }
+ } else {
+ createManager = func([]*url.URL, auth.Manager, config.Config) (box.Manager, error) { return nil, nil }
+ }
+
+ secret := cfg.GetDefault("secret", "")
+ if len(secret) < 16 && cfg.GetDefault(keyOwner, "") != "" {
+ fmt.Fprintf(os.Stderr, "secret must have at least length 16 when authentication is enabled, but is %q\n", secret)
return 2
}
- setupOperations(cfg, command.Places)
- kernel.Main.Start(command.Header)
- exitCode, err := command.Func(fs, cfg)
+ cfg.Delete("secret")
+ secretHash := fmt.Sprintf("%x", sha256.Sum256([]byte(string(secret))))
+
+ kern.SetCreators(
+ func(readonly bool, owner id.Zid) (auth.Manager, error) {
+ return impl.New(readonly, owner, secretHash), nil
+ },
+ createManager,
+ func(srv server.Server, plMgr box.Manager, authMgr auth.Manager, rtConfig config.Config) error {
+ setupRouting(srv, plMgr, authMgr, rtConfig)
+ return nil
+ },
+ )
+
+ if command.Simple {
+ if err := kern.SetConfig(kernel.ConfigService, kernel.ConfigSimpleMode, "true"); err != nil {
+ kern.GetKernelLogger().Error("unable to set simple-mode", "err", err)
+ return 1
+ }
+ }
+ kern.Start(command.Header, command.LineServer, filename)
+ exitCode, err := command.Func(fs)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", name, err)
}
- kernel.Main.Shutdown(true)
+ kern.Shutdown(true)
return exitCode
}
+// runSimple is called, when the user just starts the software via a double click
+// or via a simple call “./zettelstore“ on the command line.
+func runSimple() int {
+ if _, _, err := searchAndReadConfiguration(); err == nil {
+ return executeCommand(strRunSimple)
+ }
+ dir := "./zettel"
+ if err := os.MkdirAll(dir, 0750); err != nil {
+ fmt.Fprintf(os.Stderr, "Unable to create zettel directory %q (%s)\n", dir, err)
+ return 1
+ }
+ return executeCommand(strRunSimple, "-d", dir)
+}
+
+var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
+var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
+
// Main is the real entrypoint of the zettelstore.
-func Main(progName, buildVersion string) {
- kernel.Main.SetConfig(kernel.CoreService, kernel.CoreProgname, progName)
- kernel.Main.SetConfig(kernel.CoreService, kernel.CoreVersion, buildVersion)
- var exitCode int
- if len(os.Args) <= 1 {
- exitCode = runSimple()
- } else {
- exitCode = executeCommand(os.Args[1], os.Args[2:]...)
- }
- if exitCode != 0 {
- os.Exit(exitCode)
- }
+func Main(progName, buildVersion string) int {
+ info := retrieveVCSInfo(buildVersion)
+ fullVersion := info.revision
+ if info.dirty {
+ fullVersion += "-dirty"
+ }
+ kernel.Main.Setup(progName, fullVersion, info.time)
+ flag.Parse()
+ if *cpuprofile != "" || *memprofile != "" {
+ var err error
+ if *cpuprofile != "" {
+ err = kernel.Main.StartProfiling(kernel.ProfileCPU, *cpuprofile)
+ } else {
+ err = kernel.Main.StartProfiling(kernel.ProfileHead, *memprofile)
+ }
+ if err != nil {
+ kernel.Main.GetKernelLogger().Error("start profiling", "err", err)
+ return 1
+ }
+ defer func() {
+ if err = kernel.Main.StopProfiling(); err != nil {
+ kernel.Main.GetKernelLogger().Error("stop profiling", "err", err)
+ }
+ }()
+ }
+ args := flag.Args()
+ if len(args) == 0 {
+ return runSimple()
+ }
+ return executeCommand(args[0], args[1:]...)
+}
+
+type vcsInfo struct {
+ revision string
+ dirty bool
+ time time.Time
+}
+
+func retrieveVCSInfo(version string) vcsInfo {
+ buildTime := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
+ info, ok := debug.ReadBuildInfo()
+ if !ok {
+ return vcsInfo{revision: version, dirty: false, time: buildTime}
+ }
+ result := vcsInfo{time: buildTime}
+ for _, kv := range info.Settings {
+ switch kv.Key {
+ case "vcs.revision":
+ revision := "+" + kv.Value
+ if len(revision) > 11 {
+ revision = revision[:11]
+ }
+ result.revision = version + revision
+ case "vcs.modified":
+ if kv.Value == "true" {
+ result.dirty = true
+ }
+ case "vcs.time":
+ if t, err := time.Parse(time.RFC3339, kv.Value); err == nil {
+ result.time = t
+ }
+ }
+ }
+ return result
}
Index: cmd/register.go
==================================================================
--- cmd/register.go
+++ cmd/register.go
@@ -1,33 +1,23 @@
//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
+// Copyright (c) 2020-present Detlef Stern
//
-// This file is part of zettelstore.
+// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
//-----------------------------------------------------------------------------
-// Package cmd provides command generic functions.
package cmd
-// Mention all needed encoders, parsers and stores to have them registered.
+// Mention all needed boxes, encoders, and parsers to have them registered.
import (
- _ "zettelstore.de/z/encoder/htmlenc" // Allow to use HTML encoder.
- _ "zettelstore.de/z/encoder/jsonenc" // Allow to use JSON encoder.
- _ "zettelstore.de/z/encoder/nativeenc" // Allow to use native encoder.
- _ "zettelstore.de/z/encoder/rawenc" // Allow to use raw encoder.
- _ "zettelstore.de/z/encoder/textenc" // Allow to use text encoder.
- _ "zettelstore.de/z/encoder/zmkenc" // Allow to use zmk encoder.
- _ "zettelstore.de/z/kernel/impl" // Allow kernel implementation to create itself
- _ "zettelstore.de/z/parser/blob" // Allow to use BLOB parser.
- _ "zettelstore.de/z/parser/markdown" // Allow to use markdown parser.
- _ "zettelstore.de/z/parser/none" // Allow to use none parser.
- _ "zettelstore.de/z/parser/plain" // Allow to use plain parser.
- _ "zettelstore.de/z/parser/zettelmark" // Allow to use zettelmark parser.
- _ "zettelstore.de/z/place/constplace" // Allow to use global internal place.
- _ "zettelstore.de/z/place/dirplace" // Allow to use directory place.
- _ "zettelstore.de/z/place/fileplace" // Allow to use file place.
- _ "zettelstore.de/z/place/memplace" // Allow to use memory place.
- _ "zettelstore.de/z/place/progplace" // Allow to use computed place.
+ _ "zettelstore.de/z/internal/box/compbox" // Allow to use computed box.
+ _ "zettelstore.de/z/internal/box/constbox" // Allow to use global internal box.
+ _ "zettelstore.de/z/internal/box/dirbox" // Allow to use directory box.
+ _ "zettelstore.de/z/internal/box/filebox" // Allow to use file box.
+ _ "zettelstore.de/z/internal/box/membox" // Allow to use in-memory box.
)
Index: cmd/zettelstore/main.go
==================================================================
--- cmd/zettelstore/main.go
+++ cmd/zettelstore/main.go
@@ -1,21 +1,29 @@
//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
+// Copyright (c) 2020-present Detlef Stern
//
-// This file is part of zettelstore.
+// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
//-----------------------------------------------------------------------------
// Package main is the starting point for the zettelstore command.
package main
-import "zettelstore.de/z/cmd"
+import (
+ "os"
+
+ "zettelstore.de/z/cmd"
+)
// Version variable. Will be filled by build process.
-var version string = ""
+var version string
func main() {
- cmd.Main("Zettelstore", version)
+ exitCode := cmd.Main("Zettelstore", version)
+ os.Exit(exitCode)
}
DELETED collect/collect.go
Index: collect/collect.go
==================================================================
--- collect/collect.go
+++ /dev/null
@@ -1,103 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package collect provides functions to collect items from a syntax tree.
-package collect
-
-import (
- "zettelstore.de/z/ast"
-)
-
-// Summary stores the relevant parts of the syntax tree
-type Summary struct {
- Links []*ast.Reference // list of all referenced links
- Images []*ast.Reference // list of all referenced images
- Cites []*ast.CiteNode // list of all referenced citations
-}
-
-// References returns all references mentioned in the given zettel. This also
-// includes references to images.
-func References(zn *ast.ZettelNode) Summary {
- lv := linkVisitor{}
- ast.NewTopDownTraverser(&lv).VisitBlockSlice(zn.Ast)
- return lv.summary
-}
-
-type linkVisitor struct {
- summary Summary
-}
-
-// VisitVerbatim does nothing.
-func (lv *linkVisitor) VisitVerbatim(vn *ast.VerbatimNode) {}
-
-// VisitRegion does nothing.
-func (lv *linkVisitor) VisitRegion(rn *ast.RegionNode) {}
-
-// VisitHeading does nothing.
-func (lv *linkVisitor) VisitHeading(hn *ast.HeadingNode) {}
-
-// VisitHRule does nothing.
-func (lv *linkVisitor) VisitHRule(hn *ast.HRuleNode) {}
-
-// VisitList does nothing.
-func (lv *linkVisitor) VisitNestedList(ln *ast.NestedListNode) {}
-
-// VisitDescriptionList does nothing.
-func (lv *linkVisitor) VisitDescriptionList(dn *ast.DescriptionListNode) {}
-
-// VisitPara does nothing.
-func (lv *linkVisitor) VisitPara(pn *ast.ParaNode) {}
-
-// VisitTable does nothing.
-func (lv *linkVisitor) VisitTable(tn *ast.TableNode) {}
-
-// VisitBLOB does nothing.
-func (lv *linkVisitor) VisitBLOB(bn *ast.BLOBNode) {}
-
-// VisitText does nothing.
-func (lv *linkVisitor) VisitText(tn *ast.TextNode) {}
-
-// VisitTag does nothing.
-func (lv *linkVisitor) VisitTag(tn *ast.TagNode) {}
-
-// VisitSpace does nothing.
-func (lv *linkVisitor) VisitSpace(sn *ast.SpaceNode) {}
-
-// VisitBreak does nothing.
-func (lv *linkVisitor) VisitBreak(bn *ast.BreakNode) {}
-
-// VisitLink collects the given link as a reference.
-func (lv *linkVisitor) VisitLink(ln *ast.LinkNode) {
- lv.summary.Links = append(lv.summary.Links, ln.Ref)
-}
-
-// VisitImage collects the image links as a reference.
-func (lv *linkVisitor) VisitImage(in *ast.ImageNode) {
- if in.Ref != nil {
- lv.summary.Images = append(lv.summary.Images, in.Ref)
- }
-}
-
-// VisitCite collects the citation.
-func (lv *linkVisitor) VisitCite(cn *ast.CiteNode) {
- lv.summary.Cites = append(lv.summary.Cites, cn)
-}
-
-// VisitFootnote does nothing.
-func (lv *linkVisitor) VisitFootnote(fn *ast.FootnoteNode) {}
-
-// VisitMark does nothing.
-func (lv *linkVisitor) VisitMark(mn *ast.MarkNode) {}
-
-// VisitFormat does nothing.
-func (lv *linkVisitor) VisitFormat(fn *ast.FormatNode) {}
-
-// VisitLiteral does nothing.
-func (lv *linkVisitor) VisitLiteral(ln *ast.LiteralNode) {}
DELETED collect/collect_test.go
Index: collect/collect_test.go
==================================================================
--- collect/collect_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package collect_test provides some unit test for collectors.
-package collect_test
-
-import (
- "testing"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/collect"
-)
-
-func parseRef(s string) *ast.Reference {
- r := ast.ParseReference(s)
- if !r.IsValid() {
- panic(s)
- }
- return r
-}
-
-func TestLinks(t *testing.T) {
- zn := &ast.ZettelNode{}
- summary := collect.References(zn)
- if summary.Links != nil || summary.Images != nil {
- t.Error("No links/images expected, but got:", summary.Links, "and", summary.Images)
- }
-
- intNode := &ast.LinkNode{Ref: parseRef("01234567890123")}
- para := &ast.ParaNode{
- Inlines: ast.InlineSlice{
- intNode,
- &ast.LinkNode{Ref: parseRef("https://zettelstore.de/z")},
- },
- }
- zn.Ast = ast.BlockSlice{para}
- summary = collect.References(zn)
- if summary.Links == nil || summary.Images != nil {
- t.Error("Links expected, and no images, but got:", summary.Links, "and", summary.Images)
- }
-
- para.Inlines = append(para.Inlines, intNode)
- summary = collect.References(zn)
- if cnt := len(summary.Links); cnt != 3 {
- t.Error("Link count does not work. Expected: 3, got", summary.Links)
- }
-}
-
-func TestImage(t *testing.T) {
- zn := &ast.ZettelNode{
- Ast: ast.BlockSlice{
- &ast.ParaNode{
- Inlines: ast.InlineSlice{
- &ast.ImageNode{Ref: parseRef("12345678901234")},
- },
- },
- },
- }
- summary := collect.References(zn)
- if summary.Images == nil {
- t.Error("Only image expected, but got: ", summary.Images)
- }
-}
DELETED collect/order.go
Index: collect/order.go
==================================================================
--- collect/order.go
+++ /dev/null
@@ -1,69 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package collect provides functions to collect items from a syntax tree.
-package collect
-
-import "zettelstore.de/z/ast"
-
-// Order of internal reference within the given zettel.
-func Order(zn *ast.ZettelNode) (result []*ast.Reference) {
- for _, bn := range zn.Ast {
- if ln, ok := bn.(*ast.NestedListNode); ok {
- switch ln.Code {
- case ast.NestedListOrdered, ast.NestedListUnordered:
- for _, is := range ln.Items {
- if ref := firstItemZettelReference(is); ref != nil {
- result = append(result, ref)
- }
- }
- }
- }
- }
- return result
-}
-
-func firstItemZettelReference(is ast.ItemSlice) *ast.Reference {
- for _, in := range is {
- if pn, ok := in.(*ast.ParaNode); ok {
- if ref := firstInlineZettelReference(pn.Inlines); ref != nil {
- return ref
- }
- }
- }
- return nil
-}
-
-func firstInlineZettelReference(ins ast.InlineSlice) (result *ast.Reference) {
- for _, inl := range ins {
- switch in := inl.(type) {
- case *ast.LinkNode:
- if ref := in.Ref; ref.IsZettel() {
- return ref
- }
- result = firstInlineZettelReference(in.Inlines)
- case *ast.ImageNode:
- result = firstInlineZettelReference(in.Inlines)
- case *ast.CiteNode:
- result = firstInlineZettelReference(in.Inlines)
- case *ast.FootnoteNode:
- // Ignore references in footnotes
- continue
- case *ast.FormatNode:
- result = firstInlineZettelReference(in.Inlines)
- default:
- continue
- }
- if result != nil {
- return result
- }
- }
- return nil
-}
DELETED collect/split.go
Index: collect/split.go
==================================================================
--- collect/split.go
+++ /dev/null
@@ -1,47 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package collect provides functions to collect items from a syntax tree.
-package collect
-
-import "zettelstore.de/z/ast"
-
-// DivideReferences divides the given list of rederences into zettel, local, and external References.
-func DivideReferences(all []*ast.Reference) (zettel, local, external []*ast.Reference) {
- if len(all) == 0 {
- return nil, nil, nil
- }
-
- mapZettel := make(map[string]bool)
- mapLocal := make(map[string]bool)
- mapExternal := make(map[string]bool)
- for _, ref := range all {
- if ref.State == ast.RefStateSelf {
- continue
- }
- if ref.IsZettel() {
- zettel = appendRefToList(zettel, mapZettel, ref)
- } else if ref.IsExternal() {
- external = appendRefToList(external, mapExternal, ref)
- } else {
- local = appendRefToList(local, mapLocal, ref)
- }
- }
- return zettel, local, external
-}
-
-func appendRefToList(reflist []*ast.Reference, refSet map[string]bool, ref *ast.Reference) []*ast.Reference {
- s := ref.String()
- if _, ok := refSet[s]; !ok {
- reflist = append(reflist, ref)
- refSet[s] = true
- }
- return reflist
-}
DELETED config/config.go
Index: config/config.go
==================================================================
--- config/config.go
+++ /dev/null
@@ -1,108 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package config provides functions to retrieve runtime configuration data.
-package config
-
-import (
- "zettelstore.de/z/domain/id"
- "zettelstore.de/z/domain/meta"
-)
-
-// Config allows to retrieve all defined configuration values that can be changed during runtime.
-type Config interface {
- AuthConfig
-
- // AddDefaultValues enriches the given meta data with its default values.
- AddDefaultValues(m *meta.Meta) *meta.Meta
-
- // GetDefaultTitle returns the current value of the "default-title" key.
- GetDefaultTitle() string
-
- // GetDefaultRole returns the current value of the "default-role" key.
- GetDefaultRole() string
-
- // GetDefaultSyntax returns the current value of the "default-syntax" key.
- GetDefaultSyntax() string
-
- // GetDefaultLang returns the current value of the "default-lang" key.
- GetDefaultLang() string
-
- // GetSiteName returns the current value of the "site-name" key.
- GetSiteName() string
-
- // GetHomeZettel returns the value of the "home-zettel" key.
- GetHomeZettel() id.Zid
-
- // GetDefaultVisibility returns the default value for zettel visibility.
- GetDefaultVisibility() meta.Visibility
-
- // GetYAMLHeader returns the current value of the "yaml-header" key.
- GetYAMLHeader() bool
-
- // GetZettelFileSyntax returns the current value of the "zettel-file-syntax" key.
- GetZettelFileSyntax() []string
-
- // GetMarkerExternal returns the current value of the "marker-external" key.
- GetMarkerExternal() string
-
- // GetFooterHTML returns HTML code that should be embedded into the footer
- // of each WebUI page.
- GetFooterHTML() string
-
- // GetListPageSize returns the maximum length of a list to be returned in WebUI.
- // A value less or equal to zero signals no limit.
- GetListPageSize() int
-}
-
-// AuthConfig are relevant configuration values for authentication.
-type AuthConfig interface {
- // GetExpertMode returns the current value of the "expert-mode" key
- GetExpertMode() bool
-
- // GetVisibility returns the visibility value of the metadata.
- GetVisibility(m *meta.Meta) meta.Visibility
-}
-
-// GetTitle returns the value of the "title" key of the given meta. If there
-// is no such value, GetDefaultTitle is returned.
-func GetTitle(m *meta.Meta, cfg Config) string {
- if val, ok := m.Get(meta.KeyTitle); ok {
- return val
- }
- return cfg.GetDefaultTitle()
-}
-
-// GetRole returns the value of the "role" key of the given meta. If there
-// is no such value, GetDefaultRole is returned.
-func GetRole(m *meta.Meta, cfg Config) string {
- if val, ok := m.Get(meta.KeyRole); ok {
- return val
- }
- return cfg.GetDefaultRole()
-}
-
-// GetSyntax returns the value of the "syntax" key of the given meta. If there
-// is no such value, GetDefaultSyntax is returned.
-func GetSyntax(m *meta.Meta, cfg Config) string {
- if val, ok := m.Get(meta.KeySyntax); ok {
- return val
- }
- return cfg.GetDefaultSyntax()
-}
-
-// GetLang returns the value of the "lang" key of the given meta. If there is
-// no such value, GetDefaultLang is returned.
-func GetLang(m *meta.Meta, cfg Config) string {
- if val, ok := m.Get(meta.KeyLang); ok {
- return val
- }
- return cfg.GetDefaultLang()
-}
ADDED docs/development/00010000000000.zettel
Index: docs/development/00010000000000.zettel
==================================================================
--- /dev/null
+++ docs/development/00010000000000.zettel
@@ -0,0 +1,11 @@
+id: 00010000000000
+title: Developments Notes
+role: zettel
+syntax: zmk
+created: 00010101000000
+modified: 20231218182020
+
+* [[Required Software|20210916193200]]
+* [[Fuzzing tests|20221026184300]]
+* [[Checklist for Release|20210916194900]]
+* [[Development tools|20231218181900]]
ADDED docs/development/20210916193200.zettel
Index: docs/development/20210916193200.zettel
==================================================================
--- /dev/null
+++ docs/development/20210916193200.zettel
@@ -0,0 +1,29 @@
+id: 20210916193200
+title: Required Software
+role: zettel
+syntax: zmk
+created: 20210916193200
+modified: 20241213124936
+
+The following software must be installed:
+
+* A current, supported [[release of Go|https://go.dev/doc/devel/release]],
+* [[Fossil|https://fossil-scm.org/]],
+* [[Git|https://git-scm.org/]] (most dependencies are accessible via Git only).
+
+Make sure that the software is in your path, e.g. via:
+```sh
+export PATH=$PATH:/usr/local/go/bin
+export PATH=$PATH:$(go env GOPATH)/bin
+```
+
+The internal build tool needs the following software tools.
+They can be installed / updated via the build tool itself: ``go run tools/devtools/devtools.go``.
+
+Otherwise you can install the software by hand:
+
+* [[shadow|https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shadow]] via ``go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest``,
+* [[staticcheck|https://staticcheck.io/]] via ``go install honnef.co/go/tools/cmd/staticcheck@latest``,
+* [[unparam|https://mvdan.cc/unparam]][^[[GitHub|https://github.com/mvdan/unparam]]] via ``go install mvdan.cc/unparam@latest``,
+* [[revive|https://revive.run]] via ``go install github.com/mgechev/revive@vlatest``,
+* [[govulncheck|https://golang.org/x/vuln/cmd/govulncheck]] via ``go install golang.org/x/vuln/cmd/govulncheck@latest``,
ADDED docs/development/20210916194900.zettel
Index: docs/development/20210916194900.zettel
==================================================================
--- /dev/null
+++ docs/development/20210916194900.zettel
@@ -0,0 +1,59 @@
+id: 20210916194900
+title: Checklist for Release
+role: zettel
+syntax: zmk
+created: 20210916194900
+modified: 20241213125640
+
+# Sync with the official repository:
+#* ``fossil sync -u``
+# Make sure that there is no workspace defined:
+#* ``ls ..`` must not have a file ''go.work'', in no parent folder.
+# Make sure that all dependencies are up-to-date:
+#* ``cat go.mod``
+# Clean up your Go workspace:
+#* ``go run tools/clean/clean.go`` (alternatively: ``make clean``)
+# All internal tests must succeed:
+#* ``go run tools/check/check.go -r`` (alternatively: ``make relcheck``)
+# The API tests must succeed on every development platform:
+#* ``go run tools/testapi/testapi.go`` (alternatively: ``make api``)
+# Run [[linkchecker|https://linkchecker.github.io/linkchecker/]] with the manual:
+#* ``go run -race cmd/zettelstore/main.go run -d docs/manual``
+#* ``linkchecker http://127.0.0.1:23123 2>&1 | tee lc.txt``
+#* Check all ""Error: 404 Not Found""
+#* Check all ""Error: 403 Forbidden"": allowed for endpoint ''/z'' for those zettel that are accessible only in ''expert-mode''
+#* Try to resolve other error messages and warnings
+#* Warnings about empty content can be ignored
+# On every development platform, the box with 10.000 zettel must run, with ''-race'' enabled:
+#* ``go run -race cmd/zettelstore/main.go run -d DIR``
+# Create a development release:
+#* ``go run tools/build.go release`` (alternatively: ``make release``)
+# On every platform (esp. macOS), the box with 10.000 zettel must run properly:
+#* ``./zettelstore -d DIR``
+# Update files in directory ''www'':
+#* ''index.wiki''
+#* ''download.wiki''
+#* ''changes.wiki''
+#* ''plan.wiki''
+# Set file ''VERSION'' to the new release version.
+ It **must** consists of three numbers: ''MAJOR.MINOR.PATCH'', even if ''PATCH'' is zero.
+# Disable Fossil autosync mode:
+#* ``fossil setting autosync off``
+# Commit the new release version:
+#* ``fossil commit --tag release --tag vVERSION -m "Version VERSION"``
+#* **Important:** the tag must follow the given pattern, e.g. ''v0.0.15''.
+ Otherwise client software will not be able to import ''zettelstore.de/z''.
+# Clean up your Go workspace:
+#* ``go run tools/clean/clean.go`` (alternatively: ``make clean``)
+# Create the release:
+#* ``go run tools/build/build.go release`` (alternatively: ``make release``)
+# Remove previous executables:
+#* ``fossil uv remove --glob '*-PREVVERSION*'``
+# Add executables for release:
+#* ``cd releases``
+#* ``fossil uv add *.zip``
+#* ``cd ..``
+#* Synchronize with main repository:
+#* ``fossil sync -u``
+# Enable autosync:
+#* ``fossil setting autosync on``
ADDED docs/development/20221026184300.zettel
Index: docs/development/20221026184300.zettel
==================================================================
--- /dev/null
+++ docs/development/20221026184300.zettel
@@ -0,0 +1,13 @@
+id: 20221026184300
+title: Fuzzing Tests
+role: zettel
+syntax: zmk
+created: 20221026184320
+modified: 20221102140156
+
+The source code contains some simple [[fuzzing tests|https://go.dev/security/fuzz/]].
+You should call them regularly to make sure that the software will cope with unusual input.
+
+```sh
+go test -fuzz=FuzzParseZmk zettelstore.de/z/internal/parser/
+```
ADDED docs/development/20231218181900.zettel
Index: docs/development/20231218181900.zettel
==================================================================
--- /dev/null
+++ docs/development/20231218181900.zettel
@@ -0,0 +1,116 @@
+id: 20231218181900
+title: Development tools
+role: zettel
+syntax: zmk
+created: 20231218181956
+modified: 20231218184500
+
+The source code contains some tools to assist the development of Zettelstore.
+These are located in the ''tools'' directory.
+
+Most tool support the generic option ``-v``, which log internal activities.
+
+Some of the tools can be called easier by using ``make``, that reads in a provided ''Makefile''.
+
+=== Check
+The ""check"" tool automates some testing activities.
+It is called via the command line:
+```
+# go run tools/check/check.go
+```
+There is an additional option ``-r`` to check in advance of a release.
+
+The following checks are executed:
+* Execution of unit tests, like ``go test ./...``
+* Analyze the source code for general problems, as in ``go vet ./...``
+* Tries to find shadowed variable, via ``shadow ./...``
+* Performs some additional checks on the source code, via ``staticcheck ./...``
+* Checks the usage of function parameters and usage of return values, via ``unparam ./...``.
+ In case the option ''-r'' is set, the check includes exported functions and internal tests.
+* In case option ''-r'' is set, the source code is checked against the vulnerability database, via ``govulncheck ./...``
+
+Please note, that most of the tools above are not automatically installed in a standard Go distribution.
+Use the command ""devtools"" to install them.
+
+=== Devtools
+The following command installs all needed tools:
+```
+# go run tooles/devtools/devtools.go
+```
+It will also automatically update these tools.
+
+=== TestAPI
+The following command will perform some high-level tests:
+```sh
+# go run tools/testapi/testapi.go
+```
+Basically, a Zettelstore will be started and then API calls will be made to simulate some typical activities with the Zettelstore.
+
+If a Zettelstore is already running on port 23123, this Zettelstore will be used instead.
+Even if the API test should clean up later, some zettel might stay created if a test fails.
+This feature is used, if you want to have more control on the running Zettelstore.
+You should start it with the following command:
+```sh
+# go run -race cmd/zettelstore/main.go run -c testdata/testbox/19700101000000.zettel
+```
+This allows you to debug failing API tests.
+
+=== HTMLlint
+The following command will check the generated HTML code for validity:
+```sh
+# go run tools/htmllint/htmllint.go
+```
+In addition, you might specify the URL od a running Zettelstore.
+Otherwise ''http://localhost:23123'' is used.
+
+This command fetches first the list of all zettel.
+This list is used to check the generated HTML code (''ZID'' is the paceholder for the zettel identification):
+
+* Check all zettel HTML encodings, via the path ''/z/ZID?enc=html&part=zettel''
+* Check all zettel web views, via the path ''/h/ZID''
+* The info page of all zettel is checked, via path ''/i/ZID''
+* A subset of max. 100 zettel will be checked for the validity of their edit page, via ''/e/ZID''
+* 10 random zettel are checked for a valid create form, via ''/c/ZID''
+* A maximum of 200 random zettel are checked for a valid delete dialog, via ''/d/ZID''
+
+Depending on the selected Zettelstore, the command might take a long time.
+
+You can shorten the time, if you disable any zettel query in the footer.
+
+=== Build
+The ""build"" tool allows to build the software, either for tests or for a release.
+
+The following command will create a Zettelstore executable for the architecture of the current computer:
+```sh
+# go tools/build/build.go build
+```
+You will find the executable in the ''bin'' directory.
+
+A full release will be build in the directory ''releases'', containing ZIP files for the computer architectures ""Linux/amd64"", ""Linux/arm"", ""MacOS/arm64"", ""MacOS/amd64"", and ""Windows/amd64"".
+In addition, the manual is also build as a ZIP file:
+```sh
+# go run tools/build/build.go release
+```
+
+If you just want the ZIP file with the manual, please use:
+```sh
+# go run tools/build/build.go manual
+```
+
+In case you want to check the version of the Zettelstore to be build, use:
+```sh
+# go run tools/build/build.go version
+```
+
+=== Clean
+To remove the directories ''bin'' and ''releases'', as well as all cached Go libraries used by Zettelstore, execute:
+```sh
+# go run tools/clean/clean.go
+```
+
+Internally, the following commands are executed
+```sh
+# rm -rf bin releases
+# go clean ./...
+# go clean -cache -modcache -testcache
+```
Index: docs/manual/00000000000100.zettel
==================================================================
--- docs/manual/00000000000100.zettel
+++ docs/manual/00000000000100.zettel
@@ -1,13 +1,14 @@
id: 00000000000100
title: Zettelstore Runtime Configuration
role: configuration
syntax: none
-default-copyright: (c) 2020-2021 by Detlef Stern ")
- inPara = true
- }
- v.acceptInlineSlice(pn.Inlines)
- } else {
- if inPara {
- v.writeEndPara()
- inPara = false
- }
- v.acceptItemSlice(item)
- }
- }
- if inPara {
- v.writeEndPara()
- }
- v.b.WriteString(" Unable to display BLOB with syntax '", bn.Syntax, "'.
+footer-zettel: 00001000000100
home-zettel: 00001000000000
-no-index: true
+modified: 20221205173642
site-name: Zettelstore Manual
visibility: owner
ADDED docs/manual/00000000025001
Index: docs/manual/00000000025001
==================================================================
--- /dev/null
+++ docs/manual/00000000025001
@@ -0,0 +1,7 @@
+id: 00000000025001
+title: Zettelstore User CSS
+role: configuration
+syntax: css
+created: 20210622110143
+modified: 20220926183101
+visibility: public
ADDED docs/manual/00000000025001.css
Index: docs/manual/00000000025001.css
==================================================================
--- /dev/null
+++ docs/manual/00000000025001.css
@@ -0,0 +1,2 @@
+/* User-defined CSS */
+.example { border-style: dotted !important }
Index: docs/manual/00001000000000.zettel
==================================================================
--- docs/manual/00001000000000.zettel
+++ docs/manual/00001000000000.zettel
@@ -1,10 +1,13 @@
id: 00001000000000
title: Zettelstore Manual
role: manual
tags: #manual #zettelstore
syntax: zmk
+created: 20210126175322
+modified: 20241128141924
+show-back-links: false
* [[Introduction|00001001000000]]
* [[Design goals|00001002000000]]
* [[Installation|00001003000000]]
* [[Configuration|00001004000000]]
@@ -13,9 +16,12 @@
* [[Zettelmarkup|00001007000000]]
* [[Other markup languages|00001008000000]]
* [[Security|00001010000000]]
* [[API|00001012000000]]
* [[Web user interface|00001014000000]]
-* Troubleshooting
+* [[Tips and Tricks|00001017000000]]
+* [[Troubleshooting|00001018000000]]
* Frequently asked questions
+
+Version: {{00001000000001}}
Licensed under the EUPL-1.2-or-later.
ADDED docs/manual/00001000000001.zettel
Index: docs/manual/00001000000001.zettel
==================================================================
--- /dev/null
+++ docs/manual/00001000000001.zettel
@@ -0,0 +1,8 @@
+id: 00001000000001
+title: Manual Version
+role: configuration
+syntax: zmk
+created: 20231002142915
+modified: 20231002142948
+
+To be set by build tool.
ADDED docs/manual/00001000000002.zettel
Index: docs/manual/00001000000002.zettel
==================================================================
--- /dev/null
+++ docs/manual/00001000000002.zettel
@@ -0,0 +1,7 @@
+id: 00001000000002
+title: manual
+role: role
+syntax: zmk
+created: 20231128184200
+
+Zettel with the role ""manual"" contain the manual of the zettelstore.
ADDED docs/manual/00001000000100.zettel
Index: docs/manual/00001000000100.zettel
==================================================================
--- /dev/null
+++ docs/manual/00001000000100.zettel
@@ -0,0 +1,8 @@
+id: 00001000000100
+title: Footer Zettel
+role: configuration
+syntax: zmk
+created: 20221205173520
+modified: 20221207175927
+
+[[Imprint / Privacy|/home/doc/trunk/www/impri.wiki]]
Index: docs/manual/00001001000000.zettel
==================================================================
--- docs/manual/00001001000000.zettel
+++ docs/manual/00001001000000.zettel
@@ -1,25 +1,17 @@
id: 00001001000000
title: Introduction to the Zettelstore
role: manual
tags: #introduction #manual #zettelstore
syntax: zmk
-
-[[Personal knowledge
-management|https://en.wikipedia.org/wiki/Personal_knowledge_management]] is
-about collecting, classifying, storing, searching, retrieving, assessing,
-evaluating, and sharing knowledge as a daily activity. Personal knowledge
-management is done by most people, not necessarily as part of their main
-business. It is essential for knowledge workers, like students, researchers,
-lecturers, software developers, scientists, engineers, architects, to name
-a few. Many hobbyists build up a significant amount of knowledge, even if the
-do not need to think for a living. Personal knowledge management can be seen as
-a prerequisite for many kinds of collaboration.
-
-Zettelstore is a software that collects and relates your notes (""zettel"")
-to represent and enhance your knowledge. It helps with many tasks of personal
-knowledge management by explicitly supporting the ""[[Zettelkasten
-method|https://en.wikipedia.org/wiki/Zettelkasten]]"". The method is based on
-creating many individual notes, each with one idea or information, that are
-related to each other. Since knowledge is typically build up gradually, one
-major focus is a long-term store of these notes, hence the name
-""Zettelstore"".
+created: 20210126175322
+modified: 20250102181246
+
+[[Personal knowledge management|https://en.wikipedia.org/wiki/Personal_knowledge_management]] involves collecting, classifying, storing, searching, retrieving, assessing, evaluating, and sharing knowledge as a daily activity.
+It's done by most individuals, not necessarily as part of their main business.
+It's essential for knowledge workers, such as students, researchers, lecturers, software developers, scientists, engineers, architects, etc.
+Many hobbyists build up a significant amount of knowledge, even if they do not need to think for a living.
+Personal knowledge management can be seen as a prerequisite for many kinds of collaboration.
+
+Zettelstore is software that collects and relates your notes (""zettel"") to represent and enhance your knowledge, supporting the ""[[Zettelkasten method|https://en.wikipedia.org/wiki/Zettelkasten]]"".
+The method is based on creating many individual notes, each containing one idea or piece of information, which are related to each other.
+Since knowledge is typically built up gradually, one major focus is a long-term store of these notes, hence the name ""Zettelstore"".
Index: docs/manual/00001002000000.zettel
==================================================================
--- docs/manual/00001002000000.zettel
+++ docs/manual/00001002000000.zettel
@@ -1,31 +1,43 @@
id: 00001002000000
title: Design goals for the Zettelstore
+role: manual
tags: #design #goal #manual #zettelstore
syntax: zmk
-role: manual
+created: 20210126175322
+modified: 20250602181324
Zettelstore supports the following design goals:
; Longevity of stored notes / zettel
: Every zettel you create should be readable without the help of any tool, even without Zettelstore.
-: It should be not hard to write other software that works with your zettel.
+: It should not be hard to write other software that works with your zettel.
+: Normal zettel should be stored in a single file.
+ If this is not possible: at most in two files: one for the metadata, one for the content.
+ The only exceptions are [[predefined zettel|00001005090000]] stored in the Zettelstore executable.
+: There is no additional database.
; Single user
: All zettel belong to you, only to you.
Zettelstore provides its services only to one person: you.
- If your device is securely configured, there should be no risk that others are able to read or update your zettel.
+ If the computer running Zettelstore is securely configured, there should be no risk that others are able to read or update your zettel.
: If you want, you can customize Zettelstore in a way that some specific or all persons are able to read some of your zettel.
; Ease of installation
-: If you want to use the Zettelstore software, all you need is to copy the executable to an appropriate place and start working.
+: If you want to use the Zettelstore software, all you need is to copy the executable to an appropriate file directory and start working.
: Upgrading the software is done just by replacing the executable with a newer one.
; Ease of operation
-: There is only one executable for Zettelstore and one directory, where your zettel are placed.
+: There is only one executable for Zettelstore and one directory, where your zettel are stored.
: If you decide to use multiple directories, you are free to configure Zettelstore appropriately.
; Multiple modes of operation
: You can use Zettelstore as a standalone software on your device, but you are not restricted to it.
-: You can install the software on a central server, or you can install it on all your devices with no restrictions how to synchronize your zettel.
+: You can install the software on a central server, or you can install it on all your devices with no restrictions on how to synchronize your zettel.
; Multiple user interfaces
-: Zettelstore provides a default web-based user interface.
- Anybody can provide alternative user interfaces, e.g. for special purposes.
+: Zettelstore provides a default [[web-based user interface|00001014000000]].
+ Anyone can provide alternative user interfaces, e.g. for special purposes.
; Simple service
: The purpose of Zettelstore is to safely store your zettel and to provide some initial relations between them.
: External software can be written to deeply analyze your zettel and the structures they form.
+; Security by default
+: Without any customization, Zettelstore provides its services in a safe and secure manner and does not expose you (or other users) to security risks.
+: If you know what you are doing, Zettelstore allows you to relax some security-related preferences.
+ However, even in this case, the more secure way is chosen.
+: Zettelstore features a minimal design and relies on external software only when absolutely necessary.
+: There will be no plugin mechanism, which allows external software to control the inner workings of the Zettelstore software.
Index: docs/manual/00001003000000.zettel
==================================================================
--- docs/manual/00001003000000.zettel
+++ docs/manual/00001003000000.zettel
@@ -1,72 +1,33 @@
id: 00001003000000
title: Installation of the Zettelstore software
role: manual
tags: #installation #manual #zettelstore
syntax: zmk
+created: 20210126175322
+modified: 20250415170240
=== The curious user
You just want to check out the Zettelstore software
-* Grab the appropriate executable and copy it into any directory
-* Start the Zettelstore software, e.g. with a double click
-* A sub-directory ""zettel"" will be created in the directory where you placed the executable.
+* Grab the appropriate executable and copy it to any directory
+* Start the Zettelstore software, e.g. with a double click[^On Windows and macOS, the operating system tries to protect you from possible malicious software.
+ If you encounter a problem, please refer to the [[Troubleshooting|00001018000000]] page.]
+* A sub-directory ""zettel"" will be created in the directory where you put the executable.
It will contain your future zettel.
-* Open the URI [[http://localhost:23123]] with your web browser.
- It will present you a mostly empty Zettelstore.
+* Open the URI [[http://localhost:23123/]] with your web browser.
+ A mostly empty Zettelstore is presented.
There will be a zettel titled ""[[Home|00010000000000]]"" that contains some helpful information.
-* Please read the instructions for the web-based user interface and learn about the various ways to write zettel.
+* Please read the instructions for the [[web-based user interface|00001014000000]] and learn about the various ways to write zettel.
* If you restart your device, please make sure to start your Zettelstore again.
=== The intermediate user
-You already tried the Zettelstore software and now you want to use it permanently.
+You have already tried the Zettelstore software and now you want to use it permanently.
+Zettelstore should start automatically when you log into your computer.
-* Grab the appropriate executable and copy it into the appropriate directory
-* ...
+Please follow [[these instructions|00001003300000]].
=== The server administrator
You want to provide a shared Zettelstore that can be used from your various devices.
Installing Zettelstore as a Linux service is not that hard.
-Grab the appropriate executable and copy it into the appropriate directory:
-```sh
-# sudo mv zettelstore /usr/local/bin/zettelstore
-```
-Create a group named ''zettelstore'':
-```sh
-# sudo groupadd --system zettelstore
-```
-Create a system user of that group, named ''zettelstore'', with a home folder:
-```sh
-# sudo useradd --system --gid zettelstore \
- --create-home --home-dir /var/lib/zettelstore \
- --shell /usr/sbin/nologin \
- --comment "Zettelstore server" \
- zettelstore
-```
-Create a systemd service file and place it into ''/etc/systemd/system/zettelstore.service'':
-```ini
-[Unit]
-Description=Zettelstore
-After=network.target
-
-[Service]
-Type=simple
-User=zettelstore
-Group=zettelstore
-ExecStart=/usr/local/bin/zettelstore run -d /var/lib/zettelstore
-WorkingDirectory=/var/lib/zettelstore
-
-[Install]
-WantedBy=multi-user.target
-```
-Double-check everything. Now you can enable and start the zettelstore as a service:
-```sh
-# sudo systemctl daemon-reload
-# sudo systemctl enable zettelstore
-# sudo systemctl start zettelstore
-```
-Use the commands ``systemctl``{=sh} and ``journalctl``{=sh} to manage the service, e.g.:
-```sh
-# sudo systemctl status zettelstore # verify that it is running
-# sudo journalctl -u zettelstore # obtain the output of the running zettelstore
-```
+Please follow [[these instructions|00001003600000]].
ADDED docs/manual/00001003300000.zettel
Index: docs/manual/00001003300000.zettel
==================================================================
--- /dev/null
+++ docs/manual/00001003300000.zettel
@@ -0,0 +1,33 @@
+id: 00001003300000
+title: Zettelstore installation for the intermediate user
+role: manual
+tags: #installation #manual #zettelstore
+syntax: zmk
+created: 20211125191727
+modified: 20250627152419
+
+You have already tried the Zettelstore software and now you want to use it permanently.
+Zettelstore should start automatically when you log into your computer.
+
+* Grab the appropriate executable and copy it into the appropriate directory
+* If you want to place your zettel into another directory, or if you want more than one [[Zettelstore box|00001004011200]], or if you want to [[enable authentication|00001010040100]], or if you want to tweak your Zettelstore in some other way, create an appropriate [[startup configuration file|00001004010000]].
+* If you created a startup configuration file, you need to test it:
+** Start a command line prompt for your operating system.
+** Navigate to the directory, where you placed the Zettelstore executable.
+ In most cases, this is done by the command ``cd DIR``, where ''DIR'' denotes the directory, where you placed the executable.
+** Start the Zettelstore:
+*** On Windows execute the command ``zettelstore.exe run -c CONFIG_FILE``
+*** On macOS execute the command ``./zettelstore run -c CONFIG_FILE``
+*** On Linux execute the command ``./zettelstore run -c CONFIG_FILE``
+** In all cases, ''CONFIG_FILE'' must be replaced with the name of the file where you wrote the startup configuration.
+** If you encounter some error messages, update the startup configuration, and try again.
+* Depending on your operating system, there are different ways to register Zettelstore to start automatically:
+** [[Windows|00001003305000]]
+** [[macOS|00001003310000]]
+** [[Linux|00001003315000]]
+
+A word of caution: Never expose Zettelstore directly to the Internet.
+As a personal service, Zettelstore is not designed to handle all aspects of the open web.
+For instance, it lacks support for certificate handling, which is necessary for encrypted HTTP connections.
+To ensure security, [[install Zettelstore on a server|00001003600000]] and place it behind a proxy server designed for Internet exposure.
+For more details, see: [[External server to encrypt message transport|00001010090100]].
ADDED docs/manual/00001003305000.zettel
Index: docs/manual/00001003305000.zettel
==================================================================
--- /dev/null
+++ docs/manual/00001003305000.zettel
@@ -0,0 +1,120 @@
+id: 00001003305000
+title: Enable Zettelstore to start automatically on Windows
+role: manual
+tags: #installation #manual #zettelstore
+syntax: zmk
+created: 20211125191727
+modified: 20250701130205
+
+Windows is a complicated beast. There are several ways to automatically start Zettelstore.
+
+=== Startup folder
+
+One way is to use the [[autostart folder|https://support.microsoft.com/en-us/windows/configure-startup-applications-in-windows-115a420a-0bff-4a6f-90e0-1934c844e473]].
+Open the folder where you have placed in the Explorer.
+Create a shortcut file for the Zettelstore executable.
+There are some ways to do this:
+* Execute a right-click on the executable, and choose the menu entry ""Create shortcut"",
+* Execute a right-click on the executable, and then click Send To > Desktop (Create shortcut).
+* Drag the executable to your Desktop with pressing the ''Alt''-Key.
+
+If you have created the shortcut file, you must move it into the Startup folder.
+Press the Windows logo key and the key ''R'', type ''shell:startup''.
+Select the OK button.
+This will open the Startup folder.
+Move the shortcut file into this folder.
+
+The next time you log into your computer, Zettelstore will be started automatically.
+However, it remains visible, at least in the task bar.
+
+You can modify the behavior by changing some properties of the shortcut file.
+
+=== Task scheduler
+
+The Windows Task scheduler allows you to start Zettelstore as a background task.
+
+This is both an advantage and a disadvantage.
+
+On the plus side, Zettelstore runs in the background, and it does not disturb you.
+All you have to do is to open your web browser, enter the appropriate URL, and there you go.
+
+On the negative side, you will not be notified when you enter the wrong data in the Task scheduler and Zettelstore fails to start.
+This can be mitigated by first using the command line prompt to start Zettelstore with the appropriate options.
+Once everything works, you can register Zettelstore to be automatically started by the task scheduler.
+There you should make sure that you have followed the first steps as described on the [[parent page|00001003300000]].
+
+To start the Task scheduler management console, press the Windows logo key and the key ''R'', type ''taskschd.msc''.
+Select the OK button.
+
+{{00001003305102}}
+
+This will start the ""Task Scheduler"".
+
+Now, create a new task with ""Create Task ...""
+
+{{00001003305104}}
+
+Enter a name for the task, e.g. ""Zettelstore"" and select the options ""Run whether user is logged in or not"" and ""Do not store password.""
+
+{{00001003305106}}
+
+Create a new trigger.
+
+{{00001003305108}}
+
+Select the option ""At startup"".
+
+{{00001003305110}}
+
+Create a new action.
+
+{{00001003305112}}
+
+The next steps are the trickiest.
+
+If you did not create a startup configuration file, then create an action that starts a program.
+Enter the file path where you placed the Zettelstore executable.
+The ""Browse ..."" button helps you with that.[^I store my Zettelstore executable in the sub-directory ''bin'' of my home directory.]
+
+It is essential that you also enter a directory, which serves as the environment for your zettelstore.
+The (sub-) directory ''zettel'', which will contain your zettel, will be placed in this directory.
+If you leave the field ""Start in (optional)"" empty, the directory will be an internal Windows system directory (most likely: ''C:\\Windows\\System32'').
+
+If you press the OK button, the ""Create Task"" tab shows up as on the right image.
+
+{{00001003305114}}\ {{00001003305116}}
+
+If you have created a startup configuration file, you must enter something into the field ""Add arguments (optional)"".
+Unfortunately, the text box is too narrow to fully see its content.
+
+I have entered the string ''run -c "C:\\Users\\Detlef Stern\\bin\\zsconfig.txt"'', because my startup configuration file has the name ''zsconfig.txt'' and I placed it into the same folder that also contains the Zettelstore executable.
+Maybe you have to adapt to this.
+
+You must also enter appropriate data for the other form fields.
+If you press the OK button, the ""Create Task"" tab shows up as on the right image.
+
+{{00001003305118}}\ {{00001003305120}}
+
+You should disable any additional conditions, since you typically want to use Zettelstore unconditionally.
+Especially, make sure that ""Start the task only if the computer is on AC power"" is disabled.
+Otherwise Zettelstore will not start if you run on battery power.
+
+{{00001003305122}}
+
+On the ""Settings"" tab, you should disable the option ""Stop the task if it runs longer than:"".
+
+{{00001003305124}}
+
+After entering the data, press the OK button.
+Under some circumstances, Windows asks for permission and you have to enter your password.
+
+As the last step, you could run the freshly created task manually.
+
+Open your browser, enter the appropriate URL and use your Zettelstore.
+In case of errors, the task will most likely stop immediately.
+Make sure that all data you have entered is valid.
+Do not forget to check the content of the startup configuration file.
+Use the command prompt to debug your configuration.
+
+Sometimes, for example when your computer was in stand-by and it wakes up, these tasks are not started.
+In this case execute the task scheduler and run the task manually.
ADDED docs/manual/00001003305102.png
Index: docs/manual/00001003305102.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305102.png
cannot compute difference between binary files
ADDED docs/manual/00001003305104.png
Index: docs/manual/00001003305104.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305104.png
cannot compute difference between binary files
ADDED docs/manual/00001003305106.png
Index: docs/manual/00001003305106.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305106.png
cannot compute difference between binary files
ADDED docs/manual/00001003305108.png
Index: docs/manual/00001003305108.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305108.png
cannot compute difference between binary files
ADDED docs/manual/00001003305110.png
Index: docs/manual/00001003305110.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305110.png
cannot compute difference between binary files
ADDED docs/manual/00001003305112.png
Index: docs/manual/00001003305112.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305112.png
cannot compute difference between binary files
ADDED docs/manual/00001003305114.png
Index: docs/manual/00001003305114.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305114.png
cannot compute difference between binary files
ADDED docs/manual/00001003305116.png
Index: docs/manual/00001003305116.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305116.png
cannot compute difference between binary files
ADDED docs/manual/00001003305118.png
Index: docs/manual/00001003305118.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305118.png
cannot compute difference between binary files
ADDED docs/manual/00001003305120.png
Index: docs/manual/00001003305120.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305120.png
cannot compute difference between binary files
ADDED docs/manual/00001003305122.png
Index: docs/manual/00001003305122.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305122.png
cannot compute difference between binary files
ADDED docs/manual/00001003305124.png
Index: docs/manual/00001003305124.png
==================================================================
--- /dev/null
+++ docs/manual/00001003305124.png
cannot compute difference between binary files
ADDED docs/manual/00001003310000.zettel
Index: docs/manual/00001003310000.zettel
==================================================================
--- /dev/null
+++ docs/manual/00001003310000.zettel
@@ -0,0 +1,95 @@
+id: 00001003310000
+title: Enable Zettelstore to start automatically on macOS
+role: manual
+tags: #installation #manual #zettelstore
+syntax: zmk
+created: 20220114181521
+modified: 20220119124635
+
+There are several ways to automatically start Zettelstore.
+
+* [[Login Items|#login-items]]
+* [[Launch Agent|#launch-agent]]
+
+=== Login Items
+
+Via macOS's system preferences, everybody is able to specify executables that are started when a user is logged in.
+To do this, start system preferences and select ""Users & Groups"".
+
+{{00001003310104}}
+
+In the next screen, select the current user and then click on ""Login Items"".
+
+{{00001003310106}}
+
+Click on the plus sign at the bottom and select the Zettelstore executable.
+
+{{00001003310108}}
+
+Optionally select the ""Hide"" check box.
+
+{{00001003310110}}
+
+The next time you log into your macOS computer, Zettelstore will be started automatically.
+
+Unfortunately, hiding the Zettelstore windows does not always work.
+Therefore, this method is just a way to automate navigating to the directory where the Zettelstore executable is placed and to click on that icon.
+
+If you don't want the Zettelstore window, you should try the next method.
+
+=== Launch Agent
+
+If you want to execute Zettelstore automatically and less visible, and if you know a little bit about working in the terminal application, then you could try to run Zettelstore under the control of the [[Launchd system|https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/Introduction.html]].
+
+First, you have to create a description for ""Launchd"".
+This is a text file named ''zettelstore.plist'' with the following content.
+It assumes that you have copied the Zettelstore executable in a local folder called ''~/bin'' and have created a file for [[startup configuration|00001004010000]] called ''zettelstore.cfg'', which is placed in the same folder[^If you are not using a configuration file, just remove the lines ``
.
-func (v *visitor) VisitHRule(hn *ast.HRuleNode) {
- v.b.WriteString("
\n")
- } else {
- v.b.WriteString(">\n")
- }
-}
-
-var listCode = map[ast.NestedListCode]string{
- ast.NestedListOrdered: "ol",
- ast.NestedListUnordered: "ul",
-}
-
-// VisitNestedList writes HTML code for lists and blockquotes.
-func (v *visitor) VisitNestedList(ln *ast.NestedListNode) {
- v.lang.push(ln.Attrs)
- defer v.lang.pop()
-
- if ln.Code == ast.NestedListQuote {
- // NestedListQuote -> HTML doesn't use
\n")
- inPara := false
- for _, item := range ln.Items {
- if pn := getParaItem(item); pn != nil {
- if inPara {
- v.b.WriteByte('\n')
- } else {
- v.b.WriteString("
\n")
-}
-
-func getParaItem(its ast.ItemSlice) *ast.ParaNode {
- if len(its) != 1 {
- return nil
- }
- if pn, ok := its[0].(*ast.ParaNode); ok {
- return pn
- }
- return nil
-}
-
-func isCompactList(insl []ast.ItemSlice) bool {
- for _, ins := range insl {
- if !isCompactSlice(ins) {
- return false
- }
- }
- return true
-}
-
-func isCompactSlice(ins ast.ItemSlice) bool {
- if len(ins) < 1 {
- return true
- }
- if len(ins) == 1 {
- switch ins[0].(type) {
- case *ast.ParaNode, *ast.VerbatimNode, *ast.HRuleNode:
- return true
- case *ast.NestedListNode:
- return false
- }
- }
- return false
-}
-
-// writeItemSliceOrPara emits the content of a paragraph if the paragraph is
-// the only element of the block slice and if compact mode is true. Otherwise,
-// the item slice is emitted normally.
-func (v *visitor) writeItemSliceOrPara(ins ast.ItemSlice, compact bool) {
- if compact && len(ins) == 1 {
- if para, ok := ins[0].(*ast.ParaNode); ok {
- v.acceptInlineSlice(para.Inlines)
- return
- }
- }
- v.acceptItemSlice(ins)
-}
-
-func (v *visitor) writeDescriptionsSlice(ds ast.DescriptionSlice) {
- if len(ds) == 1 {
- if para, ok := ds[0].(*ast.ParaNode); ok {
- v.acceptInlineSlice(para.Inlines)
- return
- }
- }
- for _, dn := range ds {
- dn.Accept(v)
- }
-}
-
-// VisitDescriptionList emits a HTML description list.
-func (v *visitor) VisitDescriptionList(dn *ast.DescriptionListNode) {
- v.b.WriteString("\n")
- for _, descr := range dn.Descriptions {
- v.b.WriteString("
\n")
-}
-
-// VisitTable emits a HTML table.
-func (v *visitor) VisitTable(tn *ast.TableNode) {
- v.b.WriteString("\n")
- if len(tn.Header) > 0 {
- v.b.WriteString("\n")
- v.writeRow(tn.Header, "
\n")
-}
-
-var alignStyle = map[ast.Alignment]string{
- ast.AlignDefault: ">",
- ast.AlignLeft: " style=\"text-align:left\">",
- ast.AlignCenter: " style=\"text-align:center\">",
- ast.AlignRight: " style=\"text-align:right\">",
-}
-
-func (v *visitor) writeRow(row ast.TableRow, cellStart, cellEnd string) {
- v.b.WriteString("")
- v.b.WriteString(" \n")
- }
- if len(tn.Rows) > 0 {
- v.b.WriteString("\n")
- for _, row := range tn.Rows {
- v.writeRow(row, "")
- }
- v.b.WriteString(" \n")
- }
- v.b.WriteString("")
- for _, cell := range row {
- v.b.WriteString(cellStart)
- if len(cell.Inlines) == 0 {
- v.b.WriteByte('>')
- } else {
- v.b.WriteString(alignStyle[cell.Align])
- v.acceptInlineSlice(cell.Inlines)
- }
- v.b.WriteString(cellEnd)
- }
- v.b.WriteString(" \n")
-}
-
-// VisitBLOB writes the binary object as a value.
-func (v *visitor) VisitBLOB(bn *ast.BLOBNode) {
- switch bn.Syntax {
- case "gif", "jpeg", "png":
- v.b.WriteStrings("\n")
- default:
- v.b.WriteStrings("
", ln.Attrs, ln.Text)
- case ast.LiteralKeyb:
- v.writeLiteral("", ln.Attrs, ln.Text)
- case ast.LiteralOutput:
- v.writeLiteral("", ln.Attrs, ln.Text)
- case ast.LiteralComment:
- v.b.WriteString("")
- case ast.LiteralHTML:
- if !ignoreHTMLText(ln.Text) {
- v.b.WriteString(ln.Text)
- }
- default:
- panic(fmt.Sprintf("Unknown literal code %v", ln.Code))
- }
-}
-
-func (v *visitor) writeLiteral(codeS, codeE string, attrs *ast.Attributes, text string) {
- oldVisible := v.visibleSpace
- if attrs != nil {
- v.visibleSpace = attrs.HasDefault()
- }
- v.b.WriteString(codeS)
- v.visitAttributes(attrs)
- v.b.WriteByte('>')
- v.writeHTMLEscaped(text)
- v.b.WriteString(codeE)
- v.visibleSpace = oldVisible
-}
DELETED encoder/htmlenc/langstack.go
Index: encoder/htmlenc/langstack.go
==================================================================
--- encoder/htmlenc/langstack.go
+++ /dev/null
@@ -1,36 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package htmlenc encodes the abstract syntax tree into HTML5.
-package htmlenc
-
-import "zettelstore.de/z/ast"
-
-type langStack struct {
- items []string
-}
-
-func newLangStack(lang string) langStack {
- items := make([]string, 1, 16)
- items[0] = lang
- return langStack{items}
-}
-
-func (s langStack) top() string { return s.items[len(s.items)-1] }
-
-func (s *langStack) pop() { s.items = s.items[0 : len(s.items)-1] }
-
-func (s *langStack) push(attrs *ast.Attributes) {
- if value, ok := attrs.Get("lang"); ok {
- s.items = append(s.items, value)
- } else {
- s.items = append(s.items, s.top())
- }
-}
DELETED encoder/htmlenc/langstack_test.go
Index: encoder/htmlenc/langstack_test.go
==================================================================
--- encoder/htmlenc/langstack_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package htmlenc encodes the abstract syntax tree into HTML5.
-package htmlenc
-
-import (
- "testing"
-
- "zettelstore.de/z/ast"
-)
-
-func TestStackSimple(t *testing.T) {
- exp := "de"
- s := newLangStack(exp)
- if got := s.top(); got != exp {
- t.Errorf("Init: expected %q, but got %q", exp, got)
- return
- }
-
- a := &ast.Attributes{}
- s.push(a)
- if got := s.top(); exp != got {
- t.Errorf("Empty push: expected %q, but got %q", exp, got)
- }
-
- exp2 := "en"
- a = a.Set("lang", exp2)
- s.push(a)
- if got := s.top(); exp2 != got {
- t.Errorf("Full push: expected %q, but got %q", exp2, got)
- }
-
- s.pop()
- if got := s.top(); exp != got {
- t.Errorf("pop: expected %q, but got %q", exp, got)
- }
-}
DELETED encoder/htmlenc/visitor.go
Index: encoder/htmlenc/visitor.go
==================================================================
--- encoder/htmlenc/visitor.go
+++ /dev/null
@@ -1,165 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package htmlenc encodes the abstract syntax tree into HTML5.
-package htmlenc
-
-import (
- "io"
- "sort"
- "strconv"
- "strings"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
- "zettelstore.de/z/strfun"
-)
-
-// visitor writes the abstract syntax tree to an io.Writer.
-type visitor struct {
- env *encoder.Environment
- b encoder.BufWriter
- visibleSpace bool // Show space character in raw text
- inVerse bool // In verse block
- inInteractive bool // Rendered interactive HTML code
- lang langStack
-}
-
-func newVisitor(he *htmlEncoder, w io.Writer) *visitor {
- var lang string
- if he.env != nil {
- lang = he.env.Lang
- }
- return &visitor{
- env: he.env,
- b: encoder.NewBufWriter(w),
- lang: newLangStack(lang),
- }
-}
-
-var mapMetaKey = map[string]string{
- meta.KeyCopyright: "copyright",
- meta.KeyLicense: "license",
-}
-
-func (v *visitor) acceptMeta(m *meta.Meta) {
- for _, pair := range m.Pairs(true) {
- if env := v.env; env != nil && env.IgnoreMeta[pair.Key] {
- continue
- }
- if pair.Key == meta.KeyTitle {
- continue
- }
- if pair.Key == meta.KeyTags {
- v.writeTags(pair.Value)
- } else if key, ok := mapMetaKey[pair.Key]; ok {
- v.writeMeta("", key, pair.Value)
- } else {
- v.writeMeta("zs-", pair.Key, pair.Value)
- }
- }
-}
-
-func (v *visitor) writeTags(tags string) {
- v.b.WriteString("\n 0 {
- v.b.WriteString(", ")
- }
- v.writeQuotedEscaped(strings.TrimPrefix(val, "#"))
- }
- v.b.WriteString("\">")
-}
-
-func (v *visitor) writeMeta(prefix, key, value string) {
- v.b.WriteStrings("\n")
-}
-
-func (v *visitor) acceptBlockSlice(bns ast.BlockSlice) {
- for _, bn := range bns {
- bn.Accept(v)
- }
-}
-func (v *visitor) acceptItemSlice(ins ast.ItemSlice) {
- for _, in := range ins {
- in.Accept(v)
- }
-}
-func (v *visitor) acceptInlineSlice(ins ast.InlineSlice) {
- for _, in := range ins {
- in.Accept(v)
- }
-}
-
-func (v *visitor) writeEndnotes() {
- footnotes := v.env.GetCleanFootnotes()
- if len(footnotes) > 0 {
- v.b.WriteString("\n")
- for i := 0; i < len(footnotes); i++ {
- // Do not use a range loop above, because a footnote may contain
- // a footnote. Therefore v.enc.footnote may grow during the loop.
- fn := footnotes[i]
- n := strconv.Itoa(i + 1)
- v.b.WriteStrings("- ")
- v.acceptInlineSlice(fn.Inlines)
- v.b.WriteStrings(
- " ↩︎
\n")
- }
- v.b.WriteString("
\n")
- }
-}
-
-// visitAttributes write HTML attributes
-func (v *visitor) visitAttributes(a *ast.Attributes) {
- if a == nil || len(a.Attrs) == 0 {
- return
- }
- keys := make([]string, 0, len(a.Attrs))
- for k := range a.Attrs {
- if k != "-" {
- keys = append(keys, k)
- }
- }
- sort.Strings(keys)
-
- for _, k := range keys {
- if k == "" || k == "-" {
- continue
- }
- v.b.WriteStrings(" ", k)
- vl := a.Attrs[k]
- if len(vl) > 0 {
- v.b.WriteString("=\"")
- v.writeQuotedEscaped(vl)
- v.b.WriteByte('"')
- }
- }
-}
-
-func (v *visitor) writeHTMLEscaped(s string) {
- strfun.HTMLEscape(&v.b, s, v.visibleSpace)
-}
-
-func (v *visitor) writeQuotedEscaped(s string) {
- strfun.HTMLAttrEscape(&v.b, s)
-}
-
-func (v *visitor) writeReference(ref *ast.Reference) {
- if ref.URL == nil {
- v.writeHTMLEscaped(ref.Value)
- return
- }
- v.b.WriteString(ref.URL.String())
-}
DELETED encoder/jsonenc/djsonenc.go
Index: encoder/jsonenc/djsonenc.go
==================================================================
--- encoder/jsonenc/djsonenc.go
+++ /dev/null
@@ -1,574 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package jsonenc encodes the abstract syntax tree into JSON.
-package jsonenc
-
-import (
- "fmt"
- "io"
- "sort"
- "strconv"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
- "zettelstore.de/z/encoder/encfun"
-)
-
-func init() {
- encoder.Register("djson", encoder.Info{
- Create: func(env *encoder.Environment) encoder.Encoder { return &jsonDetailEncoder{env: env} },
- })
-}
-
-type jsonDetailEncoder struct {
- env *encoder.Environment
-}
-
-// WriteZettel writes the encoded zettel to the writer.
-func (je *jsonDetailEncoder) WriteZettel(w io.Writer, zn *ast.ZettelNode, inhMeta bool) (int, error) {
- v := newDetailVisitor(w, je)
- v.b.WriteString("{\"meta\":{\"title\":")
- v.acceptInlineSlice(encfun.MetaAsInlineSlice(zn.InhMeta, meta.KeyTitle))
- if inhMeta {
- v.writeMeta(zn.InhMeta)
- } else {
- v.writeMeta(zn.Meta)
- }
- v.b.WriteByte('}')
- v.b.WriteString(",\"content\":")
- v.acceptBlockSlice(zn.Ast)
- v.b.WriteByte('}')
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteMeta encodes meta data as JSON.
-func (je *jsonDetailEncoder) WriteMeta(w io.Writer, m *meta.Meta) (int, error) {
- v := newDetailVisitor(w, je)
- v.b.WriteString("{\"title\":")
- v.acceptInlineSlice(encfun.MetaAsInlineSlice(m, meta.KeyTitle))
- v.writeMeta(m)
- v.b.WriteByte('}')
- length, err := v.b.Flush()
- return length, err
-}
-
-func (je *jsonDetailEncoder) WriteContent(w io.Writer, zn *ast.ZettelNode) (int, error) {
- return je.WriteBlocks(w, zn.Ast)
-}
-
-// WriteBlocks writes a block slice to the writer
-func (je *jsonDetailEncoder) WriteBlocks(w io.Writer, bs ast.BlockSlice) (int, error) {
- v := newDetailVisitor(w, je)
- v.acceptBlockSlice(bs)
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteInlines writes an inline slice to the writer
-func (je *jsonDetailEncoder) WriteInlines(w io.Writer, is ast.InlineSlice) (int, error) {
- v := newDetailVisitor(w, je)
- v.acceptInlineSlice(is)
- length, err := v.b.Flush()
- return length, err
-}
-
-// detailVisitor writes the abstract syntax tree to an io.Writer.
-type detailVisitor struct {
- b encoder.BufWriter
- env *encoder.Environment
-}
-
-func newDetailVisitor(w io.Writer, je *jsonDetailEncoder) *detailVisitor {
- return &detailVisitor{b: encoder.NewBufWriter(w), env: je.env}
-}
-
-// VisitPara emits JSON code for a paragraph.
-func (v *detailVisitor) VisitPara(pn *ast.ParaNode) {
- v.writeNodeStart("Para")
- v.writeContentStart('i')
- v.acceptInlineSlice(pn.Inlines)
- v.b.WriteByte('}')
-}
-
-var verbatimCode = map[ast.VerbatimCode]string{
- ast.VerbatimProg: "CodeBlock",
- ast.VerbatimComment: "CommentBlock",
- ast.VerbatimHTML: "HTMLBlock",
-}
-
-// VisitVerbatim emits JSON code for verbatim lines.
-func (v *detailVisitor) VisitVerbatim(vn *ast.VerbatimNode) {
- code, ok := verbatimCode[vn.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown verbatim code %v", vn.Code))
- }
- v.writeNodeStart(code)
- v.visitAttributes(vn.Attrs)
- v.writeContentStart('l')
- for i, line := range vn.Lines {
- if i > 0 {
- v.b.WriteByte(',')
- }
- writeEscaped(&v.b, line)
- }
- v.b.WriteString("]}")
-}
-
-var regionCode = map[ast.RegionCode]string{
- ast.RegionSpan: "SpanBlock",
- ast.RegionQuote: "QuoteBlock",
- ast.RegionVerse: "VerseBlock",
-}
-
-// VisitRegion writes JSON code for block regions.
-func (v *detailVisitor) VisitRegion(rn *ast.RegionNode) {
- code, ok := regionCode[rn.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown region code %v", rn.Code))
- }
- v.writeNodeStart(code)
- v.visitAttributes(rn.Attrs)
- v.writeContentStart('b')
- v.acceptBlockSlice(rn.Blocks)
- if len(rn.Inlines) > 0 {
- v.writeContentStart('i')
- v.acceptInlineSlice(rn.Inlines)
- }
- v.b.WriteByte('}')
-}
-
-// VisitHeading writes the JSON code for a heading.
-func (v *detailVisitor) VisitHeading(hn *ast.HeadingNode) {
- v.writeNodeStart("Heading")
- v.visitAttributes(hn.Attrs)
- v.writeContentStart('n')
- v.b.WriteString(strconv.Itoa(hn.Level))
- if slug := hn.Slug; len(slug) > 0 {
- v.writeContentStart('s')
- v.b.WriteStrings("\"", slug, "\"")
- }
- v.writeContentStart('i')
- v.acceptInlineSlice(hn.Inlines)
- v.b.WriteByte('}')
-}
-
-// VisitHRule writes JSON code for a horizontal rule:
.
-func (v *detailVisitor) VisitHRule(hn *ast.HRuleNode) {
- v.writeNodeStart("Hrule")
- v.visitAttributes(hn.Attrs)
- v.b.WriteByte('}')
-}
-
-var listCode = map[ast.NestedListCode]string{
- ast.NestedListOrdered: "OrderedList",
- ast.NestedListUnordered: "BulletList",
- ast.NestedListQuote: "QuoteList",
-}
-
-// VisitNestedList writes JSON code for lists and blockquotes.
-func (v *detailVisitor) VisitNestedList(ln *ast.NestedListNode) {
- v.writeNodeStart(listCode[ln.Code])
- v.writeContentStart('c')
- for i, item := range ln.Items {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.acceptItemSlice(item)
- }
- v.b.WriteString("]}")
-}
-
-// VisitDescriptionList emits a JSON description list.
-func (v *detailVisitor) VisitDescriptionList(dn *ast.DescriptionListNode) {
- v.writeNodeStart("DescriptionList")
- v.writeContentStart('g')
- for i, def := range dn.Descriptions {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.b.WriteByte('[')
- v.acceptInlineSlice(def.Term)
-
- if len(def.Descriptions) > 0 {
- for _, b := range def.Descriptions {
- v.b.WriteByte(',')
- v.acceptDescriptionSlice(b)
- }
- }
- v.b.WriteByte(']')
- }
- v.b.WriteString("]}")
-}
-
-// VisitTable emits a JSON table.
-func (v *detailVisitor) VisitTable(tn *ast.TableNode) {
- v.writeNodeStart("Table")
- v.writeContentStart('p')
-
- // Table header
- v.b.WriteByte('[')
- for i, cell := range tn.Header {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.writeCell(cell)
- }
- v.b.WriteString("],")
-
- // Table rows
- v.b.WriteByte('[')
- for i, row := range tn.Rows {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.b.WriteByte('[')
- for j, cell := range row {
- if j > 0 {
- v.b.WriteByte(',')
- }
- v.writeCell(cell)
- }
- v.b.WriteByte(']')
- }
- v.b.WriteString("]]}")
-}
-
-var alignmentCode = map[ast.Alignment]string{
- ast.AlignDefault: "[\"\",",
- ast.AlignLeft: "[\"<\",",
- ast.AlignCenter: "[\":\",",
- ast.AlignRight: "[\">\",",
-}
-
-func (v *detailVisitor) writeCell(cell *ast.TableCell) {
- v.b.WriteString(alignmentCode[cell.Align])
- v.acceptInlineSlice(cell.Inlines)
- v.b.WriteByte(']')
-}
-
-// VisitBLOB writes the binary object as a value.
-func (v *detailVisitor) VisitBLOB(bn *ast.BLOBNode) {
- v.writeNodeStart("Blob")
- v.writeContentStart('q')
- writeEscaped(&v.b, bn.Title)
- v.writeContentStart('s')
- writeEscaped(&v.b, bn.Syntax)
- v.writeContentStart('o')
- v.b.WriteBase64(bn.Blob)
- v.b.WriteString("\"}")
-}
-
-// VisitText writes text content.
-func (v *detailVisitor) VisitText(tn *ast.TextNode) {
- v.writeNodeStart("Text")
- v.writeContentStart('s')
- writeEscaped(&v.b, tn.Text)
- v.b.WriteByte('}')
-}
-
-// VisitTag writes tag content.
-func (v *detailVisitor) VisitTag(tn *ast.TagNode) {
- v.writeNodeStart("Tag")
- v.writeContentStart('s')
- writeEscaped(&v.b, tn.Tag)
- v.b.WriteByte('}')
-}
-
-// VisitSpace emits a white space.
-func (v *detailVisitor) VisitSpace(sn *ast.SpaceNode) {
- v.writeNodeStart("Space")
- if l := len(sn.Lexeme); l > 1 {
- v.writeContentStart('n')
- v.b.WriteString(strconv.Itoa(l))
- }
- v.b.WriteByte('}')
-}
-
-// VisitBreak writes JSON code for line breaks.
-func (v *detailVisitor) VisitBreak(bn *ast.BreakNode) {
- if bn.Hard {
- v.writeNodeStart("Hard")
- } else {
- v.writeNodeStart("Soft")
- }
- v.b.WriteByte('}')
-}
-
-var mapRefState = map[ast.RefState]string{
- ast.RefStateInvalid: "invalid",
- ast.RefStateZettel: "zettel",
- ast.RefStateSelf: "self",
- ast.RefStateFound: "zettel",
- ast.RefStateBroken: "broken",
- ast.RefStateHosted: "local",
- ast.RefStateBased: "based",
- ast.RefStateExternal: "external",
-}
-
-// VisitLink writes JSON code for links.
-func (v *detailVisitor) VisitLink(ln *ast.LinkNode) {
- ln, n := v.env.AdaptLink(ln)
- if n != nil {
- n.Accept(v)
- return
- }
- v.writeNodeStart("Link")
- v.visitAttributes(ln.Attrs)
- v.writeContentStart('q')
- writeEscaped(&v.b, mapRefState[ln.Ref.State])
- v.writeContentStart('s')
- writeEscaped(&v.b, ln.Ref.String())
- v.writeContentStart('i')
- v.acceptInlineSlice(ln.Inlines)
- v.b.WriteByte('}')
-}
-
-// VisitImage writes JSON code for images.
-func (v *detailVisitor) VisitImage(in *ast.ImageNode) {
- in, n := v.env.AdaptImage(in)
- if n != nil {
- n.Accept(v)
- return
- }
- v.writeNodeStart("Image")
- v.visitAttributes(in.Attrs)
- if in.Ref == nil {
- v.writeContentStart('j')
- v.b.WriteString("\"s\":")
- writeEscaped(&v.b, in.Syntax)
- switch in.Syntax {
- case "svg":
- v.writeContentStart('q')
- writeEscaped(&v.b, string(in.Blob))
- default:
- v.writeContentStart('o')
- v.b.WriteBase64(in.Blob)
- v.b.WriteByte('"')
- }
- v.b.WriteByte('}')
- } else {
- v.writeContentStart('s')
- writeEscaped(&v.b, in.Ref.String())
- }
- if len(in.Inlines) > 0 {
- v.writeContentStart('i')
- v.acceptInlineSlice(in.Inlines)
- }
- v.b.WriteByte('}')
-}
-
-// VisitCite writes code for citations.
-func (v *detailVisitor) VisitCite(cn *ast.CiteNode) {
- v.writeNodeStart("Cite")
- v.visitAttributes(cn.Attrs)
- v.writeContentStart('s')
- writeEscaped(&v.b, cn.Key)
- if len(cn.Inlines) > 0 {
- v.writeContentStart('i')
- v.acceptInlineSlice(cn.Inlines)
- }
- v.b.WriteByte('}')
-}
-
-// VisitFootnote write JSON code for a footnote.
-func (v *detailVisitor) VisitFootnote(fn *ast.FootnoteNode) {
- v.writeNodeStart("Footnote")
- v.visitAttributes(fn.Attrs)
- v.writeContentStart('i')
- v.acceptInlineSlice(fn.Inlines)
- v.b.WriteByte('}')
-}
-
-// VisitMark writes JSON code to mark a position.
-func (v *detailVisitor) VisitMark(mn *ast.MarkNode) {
- v.writeNodeStart("Mark")
- if len(mn.Text) > 0 {
- v.writeContentStart('s')
- writeEscaped(&v.b, mn.Text)
- }
- v.b.WriteByte('}')
-}
-
-var formatCode = map[ast.FormatCode]string{
- ast.FormatItalic: "Italic",
- ast.FormatEmph: "Emph",
- ast.FormatBold: "Bold",
- ast.FormatStrong: "Strong",
- ast.FormatMonospace: "Mono",
- ast.FormatStrike: "Strikethrough",
- ast.FormatDelete: "Delete",
- ast.FormatUnder: "Underline",
- ast.FormatInsert: "Insert",
- ast.FormatSuper: "Super",
- ast.FormatSub: "Sub",
- ast.FormatQuote: "Quote",
- ast.FormatQuotation: "Quotation",
- ast.FormatSmall: "Small",
- ast.FormatSpan: "Span",
-}
-
-// VisitFormat write JSON code for formatting text.
-func (v *detailVisitor) VisitFormat(fn *ast.FormatNode) {
- v.writeNodeStart(formatCode[fn.Code])
- v.visitAttributes(fn.Attrs)
- v.writeContentStart('i')
- v.acceptInlineSlice(fn.Inlines)
- v.b.WriteByte('}')
-}
-
-var literalCode = map[ast.LiteralCode]string{
- ast.LiteralProg: "Code",
- ast.LiteralKeyb: "Input",
- ast.LiteralOutput: "Output",
- ast.LiteralComment: "Comment",
- ast.LiteralHTML: "HTML",
-}
-
-// VisitLiteral write JSON code for literal inline text.
-func (v *detailVisitor) VisitLiteral(ln *ast.LiteralNode) {
- code, ok := literalCode[ln.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown literal code %v", ln.Code))
- }
- v.writeNodeStart(code)
- v.visitAttributes(ln.Attrs)
- v.writeContentStart('s')
- writeEscaped(&v.b, ln.Text)
- v.b.WriteByte('}')
-}
-
-func (v *detailVisitor) acceptBlockSlice(bns ast.BlockSlice) {
- v.b.WriteByte('[')
- for i, bn := range bns {
- if i > 0 {
- v.b.WriteByte(',')
- }
- bn.Accept(v)
- }
- v.b.WriteByte(']')
-}
-
-func (v *detailVisitor) acceptItemSlice(ins ast.ItemSlice) {
- v.b.WriteByte('[')
- for i, in := range ins {
- if i > 0 {
- v.b.WriteByte(',')
- }
- in.Accept(v)
- }
- v.b.WriteByte(']')
-}
-
-func (v *detailVisitor) acceptDescriptionSlice(dns ast.DescriptionSlice) {
- v.b.WriteByte('[')
- for i, dn := range dns {
- if i > 0 {
- v.b.WriteByte(',')
- }
- dn.Accept(v)
- }
- v.b.WriteByte(']')
-}
-
-func (v *detailVisitor) acceptInlineSlice(ins ast.InlineSlice) {
- v.b.WriteByte('[')
- for i, in := range ins {
- if i > 0 {
- v.b.WriteByte(',')
- }
- in.Accept(v)
- }
- v.b.WriteByte(']')
-}
-
-// visitAttributes write JSON attributes
-func (v *detailVisitor) visitAttributes(a *ast.Attributes) {
- if a == nil || len(a.Attrs) == 0 {
- return
- }
- keys := make([]string, 0, len(a.Attrs))
- for k := range a.Attrs {
- keys = append(keys, k)
- }
- sort.Strings(keys)
-
- v.b.WriteString(",\"a\":{\"")
- for i, k := range keys {
- if i > 0 {
- v.b.WriteString("\",\"")
- }
- v.b.Write(Escape(k))
- v.b.WriteString("\":\"")
- v.b.Write(Escape(a.Attrs[k]))
- }
- v.b.WriteString("\"}")
-}
-
-func (v *detailVisitor) writeNodeStart(t string) {
- v.b.WriteStrings("{\"t\":\"", t, "\"")
-}
-
-var contentCode = map[rune][]byte{
- 'b': []byte(",\"b\":"), // List of blocks
- 'c': []byte(",\"c\":["), // List of list of blocks
- 'g': []byte(",\"g\":["), // General list
- 'i': []byte(",\"i\":"), // List of inlines
- 'j': []byte(",\"j\":{"), // Embedded JSON object
- 'l': []byte(",\"l\":["), // List of lines
- 'n': []byte(",\"n\":"), // Number
- 'o': []byte(",\"o\":\""), // Byte object
- 'p': []byte(",\"p\":["), // Generic tuple
- 'q': []byte(",\"q\":"), // String, if 's' is also needed
- 's': []byte(",\"s\":"), // String
- 't': []byte("Content code 't' is not allowed"),
- 'y': []byte("Content code 'y' is not allowed"), // field after 'j'
-}
-
-func (v *detailVisitor) writeContentStart(code rune) {
- if b, ok := contentCode[code]; ok {
- v.b.Write(b)
- return
- }
- panic("Unknown content code " + strconv.Itoa(int(code)))
-}
-
-func (v *detailVisitor) writeMeta(m *meta.Meta) {
- for _, p := range m.Pairs(true) {
- if p.Key == meta.KeyTitle {
- continue
- }
- v.b.WriteString(",\"")
- v.b.Write(Escape(p.Key))
- v.b.WriteString("\":")
- if m.Type(p.Key).IsSet {
- v.writeSetValue(p.Value)
- } else {
- v.b.WriteByte('"')
- v.b.Write(Escape(p.Value))
- v.b.WriteByte('"')
- }
- }
-}
-
-func (v *detailVisitor) writeSetValue(value string) {
- v.b.WriteByte('[')
- for i, val := range meta.ListFromValue(value) {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.b.WriteByte('"')
- v.b.Write(Escape(val))
- v.b.WriteByte('"')
- }
- v.b.WriteByte(']')
-}
DELETED encoder/jsonenc/jsonenc.go
Index: encoder/jsonenc/jsonenc.go
==================================================================
--- encoder/jsonenc/jsonenc.go
+++ /dev/null
@@ -1,111 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package jsonenc encodes the abstract syntax tree into some JSON formats.
-package jsonenc
-
-import (
- "bytes"
- "io"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
-)
-
-func init() {
- encoder.Register("json", encoder.Info{
- Create: func(*encoder.Environment) encoder.Encoder { return &jsonEncoder{} },
- Default: true,
- })
-}
-
-// jsonEncoder is just a stub. It is not implemented. The real implementation
-// is in file web/adapter/json.go
-type jsonEncoder struct{}
-
-// WriteZettel writes the encoded zettel to the writer.
-func (je *jsonEncoder) WriteZettel(
- w io.Writer, zn *ast.ZettelNode, inhMeta bool) (int, error) {
- return 0, encoder.ErrNoWriteZettel
-}
-
-// WriteMeta encodes meta data as HTML5.
-func (je *jsonEncoder) WriteMeta(w io.Writer, meta *meta.Meta) (int, error) {
- return 0, encoder.ErrNoWriteMeta
-}
-
-func (je *jsonEncoder) WriteContent(w io.Writer, zn *ast.ZettelNode) (int, error) {
- return 0, encoder.ErrNoWriteContent
-}
-
-// WriteBlocks writes a block slice to the writer
-func (je *jsonEncoder) WriteBlocks(w io.Writer, bs ast.BlockSlice) (int, error) {
- return 0, encoder.ErrNoWriteBlocks
-}
-
-// WriteInlines writes an inline slice to the writer
-func (je *jsonEncoder) WriteInlines(w io.Writer, is ast.InlineSlice) (int, error) {
- return 0, encoder.ErrNoWriteInlines
-}
-
-var (
- jsBackslash = []byte{'\\', '\\'}
- jsDoubleQuote = []byte{'\\', '"'}
- jsNewline = []byte{'\\', 'n'}
- jsTab = []byte{'\\', 't'}
- jsCr = []byte{'\\', 'r'}
- jsUnicode = []byte{'\\', 'u', '0', '0', '0', '0'}
- jsHex = []byte("0123456789ABCDEF")
-)
-
-// Escape returns the given string as a byte slice, where every non-printable
-// rune is made printable.
-func Escape(s string) []byte {
- var buf bytes.Buffer
-
- last := 0
- for i, ch := range s {
- var b []byte
- switch ch {
- case '\t':
- b = jsTab
- case '\r':
- b = jsCr
- case '\n':
- b = jsNewline
- case '"':
- b = jsDoubleQuote
- case '\\':
- b = jsBackslash
- default:
- if ch < ' ' {
- b = jsUnicode
- b[2] = '0'
- b[3] = '0'
- b[4] = jsHex[ch>>4]
- b[5] = jsHex[ch&0xF]
- } else {
- continue
- }
- }
- buf.WriteString(s[last:i])
- buf.Write(b)
- last = i + 1
- }
- buf.WriteString(s[last:])
- return buf.Bytes()
-}
-
-func writeEscaped(b *encoder.BufWriter, s string) {
- b.WriteByte('"')
- b.Write(Escape(s))
- b.WriteByte('"')
-}
DELETED encoder/nativeenc/nativeenc.go
Index: encoder/nativeenc/nativeenc.go
==================================================================
--- encoder/nativeenc/nativeenc.go
+++ /dev/null
@@ -1,614 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package nativeenc encodes the abstract syntax tree into native format.
-package nativeenc
-
-import (
- "fmt"
- "io"
- "sort"
- "strconv"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
- "zettelstore.de/z/encoder/encfun"
- "zettelstore.de/z/parser"
-)
-
-func init() {
- encoder.Register("native", encoder.Info{
- Create: func(env *encoder.Environment) encoder.Encoder { return &nativeEncoder{env: env} },
- })
-}
-
-type nativeEncoder struct {
- env *encoder.Environment
-}
-
-// WriteZettel encodes the zettel to the writer.
-func (ne *nativeEncoder) WriteZettel(
- w io.Writer, zn *ast.ZettelNode, inhMeta bool) (int, error) {
- v := newVisitor(w, ne)
- v.b.WriteString("[Title ")
- v.acceptInlineSlice(encfun.MetaAsInlineSlice(zn.InhMeta, meta.KeyTitle))
- v.b.WriteByte(']')
- if inhMeta {
- v.acceptMeta(zn.InhMeta, false)
- } else {
- v.acceptMeta(zn.Meta, false)
- }
- v.b.WriteByte('\n')
- v.acceptBlockSlice(zn.Ast)
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteMeta encodes meta data in native format.
-func (ne *nativeEncoder) WriteMeta(w io.Writer, m *meta.Meta) (int, error) {
- v := newVisitor(w, ne)
- v.acceptMeta(m, true)
- length, err := v.b.Flush()
- return length, err
-}
-
-func (ne *nativeEncoder) WriteContent(w io.Writer, zn *ast.ZettelNode) (int, error) {
- return ne.WriteBlocks(w, zn.Ast)
-}
-
-// WriteBlocks writes a block slice to the writer
-func (ne *nativeEncoder) WriteBlocks(w io.Writer, bs ast.BlockSlice) (int, error) {
- v := newVisitor(w, ne)
- v.acceptBlockSlice(bs)
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteInlines writes an inline slice to the writer
-func (ne *nativeEncoder) WriteInlines(w io.Writer, is ast.InlineSlice) (int, error) {
- v := newVisitor(w, ne)
- v.acceptInlineSlice(is)
- length, err := v.b.Flush()
- return length, err
-}
-
-// visitor writes the abstract syntax tree to an io.Writer.
-type visitor struct {
- b encoder.BufWriter
- level int
- env *encoder.Environment
-}
-
-func newVisitor(w io.Writer, enc *nativeEncoder) *visitor {
- return &visitor{b: encoder.NewBufWriter(w), env: enc.env}
-}
-
-var (
- rawBackslash = []byte{'\\', '\\'}
- rawDoubleQuote = []byte{'\\', '"'}
- rawNewline = []byte{'\\', 'n'}
-)
-
-func (v *visitor) acceptMeta(m *meta.Meta, withTitle bool) {
- if withTitle {
- v.b.WriteString("[Title ")
- v.acceptInlineSlice(parser.ParseMetadata(m.GetDefault(meta.KeyTitle, "")))
- v.b.WriteByte(']')
- }
- v.writeMetaString(m, meta.KeyRole, "Role")
- v.writeMetaList(m, meta.KeyTags, "Tags")
- v.writeMetaString(m, meta.KeySyntax, "Syntax")
- pairs := m.PairsRest(true)
- if len(pairs) == 0 {
- return
- }
- v.b.WriteString("\n[Header")
- v.level++
- for i, p := range pairs {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.writeNewLine()
- v.b.WriteByte('[')
- v.b.WriteStrings(p.Key, " \"")
- v.writeEscaped(p.Value)
- v.b.WriteString("\"]")
- }
- v.level--
- v.b.WriteByte(']')
-}
-
-func (v *visitor) writeMetaString(m *meta.Meta, key, native string) {
- if val, ok := m.Get(key); ok && len(val) > 0 {
- v.b.WriteStrings("\n[", native, " \"", val, "\"]")
- }
-}
-
-func (v *visitor) writeMetaList(m *meta.Meta, key, native string) {
- if vals, ok := m.GetList(key); ok && len(vals) > 0 {
- v.b.WriteStrings("\n[", native)
- for _, val := range vals {
- v.b.WriteByte(' ')
- v.b.WriteString(val)
- }
- v.b.WriteByte(']')
- }
-}
-
-// VisitPara emits native code for a paragraph.
-func (v *visitor) VisitPara(pn *ast.ParaNode) {
- v.b.WriteString("[Para ")
- v.acceptInlineSlice(pn.Inlines)
- v.b.WriteByte(']')
-}
-
-var verbatimCode = map[ast.VerbatimCode][]byte{
- ast.VerbatimProg: []byte("[CodeBlock"),
- ast.VerbatimComment: []byte("[CommentBlock"),
- ast.VerbatimHTML: []byte("[HTMLBlock"),
-}
-
-// VisitVerbatim emits native code for verbatim lines.
-func (v *visitor) VisitVerbatim(vn *ast.VerbatimNode) {
- code, ok := verbatimCode[vn.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown verbatim code %v", vn.Code))
- }
- v.b.Write(code)
- v.visitAttributes(vn.Attrs)
- v.b.WriteString(" \"")
- for i, line := range vn.Lines {
- if i > 0 {
- v.b.Write(rawNewline)
- }
- v.writeEscaped(line)
- }
- v.b.WriteString("\"]")
-}
-
-var regionCode = map[ast.RegionCode][]byte{
- ast.RegionSpan: []byte("[SpanBlock"),
- ast.RegionQuote: []byte("[QuoteBlock"),
- ast.RegionVerse: []byte("[VerseBlock"),
-}
-
-// VisitRegion writes native code for block regions.
-func (v *visitor) VisitRegion(rn *ast.RegionNode) {
- code, ok := regionCode[rn.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown region code %v", rn.Code))
- }
- v.b.Write(code)
- v.visitAttributes(rn.Attrs)
- v.level++
- v.writeNewLine()
- v.b.WriteByte('[')
- v.level++
- v.acceptBlockSlice(rn.Blocks)
- v.level--
- v.b.WriteByte(']')
- if len(rn.Inlines) > 0 {
- v.b.WriteByte(',')
- v.writeNewLine()
- v.b.WriteString("[Cite ")
- v.acceptInlineSlice(rn.Inlines)
- v.b.WriteByte(']')
- }
- v.level--
- v.b.WriteByte(']')
-}
-
-// VisitHeading writes the native code for a heading.
-func (v *visitor) VisitHeading(hn *ast.HeadingNode) {
- v.b.WriteStrings("[Heading ", strconv.Itoa(hn.Level), " \"", hn.Slug, "\"")
- v.visitAttributes(hn.Attrs)
- v.b.WriteByte(' ')
- v.acceptInlineSlice(hn.Inlines)
- v.b.WriteByte(']')
-}
-
-// VisitHRule writes native code for a horizontal rule:
.
-func (v *visitor) VisitHRule(hn *ast.HRuleNode) {
- v.b.WriteString("[Hrule")
- v.visitAttributes(hn.Attrs)
- v.b.WriteByte(']')
-}
-
-var listCode = map[ast.NestedListCode][]byte{
- ast.NestedListOrdered: []byte("[OrderedList"),
- ast.NestedListUnordered: []byte("[BulletList"),
- ast.NestedListQuote: []byte("[QuoteList"),
-}
-
-// VisitNestedList writes native code for lists and blockquotes.
-func (v *visitor) VisitNestedList(ln *ast.NestedListNode) {
- v.b.Write(listCode[ln.Code])
- v.level++
- for i, item := range ln.Items {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.writeNewLine()
- v.level++
- v.b.WriteByte('[')
- v.acceptItemSlice(item)
- v.b.WriteByte(']')
- v.level--
- }
- v.level--
- v.b.WriteByte(']')
-}
-
-// VisitDescriptionList emits a native description list.
-func (v *visitor) VisitDescriptionList(dn *ast.DescriptionListNode) {
- v.b.WriteString("[DescriptionList")
- v.level++
- for i, descr := range dn.Descriptions {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.writeNewLine()
- v.b.WriteString("[Term [")
- v.acceptInlineSlice(descr.Term)
- v.b.WriteByte(']')
-
- if len(descr.Descriptions) > 0 {
- v.level++
- for _, b := range descr.Descriptions {
- v.b.WriteByte(',')
- v.writeNewLine()
- v.b.WriteString("[Description")
- v.level++
- v.writeNewLine()
- v.acceptDescriptionSlice(b)
- v.b.WriteByte(']')
- v.level--
- }
- v.level--
- }
- v.b.WriteByte(']')
- }
- v.level--
- v.b.WriteByte(']')
-}
-
-// VisitTable emits a native table.
-func (v *visitor) VisitTable(tn *ast.TableNode) {
- v.b.WriteString("[Table")
- v.level++
- if len(tn.Header) > 0 {
- v.writeNewLine()
- v.b.WriteString("[Header ")
- for i, cell := range tn.Header {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.writeCell(cell)
- }
- v.b.WriteString("],")
- }
- for i, row := range tn.Rows {
- if i > 0 {
- v.b.WriteByte(',')
- }
- v.writeNewLine()
- v.b.WriteString("[Row ")
- for j, cell := range row {
- if j > 0 {
- v.b.WriteByte(',')
- }
- v.writeCell(cell)
- }
- v.b.WriteByte(']')
- }
- v.level--
- v.b.WriteByte(']')
-}
-
-var alignString = map[ast.Alignment]string{
- ast.AlignDefault: " Default",
- ast.AlignLeft: " Left",
- ast.AlignCenter: " Center",
- ast.AlignRight: " Right",
-}
-
-func (v *visitor) writeCell(cell *ast.TableCell) {
- v.b.WriteStrings("[Cell", alignString[cell.Align])
- if len(cell.Inlines) > 0 {
- v.b.WriteByte(' ')
- v.acceptInlineSlice(cell.Inlines)
- }
- v.b.WriteByte(']')
-}
-
-// VisitBLOB writes the binary object as a value.
-func (v *visitor) VisitBLOB(bn *ast.BLOBNode) {
- v.b.WriteString("[BLOB \"")
- v.writeEscaped(bn.Title)
- v.b.WriteString("\" \"")
- v.writeEscaped(bn.Syntax)
- v.b.WriteString("\" \"")
- v.b.WriteBase64(bn.Blob)
- v.b.WriteString("\"]")
-}
-
-// VisitText writes text content.
-func (v *visitor) VisitText(tn *ast.TextNode) {
- v.b.WriteString("Text \"")
- v.writeEscaped(tn.Text)
- v.b.WriteByte('"')
-}
-
-// VisitTag writes tag content.
-func (v *visitor) VisitTag(tn *ast.TagNode) {
- v.b.WriteString("Tag \"")
- v.writeEscaped(tn.Tag)
- v.b.WriteByte('"')
-}
-
-// VisitSpace emits a white space.
-func (v *visitor) VisitSpace(sn *ast.SpaceNode) {
- v.b.WriteString("Space")
- if l := len(sn.Lexeme); l > 1 {
- v.b.WriteByte(' ')
- v.b.WriteString(strconv.Itoa(l))
- }
-}
-
-// VisitBreak writes native code for line breaks.
-func (v *visitor) VisitBreak(bn *ast.BreakNode) {
- if bn.Hard {
- v.b.WriteString("Break")
- } else {
- v.b.WriteString("Space")
- }
-}
-
-var mapRefState = map[ast.RefState]string{
- ast.RefStateInvalid: "INVALID",
- ast.RefStateZettel: "ZETTEL",
- ast.RefStateSelf: "SELF",
- ast.RefStateFound: "ZETTEL",
- ast.RefStateBroken: "BROKEN",
- ast.RefStateHosted: "LOCAL",
- ast.RefStateBased: "BASED",
- ast.RefStateExternal: "EXTERNAL",
-}
-
-// VisitLink writes native code for links.
-func (v *visitor) VisitLink(ln *ast.LinkNode) {
- ln, n := v.env.AdaptLink(ln)
- if n != nil {
- n.Accept(v)
- return
- }
- v.b.WriteString("Link")
- v.visitAttributes(ln.Attrs)
- v.b.WriteByte(' ')
- v.b.WriteString(mapRefState[ln.Ref.State])
- v.b.WriteString(" \"")
- v.writeEscaped(ln.Ref.String())
- v.b.WriteString("\" [")
- if !ln.OnlyRef {
- v.acceptInlineSlice(ln.Inlines)
- }
- v.b.WriteByte(']')
-}
-
-// VisitImage writes native code for images.
-func (v *visitor) VisitImage(in *ast.ImageNode) {
- in, n := v.env.AdaptImage(in)
- if n != nil {
- n.Accept(v)
- return
- }
- v.b.WriteString("Image")
- v.visitAttributes(in.Attrs)
- if in.Ref == nil {
- v.b.WriteStrings(" {\"", in.Syntax, "\" \"")
- switch in.Syntax {
- case "svg":
- v.writeEscaped(string(in.Blob))
- default:
- v.b.WriteString("\" \"")
- v.b.WriteBase64(in.Blob)
- }
- v.b.WriteString("\"}")
- } else {
- v.b.WriteStrings(" \"", in.Ref.String(), "\"")
- }
- if len(in.Inlines) > 0 {
- v.b.WriteString(" [")
- v.acceptInlineSlice(in.Inlines)
- v.b.WriteByte(']')
- }
-}
-
-// VisitCite writes code for citations.
-func (v *visitor) VisitCite(cn *ast.CiteNode) {
- v.b.WriteString("Cite")
- v.visitAttributes(cn.Attrs)
- v.b.WriteString(" \"")
- v.writeEscaped(cn.Key)
- v.b.WriteByte('"')
- if len(cn.Inlines) > 0 {
- v.b.WriteString(" [")
- v.acceptInlineSlice(cn.Inlines)
- v.b.WriteByte(']')
- }
-}
-
-// VisitFootnote write native code for a footnote.
-func (v *visitor) VisitFootnote(fn *ast.FootnoteNode) {
- v.b.WriteString("Footnote")
- v.visitAttributes(fn.Attrs)
- v.b.WriteString(" [")
- v.acceptInlineSlice(fn.Inlines)
- v.b.WriteByte(']')
-}
-
-// VisitMark writes native code to mark a position.
-func (v *visitor) VisitMark(mn *ast.MarkNode) {
- v.b.WriteString("Mark")
- if len(mn.Text) > 0 {
- v.b.WriteString(" \"")
- v.writeEscaped(mn.Text)
- v.b.WriteByte('"')
- }
-}
-
-var formatCode = map[ast.FormatCode][]byte{
- ast.FormatItalic: []byte("Italic"),
- ast.FormatEmph: []byte("Emph"),
- ast.FormatBold: []byte("Bold"),
- ast.FormatStrong: []byte("Strong"),
- ast.FormatUnder: []byte("Underline"),
- ast.FormatInsert: []byte("Insert"),
- ast.FormatMonospace: []byte("Mono"),
- ast.FormatStrike: []byte("Strikethrough"),
- ast.FormatDelete: []byte("Delete"),
- ast.FormatSuper: []byte("Super"),
- ast.FormatSub: []byte("Sub"),
- ast.FormatQuote: []byte("Quote"),
- ast.FormatQuotation: []byte("Quotation"),
- ast.FormatSmall: []byte("Small"),
- ast.FormatSpan: []byte("Span"),
-}
-
-// VisitFormat write native code for formatting text.
-func (v *visitor) VisitFormat(fn *ast.FormatNode) {
- v.b.Write(formatCode[fn.Code])
- v.visitAttributes(fn.Attrs)
- v.b.WriteString(" [")
- v.acceptInlineSlice(fn.Inlines)
- v.b.WriteByte(']')
-}
-
-var literalCode = map[ast.LiteralCode][]byte{
- ast.LiteralProg: []byte("Code"),
- ast.LiteralKeyb: []byte("Input"),
- ast.LiteralOutput: []byte("Output"),
- ast.LiteralComment: []byte("Comment"),
- ast.LiteralHTML: []byte("HTML"),
-}
-
-// VisitLiteral write native code for code inline text.
-func (v *visitor) VisitLiteral(ln *ast.LiteralNode) {
- code, ok := literalCode[ln.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown literal code %v", ln.Code))
- }
- v.b.Write(code)
- v.visitAttributes(ln.Attrs)
- v.b.WriteString(" \"")
- v.writeEscaped(ln.Text)
- v.b.WriteByte('"')
-}
-
-func (v *visitor) acceptBlockSlice(bns ast.BlockSlice) {
- for i, bn := range bns {
- if i > 0 {
- v.b.WriteByte(',')
- v.writeNewLine()
- }
- bn.Accept(v)
- }
-}
-func (v *visitor) acceptItemSlice(ins ast.ItemSlice) {
- for i, in := range ins {
- if i > 0 {
- v.b.WriteByte(',')
- v.writeNewLine()
- }
- in.Accept(v)
- }
-}
-func (v *visitor) acceptDescriptionSlice(dns ast.DescriptionSlice) {
- for i, dn := range dns {
- if i > 0 {
- v.b.WriteByte(',')
- v.writeNewLine()
- }
- dn.Accept(v)
- }
-}
-func (v *visitor) acceptInlineSlice(ins ast.InlineSlice) {
- for i, in := range ins {
- if i > 0 {
- v.b.WriteByte(',')
- }
- in.Accept(v)
- }
-}
-
-// visitAttributes write native attributes
-func (v *visitor) visitAttributes(a *ast.Attributes) {
- if a == nil || len(a.Attrs) == 0 {
- return
- }
- keys := make([]string, 0, len(a.Attrs))
- for k := range a.Attrs {
- keys = append(keys, k)
- }
- sort.Strings(keys)
-
- v.b.WriteString(" (\"")
- if val, ok := a.Attrs[""]; ok {
- v.writeEscaped(val)
- }
- v.b.WriteString("\",[")
- first := true
- for _, k := range keys {
- if k == "" {
- continue
- }
- if !first {
- v.b.WriteByte(',')
- }
- v.b.WriteString(k)
- val := a.Attrs[k]
- if len(val) > 0 {
- v.b.WriteString("=\"")
- v.writeEscaped(val)
- v.b.WriteByte('"')
- }
- first = false
- }
- v.b.WriteString("])")
-}
-
-func (v *visitor) writeNewLine() {
- v.b.WriteByte('\n')
- for i := 0; i < v.level; i++ {
- v.b.WriteByte(' ')
- }
-}
-
-func (v *visitor) writeEscaped(s string) {
- last := 0
- for i, ch := range s {
- var b []byte
- switch ch {
- case '\n':
- b = rawNewline
- case '"':
- b = rawDoubleQuote
- case '\\':
- b = rawBackslash
- default:
- continue
- }
- v.b.WriteString(s[last:i])
- v.b.Write(b)
- last = i + 1
- }
- v.b.WriteString(s[last:])
-}
DELETED encoder/rawenc/rawenc.go
Index: encoder/rawenc/rawenc.go
==================================================================
--- encoder/rawenc/rawenc.go
+++ /dev/null
@@ -1,68 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package rawenc encodes the abstract syntax tree as raw content.
-package rawenc
-
-import (
- "io"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
-)
-
-func init() {
- encoder.Register("raw", encoder.Info{
- Create: func(*encoder.Environment) encoder.Encoder { return &rawEncoder{} },
- })
-}
-
-type rawEncoder struct{}
-
-// WriteZettel writes the encoded zettel to the writer.
-func (re *rawEncoder) WriteZettel(
- w io.Writer, zn *ast.ZettelNode, inhMeta bool) (int, error) {
- b := encoder.NewBufWriter(w)
- if inhMeta {
- zn.InhMeta.Write(&b, true)
- } else {
- zn.Meta.Write(&b, true)
- }
- b.WriteByte('\n')
- b.WriteString(zn.Content.AsString())
- length, err := b.Flush()
- return length, err
-}
-
-// WriteMeta encodes meta data as HTML5.
-func (re *rawEncoder) WriteMeta(w io.Writer, m *meta.Meta) (int, error) {
- b := encoder.NewBufWriter(w)
- m.Write(&b, true)
- length, err := b.Flush()
- return length, err
-}
-
-func (re *rawEncoder) WriteContent(w io.Writer, zn *ast.ZettelNode) (int, error) {
- b := encoder.NewBufWriter(w)
- b.WriteString(zn.Content.AsString())
- length, err := b.Flush()
- return length, err
-}
-
-// WriteBlocks writes a block slice to the writer
-func (re *rawEncoder) WriteBlocks(w io.Writer, bs ast.BlockSlice) (int, error) {
- return 0, encoder.ErrNoWriteBlocks
-}
-
-// WriteInlines writes an inline slice to the writer
-func (re *rawEncoder) WriteInlines(w io.Writer, is ast.InlineSlice) (int, error) {
- return 0, encoder.ErrNoWriteInlines
-}
DELETED encoder/textenc/textenc.go
Index: encoder/textenc/textenc.go
==================================================================
--- encoder/textenc/textenc.go
+++ /dev/null
@@ -1,282 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package textenc encodes the abstract syntax tree into its text.
-package textenc
-
-import (
- "io"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
- "zettelstore.de/z/parser"
-)
-
-func init() {
- encoder.Register("text", encoder.Info{
- Create: func(*encoder.Environment) encoder.Encoder { return &textEncoder{} },
- })
-}
-
-type textEncoder struct{}
-
-// WriteZettel writes metadata and content.
-func (te *textEncoder) WriteZettel(w io.Writer, zn *ast.ZettelNode, inhMeta bool) (int, error) {
- v := newVisitor(w)
- if inhMeta {
- te.WriteMeta(&v.b, zn.InhMeta)
- } else {
- te.WriteMeta(&v.b, zn.Meta)
- }
- v.acceptBlockSlice(zn.Ast)
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteMeta encodes metadata as text.
-func (te *textEncoder) WriteMeta(w io.Writer, m *meta.Meta) (int, error) {
- b := encoder.NewBufWriter(w)
- for _, pair := range m.Pairs(true) {
- switch meta.Type(pair.Key) {
- case meta.TypeBool:
- if meta.BoolValue(pair.Value) {
- b.WriteString("true")
- } else {
- b.WriteString("false")
- }
- case meta.TypeTagSet:
- for i, tag := range meta.ListFromValue(pair.Value) {
- if i > 0 {
- b.WriteByte(' ')
- }
- b.WriteString(meta.CleanTag(tag))
- }
- case meta.TypeZettelmarkup:
- te.WriteInlines(w, parser.ParseMetadata(pair.Value))
- default:
- b.WriteString(pair.Value)
- }
- b.WriteByte('\n')
- }
- length, err := b.Flush()
- return length, err
-}
-
-func (te *textEncoder) WriteContent(w io.Writer, zn *ast.ZettelNode) (int, error) {
- return te.WriteBlocks(w, zn.Ast)
-}
-
-// WriteBlocks writes the content of a block slice to the writer.
-func (te *textEncoder) WriteBlocks(w io.Writer, bs ast.BlockSlice) (int, error) {
- v := newVisitor(w)
- v.acceptBlockSlice(bs)
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteInlines writes an inline slice to the writer
-func (te *textEncoder) WriteInlines(w io.Writer, is ast.InlineSlice) (int, error) {
- v := newVisitor(w)
- v.acceptInlineSlice(is)
- length, err := v.b.Flush()
- return length, err
-}
-
-// visitor writes the abstract syntax tree to an io.Writer.
-type visitor struct {
- b encoder.BufWriter
-}
-
-func newVisitor(w io.Writer) *visitor {
- return &visitor{b: encoder.NewBufWriter(w)}
-}
-
-// VisitPara emits text code for a paragraph
-func (v *visitor) VisitPara(pn *ast.ParaNode) {
- v.acceptInlineSlice(pn.Inlines)
-}
-
-// VisitVerbatim emits text for verbatim lines.
-func (v *visitor) VisitVerbatim(vn *ast.VerbatimNode) {
- if vn.Code == ast.VerbatimComment {
- return
- }
- for i, line := range vn.Lines {
- if i > 0 {
- v.b.WriteByte('\n')
- }
- v.b.WriteString(line)
- }
-}
-
-// VisitRegion writes text code for block regions.
-func (v *visitor) VisitRegion(rn *ast.RegionNode) {
- v.acceptBlockSlice(rn.Blocks)
- if len(rn.Inlines) > 0 {
- v.b.WriteByte('\n')
- v.acceptInlineSlice(rn.Inlines)
- }
-}
-
-// VisitHeading writes the text code for a heading.
-func (v *visitor) VisitHeading(hn *ast.HeadingNode) {
- v.acceptInlineSlice(hn.Inlines)
-}
-
-// VisitHRule writes nothing for a horizontal rule.
-func (v *visitor) VisitHRule(hn *ast.HRuleNode) {}
-
-// VisitNestedList writes text code for lists and blockquotes.
-func (v *visitor) VisitNestedList(ln *ast.NestedListNode) {
- for i, item := range ln.Items {
- if i > 0 {
- v.b.WriteByte('\n')
- }
- v.acceptItemSlice(item)
- }
-}
-
-// VisitDescriptionList emits a text for a description list.
-func (v *visitor) VisitDescriptionList(dn *ast.DescriptionListNode) {
- for i, descr := range dn.Descriptions {
- if i > 0 {
- v.b.WriteByte('\n')
- }
- v.acceptInlineSlice(descr.Term)
-
- for _, b := range descr.Descriptions {
- v.b.WriteByte('\n')
- v.acceptDescriptionSlice(b)
- }
- }
-}
-
-// VisitTable emits a text table.
-func (v *visitor) VisitTable(tn *ast.TableNode) {
- if len(tn.Header) > 0 {
- for i, cell := range tn.Header {
- if i > 0 {
- v.b.WriteByte(' ')
- }
- v.acceptInlineSlice(cell.Inlines)
- }
- v.b.WriteByte('\n')
- }
- for i, row := range tn.Rows {
- if i > 0 {
- v.b.WriteByte('\n')
- }
- for j, cell := range row {
- if j > 0 {
- v.b.WriteByte(' ')
- }
- v.acceptInlineSlice(cell.Inlines)
- }
- }
-}
-
-// VisitBLOB writes nothing, because it contains no text.
-func (v *visitor) VisitBLOB(bn *ast.BLOBNode) {}
-
-// VisitText writes text content.
-func (v *visitor) VisitText(tn *ast.TextNode) {
- v.b.WriteString(tn.Text)
-}
-
-// VisitTag writes tag content.
-func (v *visitor) VisitTag(tn *ast.TagNode) {
- v.b.WriteStrings("#", tn.Tag)
-}
-
-// VisitSpace emits a white space.
-func (v *visitor) VisitSpace(sn *ast.SpaceNode) {
- v.b.WriteByte(' ')
-}
-
-// VisitBreak writes text code for line breaks.
-func (v *visitor) VisitBreak(bn *ast.BreakNode) {
- if bn.Hard {
- v.b.WriteByte('\n')
- } else {
- v.b.WriteByte(' ')
- }
-}
-
-// VisitLink writes text code for links.
-func (v *visitor) VisitLink(ln *ast.LinkNode) {
- if !ln.OnlyRef {
- v.acceptInlineSlice(ln.Inlines)
- }
-}
-
-// VisitImage writes text code for images.
-func (v *visitor) VisitImage(in *ast.ImageNode) {
- v.acceptInlineSlice(in.Inlines)
-}
-
-// VisitCite writes code for citations.
-func (v *visitor) VisitCite(cn *ast.CiteNode) {
- v.acceptInlineSlice(cn.Inlines)
-}
-
-// VisitFootnote write text code for a footnote.
-func (v *visitor) VisitFootnote(fn *ast.FootnoteNode) {
- v.b.WriteByte(' ')
- v.acceptInlineSlice(fn.Inlines)
-}
-
-// VisitMark writes nothing for a mark.
-func (v *visitor) VisitMark(mn *ast.MarkNode) {}
-
-// VisitFormat write text code for formatting text.
-func (v *visitor) VisitFormat(fn *ast.FormatNode) {
- v.acceptInlineSlice(fn.Inlines)
-}
-
-// VisitLiteral write text code for literal inline text.
-func (v *visitor) VisitLiteral(ln *ast.LiteralNode) {
- if ln.Code != ast.LiteralComment {
- v.b.WriteString(ln.Text)
- }
-}
-
-// VisitAttributes never writes any attribute data.
-func (v *visitor) VisitAttributes(a *ast.Attributes) {}
-
-func (v *visitor) acceptBlockSlice(bns ast.BlockSlice) {
- for i, bn := range bns {
- if i > 0 {
- v.b.WriteByte('\n')
- }
- bn.Accept(v)
- }
-}
-func (v *visitor) acceptItemSlice(ins ast.ItemSlice) {
- for i, in := range ins {
- if i > 0 {
- v.b.WriteByte('\n')
- }
- in.Accept(v)
- }
-}
-func (v *visitor) acceptDescriptionSlice(dns ast.DescriptionSlice) {
- for i, dn := range dns {
- if i > 0 {
- v.b.WriteByte('\n')
- }
- dn.Accept(v)
- }
-}
-func (v *visitor) acceptInlineSlice(ins ast.InlineSlice) {
- for _, in := range ins {
- in.Accept(v)
- }
-}
DELETED encoder/zmkenc/zmkenc.go
Index: encoder/zmkenc/zmkenc.go
==================================================================
--- encoder/zmkenc/zmkenc.go
+++ /dev/null
@@ -1,468 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package zmkenc encodes the abstract syntax tree back into Zettelmarkup.
-package zmkenc
-
-import (
- "fmt"
- "io"
- "sort"
-
- "zettelstore.de/z/ast"
- "zettelstore.de/z/domain/meta"
- "zettelstore.de/z/encoder"
-)
-
-func init() {
- encoder.Register("zmk", encoder.Info{
- Create: func(*encoder.Environment) encoder.Encoder { return &zmkEncoder{} },
- })
-}
-
-type zmkEncoder struct{}
-
-// WriteZettel writes the encoded zettel to the writer.
-func (ze *zmkEncoder) WriteZettel(
- w io.Writer, zn *ast.ZettelNode, inhMeta bool) (int, error) {
- v := newVisitor(w, ze)
- if inhMeta {
- zn.InhMeta.WriteAsHeader(&v.b, true)
- } else {
- zn.Meta.WriteAsHeader(&v.b, true)
- }
- v.acceptBlockSlice(zn.Ast)
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteMeta encodes meta data as zmk.
-func (ze *zmkEncoder) WriteMeta(w io.Writer, m *meta.Meta) (int, error) {
- return m.Write(w, true)
-}
-
-func (ze *zmkEncoder) WriteContent(w io.Writer, zn *ast.ZettelNode) (int, error) {
- return ze.WriteBlocks(w, zn.Ast)
-}
-
-// WriteBlocks writes the content of a block slice to the writer.
-func (ze *zmkEncoder) WriteBlocks(w io.Writer, bs ast.BlockSlice) (int, error) {
- v := newVisitor(w, ze)
- v.acceptBlockSlice(bs)
- length, err := v.b.Flush()
- return length, err
-}
-
-// WriteInlines writes an inline slice to the writer
-func (ze *zmkEncoder) WriteInlines(w io.Writer, is ast.InlineSlice) (int, error) {
- v := newVisitor(w, ze)
- v.acceptInlineSlice(is)
- length, err := v.b.Flush()
- return length, err
-}
-
-// visitor writes the abstract syntax tree to an io.Writer.
-type visitor struct {
- b encoder.BufWriter
- prefix []byte
- enc *zmkEncoder
-}
-
-func newVisitor(w io.Writer, enc *zmkEncoder) *visitor {
- return &visitor{
- b: encoder.NewBufWriter(w),
- enc: enc,
- }
-}
-
-// VisitPara emits HTML code for a paragraph: ...
-func (v *visitor) VisitPara(pn *ast.ParaNode) {
- v.acceptInlineSlice(pn.Inlines)
- v.b.WriteByte('\n')
- if len(v.prefix) == 0 {
- v.b.WriteByte('\n')
- }
-}
-
-// VisitVerbatim emits HTML code for verbatim lines.
-func (v *visitor) VisitVerbatim(vn *ast.VerbatimNode) {
- // TODO: scan cn.Lines to find embedded "`"s at beginning
- v.b.WriteString("```")
- v.visitAttributes(vn.Attrs)
- v.b.WriteByte('\n')
- for _, line := range vn.Lines {
- v.b.WriteStrings(line, "\n")
- }
- v.b.WriteString("```\n")
-}
-
-var regionCode = map[ast.RegionCode]string{
- ast.RegionSpan: ":::",
- ast.RegionQuote: "<<<",
- ast.RegionVerse: "\"\"\"",
-}
-
-// VisitRegion writes HTML code for block regions.
-func (v *visitor) VisitRegion(rn *ast.RegionNode) {
- // Scan rn.Blocks for embedded regions to adjust length of regionCode
- code, ok := regionCode[rn.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown region code %d", rn.Code))
- }
- v.b.WriteString(code)
- v.visitAttributes(rn.Attrs)
- v.b.WriteByte('\n')
- v.acceptBlockSlice(rn.Blocks)
- v.b.WriteString(code)
- if len(rn.Inlines) > 0 {
- v.b.WriteByte(' ')
- v.acceptInlineSlice(rn.Inlines)
- }
- v.b.WriteByte('\n')
-}
-
-// VisitHeading writes the HTML code for a heading.
-func (v *visitor) VisitHeading(hn *ast.HeadingNode) {
- for i := 0; i <= hn.Level; i++ {
- v.b.WriteByte('=')
- }
- v.b.WriteByte(' ')
- v.acceptInlineSlice(hn.Inlines)
- v.visitAttributes(hn.Attrs)
- v.b.WriteByte('\n')
-}
-
-// VisitHRule writes HTML code for a horizontal rule:
.
-func (v *visitor) VisitHRule(hn *ast.HRuleNode) {
- v.b.WriteString("---")
- v.visitAttributes(hn.Attrs)
- v.b.WriteByte('\n')
-}
-
-var listCode = map[ast.NestedListCode]byte{
- ast.NestedListOrdered: '#',
- ast.NestedListUnordered: '*',
- ast.NestedListQuote: '>',
-}
-
-// VisitNestedList writes HTML code for lists and blockquotes.
-func (v *visitor) VisitNestedList(ln *ast.NestedListNode) {
- v.prefix = append(v.prefix, listCode[ln.Code])
- for _, item := range ln.Items {
- v.b.Write(v.prefix)
- v.b.WriteByte(' ')
- for i, in := range item {
- if i > 0 {
- if _, ok := in.(*ast.ParaNode); ok {
- v.b.WriteByte('\n')
- for j := 0; j <= len(v.prefix); j++ {
- v.b.WriteByte(' ')
- }
- }
- }
- in.Accept(v)
- }
- }
- v.prefix = v.prefix[:len(v.prefix)-1]
- v.b.WriteByte('\n')
-}
-
-// VisitDescriptionList emits a HTML description list.
-func (v *visitor) VisitDescriptionList(dn *ast.DescriptionListNode) {
- for _, descr := range dn.Descriptions {
- v.b.WriteString("; ")
- v.acceptInlineSlice(descr.Term)
- v.b.WriteByte('\n')
-
- for _, b := range descr.Descriptions {
- v.b.WriteString(": ")
- for _, dn := range b {
- dn.Accept(v)
- }
- v.b.WriteByte('\n')
- }
- }
-}
-
-var alignCode = map[ast.Alignment]string{
- ast.AlignDefault: "",
- ast.AlignLeft: "<",
- ast.AlignCenter: ":",
- ast.AlignRight: ">",
-}
-
-// VisitTable emits a HTML table.
-func (v *visitor) VisitTable(tn *ast.TableNode) {
- if len(tn.Header) > 0 {
- for pos, cell := range tn.Header {
- v.b.WriteString("|=")
- colAlign := tn.Align[pos]
- if cell.Align != colAlign {
- v.b.WriteString(alignCode[cell.Align])
- }
- v.acceptInlineSlice(cell.Inlines)
- if colAlign != ast.AlignDefault {
- v.b.WriteString(alignCode[colAlign])
- }
- }
- v.b.WriteByte('\n')
- }
- for _, row := range tn.Rows {
- for pos, cell := range row {
- v.b.WriteByte('|')
- if cell.Align != tn.Align[pos] {
- v.b.WriteString(alignCode[cell.Align])
- }
- v.acceptInlineSlice(cell.Inlines)
- }
- v.b.WriteByte('\n')
- }
- v.b.WriteByte('\n')
-}
-
-// VisitBLOB writes the binary object as a value.
-func (v *visitor) VisitBLOB(bn *ast.BLOBNode) {
- v.b.WriteStrings(
- "%% Unable to display BLOB with title '",
- bn.Title,
- "' and syntax '",
- bn.Syntax,
- "'\n")
-}
-
-var escapeSeqs = map[string]bool{
- "\\": true,
- "//": true,
- "**": true,
- "__": true,
- "~~": true,
- "^^": true,
- ",,": true,
- "<<": true,
- "\"\"": true,
- ";;": true,
- "::": true,
- "''": true,
- "``": true,
- "++": true,
- "==": true,
-}
-
-// VisitText writes text content.
-func (v *visitor) VisitText(tn *ast.TextNode) {
- last := 0
- for i := 0; i < len(tn.Text); i++ {
- if b := tn.Text[i]; b == '\\' {
- v.b.WriteString(tn.Text[last:i])
- v.b.WriteBytes('\\', b)
- last = i + 1
- continue
- }
- if i < len(tn.Text)-1 {
- s := tn.Text[i : i+2]
- if _, ok := escapeSeqs[s]; ok {
- v.b.WriteString(tn.Text[last:i])
- for j := 0; j < len(s); j++ {
- v.b.WriteBytes('\\', s[j])
- }
- i++
- last = i + 1
- continue
- }
- }
- }
- v.b.WriteString(tn.Text[last:])
-}
-
-// VisitTag writes tag content.
-func (v *visitor) VisitTag(tn *ast.TagNode) {
- v.b.WriteStrings("#", tn.Tag)
-}
-
-// VisitSpace emits a white space.
-func (v *visitor) VisitSpace(sn *ast.SpaceNode) {
- v.b.WriteString(sn.Lexeme)
-}
-
-// VisitBreak writes HTML code for line breaks.
-func (v *visitor) VisitBreak(bn *ast.BreakNode) {
- if bn.Hard {
- v.b.WriteString("\\\n")
- } else {
- v.b.WriteByte('\n')
- }
- if prefixLen := len(v.prefix); prefixLen > 0 {
- for i := 0; i <= prefixLen; i++ {
- v.b.WriteByte(' ')
- }
- }
-}
-
-// VisitLink writes HTML code for links.
-func (v *visitor) VisitLink(ln *ast.LinkNode) {
- v.b.WriteString("[[")
- if !ln.OnlyRef {
- v.acceptInlineSlice(ln.Inlines)
- v.b.WriteByte('|')
- }
- v.b.WriteStrings(ln.Ref.String(), "]]")
-}
-
-// VisitImage writes HTML code for images.
-func (v *visitor) VisitImage(in *ast.ImageNode) {
- if in.Ref != nil {
- v.b.WriteString("{{")
- if len(in.Inlines) > 0 {
- v.acceptInlineSlice(in.Inlines)
- v.b.WriteByte('|')
- }
- v.b.WriteStrings(in.Ref.String(), "}}")
- }
-}
-
-// VisitCite writes code for citations.
-func (v *visitor) VisitCite(cn *ast.CiteNode) {
- v.b.WriteStrings("[@", cn.Key)
- if len(cn.Inlines) > 0 {
- v.b.WriteString(", ")
- v.acceptInlineSlice(cn.Inlines)
- }
- v.b.WriteByte(']')
- v.visitAttributes(cn.Attrs)
-}
-
-// VisitFootnote write HTML code for a footnote.
-func (v *visitor) VisitFootnote(fn *ast.FootnoteNode) {
- v.b.WriteString("[^")
- v.acceptInlineSlice(fn.Inlines)
- v.b.WriteByte(']')
- v.visitAttributes(fn.Attrs)
-}
-
-// VisitMark writes HTML code to mark a position.
-func (v *visitor) VisitMark(mn *ast.MarkNode) {
- v.b.WriteStrings("[!", mn.Text, "]")
-}
-
-var formatCode = map[ast.FormatCode][]byte{
- ast.FormatItalic: []byte("//"),
- ast.FormatEmph: []byte("//"),
- ast.FormatBold: []byte("**"),
- ast.FormatStrong: []byte("**"),
- ast.FormatUnder: []byte("__"),
- ast.FormatInsert: []byte("__"),
- ast.FormatStrike: []byte("~~"),
- ast.FormatDelete: []byte("~~"),
- ast.FormatSuper: []byte("^^"),
- ast.FormatSub: []byte(",,"),
- ast.FormatQuotation: []byte("<<"),
- ast.FormatQuote: []byte("\"\""),
- ast.FormatSmall: []byte(";;"),
- ast.FormatSpan: []byte("::"),
- ast.FormatMonospace: []byte("''"),
-}
-
-// VisitFormat write HTML code for formatting text.
-func (v *visitor) VisitFormat(fn *ast.FormatNode) {
- code, ok := formatCode[fn.Code]
- if !ok {
- panic(fmt.Sprintf("Unknown format code %d", fn.Code))
- }
- attrs := fn.Attrs
- switch fn.Code {
- case ast.FormatEmph, ast.FormatStrong, ast.FormatInsert, ast.FormatDelete:
- attrs = attrs.Clone()
- attrs.Set("-", "")
- }
-
- v.b.Write(code)
- v.acceptInlineSlice(fn.Inlines)
- v.b.Write(code)
- v.visitAttributes(attrs)
-}
-
-// VisitLiteral write Zettelmarkup for inline literal text.
-func (v *visitor) VisitLiteral(ln *ast.LiteralNode) {
- switch ln.Code {
- case ast.LiteralProg:
- v.writeLiteral('`', ln.Attrs, ln.Text)
- case ast.LiteralKeyb:
- v.writeLiteral('+', ln.Attrs, ln.Text)
- case ast.LiteralOutput:
- v.writeLiteral('=', ln.Attrs, ln.Text)
- case ast.LiteralComment:
- v.b.WriteStrings("%% ", ln.Text)
- case ast.LiteralHTML:
- v.b.WriteString("``")
- v.writeEscaped(ln.Text, '`')
- v.b.WriteString("``{=html,.warning}")
- default:
- panic(fmt.Sprintf("Unknown literal code %v", ln.Code))
- }
-}
-
-func (v *visitor) writeLiteral(code byte, attrs *ast.Attributes, text string) {
- v.b.WriteBytes(code, code)
- v.writeEscaped(text, code)
- v.b.WriteBytes(code, code)
- v.visitAttributes(attrs)
-}
-
-func (v *visitor) acceptBlockSlice(bns ast.BlockSlice) {
- for _, bn := range bns {
- bn.Accept(v)
- }
-}
-func (v *visitor) acceptInlineSlice(ins ast.InlineSlice) {
- for _, in := range ins {
- in.Accept(v)
- }
-}
-
-// visitAttributes write HTML attributes
-func (v *visitor) visitAttributes(a *ast.Attributes) {
- if a == nil || len(a.Attrs) == 0 {
- return
- }
- keys := make([]string, 0, len(a.Attrs))
- for k := range a.Attrs {
- keys = append(keys, k)
- }
- sort.Strings(keys)
-
- v.b.WriteByte('{')
- for i, k := range keys {
- if i > 0 {
- v.b.WriteByte(' ')
- }
- if k == "-" {
- v.b.WriteByte('-')
- continue
- }
- v.b.WriteString(k)
- if vl := a.Attrs[k]; len(vl) > 0 {
- v.b.WriteStrings("=\"", vl)
- v.b.WriteByte('"')
- }
- }
- v.b.WriteByte('}')
-}
-
-func (v *visitor) writeEscaped(s string, toEscape byte) {
- last := 0
- for i := 0; i < len(s); i++ {
- if b := s[i]; b == toEscape || b == '\\' {
- v.b.WriteString(s[last:i])
- v.b.WriteBytes('\\', b)
- last = i + 1
- }
- }
- v.b.WriteString(s[last:])
-}
Index: go.mod
==================================================================
--- go.mod
+++ go.mod
@@ -1,12 +1,19 @@
module zettelstore.de/z
-go 1.16
+go 1.24
require (
- github.com/fsnotify/fsnotify v1.4.9
- github.com/pascaldekloe/jwt v1.10.0
- github.com/yuin/goldmark v1.3.7
- golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83
- golang.org/x/term v0.0.0-20201117132131-f5c789dd3221
- golang.org/x/text v0.3.6
+ github.com/fsnotify/fsnotify v1.9.0
+ github.com/yuin/goldmark v1.7.12
+ golang.org/x/crypto v0.39.0
+ golang.org/x/term v0.32.0
+ golang.org/x/text v0.26.0
+ t73f.de/r/sx v0.0.0-20250620141036-553aa22c59dc
+ t73f.de/r/sxwebs v0.0.0-20250621125212-c25706b6e4b3
+ t73f.de/r/webs v0.0.0-20250604132257-c12dbd1f7046
+ t73f.de/r/zero v0.0.0-20250604143210-ce1230735c4c
+ t73f.de/r/zsc v0.0.0-20250702081237-f91ed9e22f72
+ t73f.de/r/zsx v0.0.0-20250526093914-c34f0bae8fd2
)
+
+require golang.org/x/sys v0.33.0 // indirect
Index: go.sum
==================================================================
--- go.sum
+++ go.sum
@@ -1,20 +1,24 @@
-github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
-github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
-github.com/pascaldekloe/jwt v1.10.0 h1:ktcIUV4TPvh404R5dIBEnPCsSwj0sqi3/0+XafE5gJs=
-github.com/pascaldekloe/jwt v1.10.0/go.mod h1:TKhllgThT7TOP5rGr2zMLKEDZRAgJfBbtKyVeRsNB9A=
-github.com/yuin/goldmark v1.3.7 h1:NSaHgaeJFCtWXCBkBKXw0rhgMuJ0VoE9FB5mWldcrQ4=
-github.com/yuin/goldmark v1.3.7/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
-golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g=
-golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
-golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
-golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/term v0.0.0-20201117132131-f5c789dd3221 h1:/ZHdbVpdR/jk3g30/d4yUL0JU9kksj8+F/bnQUVLGDM=
-golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
-golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
-golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
+github.com/yuin/goldmark v1.7.12 h1:YwGP/rrea2/CnCtUHgjuolG/PnMxdQtPMO5PvaE2/nY=
+github.com/yuin/goldmark v1.7.12/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
+golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
+golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
+golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
+golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
+golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
+golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
+golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
+t73f.de/r/sx v0.0.0-20250620141036-553aa22c59dc h1:5s02C7lwQKjOXyY4ghR6oLo+0SagSBiEiC26ju3VG40=
+t73f.de/r/sx v0.0.0-20250620141036-553aa22c59dc/go.mod h1:Ow4Btc5PCykSct4TrS1kbEB386msl/tmfmLSsEz6OAw=
+t73f.de/r/sxwebs v0.0.0-20250621125212-c25706b6e4b3 h1:+tqWPX3z5BgsRZJDpMtReHmGUioUFP+LsPpXieZ2ZsY=
+t73f.de/r/sxwebs v0.0.0-20250621125212-c25706b6e4b3/go.mod h1:zZBXrGeTfUqElkSMJhGUCuDDWNOUaZE0EH3IZwkW+RA=
+t73f.de/r/webs v0.0.0-20250604132257-c12dbd1f7046 h1:BZWNT/wYlX5sHmEtClRG0rHzZnoh8J35NcRnTvXlqy0=
+t73f.de/r/webs v0.0.0-20250604132257-c12dbd1f7046/go.mod h1:EVohQwCAlRK0kuVBEw5Gw+S44vj+6f6NU8eNJdAIK6s=
+t73f.de/r/zero v0.0.0-20250604143210-ce1230735c4c h1:Zy7GaPv/uVSjKQY7t2c0OOIdSue36x+/0sXt+xoxlpQ=
+t73f.de/r/zero v0.0.0-20250604143210-ce1230735c4c/go.mod h1:T1vFcHoymUQcr7+vENBkS1yryZRZ3YB8uRtnMy8yRBA=
+t73f.de/r/zsc v0.0.0-20250702081237-f91ed9e22f72 h1:eWdLtohzQJhMS2FA3Vbax+j6Sk6MZRf9B8uKkAifYxU=
+t73f.de/r/zsc v0.0.0-20250702081237-f91ed9e22f72/go.mod h1:mxIDqZJD02ZD+pspYPa/VHdlMmUE+DBzE5J5dp+Vb/I=
+t73f.de/r/zsx v0.0.0-20250526093914-c34f0bae8fd2 h1:GWLCd3n8mN6AGhiv8O7bhdjK0BqXQS5EExRlBdx3OPU=
+t73f.de/r/zsx v0.0.0-20250526093914-c34f0bae8fd2/go.mod h1:IQdyC9JP1i6RK55+LJVGjP3hSA9H766yCyUt1AkOU9c=
DELETED input/input.go
Index: input/input.go
==================================================================
--- input/input.go
+++ /dev/null
@@ -1,207 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package input provides an abstraction for data to be read.
-package input
-
-import (
- "html"
- "unicode"
- "unicode/utf8"
-)
-
-// Input is an abstract input source
-type Input struct {
- // Read-only, will never change
- Src string // The source string
-
- // Read-only, will change
- Ch rune // current character
- Pos int // character position in src
- readPos int // reading position (position after current character)
-}
-
-// NewInput creates a new input source.
-func NewInput(src string) *Input {
- inp := &Input{Src: src}
- inp.Next()
- return inp
-}
-
-// EOS = End of source
-const EOS = rune(-1)
-
-// Next reads the next rune into inp.Ch.
-func (inp *Input) Next() {
- if inp.readPos < len(inp.Src) {
- inp.Pos = inp.readPos
- r, w := rune(inp.Src[inp.readPos]), 1
- if r >= utf8.RuneSelf {
- r, w = utf8.DecodeRuneInString(inp.Src[inp.readPos:])
- }
- inp.readPos += w
- inp.Ch = r
- } else {
- inp.Pos = len(inp.Src)
- inp.Ch = EOS
- }
-}
-
-// Peek returns the rune following the most recently read rune without
-// advancing. If end-of-source was already found peek returns EOS.
-func (inp *Input) Peek() rune {
- return inp.PeekN(0)
-}
-
-// PeekN returns the n-th rune after the most recently read rune without
-// advancing. If end-of-source was already found peek returns EOS.
-func (inp *Input) PeekN(n int) rune {
- pos := inp.readPos + n
- if pos < len(inp.Src) {
- r := rune(inp.Src[pos])
- if r >= utf8.RuneSelf {
- r, _ = utf8.DecodeRuneInString(inp.Src[pos:])
- }
- if r == '\t' {
- return ' '
- }
- return r
- }
- return EOS
-}
-
-// IsEOLEOS returns true if char is either EOS or EOL.
-func IsEOLEOS(ch rune) bool {
- switch ch {
- case EOS, '\n', '\r':
- return true
- }
- return false
-}
-
-// EatEOL transforms both "\r" and "\r\n" into "\n".
-func (inp *Input) EatEOL() {
- switch inp.Ch {
- case '\r':
- if inp.Peek() == '\n' {
- inp.Next()
- }
- inp.Ch = '\n'
- inp.Next()
- case '\n':
- inp.Next()
- }
-}
-
-// SetPos allows to reset the read position.
-func (inp *Input) SetPos(pos int) {
- inp.readPos = pos
- inp.Next()
-}
-
-// SkipToEOL reads until the next end-of-line.
-func (inp *Input) SkipToEOL() {
- for {
- switch inp.Ch {
- case EOS, '\n', '\r':
- return
- }
- inp.Next()
- }
-}
-
-// ScanEntity scans either a named or a numbered entity and returns it as a string.
-//
-// For numbered entities (like { or ģ) html.UnescapeString returns
-// sometimes other values as expected, if the number is not well-formed. This
-// may happen because of some strange HTML parsing rules. But these do not
-// apply to Zettelmarkup. Therefore, I parse the number here in the code.
-func (inp *Input) ScanEntity() (res string, success bool) {
- if inp.Ch != '&' {
- return "", false
- }
- pos := inp.Pos
- inp.Next()
- if inp.Ch == '#' {
- inp.Next()
- if inp.Ch == 'x' || inp.Ch == 'X' {
- return inp.scanEntityBase16()
- }
- return inp.scanEntityBase10()
- }
- return inp.scanEntityNamed(pos)
-}
-
-func (inp *Input) scanEntityBase16() (string, bool) {
- inp.Next()
- if inp.Ch == ';' {
- return "", false
- }
- code := 0
- for {
- switch ch := inp.Ch; ch {
- case ';':
- inp.Next()
- return string(rune(code)), true
- case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
- code = 16*code + int(ch-'0')
- case 'a', 'b', 'c', 'd', 'e', 'f':
- code = 16*code + int(ch-'a'+10)
- case 'A', 'B', 'C', 'D', 'E', 'F':
- code = 16*code + int(ch-'A'+10)
- default:
- return "", false
- }
- if code > unicode.MaxRune {
- return "", false
- }
- inp.Next()
- }
-}
-
-func (inp *Input) scanEntityBase10() (string, bool) {
- // Base 10 code
- if inp.Ch == ';' {
- return "", false
- }
- code := 0
- for {
- switch ch := inp.Ch; ch {
- case ';':
- inp.Next()
- return string(rune(code)), true
- case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
- code = 10*code + int(ch-'0')
- default:
- return "", false
- }
- if code > unicode.MaxRune {
- return "", false
- }
- inp.Next()
- }
-}
-func (inp *Input) scanEntityNamed(pos int) (string, bool) {
- for {
- switch inp.Ch {
- case EOS, '\n', '\r':
- return "", false
- case ';':
- inp.Next()
- es := inp.Src[pos:inp.Pos]
- ues := html.UnescapeString(es)
- if es == ues {
- return "", false
- }
- return ues, true
- }
- inp.Next()
- }
-}
DELETED input/input_test.go
Index: input/input_test.go
==================================================================
--- input/input_test.go
+++ /dev/null
@@ -1,67 +0,0 @@
-//-----------------------------------------------------------------------------
-// Copyright (c) 2020-2021 Detlef Stern
-//
-// This file is part of zettelstore.
-//
-// Zettelstore is licensed under the latest version of the EUPL (European Union
-// Public License). Please see file LICENSE.txt for your rights and obligations
-// under this license.
-//-----------------------------------------------------------------------------
-
-// Package input_test provides some unit-tests for reading data.
-package input_test
-
-import (
- "testing"
-
- "zettelstore.de/z/input"
-)
-
-func TestEatEOL(t *testing.T) {
- inp := input.NewInput("")
- inp.EatEOL()
- if inp.Ch != input.EOS {
- t.Errorf("No EOS found: %q", inp.Ch)
- }
- if inp.Pos != 0 {
- t.Errorf("Pos != 0: %d", inp.Pos)
- }
-
- inp = input.NewInput("ABC")
- if inp.Ch != 'A' {
- t.Errorf("First ch != 'A', got %q", inp.Ch)
- }
- inp.EatEOL()
- if inp.Ch != 'A' {
- t.Errorf("First ch != 'A', got %q", inp.Ch)
- }
-}
-
-func TestScanEntity(t *testing.T) {
- var testcases = []struct {
- text string
- exp string
- }{
- {"", ""},
- {"a", ""},
- {"&", "&"},
- {" ", "\t"},
- {""", "\""},
- }
- for id, tc := range testcases {
- inp := input.NewInput(tc.text)
- got, ok := inp.ScanEntity()
- if !ok {
- if tc.exp != "" {
- t.Errorf("ID=%d, text=%q: expected error, but got %q", id, tc.text, got)
- }
- if inp.Pos != 0 {
- t.Errorf("ID=%d, text=%q: input position advances to %d", id, tc.text, inp.Pos)
- }
- continue
- }
- if tc.exp != got {
- t.Errorf("ID=%d, text=%q: expected %q, but got %q", id, tc.text, tc.exp, got)
- }
- }
-}
ADDED internal/ast/ast.go
Index: internal/ast/ast.go
==================================================================
--- /dev/null
+++ internal/ast/ast.go
@@ -0,0 +1,103 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package ast provides the abstract syntax tree for parsed zettel content.
+package ast
+
+import (
+ "net/url"
+ "strings"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "zettelstore.de/z/internal/zettel"
+)
+
+// ZettelNode is the root node of the abstract syntax tree.
+// It is *not* part of the visitor pattern.
+type ZettelNode struct {
+ Meta *meta.Meta // Original metadata
+ Content zettel.Content // Original content
+ Zid id.Zid // Zettel identification.
+ InhMeta *meta.Meta // Metadata of the zettel, with inherited values.
+ BlocksAST BlockSlice // Zettel abstract syntax tree is a sequence of block nodes.
+ Syntax string // Syntax / parser that produced the Ast
+}
+
+// Node is the interface, all nodes must implement.
+type Node interface {
+ WalkChildren(v Visitor)
+}
+
+// BlockNode is the interface that all block nodes must implement.
+type BlockNode interface {
+ Node
+ blockNode()
+}
+
+// ItemNode is a node that can occur as a list item.
+type ItemNode interface {
+ BlockNode
+ itemNode()
+}
+
+// ItemSlice is a slice of ItemNodes.
+type ItemSlice []ItemNode
+
+// DescriptionNode is a node that contains just textual description.
+type DescriptionNode interface {
+ ItemNode
+ descriptionNode()
+}
+
+// DescriptionSlice is a slice of DescriptionNodes.
+type DescriptionSlice []DescriptionNode
+
+// InlineNode is the interface that all inline nodes must implement.
+type InlineNode interface {
+ Node
+ inlineNode()
+}
+
+// Reference is a reference to external or internal material.
+type Reference struct {
+ URL *url.URL
+ Value string
+ State RefState
+}
+
+// RefState indicates the state of the reference.
+type RefState int
+
+// Constants for RefState
+const (
+ RefStateInvalid RefState = iota // Invalid Reference
+ RefStateZettel // Reference to an internal zettel
+ RefStateSelf // Reference to same zettel with a fragment
+ RefStateFound // Reference to an existing internal zettel, URL is ajusted
+ RefStateBroken // Reference to a non-existing internal zettel
+ RefStateHosted // Reference to local hosted non-Zettel, without URL change
+ RefStateBased // Reference to local non-Zettel, to be prefixed
+ RefStateQuery // Reference to a zettel query
+ RefStateExternal // Reference to external material
+)
+
+// ParseSpacedText returns an inline slice that consists just of test and space node.
+// No Zettelmarkup parsing is done. It is typically used to transform the zettel
+// description into an inline slice.
+func ParseSpacedText(s string) InlineSlice {
+ return InlineSlice{&TextNode{Text: NormalizedSpacedText(s)}}
+}
+
+// NormalizedSpacedText returns the given string, but normalize multiple spaces to one space.
+func NormalizedSpacedText(s string) string { return strings.Join(strings.Fields(s), " ") }
ADDED internal/ast/block.go
Index: internal/ast/block.go
==================================================================
--- /dev/null
+++ internal/ast/block.go
@@ -0,0 +1,303 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package ast
+
+import "t73f.de/r/zsx"
+
+// Definition of Block nodes.
+
+// BlockSlice is a slice of BlockNodes.
+type BlockSlice []BlockNode
+
+func (*BlockSlice) blockNode() { /* Just a marker */ }
+
+// WalkChildren walks down to the descriptions.
+func (bs *BlockSlice) WalkChildren(v Visitor) {
+ if bs != nil {
+ for _, bn := range *bs {
+ Walk(v, bn)
+ }
+ }
+}
+
+// FirstParagraphInlines returns the inline list of the first paragraph that
+// contains a inline list.
+func (bs BlockSlice) FirstParagraphInlines() InlineSlice {
+ for _, bn := range bs {
+ pn, ok := bn.(*ParaNode)
+ if !ok {
+ continue
+ }
+ if inl := pn.Inlines; len(inl) > 0 {
+ return inl
+ }
+ }
+ return nil
+}
+
+//--------------------------------------------------------------------------
+
+// ParaNode contains just a sequence of inline elements.
+// Another name is "paragraph".
+type ParaNode struct {
+ Inlines InlineSlice
+}
+
+func (*ParaNode) blockNode() { /* Just a marker */ }
+func (*ParaNode) itemNode() { /* Just a marker */ }
+func (*ParaNode) descriptionNode() { /* Just a marker */ }
+
+// CreateParaNode creates a parameter block from inline nodes.
+func CreateParaNode(nodes ...InlineNode) *ParaNode { return &ParaNode{Inlines: nodes} }
+
+// WalkChildren walks down the inline elements.
+func (pn *ParaNode) WalkChildren(v Visitor) { Walk(v, &pn.Inlines) }
+
+//--------------------------------------------------------------------------
+
+// VerbatimNode contains uninterpreted text
+type VerbatimNode struct {
+ Kind VerbatimKind
+ Attrs zsx.Attributes
+ Content []byte
+}
+
+// VerbatimKind specifies the format that is applied to code inline nodes.
+type VerbatimKind int
+
+// Constants for VerbatimCode
+const (
+ _ VerbatimKind = iota
+ VerbatimZettel // Zettel content
+ VerbatimCode // Program code
+ VerbatimEval // Code to be externally interpreted. Syntax is stored in default attribute.
+ VerbatimComment // Block comment
+ VerbatimHTML // Block HTML, e.g. for Markdown
+ VerbatimMath // Block math mode
+)
+
+func (*VerbatimNode) blockNode() { /* Just a marker */ }
+func (*VerbatimNode) itemNode() { /* Just a marker */ }
+
+// WalkChildren does nothing.
+func (*VerbatimNode) WalkChildren(Visitor) { /* No children*/ }
+
+//--------------------------------------------------------------------------
+
+// RegionNode encapsulates a region of block nodes.
+type RegionNode struct {
+ Kind RegionKind
+ Attrs zsx.Attributes
+ Blocks BlockSlice
+ Inlines InlineSlice // Optional text at the end of the region
+}
+
+// RegionKind specifies the actual region type.
+type RegionKind int
+
+// Values for RegionCode
+const (
+ _ RegionKind = iota
+ RegionSpan // Just a span of blocks
+ RegionQuote // A longer quotation
+ RegionVerse // Line breaks matter
+)
+
+func (*RegionNode) blockNode() { /* Just a marker */ }
+func (*RegionNode) itemNode() { /* Just a marker */ }
+
+// WalkChildren walks down the blocks and the text.
+func (rn *RegionNode) WalkChildren(v Visitor) {
+ Walk(v, &rn.Blocks)
+ Walk(v, &rn.Inlines)
+}
+
+//--------------------------------------------------------------------------
+
+// HeadingNode stores the heading text and level.
+type HeadingNode struct {
+ Level int
+ Attrs zsx.Attributes
+ Slug string // Heading text, normalized
+ Fragment string // Heading text, suitable to be used as an unique URL fragment
+ Inlines InlineSlice // Heading text, possibly formatted
+}
+
+func (*HeadingNode) blockNode() { /* Just a marker */ }
+func (*HeadingNode) itemNode() { /* Just a marker */ }
+
+// WalkChildren walks the heading text.
+func (hn *HeadingNode) WalkChildren(v Visitor) { Walk(v, &hn.Inlines) }
+
+//--------------------------------------------------------------------------
+
+// HRuleNode specifies a horizontal rule.
+type HRuleNode struct {
+ Attrs zsx.Attributes
+}
+
+func (*HRuleNode) blockNode() { /* Just a marker */ }
+func (*HRuleNode) itemNode() { /* Just a marker */ }
+
+// WalkChildren does nothing.
+func (*HRuleNode) WalkChildren(Visitor) { /* No children*/ }
+
+//--------------------------------------------------------------------------
+
+// NestedListNode specifies a nestable list, either ordered or unordered.
+type NestedListNode struct {
+ Kind NestedListKind
+ Attrs zsx.Attributes
+ Items []ItemSlice
+}
+
+// NestedListKind specifies the actual list type.
+type NestedListKind uint8
+
+// Values for ListCode
+const (
+ _ NestedListKind = iota
+ NestedListOrdered // Ordered list.
+ NestedListUnordered // Unordered list.
+ NestedListQuote // Quote list.
+)
+
+func (*NestedListNode) blockNode() { /* Just a marker */ }
+func (*NestedListNode) itemNode() { /* Just a marker */ }
+
+// WalkChildren walks down the items.
+func (ln *NestedListNode) WalkChildren(v Visitor) {
+ if items := ln.Items; items != nil {
+ for _, item := range items {
+ WalkItemSlice(v, item)
+ }
+ }
+}
+
+//--------------------------------------------------------------------------
+
+// DescriptionListNode specifies a description list.
+type DescriptionListNode struct {
+ Attrs zsx.Attributes
+ Descriptions []Description
+}
+
+// Description is one element of a description list.
+type Description struct {
+ Term InlineSlice
+ Descriptions []DescriptionSlice
+}
+
+func (*DescriptionListNode) blockNode() { /* Just a marker */ }
+
+// WalkChildren walks down to the descriptions.
+func (dn *DescriptionListNode) WalkChildren(v Visitor) {
+ if descrs := dn.Descriptions; descrs != nil {
+ for i, desc := range descrs {
+ if len(desc.Term) > 0 {
+ Walk(v, &descrs[i].Term) // Otherwise, changes in desc.Term will not go back into AST
+ }
+ if dss := desc.Descriptions; dss != nil {
+ for _, dns := range dss {
+ WalkDescriptionSlice(v, dns)
+ }
+ }
+ }
+ }
+}
+
+//--------------------------------------------------------------------------
+
+// TableNode specifies a full table
+type TableNode struct {
+ Header TableRow // The header row
+ Align []Alignment // Default column alignment
+ Rows []TableRow // The slice of cell rows
+}
+
+// TableCell contains the data for one table cell
+type TableCell struct {
+ Align Alignment // Cell alignment
+ Inlines InlineSlice // Cell content
+}
+
+// TableRow is a slice of cells.
+type TableRow []*TableCell
+
+// Alignment specifies text alignment.
+// Currently only for tables.
+type Alignment int
+
+// Constants for Alignment.
+const (
+ _ Alignment = iota
+ AlignDefault // Default alignment, inherited
+ AlignLeft // Left alignment
+ AlignCenter // Center the content
+ AlignRight // Right alignment
+)
+
+func (*TableNode) blockNode() { /* Just a marker */ }
+
+// WalkChildren walks down to the cells.
+func (tn *TableNode) WalkChildren(v Visitor) {
+ if header := tn.Header; header != nil {
+ for i := range header {
+ Walk(v, header[i]) // Otherwise changes will not go back
+ }
+ }
+ if rows := tn.Rows; rows != nil {
+ for _, row := range rows {
+ for i := range row {
+ Walk(v, &row[i].Inlines) // Otherwise changes will not go back
+ }
+ }
+ }
+}
+
+// WalkChildren walks the list of inline elements.
+func (cell *TableCell) WalkChildren(v Visitor) {
+ Walk(v, &cell.Inlines) // Otherwise changes will not go back
+}
+
+//--------------------------------------------------------------------------
+
+// TranscludeNode specifies block content from other zettel to embedded in
+// current zettel
+type TranscludeNode struct {
+ Attrs zsx.Attributes
+ Ref *Reference
+ Inlines InlineSlice // Optional text.
+}
+
+func (*TranscludeNode) blockNode() { /* Just a marker */ }
+
+// WalkChildren walks the associated text.
+func (tn *TranscludeNode) WalkChildren(v Visitor) { Walk(v, &tn.Inlines) }
+
+//--------------------------------------------------------------------------
+
+// BLOBNode contains just binary data that must be interpreted according to
+// a syntax.
+type BLOBNode struct {
+ Attrs zsx.Attributes
+ Description InlineSlice
+ Syntax string
+ Blob []byte
+}
+
+func (*BLOBNode) blockNode() { /* Just a marker */ }
+
+// WalkChildren does nothing.
+func (*BLOBNode) WalkChildren(Visitor) { /* No children*/ }
ADDED internal/ast/inline.go
Index: internal/ast/inline.go
==================================================================
--- /dev/null
+++ internal/ast/inline.go
@@ -0,0 +1,210 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package ast
+
+import "t73f.de/r/zsx"
+
+// Definitions of inline nodes.
+
+// InlineSlice is a list of BlockNodes.
+type InlineSlice []InlineNode
+
+func (*InlineSlice) inlineNode() { /* Just a marker */ }
+
+// WalkChildren walks down to the list.
+func (is *InlineSlice) WalkChildren(v Visitor) {
+ if is != nil {
+ for _, in := range *is {
+ Walk(v, in)
+ }
+ }
+}
+
+// --------------------------------------------------------------------------
+
+// TextNode just contains some text.
+type TextNode struct {
+ Text string // The text itself.
+}
+
+func (*TextNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren does nothing.
+func (*TextNode) WalkChildren(Visitor) { /* No children*/ }
+
+// --------------------------------------------------------------------------
+
+// BreakNode signals a new line that must / should be interpreted as a new line break.
+type BreakNode struct {
+ Hard bool // Hard line break?
+}
+
+func (*BreakNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren does nothing.
+func (*BreakNode) WalkChildren(Visitor) { /* No children*/ }
+
+// --------------------------------------------------------------------------
+
+// LinkNode contains the specified link.
+type LinkNode struct {
+ Attrs zsx.Attributes // Optional attributes
+ Ref *Reference
+ Inlines InlineSlice // The text associated with the link.
+}
+
+func (*LinkNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren walks to the link text.
+func (ln *LinkNode) WalkChildren(v Visitor) {
+ if len(ln.Inlines) > 0 {
+ Walk(v, &ln.Inlines)
+ }
+}
+
+// --------------------------------------------------------------------------
+
+// EmbedRefNode contains the specified embedded reference material.
+type EmbedRefNode struct {
+ Attrs zsx.Attributes // Optional attributes
+ Ref *Reference // The reference to be embedded.
+ Syntax string // Syntax of referenced material, if known
+ Inlines InlineSlice // Optional text associated with the image.
+}
+
+func (*EmbedRefNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren walks to the text that describes the embedded material.
+func (en *EmbedRefNode) WalkChildren(v Visitor) { Walk(v, &en.Inlines) }
+
+// --------------------------------------------------------------------------
+
+// EmbedBLOBNode contains the specified embedded BLOB material.
+type EmbedBLOBNode struct {
+ Attrs zsx.Attributes // Optional attributes
+ Syntax string // Syntax of Blob
+ Blob []byte // BLOB data itself.
+ Inlines InlineSlice // Optional text associated with the image.
+}
+
+func (*EmbedBLOBNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren walks to the text that describes the embedded material.
+func (en *EmbedBLOBNode) WalkChildren(v Visitor) { Walk(v, &en.Inlines) }
+
+// --------------------------------------------------------------------------
+
+// CiteNode contains the specified citation.
+type CiteNode struct {
+ Attrs zsx.Attributes // Optional attributes
+ Key string // The citation key
+ Inlines InlineSlice // Optional text associated with the citation.
+}
+
+func (*CiteNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren walks to the cite text.
+func (cn *CiteNode) WalkChildren(v Visitor) { Walk(v, &cn.Inlines) }
+
+// --------------------------------------------------------------------------
+
+// MarkNode contains the specified merked position.
+// It is a BlockNode too, because although it is typically parsed during inline
+// mode, it is moved into block mode afterwards.
+type MarkNode struct {
+ Mark string // The mark text itself
+ Slug string // Slugified form of Mark
+ Fragment string // Unique form of Slug
+ Inlines InlineSlice // Marked inline content
+}
+
+func (*MarkNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren does nothing.
+func (mn *MarkNode) WalkChildren(v Visitor) {
+ if len(mn.Inlines) > 0 {
+ Walk(v, &mn.Inlines)
+ }
+}
+
+// --------------------------------------------------------------------------
+
+// FootnoteNode contains the specified footnote.
+type FootnoteNode struct {
+ Attrs zsx.Attributes // Optional attributes
+ Inlines InlineSlice // The footnote text.
+}
+
+func (*FootnoteNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren walks to the footnote text.
+func (fn *FootnoteNode) WalkChildren(v Visitor) { Walk(v, &fn.Inlines) }
+
+// --------------------------------------------------------------------------
+
+// FormatNode specifies some inline formatting.
+type FormatNode struct {
+ Kind FormatKind
+ Attrs zsx.Attributes // Optional attributes.
+ Inlines InlineSlice
+}
+
+// FormatKind specifies the format that is applied to the inline nodes.
+type FormatKind int
+
+// Constants for FormatCode
+const (
+ _ FormatKind = iota
+ FormatEmph // Emphasized text
+ FormatStrong // Strongly emphasized text
+ FormatInsert // Inserted text
+ FormatDelete // Deleted text
+ FormatSuper // Superscripted text
+ FormatSub // SubscriptedText
+ FormatQuote // Quoted text
+ FormatMark // Marked text
+ FormatSpan // Generic inline container
+)
+
+func (*FormatNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren walks to the formatted text.
+func (fn *FormatNode) WalkChildren(v Visitor) { Walk(v, &fn.Inlines) }
+
+// --------------------------------------------------------------------------
+
+// LiteralNode specifies some uninterpreted text.
+type LiteralNode struct {
+ Kind LiteralKind
+ Attrs zsx.Attributes // Optional attributes.
+ Content []byte
+}
+
+// LiteralKind specifies the format that is applied to code inline nodes.
+type LiteralKind int
+
+// Constants for LiteralCode
+const (
+ _ LiteralKind = iota
+ LiteralCode // Inline program code
+ LiteralInput // Computer input, e.g. Keyboard strokes
+ LiteralOutput // Computer output
+ LiteralComment // Inline comment
+ LiteralMath // Inline math mode
+)
+
+func (*LiteralNode) inlineNode() { /* Just a marker */ }
+
+// WalkChildren does nothing.
+func (*LiteralNode) WalkChildren(Visitor) { /* No children*/ }
ADDED internal/ast/ref.go
Index: internal/ast/ref.go
==================================================================
--- /dev/null
+++ internal/ast/ref.go
@@ -0,0 +1,109 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package ast
+
+import (
+ "net/url"
+ "strings"
+
+ "t73f.de/r/zsc/api"
+ "t73f.de/r/zsc/domain/id"
+)
+
+// QueryPrefix is the prefix that denotes a query expression.
+const QueryPrefix = api.QueryPrefix
+
+// ParseReference parses a string and returns a reference.
+func ParseReference(s string) *Reference {
+ if invalidReference(s) {
+ return &Reference{URL: nil, Value: s, State: RefStateInvalid}
+ }
+ if strings.HasPrefix(s, QueryPrefix) {
+ return &Reference{URL: nil, Value: s[len(QueryPrefix):], State: RefStateQuery}
+ }
+ if state, ok := localState(s); ok {
+ if state == RefStateBased {
+ s = s[1:]
+ }
+ u, err := url.Parse(s)
+ if err == nil {
+ return &Reference{URL: u, Value: s, State: state}
+ }
+ }
+ u, err := url.Parse(s)
+ if err != nil {
+ return &Reference{URL: nil, Value: s, State: RefStateInvalid}
+ }
+ if !externalURL(u) {
+ if _, err = id.Parse(u.Path); err == nil {
+ return &Reference{URL: u, Value: s, State: RefStateZettel}
+ }
+ if u.Path == "" && u.Fragment != "" {
+ return &Reference{URL: u, Value: s, State: RefStateSelf}
+ }
+ }
+ return &Reference{URL: u, Value: s, State: RefStateExternal}
+}
+
+func invalidReference(s string) bool { return s == "" || s == "00000000000000" }
+func externalURL(u *url.URL) bool {
+ return u.Scheme != "" || u.Opaque != "" || u.Host != "" || u.User != nil
+}
+
+func localState(path string) (RefState, bool) {
+ if len(path) > 0 && path[0] == '/' {
+ if len(path) > 1 && path[1] == '/' {
+ return RefStateBased, true
+ }
+ return RefStateHosted, true
+ }
+ if len(path) > 1 && path[0] == '.' {
+ if len(path) > 2 && path[1] == '.' && path[2] == '/' {
+ return RefStateHosted, true
+ }
+ return RefStateHosted, path[1] == '/'
+ }
+ return RefStateInvalid, false
+}
+
+// String returns the string representation of a reference.
+func (r Reference) String() string {
+ if r.State == RefStateQuery {
+ return QueryPrefix + r.Value
+ }
+ if r.URL != nil {
+ return r.URL.String()
+ }
+ return r.Value
+}
+
+// IsValid returns true if reference is valid
+func (r *Reference) IsValid() bool { return r.State != RefStateInvalid }
+
+// IsZettel returns true if it is a referencen to a local zettel.
+func (r *Reference) IsZettel() bool {
+ switch r.State {
+ case RefStateZettel, RefStateSelf, RefStateFound, RefStateBroken:
+ return true
+ }
+ return false
+}
+
+// IsLocal returns true if reference is local
+func (r *Reference) IsLocal() bool {
+ return r.State == RefStateHosted || r.State == RefStateBased
+}
+
+// IsExternal returns true if it is a referencen to external material.
+func (r *Reference) IsExternal() bool { return r.State == RefStateExternal }
ADDED internal/ast/ref_test.go
Index: internal/ast/ref_test.go
==================================================================
--- /dev/null
+++ internal/ast/ref_test.go
@@ -0,0 +1,98 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package ast_test
+
+import (
+ "testing"
+
+ "zettelstore.de/z/internal/ast"
+)
+
+func TestParseReference(t *testing.T) {
+ t.Parallel()
+ testcases := []struct {
+ link string
+ err bool
+ exp string
+ }{
+ {"", true, ""},
+ {"123", false, "123"},
+ {",://", true, ""},
+ }
+
+ for i, tc := range testcases {
+ got := ast.ParseReference(tc.link)
+ if got.IsValid() == tc.err {
+ t.Errorf(
+ "TC=%d, expected parse error of %q: %v, but got %q", i, tc.link, tc.err, got)
+ }
+ if got.IsValid() && got.String() != tc.exp {
+ t.Errorf("TC=%d, Reference of %q is %q, but got %q", i, tc.link, tc.exp, got)
+ }
+ }
+}
+
+func TestReferenceIsZettelMaterial(t *testing.T) {
+ t.Parallel()
+ testcases := []struct {
+ link string
+ isZettel bool
+ isExternal bool
+ isLocal bool
+ }{
+ {"", false, false, false},
+ {"00000000000000", false, false, false},
+ {"http://zettelstore.de/z/ast", false, true, false},
+ {"12345678901234", true, false, false},
+ {"12345678901234#local", true, false, false},
+ {"http://12345678901234", false, true, false},
+ {"http://zettelstore.de/z/12345678901234", false, true, false},
+ {"http://zettelstore.de/12345678901234", false, true, false},
+ {"/12345678901234", false, false, true},
+ {"//12345678901234", false, false, true},
+ {"./12345678901234", false, false, true},
+ {"../12345678901234", false, false, true},
+ {".../12345678901234", false, true, false},
+ }
+
+ for i, tc := range testcases {
+ ref := ast.ParseReference(tc.link)
+ isZettel := ref.IsZettel()
+ if isZettel != tc.isZettel {
+ t.Errorf(
+ "TC=%d, Reference %q isZettel=%v expected, but got %v",
+ i,
+ tc.link,
+ tc.isZettel,
+ isZettel)
+ }
+ isLocal := ref.IsLocal()
+ if isLocal != tc.isLocal {
+ t.Errorf(
+ "TC=%d, Reference %q isLocal=%v expected, but got %v",
+ i,
+ tc.link,
+ tc.isLocal, isLocal)
+ }
+ isExternal := ref.IsExternal()
+ if isExternal != tc.isExternal {
+ t.Errorf(
+ "TC=%d, Reference %q isExternal=%v expected, but got %v",
+ i,
+ tc.link,
+ tc.isExternal,
+ isExternal)
+ }
+ }
+}
ADDED internal/ast/sztrans/sztrans.go
Index: internal/ast/sztrans/sztrans.go
==================================================================
--- /dev/null
+++ internal/ast/sztrans/sztrans.go
@@ -0,0 +1,651 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2025-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2025-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package sztrans allows to transform a sz representation of text into an
+// abstract syntax tree.
+package sztrans
+
+import (
+ "fmt"
+ "log"
+
+ "t73f.de/r/sx"
+ "t73f.de/r/zsc/sz"
+ "t73f.de/r/zsx"
+
+ "zettelstore.de/z/internal/ast"
+)
+
+type transformer struct{}
+
+// GetBlockSlice returns the sz representations as a AST BlockSlice
+func GetBlockSlice(pair *sx.Pair) (ast.BlockSlice, error) {
+ if pair == nil {
+ return nil, nil
+ }
+ var t transformer
+ if obj := zsx.Walk(&t, pair, nil); !obj.IsNil() {
+ if sxn, isNode := obj.(sxNode); isNode {
+ if bs, ok := sxn.node.(*ast.BlockSlice); ok {
+ return *bs, nil
+ }
+ return nil, fmt.Errorf("no BlockSlice AST: %T/%v for %v", sxn.node, sxn.node, pair)
+ }
+ return nil, fmt.Errorf("no AST for %v: %v", pair, obj)
+ }
+ return nil, fmt.Errorf("error walking %v", pair)
+}
+
+func (t *transformer) VisitBefore(pair *sx.Pair, _ *sx.Pair) (sx.Object, bool) {
+ if sym, isSymbol := sx.GetSymbol(pair.Car()); isSymbol {
+ switch sym {
+ case zsx.SymText:
+ if p := pair.Tail(); p != nil {
+ if s, isString := sx.GetString(p.Car()); isString {
+ return sxNode{&ast.TextNode{Text: s.GetValue()}}, true
+ }
+ }
+ case zsx.SymSoft:
+ return sxNode{&ast.BreakNode{Hard: false}}, true
+ case zsx.SymHard:
+ return sxNode{&ast.BreakNode{Hard: true}}, true
+ case zsx.SymLiteralCode:
+ return handleLiteral(ast.LiteralCode, pair.Tail())
+ case zsx.SymLiteralComment:
+ return handleLiteral(ast.LiteralComment, pair.Tail())
+ case zsx.SymLiteralInput:
+ return handleLiteral(ast.LiteralInput, pair.Tail())
+ case zsx.SymLiteralMath:
+ return handleLiteral(ast.LiteralMath, pair.Tail())
+ case zsx.SymLiteralOutput:
+ return handleLiteral(ast.LiteralOutput, pair.Tail())
+ case zsx.SymThematic:
+ return sxNode{&ast.HRuleNode{Attrs: zsx.GetAttributes(pair.Tail().Head())}}, true
+ case zsx.SymVerbatimComment:
+ return handleVerbatim(ast.VerbatimComment, pair.Tail())
+ case zsx.SymVerbatimEval:
+ return handleVerbatim(ast.VerbatimEval, pair.Tail())
+ case zsx.SymVerbatimHTML:
+ return handleVerbatim(ast.VerbatimHTML, pair.Tail())
+ case zsx.SymVerbatimMath:
+ return handleVerbatim(ast.VerbatimMath, pair.Tail())
+ case zsx.SymVerbatimCode:
+ return handleVerbatim(ast.VerbatimCode, pair.Tail())
+ case zsx.SymVerbatimZettel:
+ return handleVerbatim(ast.VerbatimZettel, pair.Tail())
+ }
+ }
+ return sx.Nil(), false
+}
+
+func handleLiteral(kind ast.LiteralKind, rest *sx.Pair) (sx.Object, bool) {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ if s, isString := sx.GetString(curr.Car()); isString {
+ return sxNode{&ast.LiteralNode{
+ Kind: kind,
+ Attrs: attrs,
+ Content: []byte(s.GetValue())}}, true
+ }
+ }
+ }
+ return nil, false
+}
+
+func handleVerbatim(kind ast.VerbatimKind, rest *sx.Pair) (sx.Object, bool) {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ if s, isString := sx.GetString(curr.Car()); isString {
+ return sxNode{&ast.VerbatimNode{
+ Kind: kind,
+ Attrs: attrs,
+ Content: []byte(s.GetValue()),
+ }}, true
+ }
+ }
+ }
+ return nil, false
+}
+
+func (t *transformer) VisitAfter(pair *sx.Pair, _ *sx.Pair) sx.Object {
+ if sym, isSymbol := sx.GetSymbol(pair.Car()); isSymbol {
+ switch sym {
+ case zsx.SymBlock:
+ bns := collectBlocks(pair.Tail())
+ return sxNode{&bns}
+ case zsx.SymPara:
+ return sxNode{&ast.ParaNode{Inlines: collectInlines(pair.Tail())}}
+ case zsx.SymHeading:
+ return handleHeading(pair.Tail())
+ case zsx.SymListOrdered:
+ return handleList(ast.NestedListOrdered, pair.Tail())
+ case zsx.SymListUnordered:
+ return handleList(ast.NestedListUnordered, pair.Tail())
+ case zsx.SymListQuote:
+ return handleList(ast.NestedListQuote, pair.Tail())
+ case zsx.SymDescription:
+ return handleDescription(pair.Tail())
+ case zsx.SymTable:
+ return handleTable(pair.Tail())
+ case zsx.SymCell:
+ return handleCell(pair.Tail())
+ case zsx.SymRegionBlock:
+ return handleRegion(ast.RegionSpan, pair.Tail())
+ case zsx.SymRegionQuote:
+ return handleRegion(ast.RegionQuote, pair.Tail())
+ case zsx.SymRegionVerse:
+ return handleRegion(ast.RegionVerse, pair.Tail())
+ case zsx.SymTransclude:
+ return handleTransclude(pair.Tail())
+ case zsx.SymBLOB:
+ return handleBLOB(pair.Tail())
+
+ case zsx.SymLink:
+ return handleLink(pair.Tail())
+ case zsx.SymEmbed:
+ return handleEmbed(pair.Tail())
+ case zsx.SymEmbedBLOB:
+ return handleEmbedBLOB(pair.Tail())
+ case zsx.SymCite:
+ return handleCite(pair.Tail())
+ case zsx.SymMark:
+ return handleMark(pair.Tail())
+ case zsx.SymEndnote:
+ return handleEndnote(pair.Tail())
+ case zsx.SymFormatDelete:
+ return handleFormat(ast.FormatDelete, pair.Tail())
+ case zsx.SymFormatEmph:
+ return handleFormat(ast.FormatEmph, pair.Tail())
+ case zsx.SymFormatInsert:
+ return handleFormat(ast.FormatInsert, pair.Tail())
+ case zsx.SymFormatMark:
+ return handleFormat(ast.FormatMark, pair.Tail())
+ case zsx.SymFormatQuote:
+ return handleFormat(ast.FormatQuote, pair.Tail())
+ case zsx.SymFormatSpan:
+ return handleFormat(ast.FormatSpan, pair.Tail())
+ case zsx.SymFormatSub:
+ return handleFormat(ast.FormatSub, pair.Tail())
+ case zsx.SymFormatSuper:
+ return handleFormat(ast.FormatSuper, pair.Tail())
+ case zsx.SymFormatStrong:
+ return handleFormat(ast.FormatStrong, pair.Tail())
+ }
+ log.Println("MISS", pair)
+ }
+ return pair
+}
+
+func collectBlocks(lst *sx.Pair) (result ast.BlockSlice) {
+ for val := range lst.Values() {
+ if sxn, isNode := val.(sxNode); isNode {
+ if bn, isInline := sxn.node.(ast.BlockNode); isInline {
+ result = append(result, bn)
+ }
+ }
+ }
+ return result
+}
+
+func collectInlines(lst *sx.Pair) (result ast.InlineSlice) {
+ for val := range lst.Values() {
+ if sxn, isNode := val.(sxNode); isNode {
+ if in, isInline := sxn.node.(ast.InlineNode); isInline {
+ result = append(result, in)
+ }
+ }
+ }
+ return result
+}
+
+func handleHeading(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ if num, isNumber := rest.Car().(sx.Int64); isNumber && num > 0 && num < 6 {
+ if curr := rest.Tail(); curr != nil {
+ attrs := zsx.GetAttributes(curr.Head())
+ if curr = curr.Tail(); curr != nil {
+ if sSlug, isSlug := sx.GetString(curr.Car()); isSlug {
+ if curr = curr.Tail(); curr != nil {
+ if sUniq, isUniq := sx.GetString(curr.Car()); isUniq {
+ return sxNode{&ast.HeadingNode{
+ Level: int(num),
+ Attrs: attrs,
+ Slug: sSlug.GetValue(),
+ Fragment: sUniq.GetValue(),
+ Inlines: collectInlines(curr.Tail()),
+ }}
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ log.Println("HEAD", rest)
+ return rest
+}
+
+func handleList(kind ast.NestedListKind, rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ return sxNode{&ast.NestedListNode{
+ Kind: kind,
+ Items: collectItemSlices(rest.Tail()),
+ Attrs: attrs}}
+ }
+ log.Println("LIST", kind, rest)
+ return rest
+}
+
+func collectItemSlices(lst *sx.Pair) (result []ast.ItemSlice) {
+ for val := range lst.Values() {
+ if sxn, isNode := val.(sxNode); isNode {
+ if bns, isBlockSlice := sxn.node.(*ast.BlockSlice); isBlockSlice {
+ items := make(ast.ItemSlice, len(*bns))
+ for i, bn := range *bns {
+ if it, ok := bn.(ast.ItemNode); ok {
+ items[i] = it
+ }
+ }
+ result = append(result, items)
+ }
+ if ins, isInline := sxn.node.(*ast.InlineSlice); isInline {
+ items := make(ast.ItemSlice, len(*ins))
+ for i, bn := range *ins {
+ if it, ok := bn.(ast.ItemNode); ok {
+ items[i] = it
+ }
+ }
+ result = append(result, items)
+ }
+ }
+ }
+ return result
+}
+
+func handleDescription(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ var descs []ast.Description
+ for curr := rest.Tail(); curr != nil; {
+ term := collectInlines(curr.Head())
+ curr = curr.Tail()
+ if curr == nil {
+ descr := ast.Description{Term: term, Descriptions: nil}
+ descs = append(descs, descr)
+ break
+ }
+
+ car := curr.Car()
+ if sx.IsNil(car) {
+ descs = append(descs, ast.Description{Term: term, Descriptions: nil})
+ curr = curr.Tail()
+ continue
+ }
+
+ sxn, isNode := car.(sxNode)
+ if !isNode {
+ descs = nil
+ break
+ }
+ blocks, isBlocks := sxn.node.(*ast.BlockSlice)
+ if !isBlocks {
+ descs = nil
+ break
+ }
+
+ descSlice := make([]ast.DescriptionSlice, 0, len(*blocks))
+ for _, bn := range *blocks {
+ bns, isBns := bn.(*ast.BlockSlice)
+ if !isBns {
+ continue
+ }
+ ds := make(ast.DescriptionSlice, 0, len(*bns))
+ for _, b := range *bns {
+ if defNode, isDef := b.(ast.DescriptionNode); isDef {
+ ds = append(ds, defNode)
+ }
+ }
+ descSlice = append(descSlice, ds)
+ }
+
+ descr := ast.Description{Term: term, Descriptions: descSlice}
+ descs = append(descs, descr)
+
+ curr = curr.Tail()
+ }
+ if len(descs) > 0 {
+ return sxNode{&ast.DescriptionListNode{
+ Attrs: attrs,
+ Descriptions: descs,
+ }}
+ }
+ }
+ log.Println("DESC", rest)
+ return rest
+}
+
+func handleTable(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ header := collectRow(rest.Head())
+ cols := len(header)
+
+ var rows []ast.TableRow
+ for curr := range rest.Tail().Pairs() {
+ row := collectRow(curr.Head())
+ rows = append(rows, row)
+ cols = max(cols, len(row))
+ }
+ align := make([]ast.Alignment, cols)
+ for i := range cols {
+ align[i] = ast.AlignDefault
+ }
+
+ return sxNode{&ast.TableNode{
+ Header: header,
+ Align: align,
+ Rows: rows,
+ }}
+ }
+ log.Println("TABL", rest)
+ return rest
+}
+
+func collectRow(lst *sx.Pair) (row ast.TableRow) {
+ for curr := range lst.Values() {
+ if sxn, isNode := curr.(sxNode); isNode {
+ if cell, isCell := sxn.node.(*ast.TableCell); isCell {
+ row = append(row, cell)
+ }
+ }
+ }
+ return row
+}
+
+func handleCell(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ align := ast.AlignDefault
+ if alignPair := rest.Head().Assoc(zsx.SymAttrAlign); alignPair != nil {
+ if alignValue := alignPair.Cdr(); zsx.AttrAlignCenter.IsEqual(alignValue) {
+ align = ast.AlignCenter
+ } else if zsx.AttrAlignLeft.IsEqual(alignValue) {
+ align = ast.AlignLeft
+ } else if zsx.AttrAlignRight.IsEqual(alignValue) {
+ align = ast.AlignRight
+ }
+ }
+ return sxNode{&ast.TableCell{
+ Align: align,
+ Inlines: collectInlines(rest.Tail()),
+ }}
+ }
+ log.Println("CELL", rest)
+ return rest
+}
+
+func handleRegion(kind ast.RegionKind, rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ if blockList := curr.Head(); blockList != nil {
+ return sxNode{&ast.RegionNode{
+ Kind: kind,
+ Attrs: attrs,
+ Blocks: collectBlocks(blockList),
+ Inlines: collectInlines(curr.Tail()),
+ }}
+ }
+ }
+ }
+ log.Println("REGI", rest)
+ return rest
+}
+
+func handleTransclude(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ ref := collectReference(curr.Head())
+ return sxNode{&ast.TranscludeNode{
+ Attrs: attrs,
+ Ref: ref,
+ Inlines: collectInlines(curr.Tail()),
+ }}
+ }
+ }
+ log.Println("TRAN", rest)
+ return rest
+}
+
+func handleBLOB(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ ins := collectInlines(curr.Head())
+ if curr = curr.Tail(); curr != nil {
+ if syntax, isString := sx.GetString(curr.Car()); isString {
+ if curr = curr.Tail(); curr != nil {
+ if blob, isBlob := sx.GetString(curr.Car()); isBlob {
+ return sxNode{&ast.BLOBNode{
+ Attrs: attrs,
+ Description: ins,
+ Syntax: syntax.GetValue(),
+ Blob: []byte(blob.GetValue()),
+ }}
+
+ }
+ }
+ }
+ }
+ }
+ }
+ log.Println("BLOB", rest)
+ return rest
+}
+
+var mapRefState = map[*sx.Symbol]ast.RefState{
+ zsx.SymRefStateInvalid: ast.RefStateInvalid,
+ sz.SymRefStateZettel: ast.RefStateZettel,
+ zsx.SymRefStateSelf: ast.RefStateSelf,
+ sz.SymRefStateFound: ast.RefStateFound,
+ sz.SymRefStateBroken: ast.RefStateBroken,
+ zsx.SymRefStateHosted: ast.RefStateHosted,
+ sz.SymRefStateBased: ast.RefStateBased,
+ sz.SymRefStateQuery: ast.RefStateQuery,
+ zsx.SymRefStateExternal: ast.RefStateExternal,
+}
+
+func handleLink(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ if szref := curr.Head(); szref != nil {
+ if stateSym, isSym := sx.GetSymbol(szref.Car()); isSym {
+ refval, isString := sx.GetString(szref.Cdr())
+ if !isString {
+ refval, isString = sx.GetString(szref.Tail().Car())
+ }
+ if isString {
+ ref := ast.ParseReference(refval.GetValue())
+ ref.State = mapRefState[stateSym]
+ ins := collectInlines(curr.Tail())
+ return sxNode{&ast.LinkNode{
+ Attrs: attrs,
+ Ref: ref,
+ Inlines: ins,
+ }}
+ }
+ }
+ }
+ }
+ }
+ log.Println("LINK", rest)
+ return rest
+}
+
+func handleEmbed(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ if ref := collectReference(curr.Head()); ref != nil {
+ if curr = curr.Tail(); curr != nil {
+ if syntax, isString := sx.GetString(curr.Car()); isString {
+ return sxNode{&ast.EmbedRefNode{
+ Attrs: attrs,
+ Ref: ref,
+ Syntax: syntax.GetValue(),
+ Inlines: collectInlines(curr.Tail()),
+ }}
+ }
+ }
+ }
+ }
+ }
+ log.Println("EMBE", rest)
+ return rest
+}
+
+func handleEmbedBLOB(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ if syntax, isSyntax := sx.GetString(curr.Car()); isSyntax {
+ if curr = curr.Tail(); curr != nil {
+ if content, isContent := sx.GetString(curr.Car()); isContent {
+ return sxNode{&ast.EmbedBLOBNode{
+ Attrs: attrs,
+ Syntax: syntax.GetValue(),
+ Blob: []byte(content.GetValue()),
+ Inlines: collectInlines(curr.Tail()),
+ }}
+ }
+ }
+ }
+ }
+ }
+ log.Println("EMBL", rest)
+ return rest
+}
+
+func collectReference(pair *sx.Pair) *ast.Reference {
+ if pair != nil {
+ if sym, isSymbol := sx.GetSymbol(pair.Car()); isSymbol {
+ if next := pair.Tail(); next != nil {
+ if sRef, isString := sx.GetString(next.Car()); isString {
+ ref := ast.ParseReference(sRef.GetValue())
+ switch sym {
+ case zsx.SymRefStateInvalid:
+ ref.State = ast.RefStateInvalid
+ case sz.SymRefStateZettel:
+ ref.State = ast.RefStateZettel
+ case zsx.SymRefStateSelf:
+ ref.State = ast.RefStateSelf
+ case sz.SymRefStateFound:
+ ref.State = ast.RefStateFound
+ case sz.SymRefStateBroken:
+ ref.State = ast.RefStateBroken
+ case zsx.SymRefStateHosted:
+ ref.State = ast.RefStateHosted
+ case sz.SymRefStateBased:
+ ref.State = ast.RefStateBased
+ case sz.SymRefStateQuery:
+ ref.State = ast.RefStateQuery
+ case zsx.SymRefStateExternal:
+ ref.State = ast.RefStateExternal
+ }
+ return ref
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func handleCite(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ if curr := rest.Tail(); curr != nil {
+ if sKey, isString := sx.GetString(curr.Car()); isString {
+ return sxNode{&ast.CiteNode{
+ Attrs: attrs,
+ Key: sKey.GetValue(),
+ Inlines: collectInlines(curr.Tail()),
+ }}
+ }
+ }
+ }
+ log.Println("CITE", rest)
+ return rest
+}
+
+func handleMark(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ if sMark, isMarkS := sx.GetString(rest.Car()); isMarkS {
+ if curr := rest.Tail(); curr != nil {
+ if sSlug, isSlug := sx.GetString(curr.Car()); isSlug {
+ if curr = curr.Tail(); curr != nil {
+ if sUniq, isUniq := sx.GetString(curr.Car()); isUniq {
+ return sxNode{&ast.MarkNode{
+ Mark: sMark.GetValue(),
+ Slug: sSlug.GetValue(),
+ Fragment: sUniq.GetValue(),
+ Inlines: collectInlines(curr.Tail()),
+ }}
+ }
+ }
+ }
+ }
+ }
+ }
+ log.Println("MARK", rest)
+ return rest
+}
+
+func handleEndnote(rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ return sxNode{&ast.FootnoteNode{
+ Attrs: attrs,
+ Inlines: collectInlines(rest.Tail()),
+ }}
+ }
+ log.Println("ENDN", rest)
+ return rest
+}
+
+func handleFormat(kind ast.FormatKind, rest *sx.Pair) sx.Object {
+ if rest != nil {
+ attrs := zsx.GetAttributes(rest.Head())
+ return sxNode{&ast.FormatNode{
+ Kind: kind,
+ Attrs: attrs,
+ Inlines: collectInlines(rest.Tail()),
+ }}
+ }
+ log.Println("FORM", kind, rest)
+ return rest
+}
+
+type sxNode struct {
+ node ast.Node
+}
+
+func (sxNode) IsNil() bool { return false }
+func (sxNode) IsAtom() bool { return true }
+func (n sxNode) String() string { return fmt.Sprintf("%T/%v", n.node, n.node) }
+func (n sxNode) GoString() string { return n.String() }
+func (n sxNode) IsEqual(other sx.Object) bool {
+ return n.String() == other.String()
+}
ADDED internal/ast/walk.go
Index: internal/ast/walk.go
==================================================================
--- /dev/null
+++ internal/ast/walk.go
@@ -0,0 +1,48 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package ast
+
+// Visitor is a visitor for walking the AST.
+type Visitor interface {
+ Visit(node Node) Visitor
+}
+
+// Walk traverses the AST.
+func Walk(v Visitor, node Node) {
+ if v = v.Visit(node); v == nil {
+ return
+ }
+
+ // Implementation note:
+ // It is much faster to use interface dispatching than to use a switch statement.
+ // On my "cpu: Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz", a switch statement
+ // implementation tooks approx 940-980 ns/op. Interface dispatching is in the
+ // range of 900-930 ns/op.
+ node.WalkChildren(v)
+ v.Visit(nil)
+}
+
+// WalkItemSlice traverses an item slice.
+func WalkItemSlice(v Visitor, ins ItemSlice) {
+ for _, in := range ins {
+ Walk(v, in)
+ }
+}
+
+// WalkDescriptionSlice traverses an item slice.
+func WalkDescriptionSlice(v Visitor, dns DescriptionSlice) {
+ for _, dn := range dns {
+ Walk(v, dn)
+ }
+}
ADDED internal/ast/walk_test.go
Index: internal/ast/walk_test.go
==================================================================
--- /dev/null
+++ internal/ast/walk_test.go
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package ast_test
+
+import (
+ "testing"
+
+ "t73f.de/r/zsx"
+
+ "zettelstore.de/z/internal/ast"
+)
+
+func BenchmarkWalk(b *testing.B) {
+ root := ast.BlockSlice{
+ &ast.HeadingNode{
+ Inlines: ast.InlineSlice{&ast.TextNode{Text: "A Simple Heading"}},
+ },
+ &ast.ParaNode{
+ Inlines: ast.InlineSlice{&ast.TextNode{Text: "This is the introduction."}},
+ },
+ &ast.NestedListNode{
+ Kind: ast.NestedListUnordered,
+ Items: []ast.ItemSlice{
+ []ast.ItemNode{
+ &ast.ParaNode{
+ Inlines: ast.InlineSlice{&ast.TextNode{Text: "Item 1"}},
+ },
+ },
+ []ast.ItemNode{
+ &ast.ParaNode{
+ Inlines: ast.InlineSlice{&ast.TextNode{Text: "Item 2"}},
+ },
+ },
+ },
+ },
+ &ast.ParaNode{
+ Inlines: ast.InlineSlice{&ast.TextNode{Text: "This is some intermediate text."}},
+ },
+ ast.CreateParaNode(
+ &ast.FormatNode{
+ Kind: ast.FormatEmph,
+ Attrs: zsx.Attributes(map[string]string{
+ "": "class",
+ "color": "green",
+ }),
+ Inlines: ast.InlineSlice{&ast.TextNode{Text: "This is some emphasized text."}},
+ },
+ &ast.TextNode{Text: " "},
+ &ast.LinkNode{
+ Ref: &ast.Reference{Value: "http://zettelstore.de"},
+ Inlines: ast.InlineSlice{&ast.TextNode{Text: "URL text."}},
+ },
+ ),
+ }
+ v := benchVisitor{}
+
+ for b.Loop() {
+ ast.Walk(&v, &root)
+ }
+}
+
+type benchVisitor struct{}
+
+func (bv *benchVisitor) Visit(ast.Node) ast.Visitor { return bv }
ADDED internal/auth/auth.go
Index: internal/auth/auth.go
==================================================================
--- /dev/null
+++ internal/auth/auth.go
@@ -0,0 +1,104 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package auth provides services for authentification / authorization.
+package auth
+
+import (
+ "time"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/config"
+)
+
+// BaseManager allows to check some base auth modes.
+type BaseManager interface {
+ // IsReadonly returns true, if the systems is configured to run in read-only-mode.
+ IsReadonly() bool
+}
+
+// TokenManager provides methods to create authentication
+type TokenManager interface {
+
+ // GetToken produces a authentication token.
+ GetToken(ident *meta.Meta, d time.Duration, kind TokenKind) ([]byte, error)
+
+ // CheckToken checks the validity of the token and returns relevant data.
+ CheckToken(token []byte, k TokenKind) (TokenData, error)
+}
+
+// TokenKind specifies for which application / usage a token is/was requested.
+type TokenKind int
+
+// Allowed values of token kind
+const (
+ _ TokenKind = iota
+ KindAPI
+ KindwebUI
+)
+
+// TokenData contains some important elements from a token.
+type TokenData struct {
+ Token []byte
+ Now time.Time
+ Issued time.Time
+ Expires time.Time
+ Ident string
+ Zid id.Zid
+}
+
+// AuthzManager provides methods for authorization.
+type AuthzManager interface {
+ BaseManager
+
+ // Owner returns the zettel identifier of the owner.
+ Owner() id.Zid
+
+ // IsOwner returns true, if the given zettel identifier is that of the owner.
+ IsOwner(zid id.Zid) bool
+
+ // Returns true if authentication is enabled.
+ WithAuth() bool
+
+ // GetUserRole role returns the user role of the given user zettel.
+ GetUserRole(user *meta.Meta) meta.UserRole
+}
+
+// Manager is the main interface for providing the service.
+type Manager interface {
+ TokenManager
+ AuthzManager
+
+ BoxWithPolicy(unprotectedBox box.Box, rtConfig config.Config) (box.Box, Policy)
+}
+
+// Policy is an interface for checking access authorization.
+type Policy interface {
+ // User is allowed to create a new zettel.
+ CanCreate(user, newMeta *meta.Meta) bool
+
+ // User is allowed to read zettel
+ CanRead(user, m *meta.Meta) bool
+
+ // User is allowed to write zettel.
+ CanWrite(user, oldMeta, newMeta *meta.Meta) bool
+
+ // User is allowed to delete zettel.
+ CanDelete(user, m *meta.Meta) bool
+
+ // User is allowed to refresh box data.
+ CanRefresh(user *meta.Meta) bool
+}
ADDED internal/auth/cred/cred.go
Index: internal/auth/cred/cred.go
==================================================================
--- /dev/null
+++ internal/auth/cred/cred.go
@@ -0,0 +1,57 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package cred provides some function for handling credentials.
+package cred
+
+import (
+ "bytes"
+
+ "golang.org/x/crypto/bcrypt"
+
+ "t73f.de/r/zsc/domain/id"
+)
+
+// HashCredential returns a hashed vesion of the given credential
+func HashCredential(zid id.Zid, ident, credential string) (string, error) {
+ fullCredential := createFullCredential(zid, ident, credential)
+ res, err := bcrypt.GenerateFromPassword(fullCredential, bcrypt.DefaultCost)
+ if err != nil {
+ return "", err
+ }
+ return string(res), nil
+}
+
+// CompareHashAndCredential checks, whether the hashed credential is a possible
+// value when hashing the credential.
+func CompareHashAndCredential(hashed string, zid id.Zid, ident, credential string) (bool, error) {
+ fullCredential := createFullCredential(zid, ident, credential)
+ err := bcrypt.CompareHashAndPassword([]byte(hashed), fullCredential)
+ if err == nil {
+ return true, nil
+ }
+ if err == bcrypt.ErrMismatchedHashAndPassword {
+ return false, nil
+ }
+ return false, err
+}
+
+func createFullCredential(zid id.Zid, ident, credential string) []byte {
+ var buf bytes.Buffer
+ buf.Write(zid.Bytes())
+ buf.WriteByte(' ')
+ buf.WriteString(ident)
+ buf.WriteByte(' ')
+ buf.WriteString(credential)
+ return buf.Bytes()
+}
ADDED internal/auth/impl/digest.go
Index: internal/auth/impl/digest.go
==================================================================
--- /dev/null
+++ internal/auth/impl/digest.go
@@ -0,0 +1,89 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2023-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2023-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package impl
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/hmac"
+ "encoding/base64"
+
+ "t73f.de/r/sx"
+ "t73f.de/r/sx/sxreader"
+)
+
+var encoding = base64.RawURLEncoding
+
+const digestAlg = crypto.SHA384
+
+func sign(claim sx.Object, secret []byte) ([]byte, error) {
+ var buf bytes.Buffer
+ _, err := sx.Print(&buf, claim)
+ if err != nil {
+ return nil, err
+ }
+ token := make([]byte, encoding.EncodedLen(buf.Len()))
+ encoding.Encode(token, buf.Bytes())
+
+ digest := hmac.New(digestAlg.New, secret)
+ _, err = digest.Write(buf.Bytes())
+ if err != nil {
+ return nil, err
+ }
+ dig := digest.Sum(nil)
+ encDig := make([]byte, encoding.EncodedLen(len(dig)))
+ encoding.Encode(encDig, dig)
+
+ token = append(token, '.')
+ token = append(token, encDig...)
+ return token, nil
+}
+
+func check(token []byte, secret []byte) (sx.Object, error) {
+ i := bytes.IndexByte(token, '.')
+ if i <= 0 || 1024 < i {
+ return nil, ErrMalformedToken
+ }
+ buf := make([]byte, len(token))
+ n, err := encoding.Decode(buf, token[:i])
+ if err != nil {
+ return nil, err
+ }
+ rdr := sxreader.MakeReader(bytes.NewReader(buf[:n]))
+ obj, err := rdr.Read()
+ if err != nil {
+ return nil, err
+ }
+
+ var objBuf bytes.Buffer
+ _, err = sx.Print(&objBuf, obj)
+ if err != nil {
+ return nil, err
+ }
+
+ digest := hmac.New(digestAlg.New, secret)
+ _, err = digest.Write(objBuf.Bytes())
+ if err != nil {
+ return nil, err
+ }
+
+ n, err = encoding.Decode(buf, token[i+1:])
+ if err != nil {
+ return nil, err
+ }
+ if !hmac.Equal(buf[:n], digest.Sum(nil)) {
+ return nil, ErrMalformedToken
+ }
+ return obj, nil
+}
ADDED internal/auth/impl/impl.go
Index: internal/auth/impl/impl.go
==================================================================
--- /dev/null
+++ internal/auth/impl/impl.go
@@ -0,0 +1,180 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package impl provides services for authentification / authorization.
+package impl
+
+import (
+ "errors"
+ "hash/fnv"
+ "io"
+ "time"
+
+ "t73f.de/r/sx"
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "t73f.de/r/zsc/sexp"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/auth/policy"
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/config"
+ "zettelstore.de/z/internal/kernel"
+)
+
+type myAuth struct {
+ readonly bool
+ owner id.Zid
+ secret []byte
+}
+
+// New creates a new auth object.
+func New(readonly bool, owner id.Zid, extSecret string) auth.Manager {
+ return &myAuth{
+ readonly: readonly,
+ owner: owner,
+ secret: calcSecret(extSecret),
+ }
+}
+
+var configKeys = []string{
+ kernel.CoreProgname,
+ kernel.CoreGoVersion,
+ kernel.CoreHostname,
+ kernel.CoreGoOS,
+ kernel.CoreGoArch,
+ kernel.CoreVersion,
+}
+
+func calcSecret(extSecret string) []byte {
+ h := fnv.New128()
+ if extSecret != "" {
+ _, _ = io.WriteString(h, extSecret)
+ }
+ for _, key := range configKeys {
+ _, _ = io.WriteString(h, kernel.Main.GetConfig(kernel.CoreService, key).(string))
+ }
+ return h.Sum(nil)
+}
+
+// IsReadonly returns true, if the systems is configured to run in read-only-mode.
+func (a *myAuth) IsReadonly() bool { return a.readonly }
+
+// ErrMalformedToken signals a broken token.
+var ErrMalformedToken = errors.New("auth: malformed token")
+
+// ErrNoIdent signals that the 'ident' key is missing.
+var ErrNoIdent = errors.New("auth: missing ident")
+
+// ErrOtherKind signals that the token was defined for another token kind.
+var ErrOtherKind = errors.New("auth: wrong token kind")
+
+// ErrNoZid signals that the 'zid' key is missing.
+var ErrNoZid = errors.New("auth: missing zettel id")
+
+// GetToken returns a token to be used for authentification.
+func (a *myAuth) GetToken(ident *meta.Meta, d time.Duration, kind auth.TokenKind) ([]byte, error) {
+ subject, ok := ident.Get(meta.KeyUserID)
+ if !ok || subject == "" {
+ return nil, ErrNoIdent
+ }
+
+ now := time.Now().Round(time.Second)
+ sClaim := sx.MakeList(
+ sx.Int64(kind),
+ sx.MakeString(string(subject)),
+ sx.Int64(now.Unix()),
+ sx.Int64(now.Add(d).Unix()),
+ sx.Int64(ident.Zid),
+ )
+ return sign(sClaim, a.secret)
+}
+
+// ErrTokenExpired signals an exired token
+var ErrTokenExpired = errors.New("auth: token expired")
+
+// CheckToken checks the validity of the token and returns relevant data.
+func (a *myAuth) CheckToken(tok []byte, k auth.TokenKind) (auth.TokenData, error) {
+ var tokenData auth.TokenData
+
+ obj, err := check(tok, a.secret)
+ if err != nil {
+ return tokenData, err
+ }
+
+ tokenData.Token = tok
+ err = setupTokenData(obj, k, &tokenData)
+ return tokenData, err
+}
+
+func setupTokenData(obj sx.Object, k auth.TokenKind, tokenData *auth.TokenData) error {
+ vals, err := sexp.ParseList(obj, "isiii")
+ if err != nil {
+ return ErrMalformedToken
+ }
+ if auth.TokenKind(vals[0].(sx.Int64)) != k {
+ return ErrOtherKind
+ }
+ ident := vals[1].(sx.String).GetValue()
+ if ident == "" {
+ return ErrNoIdent
+ }
+ issued := time.Unix(int64(vals[2].(sx.Int64)), 0)
+ expires := time.Unix(int64(vals[3].(sx.Int64)), 0)
+ now := time.Now().Round(time.Second)
+ if expires.Before(now) {
+ return ErrTokenExpired
+ }
+ zid := id.Zid(vals[4].(sx.Int64))
+ if !zid.IsValid() {
+ return ErrNoZid
+ }
+
+ tokenData.Ident = string(ident)
+ tokenData.Issued = issued
+ tokenData.Now = now
+ tokenData.Expires = expires
+ tokenData.Zid = zid
+ return nil
+}
+
+func (a *myAuth) Owner() id.Zid { return a.owner }
+
+func (a *myAuth) IsOwner(zid id.Zid) bool {
+ return zid.IsValid() && zid == a.owner
+}
+
+func (a *myAuth) WithAuth() bool { return a.owner != id.Invalid }
+
+// GetUserRole role returns the user role of the given user zettel.
+func (a *myAuth) GetUserRole(user *meta.Meta) meta.UserRole {
+ if user == nil {
+ if a.WithAuth() {
+ return meta.UserRoleUnknown
+ }
+ return meta.UserRoleOwner
+ }
+ if a.IsOwner(user.Zid) {
+ return meta.UserRoleOwner
+ }
+ if val, ok := user.Get(meta.KeyUserRole); ok {
+ if ur := val.AsUserRole(); ur != meta.UserRoleUnknown {
+ return ur
+ }
+ }
+ return meta.UserRoleReader
+}
+
+func (a *myAuth) BoxWithPolicy(unprotectedBox box.Box, rtConfig config.Config) (box.Box, auth.Policy) {
+ return policy.BoxWithPolicy(a, unprotectedBox, rtConfig)
+}
ADDED internal/auth/policy/anon.go
Index: internal/auth/policy/anon.go
==================================================================
--- /dev/null
+++ internal/auth/policy/anon.go
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package policy
+
+import (
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/config"
+)
+
+type anonPolicy struct {
+ authConfig config.AuthConfig
+ pre auth.Policy
+}
+
+func (ap *anonPolicy) CanCreate(user, newMeta *meta.Meta) bool {
+ return ap.pre.CanCreate(user, newMeta)
+}
+
+func (ap *anonPolicy) CanRead(user, m *meta.Meta) bool {
+ return ap.pre.CanRead(user, m) && ap.checkVisibility(m)
+}
+
+func (ap *anonPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool {
+ return ap.pre.CanWrite(user, oldMeta, newMeta) && ap.checkVisibility(oldMeta)
+}
+
+func (ap *anonPolicy) CanDelete(user, m *meta.Meta) bool {
+ return ap.pre.CanDelete(user, m) && ap.checkVisibility(m)
+}
+
+func (ap *anonPolicy) CanRefresh(user *meta.Meta) bool {
+ if ap.authConfig.GetExpertMode() || ap.authConfig.GetSimpleMode() {
+ return true
+ }
+ return ap.pre.CanRefresh(user)
+}
+
+func (ap *anonPolicy) checkVisibility(m *meta.Meta) bool {
+ if ap.authConfig.GetVisibility(m) == meta.VisibilityExpert {
+ return ap.authConfig.GetExpertMode()
+ }
+ return true
+}
ADDED internal/auth/policy/box.go
Index: internal/auth/policy/box.go
==================================================================
--- /dev/null
+++ internal/auth/policy/box.go
@@ -0,0 +1,157 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package policy
+
+import (
+ "context"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/auth/user"
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/config"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+// BoxWithPolicy wraps the given box inside a policy box.
+func BoxWithPolicy(manager auth.AuthzManager, box box.Box, authConfig config.AuthConfig) (box.Box, auth.Policy) {
+ pol := newPolicy(manager, authConfig)
+ return newBox(box, pol), pol
+}
+
+// polBox implements a policy box.
+type polBox struct {
+ box box.Box
+ policy auth.Policy
+}
+
+// newBox creates a new policy box.
+func newBox(box box.Box, policy auth.Policy) box.Box {
+ return &polBox{
+ box: box,
+ policy: policy,
+ }
+}
+
+func (pp *polBox) Location() string {
+ return pp.box.Location()
+}
+
+func (pp *polBox) CanCreateZettel(ctx context.Context) bool {
+ return pp.box.CanCreateZettel(ctx)
+}
+
+func (pp *polBox) CreateZettel(ctx context.Context, zettel zettel.Zettel) (id.Zid, error) {
+ user := user.GetCurrentUser(ctx)
+ if pp.policy.CanCreate(user, zettel.Meta) {
+ return pp.box.CreateZettel(ctx, zettel)
+ }
+ return id.Invalid, box.NewErrNotAllowed("Create", user, id.Invalid)
+}
+
+func (pp *polBox) GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error) {
+ z, err := pp.box.GetZettel(ctx, zid)
+ if err != nil {
+ return zettel.Zettel{}, err
+ }
+ user := user.GetCurrentUser(ctx)
+ if pp.policy.CanRead(user, z.Meta) {
+ return z, nil
+ }
+ return zettel.Zettel{}, box.NewErrNotAllowed("GetZettel", user, zid)
+}
+
+func (pp *polBox) GetAllZettel(ctx context.Context, zid id.Zid) ([]zettel.Zettel, error) {
+ return pp.box.GetAllZettel(ctx, zid)
+}
+
+func (pp *polBox) FetchZids(ctx context.Context) (*idset.Set, error) {
+ return nil, box.NewErrNotAllowed("fetch-zids", user.GetCurrentUser(ctx), id.Invalid)
+}
+
+func (pp *polBox) GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) {
+ m, err := pp.box.GetMeta(ctx, zid)
+ if err != nil {
+ return nil, err
+ }
+ user := user.GetCurrentUser(ctx)
+ if pp.policy.CanRead(user, m) {
+ return m, nil
+ }
+ return nil, box.NewErrNotAllowed("GetMeta", user, zid)
+}
+
+func (pp *polBox) SelectMeta(ctx context.Context, metaSeq []*meta.Meta, q *query.Query) ([]*meta.Meta, error) {
+ user := user.GetCurrentUser(ctx)
+ canRead := pp.policy.CanRead
+ q = q.SetPreMatch(func(m *meta.Meta) bool { return canRead(user, m) })
+ return pp.box.SelectMeta(ctx, metaSeq, q)
+}
+
+func (pp *polBox) CanUpdateZettel(ctx context.Context, zettel zettel.Zettel) bool {
+ return pp.box.CanUpdateZettel(ctx, zettel)
+}
+
+func (pp *polBox) UpdateZettel(ctx context.Context, zettel zettel.Zettel) error {
+ zid := zettel.Meta.Zid
+ user := user.GetCurrentUser(ctx)
+ if !zid.IsValid() {
+ return box.ErrInvalidZid{Zid: zid.String()}
+ }
+ // Write existing zettel
+ oldZettel, err := pp.box.GetZettel(ctx, zid)
+ if err != nil {
+ return err
+ }
+ if pp.policy.CanWrite(user, oldZettel.Meta, zettel.Meta) {
+ return pp.box.UpdateZettel(ctx, zettel)
+ }
+ return box.NewErrNotAllowed("Write", user, zid)
+}
+
+func (pp *polBox) CanDeleteZettel(ctx context.Context, zid id.Zid) bool {
+ return pp.box.CanDeleteZettel(ctx, zid)
+}
+
+func (pp *polBox) DeleteZettel(ctx context.Context, zid id.Zid) error {
+ z, err := pp.box.GetZettel(ctx, zid)
+ if err != nil {
+ return err
+ }
+ user := user.GetCurrentUser(ctx)
+ if pp.policy.CanDelete(user, z.Meta) {
+ return pp.box.DeleteZettel(ctx, zid)
+ }
+ return box.NewErrNotAllowed("Delete", user, zid)
+}
+
+func (pp *polBox) Refresh(ctx context.Context) error {
+ user := user.GetCurrentUser(ctx)
+ if pp.policy.CanRefresh(user) {
+ return pp.box.Refresh(ctx)
+ }
+ return box.NewErrNotAllowed("Refresh", user, id.Invalid)
+}
+func (pp *polBox) ReIndex(ctx context.Context, zid id.Zid) error {
+ user := user.GetCurrentUser(ctx)
+ if pp.policy.CanRefresh(user) {
+ // If a user is allowed to refresh all data, it it also allowed to re-index a zettel.
+ return pp.box.ReIndex(ctx, zid)
+ }
+ return box.NewErrNotAllowed("ReIndex", user, zid)
+}
ADDED internal/auth/policy/default.go
Index: internal/auth/policy/default.go
==================================================================
--- /dev/null
+++ internal/auth/policy/default.go
@@ -0,0 +1,59 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package policy
+
+import (
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+)
+
+type defaultPolicy struct {
+ manager auth.AuthzManager
+}
+
+func (*defaultPolicy) CanCreate(_, _ *meta.Meta) bool { return true }
+func (*defaultPolicy) CanRead(_, _ *meta.Meta) bool { return true }
+func (d *defaultPolicy) CanWrite(user, oldMeta, _ *meta.Meta) bool {
+ return d.canChange(user, oldMeta)
+}
+func (d *defaultPolicy) CanDelete(user, m *meta.Meta) bool { return d.canChange(user, m) }
+
+func (*defaultPolicy) CanRefresh(user *meta.Meta) bool { return user != nil }
+
+func (d *defaultPolicy) canChange(user, m *meta.Meta) bool {
+ metaRo, ok := m.Get(meta.KeyReadOnly)
+ if !ok {
+ return true
+ }
+ if user == nil {
+ // If we are here, there is no authentication.
+ // See owner.go:CanWrite.
+
+ // No authentication: check for owner-like restriction, because the user
+ // acts as an owner
+ return metaRo != meta.ValueUserRoleOwner && !metaRo.AsBool()
+ }
+
+ userRole := d.manager.GetUserRole(user)
+ switch metaRo {
+ case meta.ValueUserRoleReader:
+ return userRole > meta.UserRoleReader
+ case meta.ValueUserRoleWriter:
+ return userRole > meta.UserRoleWriter
+ case meta.ValueUserRoleOwner:
+ return userRole > meta.UserRoleOwner
+ }
+ return !metaRo.AsBool()
+}
ADDED internal/auth/policy/owner.go
Index: internal/auth/policy/owner.go
==================================================================
--- /dev/null
+++ internal/auth/policy/owner.go
@@ -0,0 +1,156 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package policy
+
+import (
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/config"
+)
+
+type ownerPolicy struct {
+ manager auth.AuthzManager
+ authConfig config.AuthConfig
+ pre auth.Policy
+}
+
+func (o *ownerPolicy) CanCreate(user, newMeta *meta.Meta) bool {
+ if user == nil || !o.pre.CanCreate(user, newMeta) {
+ return false
+ }
+ return o.userIsOwner(user) || o.userCanCreate(user, newMeta)
+}
+
+func (o *ownerPolicy) userCanCreate(user, newMeta *meta.Meta) bool {
+ if o.manager.GetUserRole(user) == meta.UserRoleReader {
+ return false
+ }
+ if _, ok := newMeta.Get(meta.KeyUserID); ok {
+ return false
+ }
+ return true
+}
+
+func (o *ownerPolicy) CanRead(user, m *meta.Meta) bool {
+ // No need to call o.pre.CanRead(user, meta), because it will always return true.
+ // Both the default and the readonly policy allow to read a zettel.
+ vis := o.authConfig.GetVisibility(m)
+ if res, ok := o.checkVisibility(user, vis); ok {
+ return res
+ }
+ return o.userIsOwner(user) || o.userCanRead(user, m, vis)
+}
+
+func (o *ownerPolicy) userCanRead(user, m *meta.Meta, vis meta.Visibility) bool {
+ switch vis {
+ case meta.VisibilityOwner, meta.VisibilityExpert:
+ return false
+ case meta.VisibilityPublic:
+ return true
+ }
+ if user == nil {
+ return false
+ }
+ if _, ok := m.Get(meta.KeyUserID); ok {
+ // Only the user can read its own zettel
+ return user.Zid == m.Zid
+ }
+ switch o.manager.GetUserRole(user) {
+ case meta.UserRoleReader, meta.UserRoleWriter, meta.UserRoleOwner:
+ return true
+ case meta.UserRoleCreator:
+ return vis == meta.VisibilityCreator
+ default:
+ return false
+ }
+}
+
+var noChangeUser = []string{
+ meta.KeyID,
+ meta.KeyRole,
+ meta.KeyUserID,
+ meta.KeyUserRole,
+}
+
+func (o *ownerPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool {
+ if user == nil || !o.pre.CanWrite(user, oldMeta, newMeta) {
+ return false
+ }
+ vis := o.authConfig.GetVisibility(oldMeta)
+ if res, ok := o.checkVisibility(user, vis); ok {
+ return res
+ }
+ if o.userIsOwner(user) {
+ return true
+ }
+ if !o.userCanRead(user, oldMeta, vis) {
+ return false
+ }
+ if _, ok := oldMeta.Get(meta.KeyUserID); ok {
+ // Here we know, that user.Zid == newMeta.Zid (because of userCanRead) and
+ // user.Zid == newMeta.Zid (because oldMeta.Zid == newMeta.Zid)
+ for _, key := range noChangeUser {
+ if oldMeta.GetDefault(key, "") != newMeta.GetDefault(key, "") {
+ return false
+ }
+ }
+ return true
+ }
+ switch userRole := o.manager.GetUserRole(user); userRole {
+ case meta.UserRoleReader, meta.UserRoleCreator:
+ return false
+ }
+ return o.userCanCreate(user, newMeta)
+}
+
+func (o *ownerPolicy) CanDelete(user, m *meta.Meta) bool {
+ if user == nil || !o.pre.CanDelete(user, m) {
+ return false
+ }
+ if res, ok := o.checkVisibility(user, o.authConfig.GetVisibility(m)); ok {
+ return res
+ }
+ return o.userIsOwner(user)
+}
+
+func (o *ownerPolicy) CanRefresh(user *meta.Meta) bool {
+ switch userRole := o.manager.GetUserRole(user); userRole {
+ case meta.UserRoleUnknown:
+ return o.authConfig.GetSimpleMode()
+ case meta.UserRoleCreator:
+ return o.authConfig.GetExpertMode() || o.authConfig.GetSimpleMode()
+ }
+ return true
+}
+
+func (o *ownerPolicy) checkVisibility(user *meta.Meta, vis meta.Visibility) (bool, bool) {
+ if vis == meta.VisibilityExpert {
+ return o.userIsOwner(user) && o.authConfig.GetExpertMode(), true
+ }
+ return false, false
+}
+
+func (o *ownerPolicy) userIsOwner(user *meta.Meta) bool {
+ if user == nil {
+ return false
+ }
+ if o.manager.IsOwner(user.Zid) {
+ return true
+ }
+ if val, ok := user.Get(meta.KeyUserRole); ok && val == meta.ValueUserRoleOwner {
+ return true
+ }
+ return false
+}
ADDED internal/auth/policy/policy.go
Index: internal/auth/policy/policy.go
==================================================================
--- /dev/null
+++ internal/auth/policy/policy.go
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package policy provides some interfaces and implementation for authorizsation policies.
+package policy
+
+import (
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/config"
+)
+
+// newPolicy creates a policy based on given constraints.
+func newPolicy(manager auth.AuthzManager, authConfig config.AuthConfig) auth.Policy {
+ var pol auth.Policy
+ if manager.IsReadonly() {
+ pol = &roPolicy{}
+ } else {
+ pol = &defaultPolicy{manager}
+ }
+ if manager.WithAuth() {
+ pol = &ownerPolicy{
+ manager: manager,
+ authConfig: authConfig,
+ pre: pol,
+ }
+ } else {
+ pol = &anonPolicy{
+ authConfig: authConfig,
+ pre: pol,
+ }
+ }
+ return &prePolicy{pol}
+}
+
+type prePolicy struct {
+ post auth.Policy
+}
+
+func (p *prePolicy) CanCreate(user, newMeta *meta.Meta) bool {
+ return newMeta != nil && p.post.CanCreate(user, newMeta)
+}
+
+func (p *prePolicy) CanRead(user, m *meta.Meta) bool {
+ return m != nil && p.post.CanRead(user, m)
+}
+
+func (p *prePolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool {
+ return oldMeta != nil && newMeta != nil && oldMeta.Zid == newMeta.Zid &&
+ p.post.CanWrite(user, oldMeta, newMeta)
+}
+
+func (p *prePolicy) CanDelete(user, m *meta.Meta) bool {
+ return m != nil && p.post.CanDelete(user, m)
+}
+
+func (p *prePolicy) CanRefresh(user *meta.Meta) bool {
+ return p.post.CanRefresh(user)
+}
ADDED internal/auth/policy/policy_test.go
Index: internal/auth/policy/policy_test.go
==================================================================
--- /dev/null
+++ internal/auth/policy/policy_test.go
@@ -0,0 +1,631 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package policy
+
+import (
+ "fmt"
+ "testing"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+)
+
+func TestPolicies(t *testing.T) {
+ t.Parallel()
+ testScene := []struct {
+ readonly bool
+ withAuth bool
+ expert bool
+ simple bool
+ }{
+ {true, true, true, true},
+ {true, true, true, false},
+ {true, true, false, true},
+ {true, true, false, false},
+ {true, false, true, true},
+ {true, false, true, false},
+ {true, false, false, true},
+ {true, false, false, false},
+ {false, true, true, true},
+ {false, true, true, false},
+ {false, true, false, true},
+ {false, true, false, false},
+ {false, false, true, true},
+ {false, false, true, false},
+ {false, false, false, true},
+ {false, false, false, false},
+ }
+ for _, ts := range testScene {
+ pol := newPolicy(
+ &testAuthzManager{readOnly: ts.readonly, withAuth: ts.withAuth},
+ &authConfig{simple: ts.simple, expert: ts.expert},
+ )
+ name := fmt.Sprintf("readonly=%v/withauth=%v/expert=%v/simple=%v",
+ ts.readonly, ts.withAuth, ts.expert, ts.simple)
+ t.Run(name, func(tt *testing.T) {
+ testCreate(tt, pol, ts.withAuth, ts.readonly)
+ testRead(tt, pol, ts.withAuth, ts.expert)
+ testWrite(tt, pol, ts.withAuth, ts.readonly, ts.expert)
+ testDelete(tt, pol, ts.withAuth, ts.readonly, ts.expert)
+ testRefresh(tt, pol, ts.withAuth, ts.expert, ts.simple)
+ })
+ }
+}
+
+type testAuthzManager struct {
+ readOnly bool
+ withAuth bool
+}
+
+func (a *testAuthzManager) IsReadonly() bool { return a.readOnly }
+func (*testAuthzManager) Owner() id.Zid { return ownerZid }
+func (*testAuthzManager) IsOwner(zid id.Zid) bool { return zid == ownerZid }
+
+func (a *testAuthzManager) WithAuth() bool { return a.withAuth }
+
+func (a *testAuthzManager) GetUserRole(user *meta.Meta) meta.UserRole {
+ if user == nil {
+ if a.WithAuth() {
+ return meta.UserRoleUnknown
+ }
+ return meta.UserRoleOwner
+ }
+ if a.IsOwner(user.Zid) {
+ return meta.UserRoleOwner
+ }
+ if val, ok := user.Get(meta.KeyUserRole); ok {
+ if ur := val.AsUserRole(); ur != meta.UserRoleUnknown {
+ return ur
+ }
+ }
+ return meta.UserRoleReader
+}
+
+type authConfig struct{ simple, expert bool }
+
+func (ac *authConfig) GetSimpleMode() bool { return ac.simple }
+func (ac *authConfig) GetExpertMode() bool { return ac.expert }
+
+func (*authConfig) GetVisibility(m *meta.Meta) meta.Visibility {
+ if val, ok := m.Get(meta.KeyVisibility); ok {
+ return val.AsVisibility()
+ }
+ return meta.VisibilityLogin
+}
+
+func testCreate(t *testing.T, pol auth.Policy, withAuth, readonly bool) {
+ t.Helper()
+ anonUser := newAnon()
+ creator := newCreator()
+ reader := newReader()
+ writer := newWriter()
+ owner := newOwner()
+ owner2 := newOwner2()
+ zettel := newZettel()
+ userZettel := newUserZettel()
+ testCases := []struct {
+ user *meta.Meta
+ meta *meta.Meta
+ exp bool
+ }{
+ // No meta
+ {anonUser, nil, false},
+ {creator, nil, false},
+ {reader, nil, false},
+ {writer, nil, false},
+ {owner, nil, false},
+ {owner2, nil, false},
+ // Ordinary zettel
+ {anonUser, zettel, !withAuth && !readonly},
+ {creator, zettel, !readonly},
+ {reader, zettel, !withAuth && !readonly},
+ {writer, zettel, !readonly},
+ {owner, zettel, !readonly},
+ {owner2, zettel, !readonly},
+ // User zettel
+ {anonUser, userZettel, !withAuth && !readonly},
+ {creator, userZettel, !withAuth && !readonly},
+ {reader, userZettel, !withAuth && !readonly},
+ {writer, userZettel, !withAuth && !readonly},
+ {owner, userZettel, !readonly},
+ {owner2, userZettel, !readonly},
+ }
+ for _, tc := range testCases {
+ t.Run("Create", func(tt *testing.T) {
+ got := pol.CanCreate(tc.user, tc.meta)
+ if tc.exp != got {
+ tt.Errorf("exp=%v, but got=%v", tc.exp, got)
+ }
+ })
+ }
+}
+
+func testRead(t *testing.T, pol auth.Policy, withAuth, expert bool) {
+ t.Helper()
+ anonUser := newAnon()
+ creator := newCreator()
+ reader := newReader()
+ writer := newWriter()
+ owner := newOwner()
+ owner2 := newOwner2()
+ zettel := newZettel()
+ publicZettel := newPublicZettel()
+ creatorZettel := newCreatorZettel()
+ loginZettel := newLoginZettel()
+ ownerZettel := newOwnerZettel()
+ expertZettel := newExpertZettel()
+ userZettel := newUserZettel()
+ testCases := []struct {
+ user *meta.Meta
+ meta *meta.Meta
+ exp bool
+ }{
+ // No meta
+ {anonUser, nil, false},
+ {creator, nil, false},
+ {reader, nil, false},
+ {writer, nil, false},
+ {owner, nil, false},
+ {owner2, nil, false},
+ // Ordinary zettel
+ {anonUser, zettel, !withAuth},
+ {creator, zettel, !withAuth},
+ {reader, zettel, true},
+ {writer, zettel, true},
+ {owner, zettel, true},
+ {owner2, zettel, true},
+ // Public zettel
+ {anonUser, publicZettel, true},
+ {creator, publicZettel, true},
+ {reader, publicZettel, true},
+ {writer, publicZettel, true},
+ {owner, publicZettel, true},
+ {owner2, publicZettel, true},
+ // Creator zettel
+ {anonUser, creatorZettel, !withAuth},
+ {creator, creatorZettel, true},
+ {reader, creatorZettel, true},
+ {writer, creatorZettel, true},
+ {owner, creatorZettel, true},
+ {owner2, creatorZettel, true},
+ // Login zettel
+ {anonUser, loginZettel, !withAuth},
+ {creator, loginZettel, !withAuth},
+ {reader, loginZettel, true},
+ {writer, loginZettel, true},
+ {owner, loginZettel, true},
+ {owner2, loginZettel, true},
+ // Owner zettel
+ {anonUser, ownerZettel, !withAuth},
+ {creator, ownerZettel, !withAuth},
+ {reader, ownerZettel, !withAuth},
+ {writer, ownerZettel, !withAuth},
+ {owner, ownerZettel, true},
+ {owner2, ownerZettel, true},
+ // Expert zettel
+ {anonUser, expertZettel, !withAuth && expert},
+ {creator, expertZettel, !withAuth && expert},
+ {reader, expertZettel, !withAuth && expert},
+ {writer, expertZettel, !withAuth && expert},
+ {owner, expertZettel, expert},
+ {owner2, expertZettel, expert},
+ // Other user zettel
+ {anonUser, userZettel, !withAuth},
+ {creator, userZettel, !withAuth},
+ {reader, userZettel, !withAuth},
+ {writer, userZettel, !withAuth},
+ {owner, userZettel, true},
+ {owner2, userZettel, true},
+ // Own user zettel
+ {creator, creator, true},
+ {reader, reader, true},
+ {writer, writer, true},
+ {owner, owner, true},
+ {owner, owner2, true},
+ {owner2, owner, true},
+ {owner2, owner2, true},
+ }
+ for _, tc := range testCases {
+ t.Run("Read", func(tt *testing.T) {
+ got := pol.CanRead(tc.user, tc.meta)
+ if tc.exp != got {
+ tt.Errorf("exp=%v, but got=%v", tc.exp, got)
+ }
+ })
+ }
+}
+
+func testWrite(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) {
+ t.Helper()
+ anonUser := newAnon()
+ creator := newCreator()
+ reader := newReader()
+ writer := newWriter()
+ owner := newOwner()
+ owner2 := newOwner2()
+ zettel := newZettel()
+ publicZettel := newPublicZettel()
+ loginZettel := newLoginZettel()
+ ownerZettel := newOwnerZettel()
+ expertZettel := newExpertZettel()
+ userZettel := newUserZettel()
+ writerNew := writer.Clone()
+ writerNew.Set(meta.KeyUserRole, owner.GetDefault(meta.KeyUserRole, ""))
+ roFalse := newRoFalseZettel()
+ roTrue := newRoTrueZettel()
+ roReader := newRoReaderZettel()
+ roWriter := newRoWriterZettel()
+ roOwner := newRoOwnerZettel()
+ notAuthNotReadonly := !withAuth && !readonly
+ testCases := []struct {
+ user *meta.Meta
+ old *meta.Meta
+ new *meta.Meta
+ exp bool
+ }{
+ // No old and new meta
+ {anonUser, nil, nil, false},
+ {creator, nil, nil, false},
+ {reader, nil, nil, false},
+ {writer, nil, nil, false},
+ {owner, nil, nil, false},
+ {owner2, nil, nil, false},
+ // No old meta
+ {anonUser, nil, zettel, false},
+ {creator, nil, zettel, false},
+ {reader, nil, zettel, false},
+ {writer, nil, zettel, false},
+ {owner, nil, zettel, false},
+ {owner2, nil, zettel, false},
+ // No new meta
+ {anonUser, zettel, nil, false},
+ {creator, zettel, nil, false},
+ {reader, zettel, nil, false},
+ {writer, zettel, nil, false},
+ {owner, zettel, nil, false},
+ {owner2, zettel, nil, false},
+ // Old an new zettel have different zettel identifier
+ {anonUser, zettel, publicZettel, false},
+ {creator, zettel, publicZettel, false},
+ {reader, zettel, publicZettel, false},
+ {writer, zettel, publicZettel, false},
+ {owner, zettel, publicZettel, false},
+ {owner2, zettel, publicZettel, false},
+ // Overwrite a normal zettel
+ {anonUser, zettel, zettel, notAuthNotReadonly},
+ {creator, zettel, zettel, notAuthNotReadonly},
+ {reader, zettel, zettel, notAuthNotReadonly},
+ {writer, zettel, zettel, !readonly},
+ {owner, zettel, zettel, !readonly},
+ {owner2, zettel, zettel, !readonly},
+ // Public zettel
+ {anonUser, publicZettel, publicZettel, notAuthNotReadonly},
+ {creator, publicZettel, publicZettel, notAuthNotReadonly},
+ {reader, publicZettel, publicZettel, notAuthNotReadonly},
+ {writer, publicZettel, publicZettel, !readonly},
+ {owner, publicZettel, publicZettel, !readonly},
+ {owner2, publicZettel, publicZettel, !readonly},
+ // Login zettel
+ {anonUser, loginZettel, loginZettel, notAuthNotReadonly},
+ {creator, loginZettel, loginZettel, notAuthNotReadonly},
+ {reader, loginZettel, loginZettel, notAuthNotReadonly},
+ {writer, loginZettel, loginZettel, !readonly},
+ {owner, loginZettel, loginZettel, !readonly},
+ {owner2, loginZettel, loginZettel, !readonly},
+ // Owner zettel
+ {anonUser, ownerZettel, ownerZettel, notAuthNotReadonly},
+ {creator, ownerZettel, ownerZettel, notAuthNotReadonly},
+ {reader, ownerZettel, ownerZettel, notAuthNotReadonly},
+ {writer, ownerZettel, ownerZettel, notAuthNotReadonly},
+ {owner, ownerZettel, ownerZettel, !readonly},
+ {owner2, ownerZettel, ownerZettel, !readonly},
+ // Expert zettel
+ {anonUser, expertZettel, expertZettel, notAuthNotReadonly && expert},
+ {creator, expertZettel, expertZettel, notAuthNotReadonly && expert},
+ {reader, expertZettel, expertZettel, notAuthNotReadonly && expert},
+ {writer, expertZettel, expertZettel, notAuthNotReadonly && expert},
+ {owner, expertZettel, expertZettel, !readonly && expert},
+ {owner2, expertZettel, expertZettel, !readonly && expert},
+ // Other user zettel
+ {anonUser, userZettel, userZettel, notAuthNotReadonly},
+ {creator, userZettel, userZettel, notAuthNotReadonly},
+ {reader, userZettel, userZettel, notAuthNotReadonly},
+ {writer, userZettel, userZettel, notAuthNotReadonly},
+ {owner, userZettel, userZettel, !readonly},
+ {owner2, userZettel, userZettel, !readonly},
+ // Own user zettel
+ {creator, creator, creator, !readonly},
+ {reader, reader, reader, !readonly},
+ {writer, writer, writer, !readonly},
+ {owner, owner, owner, !readonly},
+ {owner2, owner2, owner2, !readonly},
+ // Writer cannot change importand metadata of its own user zettel
+ {writer, writer, writerNew, notAuthNotReadonly},
+ // No r/o zettel
+ {anonUser, roFalse, roFalse, notAuthNotReadonly},
+ {creator, roFalse, roFalse, notAuthNotReadonly},
+ {reader, roFalse, roFalse, notAuthNotReadonly},
+ {writer, roFalse, roFalse, !readonly},
+ {owner, roFalse, roFalse, !readonly},
+ {owner2, roFalse, roFalse, !readonly},
+ // Reader r/o zettel
+ {anonUser, roReader, roReader, false},
+ {creator, roReader, roReader, false},
+ {reader, roReader, roReader, false},
+ {writer, roReader, roReader, !readonly},
+ {owner, roReader, roReader, !readonly},
+ {owner2, roReader, roReader, !readonly},
+ // Writer r/o zettel
+ {anonUser, roWriter, roWriter, false},
+ {creator, roWriter, roWriter, false},
+ {reader, roWriter, roWriter, false},
+ {writer, roWriter, roWriter, false},
+ {owner, roWriter, roWriter, !readonly},
+ {owner2, roWriter, roWriter, !readonly},
+ // Owner r/o zettel
+ {anonUser, roOwner, roOwner, false},
+ {creator, roOwner, roOwner, false},
+ {reader, roOwner, roOwner, false},
+ {writer, roOwner, roOwner, false},
+ {owner, roOwner, roOwner, false},
+ {owner2, roOwner, roOwner, false},
+ // r/o = true zettel
+ {anonUser, roTrue, roTrue, false},
+ {creator, roTrue, roTrue, false},
+ {reader, roTrue, roTrue, false},
+ {writer, roTrue, roTrue, false},
+ {owner, roTrue, roTrue, false},
+ {owner2, roTrue, roTrue, false},
+ }
+ for _, tc := range testCases {
+ t.Run("Write", func(tt *testing.T) {
+ got := pol.CanWrite(tc.user, tc.old, tc.new)
+ if tc.exp != got {
+ tt.Errorf("exp=%v, but got=%v", tc.exp, got)
+ }
+ })
+ }
+}
+
+func testDelete(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) {
+ t.Helper()
+ anonUser := newAnon()
+ creator := newCreator()
+ reader := newReader()
+ writer := newWriter()
+ owner := newOwner()
+ owner2 := newOwner2()
+ zettel := newZettel()
+ expertZettel := newExpertZettel()
+ roFalse := newRoFalseZettel()
+ roTrue := newRoTrueZettel()
+ roReader := newRoReaderZettel()
+ roWriter := newRoWriterZettel()
+ roOwner := newRoOwnerZettel()
+ notAuthNotReadonly := !withAuth && !readonly
+ testCases := []struct {
+ user *meta.Meta
+ meta *meta.Meta
+ exp bool
+ }{
+ // No meta
+ {anonUser, nil, false},
+ {creator, nil, false},
+ {reader, nil, false},
+ {writer, nil, false},
+ {owner, nil, false},
+ {owner2, nil, false},
+ // Any zettel
+ {anonUser, zettel, notAuthNotReadonly},
+ {creator, zettel, notAuthNotReadonly},
+ {reader, zettel, notAuthNotReadonly},
+ {writer, zettel, notAuthNotReadonly},
+ {owner, zettel, !readonly},
+ {owner2, zettel, !readonly},
+ // Expert zettel
+ {anonUser, expertZettel, notAuthNotReadonly && expert},
+ {creator, expertZettel, notAuthNotReadonly && expert},
+ {reader, expertZettel, notAuthNotReadonly && expert},
+ {writer, expertZettel, notAuthNotReadonly && expert},
+ {owner, expertZettel, !readonly && expert},
+ {owner2, expertZettel, !readonly && expert},
+ // No r/o zettel
+ {anonUser, roFalse, notAuthNotReadonly},
+ {creator, roFalse, notAuthNotReadonly},
+ {reader, roFalse, notAuthNotReadonly},
+ {writer, roFalse, notAuthNotReadonly},
+ {owner, roFalse, !readonly},
+ {owner2, roFalse, !readonly},
+ // Reader r/o zettel
+ {anonUser, roReader, false},
+ {creator, roReader, false},
+ {reader, roReader, false},
+ {writer, roReader, notAuthNotReadonly},
+ {owner, roReader, !readonly},
+ {owner2, roReader, !readonly},
+ // Writer r/o zettel
+ {anonUser, roWriter, false},
+ {creator, roWriter, false},
+ {reader, roWriter, false},
+ {writer, roWriter, false},
+ {owner, roWriter, !readonly},
+ {owner2, roWriter, !readonly},
+ // Owner r/o zettel
+ {anonUser, roOwner, false},
+ {creator, roOwner, false},
+ {reader, roOwner, false},
+ {writer, roOwner, false},
+ {owner, roOwner, false},
+ {owner2, roOwner, false},
+ // r/o = true zettel
+ {anonUser, roTrue, false},
+ {creator, roTrue, false},
+ {reader, roTrue, false},
+ {writer, roTrue, false},
+ {owner, roTrue, false},
+ {owner2, roTrue, false},
+ }
+ for _, tc := range testCases {
+ t.Run("Delete", func(tt *testing.T) {
+ got := pol.CanDelete(tc.user, tc.meta)
+ if tc.exp != got {
+ tt.Errorf("exp=%v, but got=%v", tc.exp, got)
+ }
+ })
+ }
+}
+
+func testRefresh(t *testing.T, pol auth.Policy, withAuth, expert, simple bool) {
+ t.Helper()
+ testCases := []struct {
+ user *meta.Meta
+ exp bool
+ }{
+ {newAnon(), (!withAuth && expert) || simple},
+ {newCreator(), !withAuth || expert || simple},
+ {newReader(), true},
+ {newWriter(), true},
+ {newOwner(), true},
+ {newOwner2(), true},
+ }
+ for _, tc := range testCases {
+ t.Run("Refresh", func(tt *testing.T) {
+ got := pol.CanRefresh(tc.user)
+ if tc.exp != got {
+ tt.Errorf("exp=%v, but got=%v", tc.exp, got)
+ }
+ })
+ }
+}
+
+const (
+ creatorZid = id.Zid(1013)
+ readerZid = id.Zid(1013)
+ writerZid = id.Zid(1015)
+ ownerZid = id.Zid(1017)
+ owner2Zid = id.Zid(1019)
+ zettelZid = id.Zid(1021)
+ visZid = id.Zid(1023)
+ userZid = id.Zid(1025)
+)
+
+func newAnon() *meta.Meta { return nil }
+func newCreator() *meta.Meta {
+ user := meta.New(creatorZid)
+ user.Set(meta.KeyTitle, "Creator")
+ user.Set(meta.KeyUserID, "ceator")
+ user.Set(meta.KeyUserRole, meta.ValueUserRoleCreator)
+ return user
+}
+func newReader() *meta.Meta {
+ user := meta.New(readerZid)
+ user.Set(meta.KeyTitle, "Reader")
+ user.Set(meta.KeyUserID, "reader")
+ user.Set(meta.KeyUserRole, meta.ValueUserRoleReader)
+ return user
+}
+func newWriter() *meta.Meta {
+ user := meta.New(writerZid)
+ user.Set(meta.KeyTitle, "Writer")
+ user.Set(meta.KeyUserID, "writer")
+ user.Set(meta.KeyUserRole, meta.ValueUserRoleWriter)
+ return user
+}
+func newOwner() *meta.Meta {
+ user := meta.New(ownerZid)
+ user.Set(meta.KeyTitle, "Owner")
+ user.Set(meta.KeyUserID, "owner")
+ user.Set(meta.KeyUserRole, meta.ValueUserRoleOwner)
+ return user
+}
+func newOwner2() *meta.Meta {
+ user := meta.New(owner2Zid)
+ user.Set(meta.KeyTitle, "Owner 2")
+ user.Set(meta.KeyUserID, "owner-2")
+ user.Set(meta.KeyUserRole, meta.ValueUserRoleOwner)
+ return user
+}
+func newZettel() *meta.Meta {
+ m := meta.New(zettelZid)
+ m.Set(meta.KeyTitle, "Any Zettel")
+ return m
+}
+func newPublicZettel() *meta.Meta {
+ m := meta.New(visZid)
+ m.Set(meta.KeyTitle, "Public Zettel")
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityPublic)
+ return m
+}
+func newCreatorZettel() *meta.Meta {
+ m := meta.New(visZid)
+ m.Set(meta.KeyTitle, "Creator Zettel")
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityCreator)
+ return m
+}
+func newLoginZettel() *meta.Meta {
+ m := meta.New(visZid)
+ m.Set(meta.KeyTitle, "Login Zettel")
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityLogin)
+ return m
+}
+func newOwnerZettel() *meta.Meta {
+ m := meta.New(visZid)
+ m.Set(meta.KeyTitle, "Owner Zettel")
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityOwner)
+ return m
+}
+func newExpertZettel() *meta.Meta {
+ m := meta.New(visZid)
+ m.Set(meta.KeyTitle, "Expert Zettel")
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityExpert)
+ return m
+}
+func newRoFalseZettel() *meta.Meta {
+ m := meta.New(zettelZid)
+ m.Set(meta.KeyTitle, "No r/o Zettel")
+ m.Set(meta.KeyReadOnly, meta.ValueFalse)
+ return m
+}
+func newRoTrueZettel() *meta.Meta {
+ m := meta.New(zettelZid)
+ m.Set(meta.KeyTitle, "A r/o Zettel")
+ m.Set(meta.KeyReadOnly, meta.ValueTrue)
+ return m
+}
+func newRoReaderZettel() *meta.Meta {
+ m := meta.New(zettelZid)
+ m.Set(meta.KeyTitle, "Reader r/o Zettel")
+ m.Set(meta.KeyReadOnly, meta.ValueUserRoleReader)
+ return m
+}
+func newRoWriterZettel() *meta.Meta {
+ m := meta.New(zettelZid)
+ m.Set(meta.KeyTitle, "Writer r/o Zettel")
+ m.Set(meta.KeyReadOnly, meta.ValueUserRoleWriter)
+ return m
+}
+func newRoOwnerZettel() *meta.Meta {
+ m := meta.New(zettelZid)
+ m.Set(meta.KeyTitle, "Owner r/o Zettel")
+ m.Set(meta.KeyReadOnly, meta.ValueUserRoleOwner)
+ return m
+}
+func newUserZettel() *meta.Meta {
+ m := meta.New(userZid)
+ m.Set(meta.KeyTitle, "Any User")
+ m.Set(meta.KeyUserID, "any")
+ return m
+}
ADDED internal/auth/policy/readonly.go
Index: internal/auth/policy/readonly.go
==================================================================
--- /dev/null
+++ internal/auth/policy/readonly.go
@@ -0,0 +1,24 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package policy
+
+import "t73f.de/r/zsc/domain/meta"
+
+type roPolicy struct{}
+
+func (*roPolicy) CanCreate(_, _ *meta.Meta) bool { return false }
+func (*roPolicy) CanRead(_, _ *meta.Meta) bool { return true }
+func (*roPolicy) CanWrite(_, _, _ *meta.Meta) bool { return false }
+func (*roPolicy) CanDelete(_, _ *meta.Meta) bool { return false }
+func (*roPolicy) CanRefresh(user *meta.Meta) bool { return user != nil }
ADDED internal/auth/user/user.go
Index: internal/auth/user/user.go
==================================================================
--- /dev/null
+++ internal/auth/user/user.go
@@ -0,0 +1,71 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2025-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2025-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package user provides services for working with user data.
+package user
+
+import (
+ "context"
+ "time"
+
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+)
+
+// AuthData stores all relevant authentication data for a context.
+type AuthData struct {
+ User *meta.Meta
+ Token []byte
+ Now time.Time
+ Issued time.Time
+ Expires time.Time
+}
+
+// GetAuthData returns the full authentication data from the context.
+func GetAuthData(ctx context.Context) *AuthData {
+ if ctx != nil {
+ if data, ok := ctx.Value(ctxKeyTypeSession{}).(*AuthData); ok {
+ return data
+ }
+ }
+ return nil
+}
+
+// GetCurrentUser returns the metadata of the current user, or nil if there is no one.
+func GetCurrentUser(ctx context.Context) *meta.Meta {
+ if data := GetAuthData(ctx); data != nil {
+ return data.User
+ }
+ return nil
+}
+
+// ctxKeyTypeSession is just an additional type to make context value retrieval unambiguous.
+type ctxKeyTypeSession struct{}
+
+// UpdateContext enriches the given context with some data of the current user.
+func UpdateContext(ctx context.Context, user *meta.Meta, data *auth.TokenData) context.Context {
+ if data == nil {
+ return context.WithValue(ctx, ctxKeyTypeSession{}, &AuthData{User: user})
+ }
+ return context.WithValue(
+ ctx,
+ ctxKeyTypeSession{},
+ &AuthData{
+ User: user,
+ Token: data.Token,
+ Now: data.Now,
+ Issued: data.Issued,
+ Expires: data.Expires,
+ })
+}
ADDED internal/box/box.go
Index: internal/box/box.go
==================================================================
--- /dev/null
+++ internal/box/box.go
@@ -0,0 +1,325 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package box provides a generic interface to zettel boxes.
+package box
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "time"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+ "t73f.de/r/zsc/domain/meta"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+// BaseBox is implemented by all Zettel boxes.
+type BaseBox interface {
+ // Location returns some information where the box is located.
+ // Format is dependent of the box.
+ Location() string
+
+ // GetZettel retrieves a specific zettel.
+ GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error)
+
+ // CanDeleteZettel returns true, if box could possibly delete the given zettel.
+ CanDeleteZettel(ctx context.Context, zid id.Zid) bool
+
+ // DeleteZettel removes the zettel from the box.
+ DeleteZettel(ctx context.Context, zid id.Zid) error
+}
+
+// WriteBox is a box that can create / update zettel content.
+type WriteBox interface {
+ // CanCreateZettel returns true, if box could possibly create a new zettel.
+ CanCreateZettel(ctx context.Context) bool
+
+ // CreateZettel creates a new zettel.
+ // Returns the new zettel id (and an error indication).
+ CreateZettel(ctx context.Context, zettel zettel.Zettel) (id.Zid, error)
+
+ // CanUpdateZettel returns true, if box could possibly update the given zettel.
+ CanUpdateZettel(ctx context.Context, zettel zettel.Zettel) bool
+
+ // UpdateZettel updates an existing zettel.
+ UpdateZettel(ctx context.Context, zettel zettel.Zettel) error
+}
+
+// ZidFunc is a function that processes identifier of a zettel.
+type ZidFunc func(id.Zid)
+
+// MetaFunc is a function that processes metadata of a zettel.
+type MetaFunc func(*meta.Meta)
+
+// ManagedBox is the interface of managed boxes.
+type ManagedBox interface {
+ BaseBox
+
+ // HasZettel returns true, if box conains zettel with given identifier.
+ HasZettel(context.Context, id.Zid) bool
+
+ // Apply identifier of every zettel to the given function, if predicate returns true.
+ ApplyZid(context.Context, ZidFunc, query.RetrievePredicate) error
+
+ // Apply metadata of every zettel to the given function, if predicate returns true.
+ ApplyMeta(context.Context, MetaFunc, query.RetrievePredicate) error
+
+ // ReadStats populates st with box statistics
+ ReadStats(st *ManagedBoxStats)
+}
+
+// ManagedBoxStats records statistics about the box.
+type ManagedBoxStats struct {
+ // ReadOnly indicates that the content of a box cannot change.
+ ReadOnly bool
+
+ // Zettel is the number of zettel managed by the box.
+ Zettel int
+}
+
+// StartState enumerates the possible states of starting and stopping a box.
+//
+// StartStateStopped -> StartStateStarting -> StartStateStarted -> StateStateStopping -> StartStateStopped.
+//
+// Other transitions are also possible.
+type StartState uint8
+
+// Constant values of StartState
+const (
+ StartStateStopped StartState = iota
+ StartStateStarting
+ StartStateStarted
+ StartStateStopping
+)
+
+// StartStopper performs simple lifecycle management.
+type StartStopper interface {
+ // State the current status of the box.
+ State() StartState
+
+ // Start the box. Now all other functions of the box are allowed.
+ // Starting a box, which is not in state StartStateStopped is not allowed.
+ Start(ctx context.Context) error
+
+ // Stop the started box. Now only the Start() function is allowed.
+ Stop(ctx context.Context)
+}
+
+// Refresher allow to refresh their internal data.
+type Refresher interface {
+ // Refresh the box data.
+ Refresh(context.Context)
+}
+
+// Box is to be used outside the box package and its descendants.
+type Box interface {
+ BaseBox
+ WriteBox
+
+ // FetchZids returns the set of all zettel identifer managed by the box.
+ FetchZids(ctx context.Context) (*idset.Set, error)
+
+ // GetMeta returns the metadata of the zettel with the given identifier.
+ GetMeta(context.Context, id.Zid) (*meta.Meta, error)
+
+ // SelectMeta returns a list of metadata that comply to the given selection criteria.
+ // If `metaSeq` is `nil`, the box assumes metadata of all available zettel.
+ SelectMeta(ctx context.Context, metaSeq []*meta.Meta, q *query.Query) ([]*meta.Meta, error)
+
+ // GetAllZettel retrieves a specific zettel from all managed boxes.
+ GetAllZettel(ctx context.Context, zid id.Zid) ([]zettel.Zettel, error)
+
+ // Refresh the data from the box and from its managed sub-boxes.
+ Refresh(context.Context) error
+
+ // ReIndex one zettel to update its index data.
+ ReIndex(context.Context, id.Zid) error
+}
+
+// Stats record stattistics about a box.
+type Stats struct {
+ // ReadOnly indicates that boxes cannot be modified.
+ ReadOnly bool
+
+ // NumManagedBoxes is the number of boxes managed.
+ NumManagedBoxes int
+
+ // Zettel is the number of zettel managed by the box, including
+ // duplicates across managed boxes.
+ ZettelTotal int
+
+ // LastReload stores the timestamp when a full re-index was done.
+ LastReload time.Time
+
+ // DurLastReload is the duration of the last full re-index run.
+ DurLastReload time.Duration
+
+ // IndexesSinceReload counts indexing a zettel since the full re-index.
+ IndexesSinceReload uint64
+
+ // ZettelIndexed is the number of zettel managed by the indexer.
+ ZettelIndexed int
+
+ // IndexUpdates count the number of metadata updates.
+ IndexUpdates uint64
+
+ // IndexedWords count the different words indexed.
+ IndexedWords uint64
+
+ // IndexedUrls count the different URLs indexed.
+ IndexedUrls uint64
+}
+
+// Manager is a box-managing box.
+type Manager interface {
+ Box
+ StartStopper
+ Subject
+
+ // ReadStats populates st with box statistics
+ ReadStats(st *Stats)
+
+ // Dump internal data to a Writer.
+ Dump(w io.Writer)
+}
+
+// UpdateReason gives an indication, why the ObserverFunc was called.
+type UpdateReason uint8
+
+// Values for Reason
+const (
+ _ UpdateReason = iota
+ OnReady // Box is started and fully operational
+ OnReload // Box was reloaded
+ OnZettel // Something with an existing zettel happened
+ OnDelete // A zettel was deleted
+)
+
+// UpdateInfo contains all the data about a changed zettel.
+type UpdateInfo struct {
+ Box BaseBox
+ Reason UpdateReason
+ Zid id.Zid
+}
+
+// UpdateFunc is a function to be called when a change is detected.
+type UpdateFunc func(UpdateInfo)
+
+// UpdateNotifier is an UpdateFunc, but with separate values.
+type UpdateNotifier func(BaseBox, id.Zid, UpdateReason)
+
+// Subject is a box that notifies observers about changes.
+type Subject interface {
+ // RegisterObserver registers an observer that will be notified
+ // if one or all zettel are found to be changed.
+ RegisterObserver(UpdateFunc)
+}
+
+// Enricher is used to update metadata by adding new properties.
+type Enricher interface {
+ // Enrich computes additional properties and updates the given metadata.
+ // It is typically called by zettel reading methods.
+ Enrich(ctx context.Context, m *meta.Meta, boxNumber int)
+}
+
+// NoEnrichContext will signal an enricher that nothing has to be done.
+// This is useful for an Indexer, but also for some box.Box calls, when
+// just the plain metadata is needed.
+func NoEnrichContext(ctx context.Context) context.Context {
+ return context.WithValue(ctx, ctxNoEnrichType{}, ctx)
+}
+
+type ctxNoEnrichType struct{}
+
+// DoEnrich determines if the context is not marked to not enrich metadata.
+func DoEnrich(ctx context.Context) bool {
+ _, ok := ctx.Value(ctxNoEnrichType{}).(*ctxNoEnrichType)
+ return !ok
+}
+
+// NoEnrichQuery provides a context that signals not to enrich, if the query does not need this.
+func NoEnrichQuery(ctx context.Context, q *query.Query) context.Context {
+ if q.EnrichNeeded() {
+ return ctx
+ }
+ return NoEnrichContext(ctx)
+}
+
+// ErrNotAllowed is returned if the caller is not allowed to perform the operation.
+type ErrNotAllowed struct {
+ Op string
+ User *meta.Meta
+ Zid id.Zid
+}
+
+// NewErrNotAllowed creates an new authorization error.
+func NewErrNotAllowed(op string, user *meta.Meta, zid id.Zid) error {
+ return &ErrNotAllowed{
+ Op: op,
+ User: user,
+ Zid: zid,
+ }
+}
+
+func (err *ErrNotAllowed) Error() string {
+ if err.User == nil {
+ if err.Zid.IsValid() {
+ return fmt.Sprintf(
+ "operation %q on zettel %v not allowed for not authorized user",
+ err.Op, err.Zid)
+ }
+ return fmt.Sprintf("operation %q not allowed for not authorized user", err.Op)
+ }
+ if err.Zid.IsValid() {
+ return fmt.Sprintf(
+ "operation %q on zettel %v not allowed for user %v/%v",
+ err.Op, err.Zid, err.User.GetDefault(meta.KeyUserID, "?"), err.User.Zid)
+ }
+ return fmt.Sprintf(
+ "operation %q not allowed for user %v/%v",
+ err.Op, err.User.GetDefault(meta.KeyUserID, "?"), err.User.Zid)
+}
+
+// Is return true, if the error is of type ErrNotAllowed.
+func (*ErrNotAllowed) Is(error) bool { return true }
+
+// ErrStarted is returned when trying to start an already started box.
+var ErrStarted = errors.New("box is already started")
+
+// ErrStopped is returned if calling methods on a box that was not started.
+var ErrStopped = errors.New("box is stopped")
+
+// ErrReadOnly is returned if there is an attepmt to write to a read-only box.
+var ErrReadOnly = errors.New("read-only box")
+
+// ErrZettelNotFound is returned if a zettel was not found in the box.
+type ErrZettelNotFound struct{ Zid id.Zid }
+
+func (eznf ErrZettelNotFound) Error() string { return "zettel not found: " + eznf.Zid.String() }
+
+// ErrConflict is returned if a box operation detected a conflict..
+// One example: if calculating a new zettel identifier takes too long.
+var ErrConflict = errors.New("conflict")
+
+// ErrCapacity is returned if a box has reached its capacity.
+var ErrCapacity = errors.New("capacity exceeded")
+
+// ErrInvalidZid is returned if the zettel id is not appropriate for the box operation.
+type ErrInvalidZid struct{ Zid string }
+
+func (err ErrInvalidZid) Error() string { return "invalid Zettel id: " + err.Zid }
ADDED internal/box/compbox/compbox.go
Index: internal/box/compbox/compbox.go
==================================================================
--- /dev/null
+++ internal/box/compbox/compbox.go
@@ -0,0 +1,179 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package compbox provides zettel that have computed content.
+package compbox
+
+import (
+ "context"
+ "log/slog"
+ "net/url"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+func init() {
+ manager.Register(
+ " comp",
+ func(_ *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) {
+ return getCompBox(cdata.Number, cdata.Enricher), nil
+ })
+}
+
+type compBox struct {
+ logger *slog.Logger
+ number int
+ enricher box.Enricher
+}
+
+var myConfig *meta.Meta
+var myZettel = map[id.Zid]struct {
+ meta func(id.Zid) *meta.Meta
+ content func(context.Context, *compBox) []byte
+}{
+ id.ZidVersion: {genVersionBuildM, genVersionBuildC},
+ id.ZidHost: {genVersionHostM, genVersionHostC},
+ id.ZidOperatingSystem: {genVersionOSM, genVersionOSC},
+ id.ZidModules: {genModulesM, genModulesC},
+ id.ZidLog: {genLogM, genLogC},
+ id.ZidMemory: {genMemoryM, genMemoryC},
+ id.ZidSx: {genSxM, genSxC},
+ // id.ZidHTTP: {genHttpM, genHttpC},
+ // id.ZidAPI: {genApiM, genApiC},
+ // id.ZidWebUI: {genWebUiM, genWebUiC},
+ // id.ZidConsole: {genConsoleM, genConsoleC},
+ id.ZidBoxManager: {genManagerM, genManagerC},
+ // id.ZidIndex: {genIndexM, genIndexC},
+ // id.ZidQuery: {genQueryM, genQueryC},
+ id.ZidMetadataKey: {genKeysM, genKeysC},
+ id.ZidParser: {genParserM, genParserC},
+ id.ZidStartupConfiguration: {genConfigZettelM, genConfigZettelC},
+}
+
+// Get returns the one program box.
+func getCompBox(boxNumber int, mf box.Enricher) *compBox {
+ return &compBox{
+ logger: kernel.Main.GetLogger(kernel.BoxService).With("box", "comp", "boxnum", boxNumber),
+ number: boxNumber,
+ enricher: mf,
+ }
+}
+
+// Setup remembers important values.
+func Setup(cfg *meta.Meta) { myConfig = cfg.Clone() }
+
+func (*compBox) Location() string { return "" }
+
+func (cb *compBox) GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error) {
+ if gen, ok := myZettel[zid]; ok && gen.meta != nil {
+ if m := gen.meta(zid); m != nil {
+ updateMeta(m)
+ if genContent := gen.content; genContent != nil {
+ logging.LogTrace(cb.logger, "GetZettel/Content")
+ return zettel.Zettel{
+ Meta: m,
+ Content: zettel.NewContent(genContent(ctx, cb)),
+ }, nil
+ }
+ logging.LogTrace(cb.logger, "GetZettel/NoContent")
+ return zettel.Zettel{Meta: m}, nil
+ }
+ }
+ err := box.ErrZettelNotFound{Zid: zid}
+ logging.LogTrace(cb.logger, "GetZettel/Err", "err", err)
+ return zettel.Zettel{}, err
+}
+
+func (*compBox) HasZettel(_ context.Context, zid id.Zid) bool {
+ _, found := myZettel[zid]
+ return found
+}
+
+func (cb *compBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint query.RetrievePredicate) error {
+ logging.LogTrace(cb.logger, "ApplyZid", "entries", len(myZettel))
+ for zid, gen := range myZettel {
+ if !constraint(zid) {
+ continue
+ }
+ if genMeta := gen.meta; genMeta != nil {
+ if genMeta(zid) != nil {
+ handle(zid)
+ }
+ }
+ }
+ return nil
+}
+
+func (cb *compBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint query.RetrievePredicate) error {
+ logging.LogTrace(cb.logger, "ApplyMeta", "entries", len(myZettel))
+ for zid, gen := range myZettel {
+ if !constraint(zid) {
+ continue
+ }
+ if genMeta := gen.meta; genMeta != nil {
+ if m := genMeta(zid); m != nil {
+ updateMeta(m)
+ cb.enricher.Enrich(ctx, m, cb.number)
+ handle(m)
+ }
+ }
+ }
+ return nil
+}
+
+func (*compBox) CanDeleteZettel(context.Context, id.Zid) bool { return false }
+
+func (cb *compBox) DeleteZettel(_ context.Context, zid id.Zid) (err error) {
+ if _, ok := myZettel[zid]; ok {
+ err = box.ErrReadOnly
+ } else {
+ err = box.ErrZettelNotFound{Zid: zid}
+ }
+ logging.LogTrace(cb.logger, "DeleteZettel", "err", err)
+ return err
+}
+
+func (cb *compBox) ReadStats(st *box.ManagedBoxStats) {
+ st.ReadOnly = true
+ st.Zettel = len(myZettel)
+ logging.LogTrace(cb.logger, "ReadStats", "zettel", st.Zettel)
+}
+
+func getTitledMeta(zid id.Zid, title string) *meta.Meta {
+ m := meta.New(zid)
+ m.Set(meta.KeyTitle, meta.Value(title))
+ return m
+}
+
+func updateMeta(m *meta.Meta) {
+ if _, ok := m.Get(meta.KeySyntax); !ok {
+ m.Set(meta.KeySyntax, meta.ValueSyntaxZmk)
+ }
+ m.Set(meta.KeyRole, meta.ValueRoleConfiguration)
+ if _, ok := m.Get(meta.KeyCreated); !ok {
+ m.Set(meta.KeyCreated, meta.Value(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreStarted).(string)))
+ }
+ m.Set(meta.KeyLang, meta.ValueLangEN)
+ m.Set(meta.KeyReadOnly, meta.ValueTrue)
+ if _, ok := m.Get(meta.KeyVisibility); !ok {
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityExpert)
+ }
+}
ADDED internal/box/compbox/config.go
Index: internal/box/compbox/config.go
==================================================================
--- /dev/null
+++ internal/box/compbox/config.go
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+)
+
+func genConfigZettelM(zid id.Zid) *meta.Meta {
+ if myConfig == nil {
+ return nil
+ }
+ return getTitledMeta(zid, "Zettelstore Startup Configuration")
+}
+
+func genConfigZettelC(context.Context, *compBox) []byte {
+ var buf bytes.Buffer
+ second := false
+ for key, val := range myConfig.All() {
+ if second {
+ buf.WriteByte('\n')
+ }
+ second = true
+ buf.WriteString("; ''")
+ buf.WriteString(key)
+ buf.WriteString("''")
+ if val != "" {
+ buf.WriteString("\n: ``")
+ for _, r := range val {
+ if r == '`' {
+ buf.WriteByte('\\')
+ }
+ buf.WriteRune(r)
+ }
+ buf.WriteString("``")
+ }
+ }
+ return buf.Bytes()
+}
ADDED internal/box/compbox/keys.go
Index: internal/box/compbox/keys.go
==================================================================
--- /dev/null
+++ internal/box/compbox/keys.go
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "zettelstore.de/z/internal/kernel"
+)
+
+func genKeysM(zid id.Zid) *meta.Meta {
+ m := getTitledMeta(zid, "Zettelstore Supported Metadata Keys")
+ m.Set(meta.KeyCreated, meta.Value(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVTime).(string)))
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityLogin)
+ return m
+}
+
+func genKeysC(context.Context, *compBox) []byte {
+ keys := meta.GetSortedKeyDescriptions()
+ var buf bytes.Buffer
+ buf.WriteString("|=Name<|=Type<|=Computed?:|=Property?:\n")
+ for _, kd := range keys {
+ fmt.Fprintf(&buf,
+ "|[[%v|query:%v?]]|%v|%v|%v\n", kd.Name, kd.Name, kd.Type.Name, kd.IsComputed(), kd.IsProperty())
+ }
+ return buf.Bytes()
+}
ADDED internal/box/compbox/log.go
Index: internal/box/compbox/log.go
==================================================================
--- /dev/null
+++ internal/box/compbox/log.go
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+)
+
+func genLogM(zid id.Zid) *meta.Meta {
+ m := getTitledMeta(zid, "Zettelstore Log")
+ m.Set(meta.KeySyntax, meta.ValueSyntaxText)
+ m.Set(meta.KeyModified, meta.Value(kernel.Main.GetLastLogTime().Local().Format(id.TimestampLayout)))
+ return m
+}
+
+func genLogC(context.Context, *compBox) []byte {
+ const tsFormat = "2006-01-02 15:04:05.999999"
+ entries := kernel.Main.RetrieveLogEntries()
+ var buf bytes.Buffer
+ for _, entry := range entries {
+ ts := entry.TS.Format(tsFormat)
+ buf.WriteString(ts)
+ for j := len(ts); j < len(tsFormat); j++ {
+ buf.WriteByte('0')
+ }
+ buf.WriteByte(' ')
+ buf.WriteString(logging.LevelStringPad(entry.Level))
+ buf.WriteByte(' ')
+ buf.WriteString(entry.Prefix)
+ buf.WriteByte(' ')
+ buf.WriteString(entry.Message)
+ buf.WriteByte(' ')
+ buf.WriteString(entry.Details)
+ buf.WriteByte('\n')
+ }
+ return buf.Bytes()
+}
ADDED internal/box/compbox/manager.go
Index: internal/box/compbox/manager.go
==================================================================
--- /dev/null
+++ internal/box/compbox/manager.go
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "zettelstore.de/z/internal/kernel"
+)
+
+func genManagerM(zid id.Zid) *meta.Meta {
+ return getTitledMeta(zid, "Zettelstore Box Manager")
+}
+
+func genManagerC(context.Context, *compBox) []byte {
+ kvl := kernel.Main.GetServiceStatistics(kernel.BoxService)
+ if len(kvl) == 0 {
+ return nil
+ }
+ var buf bytes.Buffer
+ buf.WriteString("|=Name|=Value>\n")
+ for _, kv := range kvl {
+ fmt.Fprintf(&buf, "| %v | %v\n", kv.Key, kv.Value)
+ }
+ return buf.Bytes()
+}
ADDED internal/box/compbox/memory.go
Index: internal/box/compbox/memory.go
==================================================================
--- /dev/null
+++ internal/box/compbox/memory.go
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2024-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2024-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "os"
+ "runtime"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "zettelstore.de/z/internal/kernel"
+)
+
+func genMemoryM(zid id.Zid) *meta.Meta {
+ return getTitledMeta(zid, "Zettelstore Memory")
+}
+
+func genMemoryC(context.Context, *compBox) []byte {
+ pageSize := os.Getpagesize()
+ var m runtime.MemStats
+ runtime.GC()
+ runtime.ReadMemStats(&m)
+
+ var buf bytes.Buffer
+ buf.WriteString("|=Name|=Value>\n")
+ fmt.Fprintf(&buf, "|Page Size|%d\n", pageSize)
+ fmt.Fprintf(&buf, "|Pages|%d\n", m.HeapSys/uint64(pageSize))
+ fmt.Fprintf(&buf, "|Heap Objects|%d\n", m.HeapObjects)
+ fmt.Fprintf(&buf, "|Heap Sys (KiB)|%d\n", m.HeapSys/1024)
+ fmt.Fprintf(&buf, "|Heap Inuse (KiB)|%d\n", m.HeapInuse/1024)
+ fmt.Fprintf(&buf, "|CPUs|%d\n", runtime.NumCPU())
+ fmt.Fprintf(&buf, "|Threads|%d\n", runtime.NumGoroutine())
+ debug := kernel.Main.GetConfig(kernel.CoreService, kernel.CoreDebug).(bool)
+ if debug {
+ for i, bysize := range m.BySize {
+ fmt.Fprintf(&buf, "|Size %2d: %d|%d - %d → %d\n",
+ i, bysize.Size, bysize.Mallocs, bysize.Frees, bysize.Mallocs-bysize.Frees)
+ }
+ }
+ return buf.Bytes()
+}
ADDED internal/box/compbox/modules.go
Index: internal/box/compbox/modules.go
==================================================================
--- /dev/null
+++ internal/box/compbox/modules.go
@@ -0,0 +1,47 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2025-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2025-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "runtime/debug"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+)
+
+func genModulesM(zid id.Zid) *meta.Meta {
+ m := getTitledMeta(zid, "Zettelstore Modules")
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityLogin)
+ m.Set(meta.KeyPrecursor, meta.Value(id.ZidDependencies.String()))
+ return m
+}
+
+func genModulesC(context.Context, *compBox) []byte {
+ info, ok := debug.ReadBuildInfo()
+ var buf bytes.Buffer
+ if !ok {
+ buf.WriteString("No module info available\n")
+ } else {
+ buf.WriteString("|=Module|Version\n")
+ fmt.Fprintf(&buf, "|Zettelstore|{{%v}}\n", id.ZidVersion)
+ for _, m := range info.Deps {
+ fmt.Fprintf(&buf, "|%s|%s\n", m.Path, m.Version)
+ }
+ }
+ fmt.Fprintf(&buf, "\nSee [[Zettelstore Dependencies|%v]] for license details.", id.ZidDependencies)
+ return buf.Bytes()
+}
ADDED internal/box/compbox/parser.go
Index: internal/box/compbox/parser.go
==================================================================
--- /dev/null
+++ internal/box/compbox/parser.go
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "slices"
+ "strings"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/parser"
+)
+
+func genParserM(zid id.Zid) *meta.Meta {
+ m := getTitledMeta(zid, "Zettelstore Supported Parser")
+ m.Set(meta.KeyCreated, meta.Value(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVTime).(string)))
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityLogin)
+ return m
+}
+
+func genParserC(context.Context, *compBox) []byte {
+ var buf bytes.Buffer
+ buf.WriteString("|=Syntax<|=Alt. Value(s):|=Text Parser?:|=Text Format?:|=Image Format?:\n")
+ syntaxes := parser.GetSyntaxes()
+ slices.Sort(syntaxes)
+ for _, syntax := range syntaxes {
+ info := parser.Get(syntax)
+ if info.Name != syntax {
+ continue
+ }
+ altNames := info.AltNames
+ slices.Sort(altNames)
+ fmt.Fprintf(
+ &buf, "|%v|%v|%v|%v|%v\n",
+ syntax, strings.Join(altNames, ", "), info.IsASTParser, info.IsTextFormat, info.IsImageFormat)
+ }
+ return buf.Bytes()
+}
ADDED internal/box/compbox/sx.go
Index: internal/box/compbox/sx.go
==================================================================
--- /dev/null
+++ internal/box/compbox/sx.go
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2024-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2024-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+
+ "t73f.de/r/sx"
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+)
+
+func genSxM(zid id.Zid) *meta.Meta {
+ return getTitledMeta(zid, "Zettelstore Sx Engine")
+}
+
+func genSxC(context.Context, *compBox) []byte {
+ var buf bytes.Buffer
+ buf.WriteString("|=Name|=Value>\n")
+ numSymbols := 0
+ for pkg := range sx.AllPackages() {
+ if size := pkg.Size(); size > 0 {
+ fmt.Fprintf(&buf, "|Symbols in package %q|%d\n", pkg.Name(), size)
+ numSymbols += size
+ }
+ }
+ fmt.Fprintf(&buf, "|All symbols|%d\n", numSymbols)
+ return buf.Bytes()
+}
ADDED internal/box/compbox/version.go
Index: internal/box/compbox/version.go
==================================================================
--- /dev/null
+++ internal/box/compbox/version.go
@@ -0,0 +1,52 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package compbox
+
+import (
+ "context"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/kernel"
+)
+
+func genVersionBuildM(zid id.Zid) *meta.Meta {
+ m := getTitledMeta(zid, "Zettelstore Version")
+ m.Set(meta.KeyCreated, meta.Value(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVTime).(string)))
+ m.Set(meta.KeyVisibility, meta.ValueVisibilityLogin)
+ return m
+}
+func genVersionBuildC(context.Context, *compBox) []byte {
+ return []byte(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVersion).(string))
+}
+
+func genVersionHostM(zid id.Zid) *meta.Meta {
+ return getTitledMeta(zid, "Zettelstore Host")
+}
+func genVersionHostC(context.Context, *compBox) []byte {
+ return []byte(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreHostname).(string))
+}
+
+func genVersionOSM(zid id.Zid) *meta.Meta {
+ return getTitledMeta(zid, "Zettelstore Operating System")
+}
+func genVersionOSC(context.Context, *compBox) []byte {
+ goOS := kernel.Main.GetConfig(kernel.CoreService, kernel.CoreGoOS).(string)
+ goArch := kernel.Main.GetConfig(kernel.CoreService, kernel.CoreGoArch).(string)
+ result := make([]byte, 0, len(goOS)+len(goArch)+1)
+ result = append(result, goOS...)
+ result = append(result, '/')
+ return append(result, goArch...)
+}
ADDED internal/box/constbox/base.css
Index: internal/box/constbox/base.css
==================================================================
--- /dev/null
+++ internal/box/constbox/base.css
@@ -0,0 +1,250 @@
+/*-----------------------------------------------------------------------------
+ * Copyright (c) 2020-present Detlef Stern
+ *
+ * This file is part of Zettelstore.
+ *
+ * Zettelstore is licensed under the latest version of the EUPL (European Union
+ * Public License). Please see file LICENSE.txt for your rights and obligations
+ * under this license.
+ *
+ * SPDX-License-Identifier: EUPL-1.2
+ * SPDX-FileCopyrightText: 2020-present Detlef Stern
+ *-----------------------------------------------------------------------------
+ */
+
+*,*::before,*::after {
+ box-sizing: border-box;
+ }
+ html {
+ font-family: serif;
+ scroll-behavior: smooth;
+ height: 100%;
+ }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ line-height: 1.4;
+ background-color: #f8f8f8 ;
+ height: 100%;
+ }
+ nav.zs-menu {
+ background-color: hsl(210, 28%, 90%);
+ overflow: auto;
+ white-space: nowrap;
+ font-family: sans-serif;
+ padding-left: .5rem;
+ }
+ nav.zs-menu > a {
+ float:left;
+ display: block;
+ text-align: center;
+ padding:.41rem .5rem;
+ text-decoration: none;
+ color:black;
+ }
+ nav.zs-menu > a:hover, .zs-dropdown:hover button { background-color: hsl(210, 28%, 80%) }
+ nav.zs-menu form { float: right }
+ nav.zs-menu form input[type=text] {
+ padding: .12rem;
+ border: none;
+ margin-top: .25rem;
+ margin-right: .5rem;
+ }
+ .zs-dropdown {
+ float: left;
+ overflow: hidden;
+ }
+ .zs-dropdown > button {
+ font-size: 16px;
+ border: none;
+ outline: none;
+ color: black;
+ padding:.41rem .5rem;
+ background-color: inherit;
+ font-family: inherit;
+ margin: 0;
+ }
+ .zs-dropdown-content {
+ display: none;
+ position: absolute;
+ background-color: #f9f9f9;
+ min-width: 160px;
+ box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
+ z-index: 1;
+ }
+ .zs-dropdown-content > a {
+ float: none;
+ color: black;
+ padding:.41rem .5rem;
+ text-decoration: none;
+ display: block;
+ text-align: left;
+ }
+ .zs-dropdown-content > a:hover { background-color: hsl(210, 28%, 75%) }
+ .zs-dropdown:hover > .zs-dropdown-content { display: block }
+ main { padding: 0 1rem }
+ article > * + * { margin-top: .5rem }
+ article header {
+ padding: 0;
+ margin: 0;
+ }
+ h1,h2,h3,h4,h5,h6 { font-family:sans-serif; font-weight:normal; margin:.4em 0 }
+ h1 { font-size:1.5em }
+ h2 { font-size:1.25em }
+ h3 { font-size:1.15em }
+ h4 { font-size:1.05em; font-weight: bold }
+ h5 { font-size:1.05em }
+ h6 { font-size:1.05em; font-weight: lighter }
+ p { margin: .5em 0 0 0 }
+ p.zs-meta-zettel { margin-top: .5em; margin-left: .5em }
+ li,figure,figcaption,dl { margin: 0 }
+ dt { margin: .5em 0 0 0 }
+ dt+dd { margin-top: 0 }
+ dd { margin: .5em 0 0 2em }
+ dd > p:first-child { margin: 0 0 0 0 }
+ blockquote {
+ border-left: .5em solid lightgray;
+ padding-left: 1em;
+ margin-left: 1em;
+ margin-right: 2em;
+ }
+ blockquote p { margin-bottom: .5em }
+ table {
+ border-collapse: collapse;
+ border-spacing: 0;
+ max-width: 100%;
+ }
+ td, th {text-align: left; padding: .25em .5em;}
+ th { font-weight: bold }
+ thead th { border-bottom: 2px solid hsl(0, 0%, 70%) }
+ td { border-bottom: 1px solid hsl(0, 0%, 85%) }
+ main form {
+ padding: 0 .5em;
+ margin: .5em 0 0 0;
+ }
+ main form:after {
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
+ visibility: hidden;
+ }
+ main form div { margin: .5em 0 0 0 }
+ input { font-family: monospace }
+ input[type="submit"],button,select { font: inherit }
+ label { font-family: sans-serif; font-size:.9rem }
+ textarea {
+ font-family: monospace;
+ resize: vertical;
+ width: 100%;
+ }
+ .zs-input {
+ padding: .5em;
+ display:block;
+ border:none;
+ border-bottom:1px solid #ccc;
+ width:100%;
+ }
+ input.zs-primary { float:right }
+ input.zs-secondary { float:left }
+ input.zs-upload {
+ padding-left: 1em;
+ padding-right: 1em;
+ }
+ a:not([class]) { text-decoration-skip-ink: auto }
+ a.broken { text-decoration: line-through }
+ a[rel~="external"]::after { content: "➚"; display: inline-block }
+ img { max-width: 100% }
+ img.right { float: right }
+ ol.zs-endnotes {
+ padding-top: .5em;
+ border-top: 1px solid;
+ }
+ kbd { font-family:monospace }
+ code,pre {
+ font-family: monospace;
+ font-size: 85%;
+ }
+ code {
+ padding: .1em .2em;
+ background: #f0f0f0;
+ border: 1px solid #ccc;
+ border-radius: .25em;
+ }
+ pre {
+ padding: .5em .7em;
+ max-width: 100%;
+ overflow: auto;
+ border: 1px solid #ccc;
+ border-radius: .5em;
+ background: #f0f0f0;
+ }
+ pre code {
+ font-size: 95%;
+ position: relative;
+ padding: 0;
+ border: none;
+ }
+ div.zs-indication {
+ padding: .5em .7em;
+ max-width: 100%;
+ border-radius: .5em;
+ border: 1px solid black;
+ }
+ div.zs-indication p:first-child { margin-top: 0 }
+ span.zs-indication {
+ border: 1px solid black;
+ border-radius: .25em;
+ padding: .1rem .2em;
+ font-size: 95%;
+ }
+ .zs-info {
+ background-color: lightblue;
+ padding: .5em 1em;
+ }
+ .zs-warning {
+ background-color: lightyellow;
+ padding: .5em 1em;
+ }
+ .zs-error {
+ background-color: lightpink;
+ border-style: none !important;
+ font-weight: bold;
+ }
+ td.left, th.left { text-align:left }
+ td.center, th.center { text-align:center }
+ td.right, th.right { text-align:right }
+ .zs-font-size-0 { font-size:75% }
+ .zs-font-size-1 { font-size:83% }
+ .zs-font-size-2 { font-size:100% }
+ .zs-font-size-3 { font-size:117% }
+ .zs-font-size-4 { font-size:150% }
+ .zs-font-size-5 { font-size:200% }
+ .zs-deprecated { border-style: dashed; padding: .2em }
+ .zs-meta {
+ font-size:.75rem;
+ color:#444;
+ margin-bottom:1em;
+ }
+ .zs-meta a { color:#444 }
+ h1+.zs-meta { margin-top:-1em }
+ nav > details { margin-top:1em }
+ details > summary {
+ width: 100%;
+ background-color: #eee;
+ font-family:sans-serif;
+ }
+ details > ul {
+ margin-top:0;
+ padding-left:2em;
+ background-color: #eee;
+ }
+ footer { padding: 0 1em }
+ @media (prefers-reduced-motion: reduce) {
+ * {
+ animation-duration: 0.01ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.01ms !important;
+ scroll-behavior: auto !important;
+ }
+ }
ADDED internal/box/constbox/base.sxn
Index: internal/box/constbox/base.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/base.sxn
@@ -0,0 +1,62 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(@@@@
+(html ,@(if lang `((@ (lang ,lang))))
+(head
+ (meta (@ (charset "utf-8")))
+ (meta (@ (name "viewport") (content "width=device-width, initial-scale=1.0")))
+ (meta (@ (name "generator") (content "Zettelstore")))
+ (meta (@ (name "format-detection") (content "telephone=no")))
+ ,@META-HEADER
+ (link (@ (rel "stylesheet") (href ,css-base-url)))
+ (link (@ (rel "stylesheet") (href ,css-user-url)))
+ ,@(ROLE-DEFAULT-meta (current-frame))
+ ,@(let* ((frame (current-frame))(rem (resolve-symbol 'ROLE-EXTRA-meta frame))) (if (defined? rem) (rem frame)))
+ (title ,title))
+(body
+ (nav (@ (class "zs-menu"))
+ (a (@ (href ,home-url)) "Home")
+ ,@(if with-auth
+ `((div (@ (class "zs-dropdown"))
+ (button "User")
+ (nav (@ (class "zs-dropdown-content"))
+ ,@(if user-is-valid
+ `((a (@ (href ,user-zettel-url)) ,user-ident)
+ (a (@ (href ,logout-url)) "Logout"))
+ `((a (@ (href ,login-url)) "Login"))
+ )
+ )))
+ )
+ (div (@ (class "zs-dropdown"))
+ (button "Lists")
+ (nav (@ (class "zs-dropdown-content"))
+ ,@list-urls
+ ,@(if (symbol-bound? 'refresh-url) `((a (@ (href ,refresh-url)) "Refresh")))
+ ))
+ ,@(if new-zettel-links
+ `((div (@ (class "zs-dropdown"))
+ (button "New")
+ (nav (@ (class "zs-dropdown-content"))
+ ,@(map wui-link new-zettel-links)
+ )))
+ )
+ (search (form (@ (action ,search-url))
+ (input (@ (type "search") (inputmode "search") (name ,query-key-query)
+ (title "General search field, with same behaviour as search field in search result list")
+ (placeholder "Search..") (dir "auto")))))
+ )
+ (main (@ (class "content")) ,DETAIL)
+ ,@(if FOOTER `((footer (hr) ,@FOOTER)))
+ ,@(if debug-mode '((div (b "WARNING: Debug mode is enabled. DO NOT USE IN PRODUCTION!"))))
+)))
ADDED internal/box/constbox/constbox.go
Index: internal/box/constbox/constbox.go
==================================================================
--- /dev/null
+++ internal/box/constbox/constbox.go
@@ -0,0 +1,486 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package constbox puts zettel inside the executable.
+package constbox
+
+import (
+ "context"
+ _ "embed" // Allow to embed file content
+ "log/slog"
+ "net/url"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+func init() {
+ manager.Register(
+ " const",
+ func(_ *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) {
+ return &constBox{
+ logger: kernel.Main.GetLogger(kernel.BoxService).With("box", "const", "boxnum", cdata.Number),
+ number: cdata.Number,
+ zettel: constZettelMap,
+ enricher: cdata.Enricher,
+ }, nil
+ })
+}
+
+type constHeader map[string]string
+
+type constZettel struct {
+ header constHeader
+ content zettel.Content
+}
+
+type constBox struct {
+ logger *slog.Logger
+ number int
+ zettel map[id.Zid]constZettel
+ enricher box.Enricher
+}
+
+func (*constBox) Location() string { return "const:" }
+
+func (cb *constBox) GetZettel(_ context.Context, zid id.Zid) (zettel.Zettel, error) {
+ if z, ok := cb.zettel[zid]; ok {
+ logging.LogTrace(cb.logger, "GetZettel")
+ return zettel.Zettel{Meta: meta.NewWithData(zid, z.header), Content: z.content}, nil
+ }
+ err := box.ErrZettelNotFound{Zid: zid}
+ logging.LogTrace(cb.logger, "GetZettel/Err", "err", err)
+ return zettel.Zettel{}, err
+}
+
+func (cb *constBox) HasZettel(_ context.Context, zid id.Zid) bool {
+ _, found := cb.zettel[zid]
+ return found
+}
+
+func (cb *constBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint query.RetrievePredicate) error {
+ logging.LogTrace(cb.logger, "ApplyZid", "entries", len(cb.zettel))
+ for zid := range cb.zettel {
+ if constraint(zid) {
+ handle(zid)
+ }
+ }
+ return nil
+}
+
+func (cb *constBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint query.RetrievePredicate) error {
+ logging.LogTrace(cb.logger, "ApplyMeta", "entries", len(cb.zettel))
+ for zid, zettel := range cb.zettel {
+ if constraint(zid) {
+ m := meta.NewWithData(zid, zettel.header)
+ cb.enricher.Enrich(ctx, m, cb.number)
+ handle(m)
+ }
+ }
+ return nil
+}
+
+func (*constBox) CanDeleteZettel(context.Context, id.Zid) bool { return false }
+
+func (cb *constBox) DeleteZettel(_ context.Context, zid id.Zid) (err error) {
+ if _, ok := cb.zettel[zid]; ok {
+ err = box.ErrReadOnly
+ } else {
+ err = box.ErrZettelNotFound{Zid: zid}
+ }
+ logging.LogTrace(cb.logger, "DeleteZettel", logging.Err(err))
+ return err
+}
+
+func (cb *constBox) ReadStats(st *box.ManagedBoxStats) {
+ st.ReadOnly = true
+ st.Zettel = len(cb.zettel)
+ logging.LogTrace(cb.logger, "ReadStats", "zettel", st.Zettel)
+}
+
+var constZettelMap = map[id.Zid]constZettel{
+ id.ZidConfiguration: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Runtime Configuration",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxNone,
+ meta.KeyCreated: "20200804111624",
+ meta.KeyVisibility: meta.ValueVisibilityOwner,
+ },
+ zettel.NewContent(nil)},
+ id.ZidLicense: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore License",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxText,
+ meta.KeyCreated: "20210504135842",
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyModified: "20220131153422",
+ meta.KeyReadOnly: meta.ValueTrue,
+ meta.KeyVisibility: meta.ValueVisibilityPublic,
+ },
+ zettel.NewContent(contentLicense)},
+ id.ZidAuthors: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Contributors",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20210504135842",
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyReadOnly: meta.ValueTrue,
+ meta.KeyVisibility: meta.ValueVisibilityLogin,
+ },
+ zettel.NewContent(contentContributors)},
+ id.ZidDependencies: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Dependencies",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyReadOnly: meta.ValueTrue,
+ meta.KeyVisibility: meta.ValueVisibilityPublic,
+ meta.KeyCreated: "20210504135842",
+ meta.KeyModified: "20250623150400",
+ },
+ zettel.NewContent(contentDependencies)},
+ id.ZidBaseTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Base HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20230510155100",
+ meta.KeyModified: "20250623131400",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentBaseSxn)},
+ id.ZidLoginTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Login Form HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20200804111624",
+ meta.KeyModified: "20240219145200",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentLoginSxn)},
+ id.ZidZettelTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Zettel HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20230510155300",
+ meta.KeyModified: "20250626113800",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentZettelSxn)},
+ id.ZidInfoTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Info HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20200804111624",
+ meta.KeyModified: "20250624160000",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentInfoSxn)},
+ id.ZidFormTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Form HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20200804111624",
+ meta.KeyModified: "20250612180300",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentFormSxn)},
+ id.ZidDeleteTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Delete HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20200804111624",
+ meta.KeyModified: "20250612180200",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentDeleteSxn)},
+ id.ZidListTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore List Zettel HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20230704122100",
+ meta.KeyModified: "20250612180200",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentListZettelSxn)},
+ id.ZidErrorTemplate: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Error HTML Template",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20210305133215",
+ meta.KeyModified: "20240219145200",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentErrorSxn)},
+ id.ZidSxnStart: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Sxn Start Code",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20230824160700",
+ meta.KeyModified: "20240219145200",
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ meta.KeyPrecursor: id.ZidSxnBase.String(),
+ },
+ zettel.NewContent(contentStartCodeSxn)},
+ id.ZidSxnBase: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Sxn Base Code",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxSxn,
+ meta.KeyCreated: "20230619132800",
+ meta.KeyModified: "20250624200200",
+ meta.KeyReadOnly: meta.ValueTrue,
+ meta.KeyVisibility: meta.ValueVisibilityExpert,
+ },
+ zettel.NewContent(contentBaseCodeSxn)},
+ id.ZidBaseCSS: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Base CSS",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxCSS,
+ meta.KeyCreated: "20200804111624",
+ meta.KeyModified: "20240827143500",
+ meta.KeyVisibility: meta.ValueVisibilityPublic,
+ },
+ zettel.NewContent(contentBaseCSS)},
+ id.ZidUserCSS: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore User CSS",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxCSS,
+ meta.KeyCreated: "20210622110143",
+ meta.KeyVisibility: meta.ValueVisibilityPublic,
+ },
+ zettel.NewContent([]byte("/* User-defined CSS */"))},
+ id.ZidEmoji: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Generic Emoji",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxGif,
+ meta.KeyReadOnly: meta.ValueTrue,
+ meta.KeyCreated: "20210504175807",
+ meta.KeyVisibility: meta.ValueVisibilityPublic,
+ },
+ zettel.NewContent(contentEmoji)},
+ id.ZidTOCListsMenu: {
+ constHeader{
+ meta.KeyTitle: "Lists Menu",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyCreated: "20241223205400",
+ meta.KeyVisibility: meta.ValueVisibilityPublic,
+ },
+ zettel.NewContent(contentMenuListsZettel)},
+ id.ZidTOCNewTemplate: {
+ constHeader{
+ meta.KeyTitle: "New Menu",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyCreated: "20210217161829",
+ meta.KeyModified: "20231129111800",
+ meta.KeyVisibility: meta.ValueVisibilityCreator,
+ },
+ zettel.NewContent(contentMenuNewZettel)},
+ id.ZidTemplateNewZettel: {
+ constHeader{
+ meta.KeyTitle: "New Zettel",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20201028185209",
+ meta.KeyModified: "20230929132900",
+ meta.NewPrefix + meta.KeyRole: meta.ValueRoleZettel,
+ meta.KeyVisibility: meta.ValueVisibilityCreator,
+ },
+ zettel.NewContent(nil)},
+ id.ZidTemplateNewRole: {
+ constHeader{
+ meta.KeyTitle: "New Role",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20231129110800",
+ meta.NewPrefix + meta.KeyRole: meta.ValueRoleRole,
+ meta.NewPrefix + meta.KeyTitle: "",
+ meta.KeyVisibility: meta.ValueVisibilityCreator,
+ },
+ zettel.NewContent(nil)},
+ id.ZidTemplateNewTag: {
+ constHeader{
+ meta.KeyTitle: "New Tag",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20230929132400",
+ meta.NewPrefix + meta.KeyRole: meta.ValueRoleTag,
+ meta.NewPrefix + meta.KeyTitle: "#",
+ meta.KeyVisibility: meta.ValueVisibilityCreator,
+ },
+ zettel.NewContent(nil)},
+ id.ZidTemplateNewUser: {
+ constHeader{
+ meta.KeyTitle: "New User",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxNone,
+ meta.KeyCreated: "20201028185209",
+ meta.NewPrefix + meta.KeyCredential: "",
+ meta.NewPrefix + meta.KeyUserID: "",
+ meta.NewPrefix + meta.KeyUserRole: meta.ValueUserRoleReader,
+ meta.KeyVisibility: meta.ValueVisibilityOwner,
+ },
+ zettel.NewContent(nil)},
+ id.ZidRoleZettelZettel: {
+ constHeader{
+ meta.KeyTitle: meta.ValueRoleZettel,
+ meta.KeyRole: meta.ValueRoleRole,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20231129161400",
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyVisibility: meta.ValueVisibilityLogin,
+ },
+ zettel.NewContent(contentRoleZettel)},
+ id.ZidRoleConfigurationZettel: {
+ constHeader{
+ meta.KeyTitle: meta.ValueRoleConfiguration,
+ meta.KeyRole: meta.ValueRoleRole,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20241213103100",
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyVisibility: meta.ValueVisibilityLogin,
+ },
+ zettel.NewContent(contentRoleConfiguration)},
+ id.ZidRoleRoleZettel: {
+ constHeader{
+ meta.KeyTitle: meta.ValueRoleRole,
+ meta.KeyRole: meta.ValueRoleRole,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20231129162900",
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyVisibility: meta.ValueVisibilityLogin,
+ },
+ zettel.NewContent(contentRoleRole)},
+ id.ZidRoleTagZettel: {
+ constHeader{
+ meta.KeyTitle: meta.ValueRoleTag,
+ meta.KeyRole: meta.ValueRoleRole,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyCreated: "20231129162000",
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyVisibility: meta.ValueVisibilityLogin,
+ },
+ zettel.NewContent(contentRoleTag)},
+ id.ZidAppDirectory: {
+ constHeader{
+ meta.KeyTitle: "Zettelstore Application Directory",
+ meta.KeyRole: meta.ValueRoleConfiguration,
+ meta.KeySyntax: meta.ValueSyntaxNone,
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyCreated: "20240703235900",
+ meta.KeyVisibility: meta.ValueVisibilityLogin,
+ },
+ zettel.NewContent(nil)},
+ id.ZidDefaultHome: {
+ constHeader{
+ meta.KeyTitle: "Home",
+ meta.KeyRole: meta.ValueRoleZettel,
+ meta.KeySyntax: meta.ValueSyntaxZmk,
+ meta.KeyLang: meta.ValueLangEN,
+ meta.KeyCreated: "20210210190757",
+ meta.KeyModified: "20241216105800",
+ },
+ zettel.NewContent(contentHomeZettel)},
+}
+
+//go:embed license.txt
+var contentLicense []byte
+
+//go:embed contributors.zettel
+var contentContributors []byte
+
+//go:embed dependencies.zettel
+var contentDependencies []byte
+
+//go:embed base.sxn
+var contentBaseSxn []byte
+
+//go:embed login.sxn
+var contentLoginSxn []byte
+
+//go:embed zettel.sxn
+var contentZettelSxn []byte
+
+//go:embed info.sxn
+var contentInfoSxn []byte
+
+//go:embed form.sxn
+var contentFormSxn []byte
+
+//go:embed delete.sxn
+var contentDeleteSxn []byte
+
+//go:embed listzettel.sxn
+var contentListZettelSxn []byte
+
+//go:embed error.sxn
+var contentErrorSxn []byte
+
+//go:embed start.sxn
+var contentStartCodeSxn []byte
+
+//go:embed wuicode.sxn
+var contentBaseCodeSxn []byte
+
+//go:embed base.css
+var contentBaseCSS []byte
+
+//go:embed emoji_spin.gif
+var contentEmoji []byte
+
+//go:embed menu_lists.zettel
+var contentMenuListsZettel []byte
+
+//go:embed menu_new.zettel
+var contentMenuNewZettel []byte
+
+//go:embed rolezettel.zettel
+var contentRoleZettel []byte
+
+//go:embed roleconfiguration.zettel
+var contentRoleConfiguration []byte
+
+//go:embed rolerole.zettel
+var contentRoleRole []byte
+
+//go:embed roletag.zettel
+var contentRoleTag []byte
+
+//go:embed home.zettel
+var contentHomeZettel []byte
ADDED internal/box/constbox/contributors.zettel
Index: internal/box/constbox/contributors.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/contributors.zettel
@@ -0,0 +1,8 @@
+Zettelstore is a software for humans made from humans.
+
+=== Licensor(s)
+* Detlef Stern [[mailto:ds@zettelstore.de]]
+** Main author
+** Maintainer
+
+=== Contributors
ADDED internal/box/constbox/delete.sxn
Index: internal/box/constbox/delete.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/delete.sxn
@@ -0,0 +1,39 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(article
+ (header (h1 "Delete Zettel " ,zid))
+ (p "Do you really want to delete this zettel?")
+ ,@(if shadowed-box
+ `((div (@ (class "zs-info"))
+ (h2 "Information")
+ (p "If you delete this zettel, the previously shadowed zettel from overlayed box " ,shadowed-box " becomes available.")
+ ))
+ )
+ ,@(if incoming
+ `((div (@ (class "zs-warning"))
+ (h2 "Warning!")
+ (p "If you delete this zettel, incoming references from the following zettel will become invalid.")
+ (ul ,@(map wui-item-link incoming))
+ ))
+ )
+ ,@(if (and (symbol-bound? 'useless) useless)
+ `((div (@ (class "zs-warning"))
+ (h2 "Warning!")
+ (p "Deleting this zettel will also delete the following files, so that they will not be interpreted as content for this zettel.")
+ (ul ,@(map wui-item useless))
+ ))
+ )
+ ,(wui-meta-desc metapairs)
+ (form (@ (method "POST")) (input (@ (class "zs-primary") (type "submit") (value "Delete"))))
+)
ADDED internal/box/constbox/dependencies.zettel
Index: internal/box/constbox/dependencies.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/dependencies.zettel
@@ -0,0 +1,150 @@
+Zettelstore is made with the help of other software and other artifacts.
+Thank you very much!
+
+This zettel lists all of them, together with their licenses.
+
+=== Go runtime and associated libraries
+; License
+: BSD 3-Clause "New" or "Revised" License
+```
+Copyright (c) 2009 The Go Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+```
+
+=== Fsnotify
+; URL
+: [[https://fsnotify.org/]]
+; License
+: BSD 3-Clause "New" or "Revised" License
+; Source
+: [[https://github.com/fsnotify/fsnotify]]
+```
+Copyright © 2012 The Go Authors. All rights reserved.
+Copyright © fsnotify Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this
+ list of conditions and the following disclaimer in the documentation and/or
+ other materials provided with the distribution.
+* Neither the name of Google Inc. nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+```
+
+=== yuin/goldmark
+; URL & Source
+: [[https://github.com/yuin/goldmark]]
+; License
+: MIT License
+```
+MIT License
+
+Copyright (c) 2019 Yusuke Inuzuka
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
+=== ASCIIToSVG
+; URL
+: [[https://github.com/asciitosvg/asciitosvg]]
+; License
+: MIT
+; Remarks
+: ASCIIToSVG was incorporated into the source code of Zettelstore and later moved into package ''t73f.de/r/webs/aasvg''.
+ The source code was changed substantially to adapt it to the needs of Zettelstore.
+```
+Copyright (c) 2015 The ASCIIToSVG Contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
+=== Sx, SxWebs, Webs, Zero, Zettelstore-Client, Zsx
+These are companion projects, written by the main developer of Zettelstore.
+They are published under the same license, [[EUPL v1.2, or later|00000000000004]].
+
+; URL & Source Sx
+: [[https://t73f.de/r/sx]]
+; URL & Source SxWebs
+: [[https://t73f.de/r/sxwebs]]
+; URL & Source Webs
+: [[https://t73f.de/r/webs]]
+; URL & Source Zero
+: [[https://t73f.de/r/zero]]
+; URL & Source Zettelstore-Client
+: [[https://t73f.de/r/zsc]]
+; URL & Source Zsx
+: [[https://t73f.de/r/zsx]]
+; License:
+: European Union Public License, version 1.2 (EUPL v1.2), or later.
ADDED internal/box/constbox/emoji_spin.gif
Index: internal/box/constbox/emoji_spin.gif
==================================================================
--- /dev/null
+++ internal/box/constbox/emoji_spin.gif
cannot compute difference between binary files
ADDED internal/box/constbox/error.sxn
Index: internal/box/constbox/error.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/error.sxn
@@ -0,0 +1,17 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(article
+ (header (h1 ,heading))
+ ,message
+)
ADDED internal/box/constbox/form.sxn
Index: internal/box/constbox/form.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/form.sxn
@@ -0,0 +1,63 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(article
+ (header (h1 ,heading))
+ (form (@ (action ,form-action-url) (method "POST") (enctype "multipart/form-data"))
+ (div
+ (label (@ (for "zs-title")) "Title " (a (@ (title "Main heading of this zettel.")) (@H "ⓘ")))
+ (input (@ (class "zs-input") (type "text") (id "zs-title") (name "title")
+ (title "Title of this zettel")
+ (placeholder "Title..") (value ,meta-title) (dir "auto") (autofocus))))
+ (div
+ (label (@ (for "zs-role")) "Role " (a (@ (title "One word, without spaces, to set the main role of this zettel.")) (@H "ⓘ")))
+ (input (@ (class "zs-input") (type "text") (pattern "\\w*") (id "zs-role") (name "role")
+ (title "One word, letters and digits, but no spaces, to set the main role of the zettel.")
+ (placeholder "role..") (value ,meta-role) (dir "auto")
+ ,@(if role-data '((list "zs-role-data")))
+ ))
+ ,@(wui-datalist "zs-role-data" role-data)
+ )
+ (div
+ (label (@ (for "zs-tags")) "Tags " (a (@ (title "Tags must begin with an '#' sign. They are separated by spaces.")) (@H "ⓘ")))
+ (input (@ (class "zs-input") (type "text") (id "zs-tags") (name "tags")
+ (title "Tags/keywords to categorize the zettel. Each tags is a word that begins with a '#' character; they are separated by spaces")
+ (placeholder "#tag") (value ,meta-tags) (dir "auto"))))
+ (div
+ (label (@ (for "zs-meta")) "Metadata " (a (@ (title "Other metadata for this zettel. Each line contains a key/value pair, separated by a colon ':'.")) (@H "ⓘ")))
+ (textarea (@ (class "zs-input") (id "zs-meta") (name "meta") (rows "4")
+ (title "Additional metadata about the zettel")
+ (placeholder "metakey: metavalue") (dir "auto")) ,meta))
+ (div
+ (label (@ (for "zs-syntax")) "Syntax " (a (@ (title "Syntax of zettel content below, one word. Typically 'zmk' (for zettelmarkup).")) (@H "ⓘ")))
+ (input (@ (class "zs-input") (type "text") (pattern "\\w*") (id "zs-syntax") (name "syntax")
+ (title "Syntax/format of zettel content below, one word, letters and digits, no spaces.")
+ (placeholder "syntax..") (value ,meta-syntax) (dir "auto")
+ ,@(if syntax-data '((list "zs-syntax-data")))
+ ))
+ ,@(wui-datalist "zs-syntax-data" syntax-data)
+ )
+ ,@(if (symbol-bound? 'content)
+ `((div
+ (label (@ (for "zs-content")) "Content " (a (@ (title "Content for this zettel, according to above syntax.")) (@H "ⓘ")))
+ (textarea (@ (class "zs-input zs-content") (id "zs-content") (name "content") (rows "20")
+ (title "Zettel content, according to the given syntax")
+ (placeholder "Zettel content..") (dir "auto")) ,content)
+ ))
+ )
+ (div
+ (input (@ (class "zs-primary") (type "submit") (value "Submit")))
+ (input (@ (class "zs-secondary") (type "submit") (value "Save") (formaction "?save")))
+ (input (@ (class "zs-upload") (type "file") (id "zs-file") (name "file")))
+ ))
+)
ADDED internal/box/constbox/home.zettel
Index: internal/box/constbox/home.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/home.zettel
@@ -0,0 +1,42 @@
+=== Thank you for using Zettelstore!
+
+You will find the latest information about Zettelstore at [[https://zettelstore.de/]].
+Check this website regularly for [[updates|https://zettelstore.de/home/doc/trunk/www/download.wiki]] to the latest version.
+You should consult the [[change log|https://zettelstore.de/home/doc/trunk/www/changes.wiki]] before updating.
+Sometimes, you have to edit some of your Zettelstore-related zettel before updating.
+Since Zettelstore is currently in a development state, every update might fix some of your problems.
+
+If you have problems concerning Zettelstore, do not hesitate to get in [[contact with the main developer|mailto:ds@zettelstore.de]].
+
+=== Reporting errors
+If you have encountered an error, please include the content of the following zettel in your mail (if possible):
+* [[Zettelstore Version|00000000000001]]: {{00000000000001}}
+* [[Zettelstore Operating System|00000000000003]]
+* [[Zettelstore Startup Configuration|00000000000096]]
+* [[Zettelstore Runtime Configuration|00000000000100]]
+
+Additionally, you have to describe, what you did before that error occurs
+and what you expected instead.
+Please do not forget to include the error message, if there is one.
+
+Some of above Zettelstore zettel can only be retrieved if you enabled ""expert mode"".
+Otherwise, only some zettel are linked.
+To enable expert mode, edit the zettel [[Zettelstore Runtime Configuration|00000000000100]]:
+please set the metadata value of the key ''expert-mode'' to true.
+To do so, enter the string ''expert-mode:true'' inside the edit view of the metadata.
+
+=== Information about this zettel
+This zettel is your home zettel.
+It is part of the Zettelstore software itself.
+Every time you click on the [[Home|//]] link in the menu bar, you will be redirected to this zettel.
+
+You can change the content of this zettel by clicking on ""Edit"" above.
+This allows you to customize your home zettel.
+
+Alternatively, you can designate another zettel as your home zettel.
+Edit the [[Zettelstore Runtime Configuration|00000000000100]] by adding the metadata key ''home-zettel''.
+Its value is the identifier of the zettel that should act as the new home zettel.
+You will find the identifier of each zettel between their ""Edit"" and the ""Info"" link above.
+The identifier of this zettel is ''00010000000000''.
+If you provide a wrong identifier, this zettel will be shown as the home zettel.
+Take a look inside the manual for further details.
ADDED internal/box/constbox/info.sxn
Index: internal/box/constbox/info.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/info.sxn
@@ -0,0 +1,52 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(article
+ (header (h1 "Information for Zettel " ,zid)
+ (p
+ (a (@ (href ,web-url)) "Web")
+ ,@(if (symbol-bound? 'edit-url) `((@H " · ") (a (@ (href ,edit-url)) "Edit")))
+ (@H " · ") (a (@ (href ,context-full-url)) "Full Context")
+ ,@(if (symbol-bound? 'thread-query-url)
+ `((@H " · [") (a (@ (href ,thread-query-url)) "Thread")
+ ,@(if (symbol-bound? 'folge-query-url) `((@H ", ") (a (@ (href ,folge-query-url)) "Folge")))
+ ,@(if (symbol-bound? 'sequel-query-url) `((@H ", ") (a (@ (href ,sequel-query-url)) "Sequel")))
+ (@H "]")))
+ ,@(ROLE-DEFAULT-actions (current-frame))
+ ,@(let* ((frame (current-frame))(rea (resolve-symbol 'ROLE-EXTRA-actions frame))) (if (defined? rea) (rea frame)))
+ ,@(if (symbol-bound? 'reindex-url) `((@H " · ") (a (@ (href ,reindex-url)) "Reindex")))
+ ,@(if (symbol-bound? 'delete-url) `((@H " · ") (a (@ (href ,delete-url)) "Delete")))
+ )
+ )
+ (h2 "Interpreted Metadata")
+ (table ,@(map wui-info-meta-table-row metadata))
+ (h2 "References")
+ ,@(if local-links `((h3 "Local") (ul ,@(map wui-local-link local-links))))
+ ,@(if query-links `((h3 "Queries") (ul ,@(map wui-item-link query-links))))
+ ,@(if ext-links `((h3 "External") (ul ,@(map wui-item-popup-link ext-links))))
+ (h3 "Unlinked")
+ ,@unlinked-content
+ (form
+ (label (@ (for "phrase")) "Search Phrase")
+ (input (@ (class "zs-input") (type "text") (id "phrase") (name ,query-key-phrase) (placeholder "Phrase..") (value ,phrase)))
+ )
+ (h2 "Parts and encodings")
+ ,(wui-enc-matrix enc-eval)
+ (h3 "Parsed (not evaluated)")
+ ,(wui-enc-matrix enc-parsed)
+ ,@(if shadow-links
+ `((h2 "Shadowed Boxes")
+ (ul ,@(map wui-item shadow-links))
+ )
+ )
+)
ADDED internal/box/constbox/license.txt
Index: internal/box/constbox/license.txt
==================================================================
--- /dev/null
+++ internal/box/constbox/license.txt
@@ -0,0 +1,295 @@
+Copyright (c) 2020-present Detlef Stern
+
+ Licensed under the EUPL
+
+Zettelstore is licensed under the European Union Public License, version 1.2 or
+later (EUPL v. 1.2). The license is available in the official languages of the
+EU. The English version is included here. Please see
+https://joinup.ec.europa.eu/community/eupl/og_page/eupl for official
+translations of the other languages.
+
+
+-------------------------------------------------------------------------------
+
+
+EUROPEAN UNION PUBLIC LICENCE v. 1.2
+EUPL © the European Union 2007, 2016
+
+This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined
+below) which is provided under the terms of this Licence. Any use of the Work,
+other than as authorised under this Licence is prohibited (to the extent such
+use is covered by a right of the copyright holder of the Work).
+
+The Work is provided under the terms of this Licence when the Licensor (as
+defined below) has placed the following notice immediately following the
+copyright notice for the Work:
+
+ Licensed under the EUPL
+
+or has expressed by any other means his willingness to license under the EUPL.
+
+1. Definitions
+
+In this Licence, the following terms have the following meaning:
+
+— ‘The Licence’: this Licence.
+— ‘The Original Work’: the work or software distributed or communicated by the
+ Licensor under this Licence, available as Source Code and also as Executable
+ Code as the case may be.
+— ‘Derivative Works’: the works or software that could be created by the
+ Licensee, based upon the Original Work or modifications thereof. This Licence
+ does not define the extent of modification or dependence on the Original Work
+ required in order to classify a work as a Derivative Work; this extent is
+ determined by copyright law applicable in the country mentioned in Article
+ 15.
+— ‘The Work’: the Original Work or its Derivative Works.
+— ‘The Source Code’: the human-readable form of the Work which is the most
+ convenient for people to study and modify.
+— ‘The Executable Code’: any code which has generally been compiled and which
+ is meant to be interpreted by a computer as a program.
+— ‘The Licensor’: the natural or legal person that distributes or communicates
+ the Work under the Licence.
+— ‘Contributor(s)’: any natural or legal person who modifies the Work under the
+ Licence, or otherwise contributes to the creation of a Derivative Work.
+— ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of
+ the Work under the terms of the Licence.
+— ‘Distribution’ or ‘Communication’: any act of selling, giving, lending,
+ renting, distributing, communicating, transmitting, or otherwise making
+ available, online or offline, copies of the Work or providing access to its
+ essential functionalities at the disposal of any other natural or legal
+ person.
+
+2. Scope of the rights granted by the Licence
+
+The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
+sublicensable licence to do the following, for the duration of copyright vested
+in the Original Work:
+
+— use the Work in any circumstance and for all usage,
+— reproduce the Work,
+— modify the Work, and make Derivative Works based upon the Work,
+— communicate to the public, including the right to make available or display
+ the Work or copies thereof to the public and perform publicly, as the case
+ may be, the Work,
+— distribute the Work or copies thereof,
+— lend and rent the Work or copies thereof,
+— sublicense rights in the Work or copies thereof.
+
+Those rights can be exercised on any media, supports and formats, whether now
+known or later invented, as far as the applicable law permits so.
+
+In the countries where moral rights apply, the Licensor waives his right to
+exercise his moral right to the extent allowed by law in order to make
+effective the licence of the economic rights here above listed.
+
+The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to
+any patents held by the Licensor, to the extent necessary to make use of the
+rights granted on the Work under this Licence.
+
+3. Communication of the Source Code
+
+The Licensor may provide the Work either in its Source Code form, or as
+Executable Code. If the Work is provided as Executable Code, the Licensor
+provides in addition a machine-readable copy of the Source Code of the Work
+along with each copy of the Work that the Licensor distributes or indicates, in
+a notice following the copyright notice attached to the Work, a repository
+where the Source Code is easily and freely accessible for as long as the
+Licensor continues to distribute or communicate the Work.
+
+4. Limitations on copyright
+
+Nothing in this Licence is intended to deprive the Licensee of the benefits
+from any exception or limitation to the exclusive rights of the rights owners
+in the Work, of the exhaustion of those rights or of other applicable
+limitations thereto.
+
+5. Obligations of the Licensee
+
+The grant of the rights mentioned above is subject to some restrictions and
+obligations imposed on the Licensee. Those obligations are the following:
+
+Attribution right: The Licensee shall keep intact all copyright, patent or
+trademarks notices and all notices that refer to the Licence and to the
+disclaimer of warranties. The Licensee must include a copy of such notices and
+a copy of the Licence with every copy of the Work he/she distributes or
+communicates. The Licensee must cause any Derivative Work to carry prominent
+notices stating that the Work has been modified and the date of modification.
+
+Copyleft clause: If the Licensee distributes or communicates copies of the
+Original Works or Derivative Works, this Distribution or Communication will be
+done under the terms of this Licence or of a later version of this Licence
+unless the Original Work is expressly distributed only under this version of
+the Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee
+(becoming Licensor) cannot offer or impose any additional terms or conditions
+on the Work or Derivative Work that alter or restrict the terms of the Licence.
+
+Compatibility clause: If the Licensee Distributes or Communicates Derivative
+Works or copies thereof based upon both the Work and another work licensed
+under a Compatible Licence, this Distribution or Communication can be done
+under the terms of this Compatible Licence. For the sake of this clause,
+‘Compatible Licence’ refers to the licences listed in the appendix attached to
+this Licence. Should the Licensee's obligations under the Compatible Licence
+conflict with his/her obligations under this Licence, the obligations of the
+Compatible Licence shall prevail.
+
+Provision of Source Code: When distributing or communicating copies of the
+Work, the Licensee will provide a machine-readable copy of the Source Code or
+indicate a repository where this Source will be easily and freely available for
+as long as the Licensee continues to distribute or communicate the Work.
+
+Legal Protection: This Licence does not grant permission to use the trade
+names, trademarks, service marks, or names of the Licensor, except as required
+for reasonable and customary use in describing the origin of the Work and
+reproducing the content of the copyright notice.
+
+6. Chain of Authorship
+
+The original Licensor warrants that the copyright in the Original Work granted
+hereunder is owned by him/her or licensed to him/her and that he/she has the
+power and authority to grant the Licence.
+
+Each Contributor warrants that the copyright in the modifications he/she brings
+to the Work are owned by him/her or licensed to him/her and that he/she has the
+power and authority to grant the Licence.
+
+Each time You accept the Licence, the original Licensor and subsequent
+Contributors grant You a licence to their contributions to the Work, under the
+terms of this Licence.
+
+7. Disclaimer of Warranty
+
+The Work is a work in progress, which is continuously improved by numerous
+Contributors. It is not a finished work and may therefore contain defects or
+‘bugs’ inherent to this type of development.
+
+For the above reason, the Work is provided under the Licence on an ‘as is’
+basis and without warranties of any kind concerning the Work, including without
+limitation merchantability, fitness for a particular purpose, absence of
+defects or errors, accuracy, non-infringement of intellectual property rights
+other than copyright as stated in Article 6 of this Licence.
+
+This disclaimer of warranty is an essential part of the Licence and a condition
+for the grant of any rights to the Work.
+
+8. Disclaimer of Liability
+
+Except in the cases of wilful misconduct or damages directly caused to natural
+persons, the Licensor will in no event be liable for any direct or indirect,
+material or moral, damages of any kind, arising out of the Licence or of the
+use of the Work, including without limitation, damages for loss of goodwill,
+work stoppage, computer failure or malfunction, loss of data or any commercial
+damage, even if the Licensor has been advised of the possibility of such
+damage. However, the Licensor will be liable under statutory product liability
+laws as far such laws apply to the Work.
+
+9. Additional agreements
+
+While distributing the Work, You may choose to conclude an additional
+agreement, defining obligations or services consistent with this Licence.
+However, if accepting obligations, You may act only on your own behalf and on
+your sole responsibility, not on behalf of the original Licensor or any other
+Contributor, and only if You agree to indemnify, defend, and hold each
+Contributor harmless for any liability incurred by, or claims asserted against
+such Contributor by the fact You have accepted any warranty or additional
+liability.
+
+10. Acceptance of the Licence
+
+The provisions of this Licence can be accepted by clicking on an icon ‘I agree’
+placed under the bottom of a window displaying the text of this Licence or by
+affirming consent in any other similar way, in accordance with the rules of
+applicable law. Clicking on that icon indicates your clear and irrevocable
+acceptance of this Licence and all of its terms and conditions.
+
+Similarly, you irrevocably accept this Licence and all of its terms and
+conditions by exercising any rights granted to You by Article 2 of this
+Licence, such as the use of the Work, the creation by You of a Derivative Work
+or the Distribution or Communication by You of the Work or copies thereof.
+
+11. Information to the public
+
+In case of any Distribution or Communication of the Work by means of electronic
+communication by You (for example, by offering to download the Work from
+a remote location) the distribution channel or media (for example, a website)
+must at least provide to the public the information requested by the applicable
+law regarding the Licensor, the Licence and the way it may be accessible,
+concluded, stored and reproduced by the Licensee.
+
+12. Termination of the Licence
+
+The Licence and the rights granted hereunder will terminate automatically upon
+any breach by the Licensee of the terms of the Licence.
+
+Such a termination will not terminate the licences of any person who has
+received the Work from the Licensee under the Licence, provided such persons
+remain in full compliance with the Licence.
+
+13. Miscellaneous
+
+Without prejudice of Article 9 above, the Licence represents the complete
+agreement between the Parties as to the Work.
+
+If any provision of the Licence is invalid or unenforceable under applicable
+law, this will not affect the validity or enforceability of the Licence as
+a whole. Such provision will be construed or reformed so as necessary to make
+it valid and enforceable.
+
+The European Commission may publish other linguistic versions or new versions
+of this Licence or updated versions of the Appendix, so far this is required
+and reasonable, without reducing the scope of the rights granted by the
+Licence. New versions of the Licence will be published with a unique version
+number.
+
+All linguistic versions of this Licence, approved by the European Commission,
+have identical value. Parties can take advantage of the linguistic version of
+their choice.
+
+14. Jurisdiction
+
+Without prejudice to specific agreement between parties,
+
+— any litigation resulting from the interpretation of this License, arising
+ between the European Union institutions, bodies, offices or agencies, as
+ a Licensor, and any Licensee, will be subject to the jurisdiction of the
+ Court of Justice of the European Union, as laid down in article 272 of the
+ Treaty on the Functioning of the European Union,
+— any litigation arising between other parties and resulting from the
+ interpretation of this License, will be subject to the exclusive jurisdiction
+ of the competent court where the Licensor resides or conducts its primary
+ business.
+
+15. Applicable Law
+
+Without prejudice to specific agreement between parties,
+
+— this Licence shall be governed by the law of the European Union Member State
+ where the Licensor has his seat, resides or has his registered office,
+— this licence shall be governed by Belgian law if the Licensor has no seat,
+ residence or registered office inside a European Union Member State.
+
+
+ Appendix
+
+
+‘Compatible Licences’ according to Article 5 EUPL are:
+
+— GNU General Public License (GPL) v. 2, v. 3
+— GNU Affero General Public License (AGPL) v. 3
+— Open Software License (OSL) v. 2.1, v. 3.0
+— Eclipse Public License (EPL) v. 1.0
+— CeCILL v. 2.0, v. 2.1
+— Mozilla Public Licence (MPL) v. 2
+— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
+— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
+ works other than software
+— European Union Public Licence (EUPL) v. 1.1, v. 1.2
+— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong
+ Reciprocity (LiLiQ-R+)
+
+The European Commission may update this Appendix to later versions of the above
+licences without producing a new version of the EUPL, as long as they provide
+the rights granted in Article 2 of this Licence and protect the covered Source
+Code from exclusive appropriation.
+
+All other changes or additions to this Appendix require the production of a new
+EUPL version.
ADDED internal/box/constbox/listzettel.sxn
Index: internal/box/constbox/listzettel.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/listzettel.sxn
@@ -0,0 +1,50 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(article
+ (header (h1 ,heading))
+ (search (form (@ (action ,search-url))
+ (input (@ (class "zs-input") (type "search") (inputmode "search") (name ,query-key-query)
+ (title "Contains the search that leads to the list below. You're allowed to modify it")
+ (placeholder "Search..") (value ,query-value) (dir "auto")))))
+ ,@(if (symbol-bound? 'tag-zettel)
+ `((p (@ (class "zs-meta-zettel")) "Tag zettel: " ,@tag-zettel))
+ )
+ ,@(if (symbol-bound? 'create-tag-zettel)
+ `((p (@ (class "zs-meta-zettel")) "Create tag zettel: " ,@create-tag-zettel))
+ )
+ ,@(if (symbol-bound? 'role-zettel)
+ `((p (@ (class "zs-meta-zettel")) "Role zettel: " ,@role-zettel))
+ )
+ ,@(if (symbol-bound? 'create-role-zettel)
+ `((p (@ (class "zs-meta-zettel")) "Create role zettel: " ,@create-role-zettel))
+ )
+ ,@content
+ ,@endnotes
+ (form (@ (action ,(if (symbol-bound? 'create-url) create-url)))
+ ,(if (symbol-bound? 'data-url)
+ `(@L "Other encodings"
+ ,(if (> num-entries 3) `(@L " of these " ,num-entries " entries: ") ": ")
+ (a (@ (href ,data-url)) "data")
+ ", "
+ (a (@ (href ,plain-url)) "plain")
+ )
+ )
+ ,@(if (symbol-bound? 'create-url)
+ `((input (@ (type "hidden") (name ,query-key-query) (value ,query-value)))
+ (input (@ (type "hidden") (name ,query-key-seed) (value ,seed)))
+ (input (@ (class "zs-primary") (type "submit") (value "Save As Zettel")))
+ )
+ )
+ )
+)
ADDED internal/box/constbox/login.sxn
Index: internal/box/constbox/login.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/login.sxn
@@ -0,0 +1,27 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(article
+ (header (h1 "Login"))
+ ,@(if retry '((div (@ (class "zs-indication zs-error")) "Wrong user name / password. Try again.")))
+ (form (@ (method "POST") (action ""))
+ (div
+ (label (@ (for "username")) "User name:")
+ (input (@ (class "zs-input") (type "text") (id "username") (name "username") (placeholder "Your user name..") (autofocus))))
+ (div
+ (label (@ (for "password")) "Password:")
+ (input (@ (class "zs-input") (type "password") (id "password") (name "password") (placeholder "Your password.."))))
+ (div
+ (input (@ (class "zs-primary") (type "submit") (value "Login"))))
+ )
+)
ADDED internal/box/constbox/menu_lists.zettel
Index: internal/box/constbox/menu_lists.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/menu_lists.zettel
@@ -0,0 +1,7 @@
+This zettel lists all entries of the ""Lists"" menu.
+
+* [[List Zettel|query:]]
+* [[List Roles|query:|role]]
+* [[List Tags|query:|tags]]
+
+An additional ""Refresh"" menu item is automatically added if appropriate.
ADDED internal/box/constbox/menu_new.zettel
Index: internal/box/constbox/menu_new.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/menu_new.zettel
@@ -0,0 +1,6 @@
+This zettel lists all zettel that should act as a template for new zettel.
+These zettel will be included in the ""New"" menu of the WebUI.
+* [[New Zettel|00000000090001]]
+* [[New Role|00000000090004]]
+* [[New Tag|00000000090003]]
+* [[New User|00000000090002]]
ADDED internal/box/constbox/roleconfiguration.zettel
Index: internal/box/constbox/roleconfiguration.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/roleconfiguration.zettel
@@ -0,0 +1,22 @@
+Zettel with role ""configuration"" are used within Zettelstore to manage and to show the current configuration of the software.
+
+Typically, there are some public zettel that show the license of this software, its dependencies.
+There is some CSS code to make the default web user interface a litte bit nicer.
+The default image to signal a broken image can be configured too.
+
+Other zettel are only visible if an user has authenticated itself, or if there is no authentication enabled.
+In this case, one additional configuration zettel is the zettel containing the version number of this software.
+Other zettel are showing the supported metadata keys and supported syntax values.
+Zettel that allow to configure the menu of template to create new zettel are also using the role ""configuration"".
+
+Most important is the zettel that contains the runtime configuration.
+You may change its metadata value to change the behaviour of the software.
+
+One configuration is the ""expert mode"".
+If enabled, and if you are authorized to see them, you will discover some more zettel.
+For example, HTML templates to customize the default web user interface, to show the application log, to see statistics about zettel boxes, to show the host name and it operating system, and many more.
+
+You are allowed to add your own configuration zettel, for example if you want to customize the look and feel of zettel by placing relevant data into your own zettel.
+
+By default, user zettel (for authentification) use also the role ""configuration"".
+However, you are allowed to change this.
ADDED internal/box/constbox/rolerole.zettel
Index: internal/box/constbox/rolerole.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/rolerole.zettel
@@ -0,0 +1,10 @@
+A zettel with the role ""role"" describes a specific role.
+The described role must be the title of such a zettel.
+
+This zettel is such a zettel, as it describes the meaning of the role ""role"".
+Therefore it has the title ""role"" too.
+If you like, this zettel is a meta-role.
+
+You are free to create your own role-describing zettel.
+For example, you want to document the intended meaning of the role.
+You might also be interested to describe needed metadata so that some software is enabled to analyse or to process your zettel.
ADDED internal/box/constbox/roletag.zettel
Index: internal/box/constbox/roletag.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/roletag.zettel
@@ -0,0 +1,6 @@
+A zettel with role ""tag"" is a zettel that describes specific tag.
+The tag name must be the title of such a zettel.
+
+Such zettel are similar to this specific zettel: this zettel describes zettel with a role ""tag"".
+These zettel with the role ""tag"" describe specific tags.
+These might form a hierarchy of meta-tags (and meta-roles).
ADDED internal/box/constbox/rolezettel.zettel
Index: internal/box/constbox/rolezettel.zettel
==================================================================
--- /dev/null
+++ internal/box/constbox/rolezettel.zettel
@@ -0,0 +1,7 @@
+A zettel with the role ""zettel"" is typically used to document your own thoughts.
+Such zettel are the main reason to use the software Zettelstore.
+
+The only predefined zettel with the role ""zettel"" is the [[default home zettel|00010000000000]], which contains some welcome information.
+
+You are free to change this.
+In this case you should modify this zettel too, so that it reflects your own use of zettel with the role ""zettel"".
ADDED internal/box/constbox/start.sxn
Index: internal/box/constbox/start.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/start.sxn
@@ -0,0 +1,17 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+;;; This zettel is the start of the loading sequence for Sx code used in the
+;;; Zettelstore. Via the precursor metadata, dependend zettel are evaluated
+;;; before this zettel. You must always depend, directly or indirectly on the
+;;; "Zettelstore Sxn Base Code" zettel. It provides the base definitions.
ADDED internal/box/constbox/wuicode.sxn
Index: internal/box/constbox/wuicode.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/wuicode.sxn
@@ -0,0 +1,141 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+;; Contains WebUI specific code, but not related to a specific template.
+
+;; wui-list-item returns the argument as a HTML list item.
+(defun wui-item (s) `(li ,s))
+
+;; wui-info-meta-table-row takes a pair and translates it into a HTML table row
+;; with two columns.
+(defun wui-info-meta-table-row (p)
+ `(tr (td (@ (class zs-info-meta-key)) ,(car p)) (td (@ (class zs-info-meta-value)) ,(cdr p))))
+
+;; wui-local-link translates a local link into HTML.
+(defun wui-local-link (l) `(li (a (@ (href ,l )) ,l)))
+
+;; wui-link takes a link (title . url) and returns a HTML reference.
+(defun wui-link (q) `(a (@ (href ,(cdr q))) ,(car q)))
+
+;; wui-item-link taks a pair (text . url) and returns a HTML link inside
+;; a list item.
+(defun wui-item-link (q) `(li ,(wui-link q)))
+
+;; wui-tdata-link taks a pair (text . url) and returns a HTML link inside
+;; a table data item.
+(defun wui-tdata-link (q) `(td ,(wui-link q)))
+
+;; wui-item-popup-link is like 'wui-item-link, but the HTML link will open
+;; a new tab / window.
+(defun wui-item-popup-link (e)
+ `(li (a (@ (href ,e) (target "_blank") (rel "external noreferrer")) ,e)))
+
+;; wui-option-value returns a value for an HTML option element.
+(defun wui-option-value (v) `(option (@ (value ,v))))
+
+;; wui-datalist returns a HTML datalist with the given HTML identifier and a
+;; list of values.
+(defun wui-datalist (id lst)
+ (if lst
+ `((datalist (@ (id ,id)) ,@(map wui-option-value lst)))))
+
+;; wui-pair-desc-item takes a pair '(term . text) and returns a list with
+;; a HTML description term and a HTML description data.
+(defun wui-pair-desc-item (p) `((dt ,(car p)) (dd ,(cdr p))))
+
+;; wui-meta-desc returns a HTML description list made from the list of pairs
+;; given.
+(defun wui-meta-desc (l)
+ `(dl ,@(apply append (map wui-pair-desc-item l))))
+
+;; wui-enc-matrix returns the HTML table of all encodings and parts.
+(defun wui-enc-matrix (matrix)
+ `(table
+ ,@(map
+ (lambda (row) `(tr (th ,(car row)) ,@(map wui-tdata-link (cdr row))))
+ matrix)))
+
+;; wui-optional-link puts the text into a link, if symbol is defined. Otherwise just return the text
+(defun wui-optional-link (text url-sym)
+ (let ((url (resolve-symbol url-sym)))
+ (if (defined? url)
+ `(a (@ (href ,(resolve-symbol url-sym))) ,text)
+ text)))
+
+;; CSS-ROLE-map is a mapping (pair list, assoc list) of role names to zettel
+;; identifier. It is used in the base template to update the metadata of the
+;; HTML page to include some role specific CSS code.
+;; Referenced in function "ROLE-DEFAULT-meta".
+(defvar CSS-ROLE-map '())
+
+;; ROLE-DEFAULT-meta returns some metadata for the base template. Any role
+;; specific code should include the returned list of this function.
+(defun ROLE-DEFAULT-meta (frame)
+ `(,@(let* ((meta-role (resolve-symbol 'meta-role frame))
+ (entry (assoc CSS-ROLE-map meta-role)))
+ (if (pair? entry)
+ `((link (@ (rel "stylesheet") (href ,(zid-content-path (cdr entry))))))
+ )
+ )
+ )
+)
+
+;; ACTION-SEPARATOR defines a HTML value that separates actions links.
+(defvar ACTION-SEPARATOR '(@H " · "))
+
+;; ROLE-DEFAULT-actions returns the default text for actions.
+(defun ROLE-DEFAULT-actions (frame)
+ `(,@(let ((copy-url (resolve-symbol 'copy-url frame)))
+ (if (defined? copy-url) `((@H " · ") (a (@ (href ,copy-url)) "Copy"))))
+ ,@(let ((sequel-url (resolve-symbol 'sequel-url frame)))
+ (if (defined? sequel-url) `((@H " · ") (a (@ (href ,sequel-url)) "Sequel"))))
+ ,@(let ((folge-url (resolve-symbol 'folge-url frame)))
+ (if (defined? folge-url) `((@H " · ") (a (@ (href ,folge-url)) "Folge"))))
+ )
+)
+
+;; ROLE-tag-actions returns an additional action "Zettel" for zettel with role "tag".
+(defun ROLE-tag-actions (frame)
+ `(,@(let ((title (resolve-symbol 'title frame)))
+ (if (and (defined? title) title)
+ `(,ACTION-SEPARATOR (a (@ (href ,(query->url (concat "tags:" title)))) "Zettel"))
+ )
+ )
+ )
+)
+
+;; ROLE-role-actions returns an additional action "Zettel" for zettel with role "role".
+(defun ROLE-role-actions (frame)
+ `(,@(let ((title (resolve-symbol 'title frame)))
+ (if (and (defined? title) title)
+ `(,ACTION-SEPARATOR (a (@ (href ,(query->url (concat "role:" title)))) "Zettel"))
+ )
+ )
+ )
+)
+
+;; ROLE-DEFAULT-heading returns the default text for headings, below the
+;; references of a zettel. In most cases it should be called from an
+;; overwriting function.
+(defun ROLE-DEFAULT-heading (frame)
+ `(,@(let ((meta-url (resolve-symbol 'meta-url frame)))
+ (if (defined? meta-url) `((br) "URL: " ,(url-to-html meta-url))))
+ ,@(let ((urls (resolve-symbol 'urls frame)))
+ (if (defined? urls)
+ (map (lambda (u) `(@L (br) ,(car u) ": " ,(url-to-html (cdr u)))) urls)
+ )
+ )
+ ,@(let ((meta-author (resolve-symbol 'meta-author frame)))
+ (if (and (defined? meta-author) meta-author) `((br) "By " ,meta-author)))
+ )
+)
ADDED internal/box/constbox/zettel.sxn
Index: internal/box/constbox/zettel.sxn
==================================================================
--- /dev/null
+++ internal/box/constbox/zettel.sxn
@@ -0,0 +1,53 @@
+;;;----------------------------------------------------------------------------
+;;; Copyright (c) 2023-present Detlef Stern
+;;;
+;;; This file is part of Zettelstore.
+;;;
+;;; Zettelstore is licensed under the latest version of the EUPL (European
+;;; Union Public License). Please see file LICENSE.txt for your rights and
+;;; obligations under this license.
+;;;
+;;; SPDX-License-Identifier: EUPL-1.2
+;;; SPDX-FileCopyrightText: 2023-present Detlef Stern
+;;;----------------------------------------------------------------------------
+
+`(article
+ (header
+ (h1 ,heading)
+ (div (@ (class "zs-meta"))
+ ,@(if (symbol-bound? 'edit-url) `((a (@ (href ,edit-url)) "Edit") (@H " · ")))
+ ,zid (@H " · ")
+ (a (@ (href ,info-url)) "Info") (@H " · ")
+ "(" ,@(if (symbol-bound? 'role-url) `((a (@ (href ,role-url)) ,meta-role)))
+ ,@(if (and (symbol-bound? 'folge-role-url) (symbol-bound? 'meta-folge-role))
+ `((@H " → ") (a (@ (href ,folge-role-url)) ,meta-folge-role)))
+ ")"
+ ,@(if tag-refs `((@H " · ") ,@tag-refs))
+ (@H " · ") (a (@ (href ,context-url)) "Context")
+ ,@(if (symbol-bound? 'thread-query-url) `((@H " · ") (a (@ (href ,thread-query-url)) "Thread")))
+ ,@(ROLE-DEFAULT-actions (current-frame))
+ ,@(let* ((frame (current-frame))(rea (resolve-symbol 'ROLE-EXTRA-actions frame))) (if (defined? rea) (rea frame)))
+ ,@(if superior-refs `((br) "Superior: " ,superior-refs))
+ ,@(if prequel-refs `((br) ,(wui-optional-link "Prequel" 'sequel-query-url) ": " ,prequel-refs))
+ ,@(if precursor-refs `((br) ,(wui-optional-link "Precursor" 'folge-query-url) ": " ,precursor-refs))
+ ,@(ROLE-DEFAULT-heading (current-frame))
+ ,@(let* ((frame (current-frame))(reh (resolve-symbol 'ROLE-EXTRA-heading frame))) (if (defined? reh) (reh frame)))
+ )
+ )
+ ,@content
+ ,endnotes
+ ,@(if (or folge-links sequel-links back-links subordinate-links)
+ `((nav
+ ,@(if folge-links
+ `((details (@ (,folge-open))
+ (summary ,(wui-optional-link "Folgezettel" 'folge-query-url))
+ (ul ,@(map wui-item-link folge-links)))))
+ ,@(if sequel-links
+ `((details (@ (,sequel-open))
+ (summary ,(wui-optional-link "Sequel" 'sequel-query-url))
+ (ul ,@(map wui-item-link sequel-links)))))
+ ,@(if subordinate-links `((details (@ (,subordinate-open)) (summary "Subordinates") (ul ,@(map wui-item-link subordinate-links)))))
+ ,@(if back-links `((details (@ (,back-open)) (summary "Incoming") (ul ,@(map wui-item-link back-links)))))
+ ))
+ )
+)
ADDED internal/box/dirbox/dirbox.go
Index: internal/box/dirbox/dirbox.go
==================================================================
--- /dev/null
+++ internal/box/dirbox/dirbox.go
@@ -0,0 +1,367 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package dirbox provides a directory-based zettel box.
+package dirbox
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager"
+ "zettelstore.de/z/internal/box/notify"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+func init() {
+ manager.Register("dir", func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) {
+ var logger *slog.Logger
+ if krnl := kernel.Main; krnl != nil {
+ logger = krnl.GetLogger(kernel.BoxService).With("box", "dir", "boxnum", cdata.Number)
+ }
+ path := getDirPath(u)
+ if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ dp := dirBox{
+ logger: logger,
+ number: cdata.Number,
+ location: u.String(),
+ readonly: box.GetQueryBool(u, "readonly"),
+ cdata: *cdata,
+ dir: path,
+ notifySpec: getDirSrvInfo(logger, u.Query().Get("type")),
+ fSrvs: makePrime(uint32(box.GetQueryInt(u, "worker", 1, 7, 1499))),
+ }
+ return &dp, nil
+ })
+}
+
+func makePrime(n uint32) uint32 {
+ for !isPrime(n) {
+ n++
+ }
+ return n
+}
+
+func isPrime(n uint32) bool {
+ if n == 0 {
+ return false
+ }
+ if n <= 3 {
+ return true
+ }
+ if n%2 == 0 {
+ return false
+ }
+ for i := uint32(3); i*i <= n; i += 2 {
+ if n%i == 0 {
+ return false
+ }
+ }
+ return true
+}
+
+type notifyTypeSpec int
+
+const (
+ _ notifyTypeSpec = iota
+ dirNotifyAny
+ dirNotifySimple
+ dirNotifyFS
+)
+
+func getDirSrvInfo(logger *slog.Logger, notifyType string) notifyTypeSpec {
+ for range 2 {
+ switch notifyType {
+ case kernel.BoxDirTypeNotify:
+ return dirNotifyFS
+ case kernel.BoxDirTypeSimple:
+ return dirNotifySimple
+ default:
+ notifyType = kernel.Main.GetConfig(kernel.BoxService, kernel.BoxDefaultDirType).(string)
+ }
+ }
+ logger.Error("Unable to set notify type, using a default", "notifyType", notifyType)
+ return dirNotifySimple
+}
+
+func getDirPath(u *url.URL) string {
+ if u.Opaque != "" {
+ return filepath.Clean(u.Opaque)
+ }
+ return filepath.Clean(u.Path)
+}
+
+// dirBox uses a directory to store zettel as files.
+type dirBox struct {
+ logger *slog.Logger
+ number int
+ location string
+ readonly bool
+ cdata manager.ConnectData
+ dir string
+ notifySpec notifyTypeSpec
+ dirSrv *notify.DirService
+ fSrvs uint32
+ fCmds []chan fileCmd
+ mxCmds sync.RWMutex
+}
+
+func (dp *dirBox) Location() string {
+ return dp.location
+}
+
+func (dp *dirBox) State() box.StartState {
+ if ds := dp.dirSrv; ds != nil {
+ switch ds.State() {
+ case notify.DsCreated:
+ return box.StartStateStopped
+ case notify.DsStarting:
+ return box.StartStateStarting
+ case notify.DsWorking:
+ return box.StartStateStarted
+ case notify.DsMissing:
+ return box.StartStateStarted
+ case notify.DsStopping:
+ return box.StartStateStopping
+ }
+ }
+ return box.StartStateStopped
+}
+
+func (dp *dirBox) Start(context.Context) error {
+ dp.mxCmds.Lock()
+ defer dp.mxCmds.Unlock()
+ dp.fCmds = make([]chan fileCmd, 0, dp.fSrvs)
+ for i := range dp.fSrvs {
+ cc := make(chan fileCmd)
+ go fileService(i, dp.logger.With("sub", "file", "fn", i), dp.dir, cc)
+ dp.fCmds = append(dp.fCmds, cc)
+ }
+
+ var notifier notify.Notifier
+ var err error
+ switch dp.notifySpec {
+ case dirNotifySimple:
+ notifier, err = notify.NewSimpleDirNotifier(dp.logger.With("notify", "simple"), dp.dir)
+ default:
+ notifier, err = notify.NewFSDirNotifier(dp.logger.With("notify", "fs"), dp.dir)
+ }
+ if err != nil {
+ dp.logger.Error("Unable to create directory supervisor", "err", err)
+ dp.stopFileServices()
+ return err
+ }
+ dp.dirSrv = notify.NewDirService(
+ dp,
+ dp.logger.With("sub", "dirsrv"),
+ notifier,
+ dp.cdata.Notify,
+ )
+ dp.dirSrv.Start()
+ return nil
+}
+
+func (dp *dirBox) Refresh(_ context.Context) {
+ dp.dirSrv.Refresh()
+ logging.LogTrace(dp.logger, "Refresh")
+}
+
+func (dp *dirBox) Stop(_ context.Context) {
+ dirSrv := dp.dirSrv
+ dp.dirSrv = nil
+ if dirSrv != nil {
+ dirSrv.Stop()
+ }
+ dp.stopFileServices()
+}
+
+func (dp *dirBox) stopFileServices() {
+ for _, c := range dp.fCmds {
+ close(c)
+ }
+}
+
+func (dp *dirBox) notifyChanged(zid id.Zid, reason box.UpdateReason) {
+ if notify := dp.cdata.Notify; notify != nil {
+ logging.LogTrace(dp.logger, "notifyChanged", "zid", zid, "reason", reason)
+ notify(dp, zid, reason)
+ }
+}
+
+func (dp *dirBox) getFileChan(zid id.Zid) chan fileCmd {
+ // Based on https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
+ sum := 2166136261 ^ uint32(zid)
+ sum *= 16777619
+ sum ^= uint32(zid >> 32)
+ sum *= 16777619
+
+ dp.mxCmds.RLock()
+ defer dp.mxCmds.RUnlock()
+ return dp.fCmds[sum%dp.fSrvs]
+}
+
+func (dp *dirBox) CanCreateZettel(_ context.Context) bool {
+ return !dp.readonly
+}
+
+func (dp *dirBox) CreateZettel(ctx context.Context, zettel zettel.Zettel) (id.Zid, error) {
+ if dp.readonly {
+ return id.Invalid, box.ErrReadOnly
+ }
+
+ newZid, err := dp.dirSrv.SetNewDirEntry()
+ if err != nil {
+ return id.Invalid, err
+ }
+ meta := zettel.Meta
+ meta.Zid = newZid
+ entry := notify.DirEntry{Zid: newZid}
+ dp.updateEntryFromMetaContent(&entry, meta, zettel.Content)
+
+ err = dp.srvSetZettel(ctx, &entry, zettel)
+ if err == nil {
+ err = dp.dirSrv.UpdateDirEntry(&entry)
+ }
+ dp.notifyChanged(meta.Zid, box.OnZettel)
+ logging.LogTrace(dp.logger, "CreateZettel", logging.Err(err), "zid", meta.Zid)
+ return meta.Zid, err
+}
+
+func (dp *dirBox) GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error) {
+ entry := dp.dirSrv.GetDirEntry(zid)
+ if !entry.IsValid() {
+ return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
+ }
+ m, c, err := dp.srvGetMetaContent(ctx, entry, zid)
+ if err != nil {
+ return zettel.Zettel{}, err
+ }
+ zettel := zettel.Zettel{Meta: m, Content: zettel.NewContent(c)}
+ logging.LogTrace(dp.logger, "GetZettel", "zid", zid)
+ return zettel, nil
+}
+
+func (dp *dirBox) HasZettel(_ context.Context, zid id.Zid) bool {
+ return dp.dirSrv.GetDirEntry(zid).IsValid()
+}
+
+func (dp *dirBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint query.RetrievePredicate) error {
+ entries := dp.dirSrv.GetDirEntries(constraint)
+ logging.LogTrace(dp.logger, "ApplyZid", "entries", len(entries))
+ for _, entry := range entries {
+ handle(entry.Zid)
+ }
+ return nil
+}
+
+func (dp *dirBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint query.RetrievePredicate) error {
+ entries := dp.dirSrv.GetDirEntries(constraint)
+ logging.LogTrace(dp.logger, "ApplyMeta", "entries", len(entries))
+
+ // The following loop could be parallelized if needed for performance.
+ for _, entry := range entries {
+ m, err := dp.srvGetMeta(ctx, entry, entry.Zid)
+ if err != nil {
+ logging.LogTrace(dp.logger, "ApplyMeta/getMeta", "err", err)
+ return err
+ }
+ dp.cdata.Enricher.Enrich(ctx, m, dp.number)
+ handle(m)
+ }
+ return nil
+}
+
+func (dp *dirBox) CanUpdateZettel(context.Context, zettel.Zettel) bool {
+ return !dp.readonly
+}
+
+func (dp *dirBox) UpdateZettel(ctx context.Context, zettel zettel.Zettel) error {
+ if dp.readonly {
+ return box.ErrReadOnly
+ }
+
+ meta := zettel.Meta
+ zid := meta.Zid
+ if !zid.IsValid() {
+ return box.ErrInvalidZid{Zid: zid.String()}
+ }
+ entry := dp.dirSrv.GetDirEntry(zid)
+ if !entry.IsValid() {
+ // Existing zettel, but new in this box.
+ entry = ¬ify.DirEntry{Zid: zid}
+ }
+ dp.updateEntryFromMetaContent(entry, meta, zettel.Content)
+ err := dp.dirSrv.UpdateDirEntry(entry)
+ if err != nil {
+ return err
+ }
+ err = dp.srvSetZettel(ctx, entry, zettel)
+ if err == nil {
+ dp.notifyChanged(zid, box.OnZettel)
+ }
+ logging.LogTrace(dp.logger, "UpdateZettel", "zid", zid, logging.Err(err))
+ return err
+}
+
+func (dp *dirBox) updateEntryFromMetaContent(entry *notify.DirEntry, m *meta.Meta, content zettel.Content) {
+ entry.SetupFromMetaContent(m, content, dp.cdata.Config.GetZettelFileSyntax)
+}
+
+func (dp *dirBox) CanDeleteZettel(_ context.Context, zid id.Zid) bool {
+ if dp.readonly {
+ return false
+ }
+ entry := dp.dirSrv.GetDirEntry(zid)
+ return entry.IsValid()
+}
+
+func (dp *dirBox) DeleteZettel(ctx context.Context, zid id.Zid) error {
+ if dp.readonly {
+ return box.ErrReadOnly
+ }
+
+ entry := dp.dirSrv.GetDirEntry(zid)
+ if !entry.IsValid() {
+ return box.ErrZettelNotFound{Zid: zid}
+ }
+ err := dp.dirSrv.DeleteDirEntry(zid)
+ if err != nil {
+ return nil
+ }
+ err = dp.srvDeleteZettel(ctx, entry, zid)
+ if err == nil {
+ dp.notifyChanged(zid, box.OnDelete)
+ }
+ logging.LogTrace(dp.logger, "DeleteZettel", "zid", zid, logging.Err(err))
+ return err
+}
+
+func (dp *dirBox) ReadStats(st *box.ManagedBoxStats) {
+ st.ReadOnly = dp.readonly
+ st.Zettel = dp.dirSrv.NumDirEntries()
+ logging.LogTrace(dp.logger, "ReadStats", "zettel", st.Zettel)
+}
ADDED internal/box/dirbox/dirbox_test.go
Index: internal/box/dirbox/dirbox_test.go
==================================================================
--- /dev/null
+++ internal/box/dirbox/dirbox_test.go
@@ -0,0 +1,53 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package dirbox
+
+import "testing"
+
+func TestIsPrime(t *testing.T) {
+ testcases := []struct {
+ n uint32
+ exp bool
+ }{
+ {0, false}, {1, true}, {2, true}, {3, true}, {4, false}, {5, true},
+ {6, false}, {7, true}, {8, false}, {9, false}, {10, false},
+ {11, true}, {12, false}, {13, true}, {14, false}, {15, false},
+ {17, true}, {19, true}, {21, false}, {23, true}, {25, false},
+ {27, false}, {29, true}, {31, true}, {33, false}, {35, false},
+ }
+ for _, tc := range testcases {
+ got := isPrime(tc.n)
+ if got != tc.exp {
+ t.Errorf("isPrime(%d)=%v, but got %v", tc.n, tc.exp, got)
+ }
+ }
+}
+
+func TestMakePrime(t *testing.T) {
+ for i := range uint32(1500) {
+ np := makePrime(i)
+ if np < i {
+ t.Errorf("makePrime(%d) < %d", i, np)
+ continue
+ }
+ if !isPrime(np) {
+ t.Errorf("makePrime(%d) == %d is not prime", i, np)
+ continue
+ }
+ if isPrime(i) && i != np {
+ t.Errorf("%d is already prime, but got %d as next prime", i, np)
+ continue
+ }
+ }
+}
ADDED internal/box/dirbox/service.go
Index: internal/box/dirbox/service.go
==================================================================
--- /dev/null
+++ internal/box/dirbox/service.go
@@ -0,0 +1,397 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package dirbox
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "time"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "t73f.de/r/zsx/input"
+
+ "zettelstore.de/z/internal/box/filebox"
+ "zettelstore.de/z/internal/box/notify"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/zettel"
+)
+
+func fileService(i uint32, logger *slog.Logger, dirPath string, cmds <-chan fileCmd) {
+ // Something may panic. Ensure a running service.
+ defer func() {
+ if ri := recover(); ri != nil {
+ kernel.Main.LogRecover("FileService", ri)
+ go fileService(i, logger, dirPath, cmds)
+ }
+ }()
+
+ logger.Debug("File service started", "i", i, "dirpath", dirPath)
+ for cmd := range cmds {
+ cmd.run(dirPath)
+ }
+ logger.Debug("File service stopped", "i", i, "dirpath", dirPath)
+}
+
+type fileCmd interface {
+ run(string)
+}
+
+const serviceTimeout = 5 * time.Second // must be shorter than the web servers timeout values for reading+writing.
+
+// COMMAND: srvGetMeta ----------------------------------------
+//
+// Retrieves the meta data from a zettel.
+
+func (dp *dirBox) srvGetMeta(ctx context.Context, entry *notify.DirEntry, zid id.Zid) (*meta.Meta, error) {
+ rc := make(chan resGetMeta, 1)
+ dp.getFileChan(zid) <- &fileGetMeta{entry, rc}
+ ctx, cancel := context.WithTimeout(ctx, serviceTimeout)
+ defer cancel()
+ select {
+ case res := <-rc:
+ return res.meta, res.err
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+}
+
+type fileGetMeta struct {
+ entry *notify.DirEntry
+ rc chan<- resGetMeta
+}
+type resGetMeta struct {
+ meta *meta.Meta
+ err error
+}
+
+func (cmd *fileGetMeta) run(dirPath string) {
+ var m *meta.Meta
+ var err error
+
+ entry := cmd.entry
+ zid := entry.Zid
+ if metaName := entry.MetaName; metaName == "" {
+ contentName := entry.ContentName
+ contentExt := entry.ContentExt
+ if contentName == "" || contentExt == "" {
+ err = fmt.Errorf("no meta, no content in getMeta, zid=%v", zid)
+ } else if entry.HasMetaInContent() {
+ m, _, err = parseMetaContentFile(zid, filepath.Join(dirPath, contentName))
+ } else {
+ m = filebox.CalcDefaultMeta(zid, contentExt)
+ }
+ } else {
+ m, err = parseMetaFile(zid, filepath.Join(dirPath, metaName))
+ }
+ if err == nil {
+ cmdCleanupMeta(m, entry)
+ }
+ cmd.rc <- resGetMeta{m, err}
+}
+
+// COMMAND: srvGetMetaContent ----------------------------------------
+//
+// Retrieves the meta data and the content of a zettel.
+
+func (dp *dirBox) srvGetMetaContent(ctx context.Context, entry *notify.DirEntry, zid id.Zid) (*meta.Meta, []byte, error) {
+ rc := make(chan resGetMetaContent, 1)
+ dp.getFileChan(zid) <- &fileGetMetaContent{entry, rc}
+ ctx, cancel := context.WithTimeout(ctx, serviceTimeout)
+ defer cancel()
+ select {
+ case res := <-rc:
+ return res.meta, res.content, res.err
+ case <-ctx.Done():
+ return nil, nil, ctx.Err()
+ }
+}
+
+type fileGetMetaContent struct {
+ entry *notify.DirEntry
+ rc chan<- resGetMetaContent
+}
+type resGetMetaContent struct {
+ meta *meta.Meta
+ content []byte
+ err error
+}
+
+func (cmd *fileGetMetaContent) run(dirPath string) {
+ var m *meta.Meta
+ var content []byte
+ var err error
+
+ entry := cmd.entry
+ zid := entry.Zid
+ contentName := entry.ContentName
+ contentExt := entry.ContentExt
+ contentPath := filepath.Join(dirPath, contentName)
+ if metaName := entry.MetaName; metaName == "" {
+ if contentName == "" || contentExt == "" {
+ err = fmt.Errorf("no meta, no content in getMetaContent, zid=%v", zid)
+ } else if entry.HasMetaInContent() {
+ m, content, err = parseMetaContentFile(zid, contentPath)
+ } else {
+ m = filebox.CalcDefaultMeta(zid, contentExt)
+ content, err = os.ReadFile(contentPath)
+ }
+ } else {
+ m, err = parseMetaFile(zid, filepath.Join(dirPath, metaName))
+ if contentName != "" {
+ var err1 error
+ content, err1 = os.ReadFile(contentPath)
+ if err == nil {
+ err = err1
+ }
+ }
+ }
+ if err == nil {
+ cmdCleanupMeta(m, entry)
+ }
+ cmd.rc <- resGetMetaContent{m, content, err}
+}
+
+// COMMAND: srvSetZettel ----------------------------------------
+//
+// Writes a new or exsting zettel.
+
+func (dp *dirBox) srvSetZettel(ctx context.Context, entry *notify.DirEntry, zettel zettel.Zettel) error {
+ rc := make(chan resSetZettel, 1)
+ dp.getFileChan(zettel.Meta.Zid) <- &fileSetZettel{entry, zettel, rc}
+ ctx, cancel := context.WithTimeout(ctx, serviceTimeout)
+ defer cancel()
+ select {
+ case err := <-rc:
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+type fileSetZettel struct {
+ entry *notify.DirEntry
+ zettel zettel.Zettel
+ rc chan<- resSetZettel
+}
+type resSetZettel = error
+
+func (cmd *fileSetZettel) run(dirPath string) {
+ var err error
+ entry := cmd.entry
+ zid := entry.Zid
+ contentName := entry.ContentName
+ m := cmd.zettel.Meta
+ content := cmd.zettel.Content.AsBytes()
+ metaName := entry.MetaName
+ if metaName == "" {
+ if contentName == "" {
+ err = fmt.Errorf("no meta, no content in setZettel, zid=%v", zid)
+ } else {
+ contentPath := filepath.Join(dirPath, contentName)
+ if entry.HasMetaInContent() {
+ err = writeZettelFile(contentPath, m, content)
+ cmd.rc <- err
+ return
+ }
+ err = writeFileContent(contentPath, content)
+ }
+ cmd.rc <- err
+ return
+ }
+
+ err = writeMetaFile(filepath.Join(dirPath, metaName), m)
+ if err == nil && contentName != "" {
+ err = writeFileContent(filepath.Join(dirPath, contentName), content)
+ }
+ cmd.rc <- err
+}
+
+func writeMetaFile(metaPath string, m *meta.Meta) error {
+ metaFile, err := openFileWrite(metaPath)
+ if err != nil {
+ return err
+ }
+ err = writeFileZid(metaFile, m.Zid)
+ if err == nil {
+ _, err = m.WriteComputed(metaFile)
+ }
+ if err1 := metaFile.Close(); err == nil {
+ err = err1
+ }
+ return err
+}
+
+func writeZettelFile(contentPath string, m *meta.Meta, content []byte) error {
+ zettelFile, err := openFileWrite(contentPath)
+ if err != nil {
+ return err
+ }
+ err = writeMetaHeader(zettelFile, m)
+ if err == nil {
+ _, err = zettelFile.Write(content)
+ }
+ if err1 := zettelFile.Close(); err == nil {
+ err = err1
+ }
+ return err
+}
+
+var (
+ newline = []byte{'\n'}
+ yamlSep = []byte{'-', '-', '-', '\n'}
+)
+
+func writeMetaHeader(w io.Writer, m *meta.Meta) (err error) {
+ if m.YamlSep {
+ _, err = w.Write(yamlSep)
+ if err != nil {
+ return err
+ }
+ }
+ err = writeFileZid(w, m.Zid)
+ if err != nil {
+ return err
+ }
+ _, err = m.WriteComputed(w)
+ if err != nil {
+ return err
+ }
+ if m.YamlSep {
+ _, err = w.Write(yamlSep)
+ } else {
+ _, err = w.Write(newline)
+ }
+ return err
+}
+
+// COMMAND: srvDeleteZettel ----------------------------------------
+//
+// Deletes an existing zettel.
+
+func (dp *dirBox) srvDeleteZettel(ctx context.Context, entry *notify.DirEntry, zid id.Zid) error {
+ rc := make(chan resDeleteZettel, 1)
+ dp.getFileChan(zid) <- &fileDeleteZettel{entry, rc}
+ ctx, cancel := context.WithTimeout(ctx, serviceTimeout)
+ defer cancel()
+ select {
+ case err := <-rc:
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+type fileDeleteZettel struct {
+ entry *notify.DirEntry
+ rc chan<- resDeleteZettel
+}
+type resDeleteZettel = error
+
+func (cmd *fileDeleteZettel) run(dirPath string) {
+ var err error
+
+ entry := cmd.entry
+ contentName := entry.ContentName
+ contentPath := filepath.Join(dirPath, contentName)
+ if metaName := entry.MetaName; metaName == "" {
+ if contentName == "" {
+ err = fmt.Errorf("no meta, no content in deleteZettel, zid=%v", entry.Zid)
+ } else {
+ err = os.Remove(contentPath)
+ }
+ } else {
+ if contentName != "" {
+ err = os.Remove(contentPath)
+ }
+ err1 := os.Remove(filepath.Join(dirPath, metaName))
+ if err == nil {
+ err = err1
+ }
+ }
+ for _, dupName := range entry.UselessFiles {
+ err1 := os.Remove(filepath.Join(dirPath, dupName))
+ if err == nil {
+ err = err1
+ }
+ }
+ cmd.rc <- err
+}
+
+// Utility functions ----------------------------------------
+
+func parseMetaFile(zid id.Zid, path string) (*meta.Meta, error) {
+ src, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ inp := input.NewInput(src)
+ return meta.NewFromInput(zid, inp), nil
+}
+
+func parseMetaContentFile(zid id.Zid, path string) (*meta.Meta, []byte, error) {
+ src, err := os.ReadFile(path)
+ if err != nil {
+ return nil, nil, err
+ }
+ inp := input.NewInput(src)
+ meta := meta.NewFromInput(zid, inp)
+ return meta, src[inp.Pos:], nil
+}
+
+func cmdCleanupMeta(m *meta.Meta, entry *notify.DirEntry) {
+ filebox.CleanupMeta(
+ m,
+ entry.Zid,
+ entry.ContentExt,
+ entry.MetaName != "",
+ entry.UselessFiles,
+ )
+}
+
+// fileMode to create a new file: user, group, and all are allowed to read and write.
+//
+// If you want to forbid others or the group to read or to write, you must set
+// umask(1) accordingly.
+const fileMode os.FileMode = 0666 //
+
+func openFileWrite(path string) (*os.File, error) {
+ return os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode)
+}
+
+func writeFileZid(w io.Writer, zid id.Zid) error {
+ _, err := io.WriteString(w, "id: ")
+ if err == nil {
+ _, err = w.Write(zid.Bytes())
+ if err == nil {
+ _, err = io.WriteString(w, "\n")
+ }
+ }
+ return err
+}
+
+func writeFileContent(path string, content []byte) error {
+ f, err := openFileWrite(path)
+ if err == nil {
+ _, err = f.Write(content)
+ if err1 := f.Close(); err == nil {
+ err = err1
+ }
+ }
+ return err
+}
ADDED internal/box/filebox/filebox.go
Index: internal/box/filebox/filebox.go
==================================================================
--- /dev/null
+++ internal/box/filebox/filebox.go
@@ -0,0 +1,96 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package filebox provides boxes that are stored in a file.
+package filebox
+
+import (
+ "errors"
+ "net/url"
+ "path/filepath"
+ "strings"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager"
+ "zettelstore.de/z/internal/kernel"
+)
+
+func init() {
+ manager.Register("file", func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) {
+ path := getFilepathFromURL(u)
+ ext := strings.ToLower(filepath.Ext(path))
+ if ext != ".zip" {
+ return nil, errors.New("unknown extension '" + ext + "' in box URL: " + u.String())
+ }
+ return &zipBox{
+ logger: kernel.Main.GetLogger(kernel.BoxService).With("box", "zip", "boxnum", cdata.Number),
+ number: cdata.Number,
+ name: path,
+ enricher: cdata.Enricher,
+ notify: cdata.Notify,
+ }, nil
+ })
+}
+
+func getFilepathFromURL(u *url.URL) string {
+ name := u.Opaque
+ if name == "" {
+ name = u.Path
+ }
+ components := strings.Split(name, "/")
+ fileName := filepath.Join(components...)
+ if len(components) > 0 && components[0] == "" {
+ return "/" + fileName
+ }
+ return fileName
+}
+
+var alternativeSyntax = map[string]meta.Value{
+ "htm": "html",
+}
+
+func calculateSyntax(ext string) meta.Value {
+ ext = strings.ToLower(ext)
+ if syntax, ok := alternativeSyntax[ext]; ok {
+ return syntax
+ }
+ return meta.Value(ext)
+}
+
+// CalcDefaultMeta returns metadata with default values for the given entry.
+func CalcDefaultMeta(zid id.Zid, ext string) *meta.Meta {
+ m := meta.New(zid)
+ m.Set(meta.KeySyntax, calculateSyntax(ext))
+ return m
+}
+
+// CleanupMeta enhances the given metadata.
+func CleanupMeta(m *meta.Meta, zid id.Zid, ext string, inMeta bool, uselessFiles []string) {
+ if inMeta {
+ if syntax, ok := m.Get(meta.KeySyntax); !ok || syntax == "" {
+ dm := CalcDefaultMeta(zid, ext)
+ syntax, ok = dm.Get(meta.KeySyntax)
+ if !ok {
+ panic("Default meta must contain syntax")
+ }
+ m.Set(meta.KeySyntax, syntax)
+ }
+ }
+
+ if len(uselessFiles) > 0 {
+ m.Set(meta.KeyUselessFiles, meta.Value(strings.Join(uselessFiles, " ")))
+ }
+}
ADDED internal/box/filebox/zipbox.go
Index: internal/box/filebox/zipbox.go
==================================================================
--- /dev/null
+++ internal/box/filebox/zipbox.go
@@ -0,0 +1,237 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package filebox
+
+import (
+ "archive/zip"
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "strings"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "t73f.de/r/zsx/input"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/notify"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+type zipBox struct {
+ logger *slog.Logger
+ number int
+ name string
+ enricher box.Enricher
+ notify box.UpdateNotifier
+ dirSrv *notify.DirService
+}
+
+func (zb *zipBox) Location() string {
+ if strings.HasPrefix(zb.name, "/") {
+ return "file://" + zb.name
+ }
+ return "file:" + zb.name
+}
+
+func (zb *zipBox) State() box.StartState {
+ if ds := zb.dirSrv; ds != nil {
+ switch ds.State() {
+ case notify.DsCreated:
+ return box.StartStateStopped
+ case notify.DsStarting:
+ return box.StartStateStarting
+ case notify.DsWorking:
+ return box.StartStateStarted
+ case notify.DsMissing:
+ return box.StartStateStarted
+ case notify.DsStopping:
+ return box.StartStateStopping
+ }
+ }
+ return box.StartStateStopped
+}
+
+func (zb *zipBox) Start(context.Context) error {
+ reader, err := zip.OpenReader(zb.name)
+ if err != nil {
+ return err
+ }
+ if err = reader.Close(); err != nil {
+ return err
+ }
+ zipNotifier := notify.NewSimpleZipNotifier(zb.logger, zb.name)
+ zb.dirSrv = notify.NewDirService(zb, zb.logger, zipNotifier, zb.notify)
+ zb.dirSrv.Start()
+ return nil
+}
+
+func (zb *zipBox) Refresh(_ context.Context) {
+ zb.dirSrv.Refresh()
+ logging.LogTrace(zb.logger, "Refresh")
+}
+
+func (zb *zipBox) Stop(context.Context) {
+ zb.dirSrv.Stop()
+ zb.dirSrv = nil
+}
+
+func (zb *zipBox) GetZettel(_ context.Context, zid id.Zid) (zettel.Zettel, error) {
+ entry := zb.dirSrv.GetDirEntry(zid)
+ if !entry.IsValid() {
+ return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
+ }
+ reader, err := zip.OpenReader(zb.name)
+ if err != nil {
+ return zettel.Zettel{}, err
+ }
+ defer func() { _ = reader.Close() }()
+
+ var m *meta.Meta
+ var src []byte
+ var inMeta bool
+
+ contentName := entry.ContentName
+ if metaName := entry.MetaName; metaName == "" {
+ if contentName == "" {
+ err = fmt.Errorf("no meta, no content in getZettel, zid=%v", zid)
+ return zettel.Zettel{}, err
+ }
+ src, err = readZipFileContent(reader, entry.ContentName)
+ if err != nil {
+ return zettel.Zettel{}, err
+ }
+ if entry.HasMetaInContent() {
+ inp := input.NewInput(src)
+ m = meta.NewFromInput(zid, inp)
+ src = src[inp.Pos:]
+ } else {
+ m = CalcDefaultMeta(zid, entry.ContentExt)
+ }
+ } else {
+ m, err = readZipMetaFile(reader, zid, metaName)
+ if err != nil {
+ return zettel.Zettel{}, err
+ }
+ inMeta = true
+ if contentName != "" {
+ src, err = readZipFileContent(reader, entry.ContentName)
+ if err != nil {
+ return zettel.Zettel{}, err
+ }
+ }
+ }
+
+ CleanupMeta(m, zid, entry.ContentExt, inMeta, entry.UselessFiles)
+ logging.LogTrace(zb.logger, "GetZettel", "zid", zid)
+ return zettel.Zettel{Meta: m, Content: zettel.NewContent(src)}, nil
+}
+
+func (zb *zipBox) HasZettel(_ context.Context, zid id.Zid) bool {
+ return zb.dirSrv.GetDirEntry(zid).IsValid()
+}
+
+func (zb *zipBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint query.RetrievePredicate) error {
+ entries := zb.dirSrv.GetDirEntries(constraint)
+ logging.LogTrace(zb.logger, "ApplyZid", "entries", len(entries))
+ for _, entry := range entries {
+ handle(entry.Zid)
+ }
+ return nil
+}
+
+func (zb *zipBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint query.RetrievePredicate) error {
+ reader, err := zip.OpenReader(zb.name)
+ if err != nil {
+ return err
+ }
+ entries := zb.dirSrv.GetDirEntries(constraint)
+ logging.LogTrace(zb.logger, "ApplyMeta", "entries", len(entries))
+ for _, entry := range entries {
+ if !constraint(entry.Zid) {
+ continue
+ }
+ m, err2 := zb.readZipMeta(reader, entry.Zid, entry)
+ if err2 != nil {
+ continue
+ }
+ zb.enricher.Enrich(ctx, m, zb.number)
+ handle(m)
+ }
+ return reader.Close()
+}
+
+func (*zipBox) CanDeleteZettel(context.Context, id.Zid) bool { return false }
+
+func (zb *zipBox) DeleteZettel(_ context.Context, zid id.Zid) error {
+ err := box.ErrReadOnly
+ entry := zb.dirSrv.GetDirEntry(zid)
+ if !entry.IsValid() {
+ err = box.ErrZettelNotFound{Zid: zid}
+ }
+ logging.LogTrace(zb.logger, "DeleteZettel", "err", err)
+ return err
+}
+
+func (zb *zipBox) ReadStats(st *box.ManagedBoxStats) {
+ st.ReadOnly = true
+ st.Zettel = zb.dirSrv.NumDirEntries()
+ logging.LogTrace(zb.logger, "ReadStats", "zettel", st.Zettel)
+}
+
+func (zb *zipBox) readZipMeta(reader *zip.ReadCloser, zid id.Zid, entry *notify.DirEntry) (m *meta.Meta, err error) {
+ var inMeta bool
+ if metaName := entry.MetaName; metaName == "" {
+ contentName := entry.ContentName
+ contentExt := entry.ContentExt
+ if contentName == "" || contentExt == "" {
+ err = fmt.Errorf("no meta, no content in getMeta, zid=%v", zid)
+ } else if entry.HasMetaInContent() {
+ m, err = readZipMetaFile(reader, zid, contentName)
+ } else {
+ m = CalcDefaultMeta(zid, contentExt)
+ }
+ } else {
+ m, err = readZipMetaFile(reader, zid, metaName)
+ }
+ if err == nil {
+ CleanupMeta(m, zid, entry.ContentExt, inMeta, entry.UselessFiles)
+ }
+ return m, err
+}
+
+func readZipMetaFile(reader *zip.ReadCloser, zid id.Zid, name string) (*meta.Meta, error) {
+ src, err := readZipFileContent(reader, name)
+ if err != nil {
+ return nil, err
+ }
+ inp := input.NewInput(src)
+ return meta.NewFromInput(zid, inp), nil
+}
+
+func readZipFileContent(reader *zip.ReadCloser, name string) ([]byte, error) {
+ f, err := reader.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ data, err := io.ReadAll(f)
+ err2 := f.Close()
+ if err == nil {
+ err = err2
+ }
+ return data, err
+}
ADDED internal/box/helper.go
Index: internal/box/helper.go
==================================================================
--- /dev/null
+++ internal/box/helper.go
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package box
+
+import (
+ "net/url"
+ "strconv"
+ "time"
+
+ "t73f.de/r/zsc/domain/id"
+)
+
+// GetNewZid calculates a new and unused zettel identifier, based on the current date and time.
+func GetNewZid(testZid func(id.Zid) (bool, error)) (id.Zid, error) {
+ withSeconds := false
+ for range 90 { // Must be completed within 9 seconds (less than web/server.writeTimeout)
+ zid := id.New(withSeconds)
+ found, err := testZid(zid)
+ if err != nil {
+ return id.Invalid, err
+ }
+ if found {
+ return zid, nil
+ }
+ // TODO: do not wait here unconditionally.
+ time.Sleep(100 * time.Millisecond)
+ withSeconds = true
+ }
+ return id.Invalid, ErrConflict
+}
+
+// GetQueryBool is a helper function to extract bool values from a box URI.
+func GetQueryBool(u *url.URL, key string) bool {
+ _, ok := u.Query()[key]
+ return ok
+}
+
+// GetQueryInt is a helper function to extract int values of a specified range from a box URI.
+func GetQueryInt(u *url.URL, key string, minVal, defVal, maxVal int) int {
+ sVal := u.Query().Get(key)
+ if sVal == "" {
+ return defVal
+ }
+ iVal, err := strconv.Atoi(sVal)
+ if err != nil {
+ return defVal
+ }
+ if iVal < minVal {
+ return minVal
+ }
+ if iVal > maxVal {
+ return maxVal
+ }
+ return iVal
+}
ADDED internal/box/manager/anteroom.go
Index: internal/box/manager/anteroom.go
==================================================================
--- /dev/null
+++ internal/box/manager/anteroom.go
@@ -0,0 +1,144 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package manager
+
+import (
+ "sync"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+)
+
+type arAction int
+
+const (
+ arNothing arAction = iota
+ arReload
+ arZettel
+)
+
+type anteroom struct {
+ next *anteroom
+ waiting *idset.Set
+ curLoad int
+ reload bool
+}
+
+type anteroomQueue struct {
+ mx sync.Mutex
+ first *anteroom
+ last *anteroom
+ maxLoad int
+}
+
+func newAnteroomQueue(maxLoad int) *anteroomQueue { return &anteroomQueue{maxLoad: maxLoad} }
+
+func (ar *anteroomQueue) EnqueueZettel(zid id.Zid) {
+ if !zid.IsValid() {
+ return
+ }
+ ar.mx.Lock()
+ defer ar.mx.Unlock()
+ if ar.first == nil {
+ ar.first = ar.makeAnteroom(zid)
+ ar.last = ar.first
+ return
+ }
+ for room := ar.first; room != nil; room = room.next {
+ if room.reload {
+ continue // Do not put zettel in reload room
+ }
+ if room.waiting.Contains(zid) {
+ // Zettel is already waiting. Nothing to do.
+ return
+ }
+ }
+ if room := ar.last; !room.reload && (ar.maxLoad == 0 || room.curLoad < ar.maxLoad) {
+ room.waiting.Add(zid)
+ room.curLoad++
+ return
+ }
+ room := ar.makeAnteroom(zid)
+ ar.last.next = room
+ ar.last = room
+}
+
+func (ar *anteroomQueue) makeAnteroom(zid id.Zid) *anteroom {
+ if zid == id.Invalid {
+ panic(zid)
+ }
+ waiting := idset.NewCap(max(ar.maxLoad, 100), zid)
+ return &anteroom{next: nil, waiting: waiting, curLoad: 1, reload: false}
+}
+
+func (ar *anteroomQueue) Reset() {
+ ar.mx.Lock()
+ defer ar.mx.Unlock()
+ ar.first = &anteroom{next: nil, waiting: nil, curLoad: 0, reload: true}
+ ar.last = ar.first
+}
+
+func (ar *anteroomQueue) Reload(allZids *idset.Set) {
+ ar.mx.Lock()
+ defer ar.mx.Unlock()
+ ar.deleteReloadedRooms()
+
+ if !allZids.IsEmpty() {
+ ar.first = &anteroom{next: ar.first, waiting: allZids, curLoad: allZids.Length(), reload: true}
+ if ar.first.next == nil {
+ ar.last = ar.first
+ }
+ } else {
+ ar.first = nil
+ ar.last = nil
+ }
+}
+
+func (ar *anteroomQueue) deleteReloadedRooms() {
+ room := ar.first
+ for room != nil && room.reload {
+ room = room.next
+ }
+ ar.first = room
+ if room == nil {
+ ar.last = nil
+ }
+}
+
+func (ar *anteroomQueue) Dequeue() (arAction, id.Zid, bool) {
+ ar.mx.Lock()
+ defer ar.mx.Unlock()
+ first := ar.first
+ if first != nil {
+ if first.waiting == nil && first.reload {
+ ar.removeFirst()
+ return arReload, id.Invalid, false
+ }
+ if zid, found := first.waiting.Pop(); found {
+ if first.waiting.IsEmpty() {
+ ar.removeFirst()
+ }
+ return arZettel, zid, first.reload
+ }
+ ar.removeFirst()
+ }
+ return arNothing, id.Invalid, false
+}
+
+func (ar *anteroomQueue) removeFirst() {
+ ar.first = ar.first.next
+ if ar.first == nil {
+ ar.last = nil
+ }
+}
ADDED internal/box/manager/anteroom_test.go
Index: internal/box/manager/anteroom_test.go
==================================================================
--- /dev/null
+++ internal/box/manager/anteroom_test.go
@@ -0,0 +1,110 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package manager
+
+import (
+ "testing"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+)
+
+func TestSimple(t *testing.T) {
+ t.Parallel()
+ ar := newAnteroomQueue(2)
+ ar.EnqueueZettel(id.Zid(1))
+ action, zid, lastReload := ar.Dequeue()
+ if zid != id.Zid(1) || action != arZettel || lastReload {
+ t.Errorf("Expected arZettel/1/false, but got %v/%v/%v", action, zid, lastReload)
+ }
+ _, zid, _ = ar.Dequeue()
+ if zid != id.Invalid {
+ t.Errorf("Expected invalid Zid, but got %v", zid)
+ }
+ ar.EnqueueZettel(id.Zid(1))
+ ar.EnqueueZettel(id.Zid(2))
+ if ar.first != ar.last {
+ t.Errorf("Expected one room, but got more")
+ }
+ ar.EnqueueZettel(id.Zid(3))
+ if ar.first == ar.last {
+ t.Errorf("Expected more than one room, but got only one")
+ }
+
+ count := 0
+ for ; count < 1000; count++ {
+ action, _, _ = ar.Dequeue()
+ if action == arNothing {
+ break
+ }
+ }
+ if count != 3 {
+ t.Errorf("Expected 3 dequeues, but got %v", count)
+ }
+}
+
+func TestReset(t *testing.T) {
+ t.Parallel()
+ ar := newAnteroomQueue(1)
+ ar.EnqueueZettel(id.Zid(1))
+ ar.Reset()
+ action, zid, _ := ar.Dequeue()
+ if action != arReload || zid != id.Invalid {
+ t.Errorf("Expected reload & invalid Zid, but got %v/%v", action, zid)
+ }
+ ar.Reload(idset.New(3, 4))
+ ar.EnqueueZettel(id.Zid(5))
+ ar.EnqueueZettel(id.Zid(5))
+ if ar.first == ar.last || ar.first.next != ar.last /*|| ar.first.next.next != ar.last*/ {
+ t.Errorf("Expected 2 rooms")
+ }
+ action, zid1, _ := ar.Dequeue()
+ if action != arZettel {
+ t.Errorf("Expected arZettel, but got %v", action)
+ }
+ action, zid2, _ := ar.Dequeue()
+ if action != arZettel {
+ t.Errorf("Expected arZettel, but got %v", action)
+ }
+ if !(zid1 == id.Zid(3) && zid2 == id.Zid(4) || zid1 == id.Zid(4) && zid2 == id.Zid(3)) {
+ t.Errorf("Zids must be 3 or 4, but got %v/%v", zid1, zid2)
+ }
+ action, zid, _ = ar.Dequeue()
+ if zid != id.Zid(5) || action != arZettel {
+ t.Errorf("Expected 5/arZettel, but got %v/%v", zid, action)
+ }
+ action, zid, _ = ar.Dequeue()
+ if action != arNothing || zid != id.Invalid {
+ t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid)
+ }
+
+ ar = newAnteroomQueue(1)
+ ar.Reload(idset.New(id.Zid(6)))
+ action, zid, _ = ar.Dequeue()
+ if zid != id.Zid(6) || action != arZettel {
+ t.Errorf("Expected 6/arZettel, but got %v/%v", zid, action)
+ }
+ action, zid, _ = ar.Dequeue()
+ if action != arNothing || zid != id.Invalid {
+ t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid)
+ }
+
+ ar = newAnteroomQueue(1)
+ ar.EnqueueZettel(id.Zid(8))
+ ar.Reload(nil)
+ action, zid, _ = ar.Dequeue()
+ if action != arNothing || zid != id.Invalid {
+ t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid)
+ }
+}
ADDED internal/box/manager/box.go
Index: internal/box/manager/box.go
==================================================================
--- /dev/null
+++ internal/box/manager/box.go
@@ -0,0 +1,310 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package manager
+
+import (
+ "context"
+ "errors"
+ "strings"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+// Conatains all box.Box related functions
+
+// Location returns some information where the box is located.
+func (mgr *Manager) Location() string {
+ if len(mgr.boxes) <= 2 {
+ return "NONE"
+ }
+ var sb strings.Builder
+ for i := range len(mgr.boxes) - 2 {
+ if i > 0 {
+ sb.WriteString(", ")
+ }
+ sb.WriteString(mgr.boxes[i].Location())
+ }
+ return sb.String()
+}
+
+// CanCreateZettel returns true, if box could possibly create a new zettel.
+func (mgr *Manager) CanCreateZettel(ctx context.Context) bool {
+ if err := mgr.checkContinue(ctx); err != nil {
+ return false
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ if box, isWriteBox := mgr.boxes[0].(box.WriteBox); isWriteBox {
+ return box.CanCreateZettel(ctx)
+ }
+ return false
+}
+
+// CreateZettel creates a new zettel.
+func (mgr *Manager) CreateZettel(ctx context.Context, ztl zettel.Zettel) (id.Zid, error) {
+ mgr.mgrLogger.Debug("CreateZettel")
+ if err := mgr.checkContinue(ctx); err != nil {
+ return id.Invalid, err
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ if box, isWriteBox := mgr.boxes[0].(box.WriteBox); isWriteBox {
+ ztl.Meta = mgr.cleanMetaProperties(ztl.Meta)
+ zid, err := box.CreateZettel(ctx, ztl)
+ if err == nil {
+ mgr.idxUpdateZettel(ctx, ztl)
+ }
+ return zid, err
+ }
+ return id.Invalid, box.ErrReadOnly
+}
+
+// GetZettel retrieves a specific zettel.
+func (mgr *Manager) GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error) {
+ mgr.mgrLogger.Debug("GetZettel", "zid", zid)
+ if err := mgr.checkContinue(ctx); err != nil {
+ return zettel.Zettel{}, err
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ return mgr.getZettel(ctx, zid)
+}
+func (mgr *Manager) getZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error) {
+ for i, p := range mgr.boxes {
+ var errZNF box.ErrZettelNotFound
+ if z, err := p.GetZettel(ctx, zid); !errors.As(err, &errZNF) {
+ if err == nil {
+ mgr.Enrich(ctx, z.Meta, i+1)
+ }
+ return z, err
+ }
+ }
+ return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
+}
+
+// GetAllZettel retrieves a specific zettel from all managed boxes.
+func (mgr *Manager) GetAllZettel(ctx context.Context, zid id.Zid) ([]zettel.Zettel, error) {
+ mgr.mgrLogger.Debug("GetAllZettel", "zid", zid)
+ if err := mgr.checkContinue(ctx); err != nil {
+ return nil, err
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ var result []zettel.Zettel
+ for i, p := range mgr.boxes {
+ if z, err := p.GetZettel(ctx, zid); err == nil {
+ mgr.Enrich(ctx, z.Meta, i+1)
+ result = append(result, z)
+ }
+ }
+ return result, nil
+}
+
+// FetchZids returns the set of all zettel identifer managed by the box.
+func (mgr *Manager) FetchZids(ctx context.Context) (*idset.Set, error) {
+ mgr.mgrLogger.Debug("FetchZids")
+ if err := mgr.checkContinue(ctx); err != nil {
+ return nil, err
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ return mgr.fetchZids(ctx)
+}
+func (mgr *Manager) fetchZids(ctx context.Context) (*idset.Set, error) {
+ numZettel := 0
+ for _, p := range mgr.boxes {
+ var mbstats box.ManagedBoxStats
+ p.ReadStats(&mbstats)
+ numZettel += mbstats.Zettel
+ }
+ result := idset.NewCap(numZettel)
+ for _, p := range mgr.boxes {
+ err := p.ApplyZid(ctx, func(zid id.Zid) { result.Add(zid) }, query.AlwaysIncluded)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return result, nil
+}
+
+func (mgr *Manager) hasZettel(ctx context.Context, zid id.Zid) bool {
+ mgr.mgrLogger.Debug("HasZettel", "zid", zid)
+ if err := mgr.checkContinue(ctx); err != nil {
+ return false
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ for _, bx := range mgr.boxes {
+ if bx.HasZettel(ctx, zid) {
+ return true
+ }
+ }
+ return false
+}
+
+// GetMeta returns just the metadata of the zettel with the given identifier.
+func (mgr *Manager) GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) {
+ mgr.mgrLogger.Debug("GetMeta", "zid", zid)
+ if err := mgr.checkContinue(ctx); err != nil {
+ return nil, err
+ }
+
+ m, err := mgr.idxStore.GetMeta(ctx, zid)
+ if err != nil {
+ // TODO: Call GetZettel and return just metadata, in case the index is not complete.
+ return nil, err
+ }
+ mgr.Enrich(ctx, m, 0)
+ return m, nil
+}
+
+// SelectMeta returns all zettel meta data that match the selection
+// criteria. The result is ordered by descending zettel id.
+func (mgr *Manager) SelectMeta(ctx context.Context, metaSeq []*meta.Meta, q *query.Query) ([]*meta.Meta, error) {
+ mgr.mgrLogger.Debug("SelectMeta", "query", q)
+ if err := mgr.checkContinue(ctx); err != nil {
+ return nil, err
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+
+ compSearch := q.RetrieveAndCompile(ctx, mgr, metaSeq)
+ if result := compSearch.Result(); result != nil {
+ logging.LogTrace(mgr.mgrLogger, "found without ApplyMeta", "count", len(result))
+ return result, nil
+ }
+ selected := map[id.Zid]*meta.Meta{}
+ for _, term := range compSearch.Terms {
+ rejected := idset.New()
+ handleMeta := func(m *meta.Meta) {
+ zid := m.Zid
+ if rejected.Contains(zid) {
+ logging.LogTrace(mgr.mgrLogger, "SelectMeta/alreadyRejected", "zid", zid)
+ return
+ }
+ if _, ok := selected[zid]; ok {
+ logging.LogTrace(mgr.mgrLogger, "SelectMeta/alreadySelected", "zid", zid)
+ return
+ }
+ if compSearch.PreMatch(m) && term.Match(m) {
+ selected[zid] = m
+ logging.LogTrace(mgr.mgrLogger, "SelectMeta/match", "zid", zid)
+ } else {
+ rejected.Add(zid)
+ logging.LogTrace(mgr.mgrLogger, "SelectMeta/reject", "zid", zid)
+ }
+ }
+ for _, p := range mgr.boxes {
+ if err2 := p.ApplyMeta(ctx, handleMeta, term.Retrieve); err2 != nil {
+ return nil, err2
+ }
+ }
+ }
+ result := make([]*meta.Meta, 0, len(selected))
+ for _, m := range selected {
+ result = append(result, m)
+ }
+ result = compSearch.AfterSearch(result)
+ logging.LogTrace(mgr.mgrLogger, "found with ApplyMeta", "count", len(result))
+ return result, nil
+}
+
+// CanUpdateZettel returns true, if box could possibly update the given zettel.
+func (mgr *Manager) CanUpdateZettel(ctx context.Context, zettel zettel.Zettel) bool {
+ if err := mgr.checkContinue(ctx); err != nil {
+ return false
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ if box, isWriteBox := mgr.boxes[0].(box.WriteBox); isWriteBox {
+ return box.CanUpdateZettel(ctx, zettel)
+ }
+ return false
+
+}
+
+// UpdateZettel updates an existing zettel.
+func (mgr *Manager) UpdateZettel(ctx context.Context, zettel zettel.Zettel) error {
+ mgr.mgrLogger.Debug("UpdateZettel", "zid", zettel.Meta.Zid)
+ if err := mgr.checkContinue(ctx); err != nil {
+ return err
+ }
+ return mgr.updateZettel(ctx, zettel)
+}
+func (mgr *Manager) updateZettel(ctx context.Context, zettel zettel.Zettel) error {
+ if box, isWriteBox := mgr.boxes[0].(box.WriteBox); isWriteBox {
+ zettel.Meta = mgr.cleanMetaProperties(zettel.Meta)
+ if err := box.UpdateZettel(ctx, zettel); err != nil {
+ return err
+ }
+ mgr.idxUpdateZettel(ctx, zettel)
+ return nil
+ }
+ return box.ErrReadOnly
+}
+
+// CanDeleteZettel returns true, if box could possibly delete the given zettel.
+func (mgr *Manager) CanDeleteZettel(ctx context.Context, zid id.Zid) bool {
+ if err := mgr.checkContinue(ctx); err != nil {
+ return false
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ for _, p := range mgr.boxes {
+ if p.CanDeleteZettel(ctx, zid) {
+ return true
+ }
+ }
+ return false
+}
+
+// DeleteZettel removes the zettel from the box.
+func (mgr *Manager) DeleteZettel(ctx context.Context, zid id.Zid) error {
+ mgr.mgrLogger.Debug("DeleteZettel", "zid", zid)
+ if err := mgr.checkContinue(ctx); err != nil {
+ return err
+ }
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ for _, p := range mgr.boxes {
+ err := p.DeleteZettel(ctx, zid)
+ if err == nil {
+ mgr.idxDeleteZettel(ctx, zid)
+ return err
+ }
+ var errZNF box.ErrZettelNotFound
+ if !errors.As(err, &errZNF) && !errors.Is(err, box.ErrReadOnly) {
+ return err
+ }
+ }
+ return box.ErrZettelNotFound{Zid: zid}
+}
+
+// Remove all (computed) properties from metadata before storing the zettel.
+func (mgr *Manager) cleanMetaProperties(m *meta.Meta) *meta.Meta {
+ result := m.Clone()
+ for key := range result.ComputedRest() {
+ if mgr.propertyKeys.Contains(key) {
+ result.Delete(key)
+ }
+ }
+ return result
+}
ADDED internal/box/manager/collect.go
Index: internal/box/manager/collect.go
==================================================================
--- /dev/null
+++ internal/box/manager/collect.go
@@ -0,0 +1,82 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package manager
+
+import (
+ "strings"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+
+ "zettelstore.de/z/internal/ast"
+ "zettelstore.de/z/internal/box/manager/store"
+ "zettelstore.de/z/strfun"
+)
+
+type collectData struct {
+ refs *idset.Set
+ words store.WordSet
+ urls store.WordSet
+}
+
+func (data *collectData) initialize() {
+ data.refs = idset.New()
+ data.words = store.NewWordSet()
+ data.urls = store.NewWordSet()
+}
+
+func collectZettelIndexData(zn *ast.ZettelNode, data *collectData) {
+ ast.Walk(data, &zn.BlocksAST)
+}
+
+func (data *collectData) Visit(node ast.Node) ast.Visitor {
+ switch n := node.(type) {
+ case *ast.VerbatimNode:
+ data.addText(string(n.Content))
+ case *ast.TranscludeNode:
+ data.addRef(n.Ref)
+ case *ast.TextNode:
+ data.addText(n.Text)
+ case *ast.LinkNode:
+ data.addRef(n.Ref)
+ case *ast.EmbedRefNode:
+ data.addRef(n.Ref)
+ case *ast.CiteNode:
+ data.addText(n.Key)
+ case *ast.LiteralNode:
+ data.addText(string(n.Content))
+ }
+ return data
+}
+
+func (data *collectData) addText(s string) {
+ for _, word := range strfun.NormalizeWords(s) {
+ data.words.Add(word)
+ }
+}
+
+func (data *collectData) addRef(ref *ast.Reference) {
+ if ref == nil {
+ return
+ }
+ if ref.IsExternal() {
+ data.urls.Add(strings.ToLower(ref.Value))
+ }
+ if !ref.IsZettel() {
+ return
+ }
+ if zid, err := id.Parse(ref.URL.Path); err == nil {
+ data.refs.Add(zid)
+ }
+}
ADDED internal/box/manager/enrich.go
Index: internal/box/manager/enrich.go
==================================================================
--- /dev/null
+++ internal/box/manager/enrich.go
@@ -0,0 +1,122 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package manager
+
+import (
+ "context"
+ "strconv"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+)
+
+// Enrich computes additional properties and updates the given metadata.
+func (mgr *Manager) Enrich(ctx context.Context, m *meta.Meta, boxNumber int) {
+ // Calculate computed, but stored values.
+ if _, hasCreated := m.Get(meta.KeyCreated); !hasCreated {
+ m.Set(meta.KeyCreated, computeCreated(m.Zid))
+ }
+
+ if box.DoEnrich(ctx) {
+ computePublished(m)
+ if boxNumber > 0 {
+ m.Set(meta.KeyBoxNumber, meta.Value(strconv.Itoa(boxNumber)))
+ }
+ mgr.idxStore.Enrich(ctx, m)
+ }
+}
+
+func computeCreated(zid id.Zid) meta.Value {
+ if zid <= 10101000000 {
+ // A year 0000 is not allowed and therefore an artificial Zid.
+ // In the year 0001, the month must be > 0.
+ // In the month 000101, the day must be > 0.
+ return "00010101000000"
+ }
+ seconds := min(zid%100, 59)
+ zid /= 100
+ minutes := min(zid%100, 59)
+ zid /= 100
+ hours := min(zid%100, 23)
+ zid /= 100
+ day := zid % 100
+ zid /= 100
+ month := zid % 100
+ year := zid / 100
+ month, day = sanitizeMonthDay(year, month, day)
+ created := ((((year*100+month)*100+day)*100+hours)*100+minutes)*100 + seconds
+ return meta.Value(created.String())
+}
+
+func sanitizeMonthDay(year, month, day id.Zid) (id.Zid, id.Zid) {
+ if day < 1 {
+ day = 1
+ }
+ if month < 1 {
+ month = 1
+ }
+ if month > 12 {
+ month = 12
+ }
+
+ switch month {
+ case 1, 3, 5, 7, 8, 10, 12:
+ if day > 31 {
+ day = 31
+ }
+ case 4, 6, 9, 11:
+ if day > 30 {
+ day = 30
+ }
+ case 2:
+ if year%4 != 0 || (year%100 == 0 && year%400 != 0) {
+ if day > 28 {
+ day = 28
+ }
+ } else {
+ if day > 29 {
+ day = 29
+ }
+ }
+ }
+ return month, day
+}
+
+func computePublished(m *meta.Meta) {
+ if _, ok := m.Get(meta.KeyPublished); ok {
+ return
+ }
+ if modified, ok := m.Get(meta.KeyModified); ok {
+ if _, ok = modified.AsTime(); ok {
+ m.Set(meta.KeyPublished, modified)
+ return
+ }
+ }
+ if created, ok := m.Get(meta.KeyCreated); ok {
+ if _, ok = created.AsTime(); ok {
+ m.Set(meta.KeyPublished, created)
+ return
+ }
+ }
+ zidValue := meta.Value(m.Zid.String())
+ if _, ok := zidValue.AsTime(); ok {
+ m.Set(meta.KeyPublished, zidValue)
+ return
+ }
+
+ // Neither the zettel was modified nor the zettel identifer contains a valid
+ // timestamp. In this case do not set the "published" property.
+}
ADDED internal/box/manager/indexer.go
Index: internal/box/manager/indexer.go
==================================================================
--- /dev/null
+++ internal/box/manager/indexer.go
@@ -0,0 +1,246 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package manager
+
+import (
+ "context"
+ "net/url"
+ "time"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager/store"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/parser"
+ "zettelstore.de/z/internal/zettel"
+ "zettelstore.de/z/strfun"
+)
+
+// SearchEqual returns all zettel that contains the given exact word.
+// The word must be normalized through Unicode NKFD, trimmed and not empty.
+func (mgr *Manager) SearchEqual(word string) *idset.Set {
+ found := mgr.idxStore.SearchEqual(word)
+ mgr.idxLogger.Debug("SearchEqual", "word", word, "found", found.Length())
+ logging.LogTrace(mgr.idxLogger, "IDs", "ids", found)
+ return found
+}
+
+// SearchPrefix returns all zettel that have a word with the given prefix.
+// The prefix must be normalized through Unicode NKFD, trimmed and not empty.
+func (mgr *Manager) SearchPrefix(prefix string) *idset.Set {
+ found := mgr.idxStore.SearchPrefix(prefix)
+ mgr.idxLogger.Debug("SearchPrefix", "prefix", prefix, "found", found.Length())
+ logging.LogTrace(mgr.idxLogger, "IDs", "ids", found)
+ return found
+}
+
+// SearchSuffix returns all zettel that have a word with the given suffix.
+// The suffix must be normalized through Unicode NKFD, trimmed and not empty.
+func (mgr *Manager) SearchSuffix(suffix string) *idset.Set {
+ found := mgr.idxStore.SearchSuffix(suffix)
+ mgr.idxLogger.Debug("SearchSuffix", "suffix", suffix, "found", found.Length())
+ logging.LogTrace(mgr.idxLogger, "IDs", "ids", found)
+ return found
+}
+
+// SearchContains returns all zettel that contains the given string.
+// The string must be normalized through Unicode NKFD, trimmed and not empty.
+func (mgr *Manager) SearchContains(s string) *idset.Set {
+ found := mgr.idxStore.SearchContains(s)
+ mgr.idxLogger.Debug("SearchContains", "s", s, "found", found.Length())
+ logging.LogTrace(mgr.idxLogger, "IDs", "ids", found)
+ return found
+}
+
+// idxIndexer runs in the background and updates the index data structures.
+// This is the main service of the idxIndexer.
+func (mgr *Manager) idxIndexer() {
+ // Something may panic. Ensure a running indexer.
+ defer func() {
+ if ri := recover(); ri != nil {
+ kernel.Main.LogRecover("Indexer", ri)
+ go mgr.idxIndexer()
+ }
+ }()
+
+ timerDuration := 15 * time.Second
+ timer := time.NewTimer(timerDuration)
+ ctx := box.NoEnrichContext(context.Background())
+ for {
+ mgr.idxWorkService(ctx)
+ if !mgr.idxSleepService(timer, timerDuration) {
+ return
+ }
+ }
+}
+
+func (mgr *Manager) idxWorkService(ctx context.Context) {
+ var start time.Time
+ for {
+ switch action, zid, lastReload := mgr.idxAr.Dequeue(); action {
+ case arNothing:
+ return
+ case arReload:
+ mgr.idxLogger.Debug("reload")
+ zids, err := mgr.FetchZids(ctx)
+ if err == nil {
+ start = time.Now()
+ mgr.idxAr.Reload(zids)
+ mgr.idxMx.Lock()
+ mgr.idxLastReload = time.Now().Local()
+ mgr.idxSinceReload = 0
+ mgr.idxMx.Unlock()
+ }
+ case arZettel:
+ mgr.idxLogger.Debug("zettel", "zid", zid)
+ zettel, err := mgr.GetZettel(ctx, zid)
+ if err != nil {
+ // Zettel was deleted or is not accessible b/c of other reasons
+ logging.LogTrace(mgr.idxLogger, "delete", "zid", zid)
+ mgr.idxDeleteZettel(ctx, zid)
+ continue
+ }
+ logging.LogTrace(mgr.idxLogger, "update", "zid", zid)
+ mgr.idxUpdateZettel(ctx, zettel)
+ mgr.idxMx.Lock()
+ if lastReload {
+ mgr.idxDurReload = time.Since(start)
+ }
+ mgr.idxSinceReload++
+ mgr.idxMx.Unlock()
+ }
+ }
+}
+
+func (mgr *Manager) idxSleepService(timer *time.Timer, timerDuration time.Duration) bool {
+ select {
+ case _, ok := <-mgr.idxReady:
+ if !ok {
+ return false
+ }
+ case _, ok := <-timer.C:
+ if !ok {
+ return false
+ }
+ // mgr.idxStore.Optimize() // TODO: make it less often, for example once per 10 minutes
+ timer.Reset(timerDuration)
+ case <-mgr.done:
+ if !timer.Stop() {
+ <-timer.C
+ }
+ return false
+ }
+ return true
+}
+
+func (mgr *Manager) idxUpdateZettel(ctx context.Context, zettel zettel.Zettel) {
+ var cData collectData
+ cData.initialize()
+ if mustIndexZettel(zettel.Meta) {
+ collectZettelIndexData(parser.ParseZettel(ctx, zettel, "", mgr.rtConfig), &cData)
+ }
+
+ m := zettel.Meta
+ zi := store.NewZettelIndex(m)
+ mgr.idxCollectFromMeta(ctx, m, zi, &cData)
+ mgr.idxProcessData(ctx, zi, &cData)
+ toCheck := mgr.idxStore.UpdateReferences(ctx, zi)
+ mgr.idxCheckZettel(toCheck)
+}
+
+func mustIndexZettel(m *meta.Meta) bool {
+ return m.Zid >= id.Zid(999999900)
+}
+
+func (mgr *Manager) idxCollectFromMeta(ctx context.Context, m *meta.Meta, zi *store.ZettelIndex, cData *collectData) {
+ for key, val := range m.Computed() {
+ descr := meta.GetDescription(key)
+ if descr.IsProperty() {
+ continue
+ }
+ switch descr.Type {
+ case meta.TypeID:
+ mgr.idxUpdateValue(ctx, descr.Inverse, string(val), zi)
+ case meta.TypeIDSet:
+ for val := range val.Fields() {
+ mgr.idxUpdateValue(ctx, descr.Inverse, val, zi)
+ }
+ case meta.TypeURL:
+ if _, err := url.Parse(string(val)); err == nil {
+ cData.urls.Add(string(val))
+ }
+ default:
+ if descr.Type.IsSet {
+ for val := range val.Fields() {
+ idxCollectMetaValue(cData.words, val)
+ }
+ } else {
+ idxCollectMetaValue(cData.words, string(val))
+ }
+ }
+ }
+}
+
+func idxCollectMetaValue(stWords store.WordSet, value string) {
+ if words := strfun.NormalizeWords(value); len(words) > 0 {
+ for _, word := range words {
+ stWords.Add(word)
+ }
+ } else {
+ stWords.Add(value)
+ }
+}
+
+func (mgr *Manager) idxProcessData(ctx context.Context, zi *store.ZettelIndex, cData *collectData) {
+ cData.refs.ForEach(func(ref id.Zid) {
+ if mgr.hasZettel(ctx, ref) {
+ zi.AddBackRef(ref)
+ } else {
+ zi.AddDeadRef(ref)
+ }
+ })
+ zi.SetWords(cData.words)
+ zi.SetUrls(cData.urls)
+}
+
+func (mgr *Manager) idxUpdateValue(ctx context.Context, inverseKey, value string, zi *store.ZettelIndex) {
+ zid, err := id.Parse(value)
+ if err != nil {
+ return
+ }
+ if !mgr.hasZettel(ctx, zid) {
+ zi.AddDeadRef(zid)
+ return
+ }
+ if inverseKey == "" {
+ zi.AddBackRef(zid)
+ return
+ }
+ zi.AddInverseRef(inverseKey, zid)
+}
+
+func (mgr *Manager) idxDeleteZettel(ctx context.Context, zid id.Zid) {
+ toCheck := mgr.idxStore.DeleteZettel(ctx, zid)
+ mgr.idxCheckZettel(toCheck)
+}
+
+func (mgr *Manager) idxCheckZettel(s *idset.Set) {
+ s.ForEach(func(zid id.Zid) {
+ mgr.idxAr.EnqueueZettel(zid)
+ })
+}
ADDED internal/box/manager/manager.go
Index: internal/box/manager/manager.go
==================================================================
--- /dev/null
+++ internal/box/manager/manager.go
@@ -0,0 +1,442 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package manager coordinates the various boxes and indexes of a Zettelstore.
+package manager
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "net/url"
+ "sync"
+ "time"
+
+ "t73f.de/r/zero/set"
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/auth"
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager/mapstore"
+ "zettelstore.de/z/internal/box/manager/store"
+ "zettelstore.de/z/internal/config"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+)
+
+// ConnectData contains all administration related values.
+type ConnectData struct {
+ Number int // number of the box, starting with 1.
+ Config config.Config
+ Enricher box.Enricher
+ Notify box.UpdateNotifier
+}
+
+// Connect returns a handle to the specified box.
+func Connect(u *url.URL, authManager auth.BaseManager, cdata *ConnectData) (box.ManagedBox, error) {
+ if authManager.IsReadonly() {
+ rawURL := u.String()
+ // TODO: the following is wrong under some circumstances:
+ // 1. fragment is set
+ if q := u.Query(); len(q) == 0 {
+ rawURL += "?readonly"
+ } else if _, ok := q["readonly"]; !ok {
+ rawURL += "&readonly"
+ }
+ var err error
+ if u, err = url.Parse(rawURL); err != nil {
+ return nil, err
+ }
+ }
+
+ if create, ok := registry[u.Scheme]; ok {
+ return create(u, cdata)
+ }
+ return nil, &ErrInvalidScheme{u.Scheme}
+}
+
+// ErrInvalidScheme is returned if there is no box with the given scheme.
+type ErrInvalidScheme struct{ Scheme string }
+
+func (err *ErrInvalidScheme) Error() string { return "Invalid scheme: " + err.Scheme }
+
+type createFunc func(*url.URL, *ConnectData) (box.ManagedBox, error)
+
+var registry = map[string]createFunc{}
+
+// Register the encoder for later retrieval.
+func Register(scheme string, create createFunc) {
+ if _, ok := registry[scheme]; ok {
+ panic(scheme)
+ }
+ registry[scheme] = create
+}
+
+// Manager is a coordinating box.
+type Manager struct {
+ mgrLogger *slog.Logger
+ stateMx sync.RWMutex
+ state box.StartState
+ mgrMx sync.RWMutex
+ rtConfig config.Config
+ boxes []box.ManagedBox
+ observers []box.UpdateFunc
+ mxObserver sync.RWMutex
+ done chan struct{}
+ infos chan box.UpdateInfo
+ propertyKeys *set.Set[string] // Set of property key names
+
+ // Indexer data
+ idxLogger *slog.Logger
+ idxStore store.Store
+ idxAr *anteroomQueue
+ idxReady chan struct{} // Signal a non-empty anteroom to background task
+
+ // Indexer stats data
+ idxMx sync.RWMutex
+ idxLastReload time.Time
+ idxDurReload time.Duration
+ idxSinceReload uint64
+}
+
+func (mgr *Manager) setState(newState box.StartState) {
+ mgr.stateMx.Lock()
+ mgr.state = newState
+ mgr.stateMx.Unlock()
+}
+
+// State returns the box.StartState of the manager.
+func (mgr *Manager) State() box.StartState {
+ mgr.stateMx.RLock()
+ state := mgr.state
+ mgr.stateMx.RUnlock()
+ return state
+}
+
+// New creates a new managing box.
+func New(boxURIs []*url.URL, authManager auth.BaseManager, rtConfig config.Config) (*Manager, error) {
+ descrs := meta.GetSortedKeyDescriptions()
+ propertyKeys := set.New[string]()
+ for _, kd := range descrs {
+ if kd.IsProperty() {
+ propertyKeys.Add(kd.Name)
+ }
+ }
+ boxLogger := kernel.Main.GetLogger(kernel.BoxService)
+ mgr := &Manager{
+ mgrLogger: boxLogger.With("box", "manager"),
+ rtConfig: rtConfig,
+ infos: make(chan box.UpdateInfo, len(boxURIs)*10),
+ propertyKeys: propertyKeys,
+
+ idxLogger: boxLogger.With("box", "index"),
+ idxStore: createIdxStore(rtConfig),
+ idxAr: newAnteroomQueue(1000),
+ idxReady: make(chan struct{}, 1),
+ }
+
+ cdata := ConnectData{Number: 1, Config: rtConfig, Enricher: mgr, Notify: mgr.notifyChanged}
+ boxes := make([]box.ManagedBox, 0, len(boxURIs)+2)
+ for _, uri := range boxURIs {
+ p, err := Connect(uri, authManager, &cdata)
+ if err != nil {
+ return nil, err
+ }
+ if p != nil {
+ boxes = append(boxes, p)
+ cdata.Number++
+ }
+ }
+ constbox, err := registry[" const"](nil, &cdata)
+ if err != nil {
+ return nil, err
+ }
+ cdata.Number++
+ compbox, err := registry[" comp"](nil, &cdata)
+ if err != nil {
+ return nil, err
+ }
+ cdata.Number++
+ boxes = append(boxes, constbox, compbox)
+ mgr.boxes = boxes
+ return mgr, nil
+}
+
+func createIdxStore(_ config.Config) store.Store {
+ return mapstore.New()
+}
+
+// RegisterObserver registers an observer that will be notified
+// if a zettel was found to be changed.
+func (mgr *Manager) RegisterObserver(f box.UpdateFunc) {
+ if f != nil {
+ mgr.mxObserver.Lock()
+ mgr.observers = append(mgr.observers, f)
+ mgr.mxObserver.Unlock()
+ }
+}
+
+func (mgr *Manager) notifier() {
+ // The call to notify may panic. Ensure a running notifier.
+ defer func() {
+ if ri := recover(); ri != nil {
+ kernel.Main.LogRecover("Notifier", ri)
+ go mgr.notifier()
+ }
+ }()
+
+ tsLastEvent := time.Now()
+ cache := destutterCache{}
+ for {
+ select {
+ case ci, ok := <-mgr.infos:
+ if ok {
+ now := time.Now()
+ if len(cache) > 1 && tsLastEvent.Add(10*time.Second).Before(now) {
+ // Cache contains entries and is definitely outdated
+ logging.LogTrace(mgr.mgrLogger, "clean destutter cache")
+ cache = destutterCache{}
+ }
+ tsLastEvent = now
+
+ reason, zid := ci.Reason, ci.Zid
+ mgr.mgrLogger.Debug("notifier", "reason", reason, "zid", zid)
+ if ignoreUpdate(cache, now, reason, zid) {
+ logging.LogTrace(mgr.mgrLogger, "notifier ignored", "reason", reason, "zid", zid)
+ continue
+ }
+
+ isStarted := mgr.State() == box.StartStateStarted
+ mgr.idxEnqueue(reason, zid)
+ if ci.Box == nil {
+ ci.Box = mgr
+ }
+ if isStarted {
+ mgr.notifyObserver(&ci)
+ }
+ }
+ case <-mgr.done:
+ return
+ }
+ }
+}
+
+type destutterData struct {
+ deadAt time.Time
+ reason box.UpdateReason
+}
+type destutterCache = map[id.Zid]destutterData
+
+func ignoreUpdate(cache destutterCache, now time.Time, reason box.UpdateReason, zid id.Zid) bool {
+ if dsd, found := cache[zid]; found {
+ if dsd.reason == reason && dsd.deadAt.After(now) {
+ return true
+ }
+ }
+ cache[zid] = destutterData{
+ deadAt: now.Add(500 * time.Millisecond),
+ reason: reason,
+ }
+ return false
+}
+
+func (mgr *Manager) idxEnqueue(reason box.UpdateReason, zid id.Zid) {
+ switch reason {
+ case box.OnReady:
+ return
+ case box.OnReload:
+ mgr.idxAr.Reset()
+ case box.OnZettel:
+ mgr.idxAr.EnqueueZettel(zid)
+ case box.OnDelete:
+ mgr.idxAr.EnqueueZettel(zid)
+ default:
+ mgr.mgrLogger.Error("Unknown notification reason", "reason", reason, "zid", zid)
+ return
+ }
+ select {
+ case mgr.idxReady <- struct{}{}:
+ default:
+ }
+}
+
+func (mgr *Manager) notifyObserver(ci *box.UpdateInfo) {
+ mgr.mxObserver.RLock()
+ observers := mgr.observers
+ mgr.mxObserver.RUnlock()
+ for _, ob := range observers {
+ ob(*ci)
+ }
+}
+
+// Start the box. Now all other functions of the box are allowed.
+// Starting an already started box is not allowed.
+func (mgr *Manager) Start(ctx context.Context) error {
+ mgr.mgrMx.Lock()
+ defer mgr.mgrMx.Unlock()
+ if mgr.State() != box.StartStateStopped {
+ return box.ErrStarted
+ }
+ mgr.setState(box.StartStateStarting)
+ for i := len(mgr.boxes) - 1; i >= 0; i-- {
+ ssi, ok := mgr.boxes[i].(box.StartStopper)
+ if !ok {
+ continue
+ }
+ err := ssi.Start(ctx)
+ if err == nil {
+ continue
+ }
+ mgr.setState(box.StartStateStopping)
+ for j := i + 1; j < len(mgr.boxes); j++ {
+ if ssj, ok2 := mgr.boxes[j].(box.StartStopper); ok2 {
+ ssj.Stop(ctx)
+ }
+ }
+ mgr.setState(box.StartStateStopped)
+ return err
+ }
+ mgr.idxAr.Reset() // Ensure an initial index run
+ mgr.done = make(chan struct{})
+ go mgr.notifier()
+
+ mgr.waitBoxesAreStarted()
+ mgr.setState(box.StartStateStarted)
+
+ mgr.notifyObserver(&box.UpdateInfo{Box: mgr, Reason: box.OnReady})
+
+ go mgr.idxIndexer()
+ return nil
+}
+
+func (mgr *Manager) waitBoxesAreStarted() {
+ const waitTime = 10 * time.Millisecond
+ const waitLoop = int(1 * time.Second / waitTime)
+ for i := 1; !mgr.allBoxesStarted(); i++ {
+ if i%waitLoop == 0 {
+ if time.Duration(i)*waitTime > time.Minute {
+ mgr.mgrLogger.Info("Waiting for more than one minute to start")
+ } else {
+ logging.LogTrace(mgr.mgrLogger, "Wait for boxes to start")
+ }
+ }
+ time.Sleep(waitTime)
+ }
+}
+
+func (mgr *Manager) allBoxesStarted() bool {
+ for _, bx := range mgr.boxes {
+ if b, ok := bx.(box.StartStopper); ok && b.State() != box.StartStateStarted {
+ return false
+ }
+ }
+ return true
+}
+
+// Stop the started box. Now only the Start() function is allowed.
+func (mgr *Manager) Stop(ctx context.Context) {
+ mgr.mgrMx.Lock()
+ defer mgr.mgrMx.Unlock()
+ if err := mgr.checkContinue(ctx); err != nil {
+ return
+ }
+ mgr.setState(box.StartStateStopping)
+ close(mgr.done)
+ for _, p := range mgr.boxes {
+ if ss, ok := p.(box.StartStopper); ok {
+ ss.Stop(ctx)
+ }
+ }
+ mgr.setState(box.StartStateStopped)
+}
+
+// Refresh internal box data.
+func (mgr *Manager) Refresh(ctx context.Context) error {
+ mgr.mgrLogger.Debug("Refresh")
+ if err := mgr.checkContinue(ctx); err != nil {
+ return err
+ }
+ mgr.infos <- box.UpdateInfo{Reason: box.OnReload, Zid: id.Invalid}
+ mgr.mgrMx.Lock()
+ defer mgr.mgrMx.Unlock()
+ for _, bx := range mgr.boxes {
+ if rb, ok := bx.(box.Refresher); ok {
+ rb.Refresh(ctx)
+ }
+ }
+ return nil
+}
+
+// ReIndex data of the given zettel.
+func (mgr *Manager) ReIndex(ctx context.Context, zid id.Zid) error {
+ mgr.mgrLogger.Debug("ReIndex")
+ if err := mgr.checkContinue(ctx); err != nil {
+ return err
+ }
+ mgr.infos <- box.UpdateInfo{Box: mgr, Reason: box.OnZettel, Zid: zid}
+ return nil
+}
+
+// ReadStats populates st with box statistics.
+func (mgr *Manager) ReadStats(st *box.Stats) {
+ mgr.mgrLogger.Debug("ReadStats")
+ mgr.mgrMx.RLock()
+ defer mgr.mgrMx.RUnlock()
+ subStats := make([]box.ManagedBoxStats, len(mgr.boxes))
+ for i, p := range mgr.boxes {
+ p.ReadStats(&subStats[i])
+ }
+
+ st.ReadOnly = true
+ sumZettel := 0
+ for _, sst := range subStats {
+ if !sst.ReadOnly {
+ st.ReadOnly = false
+ }
+ sumZettel += sst.Zettel
+ }
+ st.NumManagedBoxes = len(mgr.boxes)
+ st.ZettelTotal = sumZettel
+
+ var storeSt store.Stats
+ mgr.idxMx.RLock()
+ defer mgr.idxMx.RUnlock()
+ mgr.idxStore.ReadStats(&storeSt)
+
+ st.LastReload = mgr.idxLastReload
+ st.IndexesSinceReload = mgr.idxSinceReload
+ st.DurLastReload = mgr.idxDurReload
+ st.ZettelIndexed = storeSt.Zettel
+ st.IndexUpdates = storeSt.Updates
+ st.IndexedWords = storeSt.Words
+ st.IndexedUrls = storeSt.Urls
+}
+
+// Dump internal data structures to a Writer.
+func (mgr *Manager) Dump(w io.Writer) {
+ mgr.idxStore.Dump(w)
+}
+
+func (mgr *Manager) checkContinue(ctx context.Context) error {
+ if mgr.State() != box.StartStateStarted {
+ return box.ErrStopped
+ }
+ return ctx.Err()
+}
+
+func (mgr *Manager) notifyChanged(bbox box.BaseBox, zid id.Zid, reason box.UpdateReason) {
+ if infos := mgr.infos; infos != nil {
+ mgr.infos <- box.UpdateInfo{Box: bbox, Reason: reason, Zid: zid}
+ }
+}
ADDED internal/box/manager/mapstore/mapstore.go
Index: internal/box/manager/mapstore/mapstore.go
==================================================================
--- /dev/null
+++ internal/box/manager/mapstore/mapstore.go
@@ -0,0 +1,674 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package mapstore stored the index in main memory via a Go map.
+package mapstore
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "maps"
+ "slices"
+ "strings"
+ "sync"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager/store"
+)
+
+type zettelData struct {
+ meta *meta.Meta // a local copy of the metadata, without computed keys
+ dead *idset.Set // set of dead references in this zettel
+ forward *idset.Set // set of forward references in this zettel
+ backward *idset.Set // set of zettel that reference with zettel
+ otherRefs map[string]bidiRefs
+ words []string // list of words of this zettel
+ urls []string // list of urls of this zettel
+}
+
+type bidiRefs struct {
+ forward *idset.Set
+ backward *idset.Set
+}
+
+func (zd *zettelData) optimize() {
+ zd.dead.Optimize()
+ zd.forward.Optimize()
+ zd.backward.Optimize()
+ for _, bidi := range zd.otherRefs {
+ bidi.forward.Optimize()
+ bidi.backward.Optimize()
+ }
+}
+
+type mapStore struct {
+ mx sync.RWMutex
+ intern map[string]string // map to intern strings
+ idx map[id.Zid]*zettelData
+ dead map[id.Zid]*idset.Set // map dead refs where they occur
+ words stringRefs
+ urls stringRefs
+
+ // Stats
+ mxStats sync.Mutex
+ updates uint64
+}
+type stringRefs map[string]*idset.Set
+
+// New returns a new memory-based index store.
+func New() store.Store {
+ return &mapStore{
+ intern: make(map[string]string, 1024),
+ idx: make(map[id.Zid]*zettelData),
+ dead: make(map[id.Zid]*idset.Set),
+ words: make(stringRefs),
+ urls: make(stringRefs),
+ }
+}
+
+func (ms *mapStore) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) {
+ ms.mx.RLock()
+ defer ms.mx.RUnlock()
+ if zi, found := ms.idx[zid]; found && zi.meta != nil {
+ // zi.meta is nil, if zettel was referenced, but is not indexed yet.
+ return zi.meta.Clone(), nil
+ }
+ return nil, box.ErrZettelNotFound{Zid: zid}
+}
+
+func (ms *mapStore) Enrich(_ context.Context, m *meta.Meta) {
+ if ms.doEnrich(m) {
+ ms.mxStats.Lock()
+ ms.updates++
+ ms.mxStats.Unlock()
+ }
+}
+
+func (ms *mapStore) doEnrich(m *meta.Meta) bool {
+ ms.mx.RLock()
+ defer ms.mx.RUnlock()
+ zi, ok := ms.idx[m.Zid]
+ if !ok {
+ return false
+ }
+ var updated bool
+ if !zi.dead.IsEmpty() {
+ m.Set(meta.KeyDead, zi.dead.MetaValue())
+ updated = true
+ }
+ back := removeOtherMetaRefs(m, zi.backward.Clone())
+ if !zi.backward.IsEmpty() {
+ m.Set(meta.KeyBackward, zi.backward.MetaValue())
+ updated = true
+ }
+ if !zi.forward.IsEmpty() {
+ m.Set(meta.KeyForward, zi.forward.MetaValue())
+ back.ISubstract(zi.forward)
+ updated = true
+ }
+ for k, refs := range zi.otherRefs {
+ if !refs.backward.IsEmpty() {
+ m.Set(k, refs.backward.MetaValue())
+ back.ISubstract(refs.backward)
+ updated = true
+ }
+ }
+ if !back.IsEmpty() {
+ m.Set(meta.KeyBack, back.MetaValue())
+ updated = true
+ }
+ return updated
+}
+
+// SearchEqual returns all zettel that contains the given exact word.
+// The word must be normalized through Unicode NKFD, trimmed and not empty.
+func (ms *mapStore) SearchEqual(word string) *idset.Set {
+ ms.mx.RLock()
+ defer ms.mx.RUnlock()
+ result := idset.New()
+ if refs, ok := ms.words[word]; ok {
+ result = result.IUnion(refs)
+ }
+ if refs, ok := ms.urls[word]; ok {
+ result = result.IUnion(refs)
+ }
+ zid, err := id.Parse(word)
+ if err != nil {
+ return result
+ }
+ zi, ok := ms.idx[zid]
+ if !ok {
+ return result
+ }
+
+ return addBackwardZids(result, zid, zi)
+}
+
+// SearchPrefix returns all zettel that have a word with the given prefix.
+// The prefix must be normalized through Unicode NKFD, trimmed and not empty.
+func (ms *mapStore) SearchPrefix(prefix string) *idset.Set {
+ ms.mx.RLock()
+ defer ms.mx.RUnlock()
+ result := ms.selectWithPred(prefix, strings.HasPrefix)
+ l := len(prefix)
+ if l > 14 {
+ return result
+ }
+ maxZid, err := id.Parse(prefix + "99999999999999"[:14-l])
+ if err != nil {
+ return result
+ }
+ var minZid id.Zid
+ if l < 14 && prefix == "0000000000000"[:l] {
+ minZid = id.Zid(1)
+ } else {
+ minZid, err = id.Parse(prefix + "00000000000000"[:14-l])
+ if err != nil {
+ return result
+ }
+ }
+ for zid, zi := range ms.idx {
+ if minZid <= zid && zid <= maxZid {
+ result = addBackwardZids(result, zid, zi)
+ }
+ }
+ return result
+}
+
+// SearchSuffix returns all zettel that have a word with the given suffix.
+// The suffix must be normalized through Unicode NKFD, trimmed and not empty.
+func (ms *mapStore) SearchSuffix(suffix string) *idset.Set {
+ ms.mx.RLock()
+ defer ms.mx.RUnlock()
+ result := ms.selectWithPred(suffix, strings.HasSuffix)
+ l := len(suffix)
+ if l > 14 {
+ return result
+ }
+ val, err := id.ParseUint(suffix)
+ if err != nil {
+ return result
+ }
+ modulo := uint64(1)
+ for range l {
+ modulo *= 10
+ }
+ for zid, zi := range ms.idx {
+ if uint64(zid)%modulo == val {
+ result = addBackwardZids(result, zid, zi)
+ }
+ }
+ return result
+}
+
+// SearchContains returns all zettel that contains the given string.
+// The string must be normalized through Unicode NKFD, trimmed and not empty.
+func (ms *mapStore) SearchContains(s string) *idset.Set {
+ ms.mx.RLock()
+ defer ms.mx.RUnlock()
+ result := ms.selectWithPred(s, strings.Contains)
+ if len(s) > 14 {
+ return result
+ }
+ if _, err := id.ParseUint(s); err != nil {
+ return result
+ }
+ for zid, zi := range ms.idx {
+ if strings.Contains(zid.String(), s) {
+ result = addBackwardZids(result, zid, zi)
+ }
+ }
+ return result
+}
+
+func (ms *mapStore) selectWithPred(s string, pred func(string, string) bool) *idset.Set {
+ // Must only be called if ms.mx is read-locked!
+ result := idset.New()
+ for word, refs := range ms.words {
+ if !pred(word, s) {
+ continue
+ }
+ result.IUnion(refs)
+ }
+ for u, refs := range ms.urls {
+ if !pred(u, s) {
+ continue
+ }
+ result.IUnion(refs)
+ }
+ return result
+}
+
+func addBackwardZids(result *idset.Set, zid id.Zid, zi *zettelData) *idset.Set {
+ // Must only be called if ms.mx is read-locked!
+ result = result.Add(zid)
+ result = result.IUnion(zi.backward)
+ for _, mref := range zi.otherRefs {
+ result = result.IUnion(mref.backward)
+ }
+ return result
+}
+
+func removeOtherMetaRefs(m *meta.Meta, back *idset.Set) *idset.Set {
+ for key, val := range m.Rest() {
+ switch meta.Type(key) {
+ case meta.TypeID:
+ if zid, err := id.Parse(string(val)); err == nil {
+ back = back.Remove(zid)
+ }
+ case meta.TypeIDSet:
+ for val := range val.Fields() {
+ if zid, err := id.Parse(val); err == nil {
+ back = back.Remove(zid)
+ }
+ }
+ }
+ }
+ return back
+}
+
+func (ms *mapStore) UpdateReferences(_ context.Context, zidx *store.ZettelIndex) *idset.Set {
+ ms.mx.Lock()
+ defer ms.mx.Unlock()
+ m := ms.makeMeta(zidx)
+ zi, ziExist := ms.idx[zidx.Zid]
+ if !ziExist || zi == nil {
+ zi = &zettelData{}
+ ziExist = false
+ }
+
+ // Is this zettel an old dead reference mentioned in other zettel?
+ var toCheck *idset.Set
+ if refs, ok := ms.dead[zidx.Zid]; ok {
+ // These must be checked later again
+ toCheck = refs
+ delete(ms.dead, zidx.Zid)
+ }
+
+ zi.meta = m
+ ms.updateDeadReferences(zidx, zi)
+ ids := ms.updateForwardBackwardReferences(zidx, zi)
+ toCheck = toCheck.IUnion(ids)
+ ids = ms.updateMetadataReferences(zidx, zi)
+ toCheck = toCheck.IUnion(ids)
+ zi.words = updateStrings(zidx.Zid, ms.words, zi.words, zidx.GetWords())
+ zi.urls = updateStrings(zidx.Zid, ms.urls, zi.urls, zidx.GetUrls())
+
+ // Check if zi must be inserted into ms.idx
+ if !ziExist {
+ ms.idx[zidx.Zid] = zi
+ }
+ zi.optimize()
+ return toCheck
+}
+
+var internableKeys = map[string]bool{
+ meta.KeyRole: true,
+ meta.KeySyntax: true,
+ meta.KeyFolgeRole: true,
+ meta.KeyLang: true,
+ meta.KeyReadOnly: true,
+}
+
+func isInternableValue(key string) bool {
+ if internableKeys[key] {
+ return true
+ }
+ return strings.HasSuffix(key, meta.SuffixKeyRole)
+}
+
+func (ms *mapStore) internString(s string) string {
+ if is, found := ms.intern[s]; found {
+ return is
+ }
+ ms.intern[s] = s
+ return s
+}
+
+func (ms *mapStore) makeMeta(zidx *store.ZettelIndex) *meta.Meta {
+ origM := zidx.GetMeta()
+ copyM := meta.New(origM.Zid)
+ for key, val := range origM.All() {
+ key = ms.internString(key)
+ if isInternableValue(key) {
+ copyM.Set(key, meta.Value(ms.internString(string(val))))
+ } else if key == meta.KeyBoxNumber || !meta.IsComputed(key) {
+ copyM.Set(key, val)
+ }
+ }
+ return copyM
+}
+
+func (ms *mapStore) updateDeadReferences(zidx *store.ZettelIndex, zi *zettelData) {
+ // Must only be called if ms.mx is write-locked!
+ drefs := zidx.GetDeadRefs()
+ newRefs, remRefs := zi.dead.Diff(drefs)
+ zi.dead = drefs
+ remRefs.ForEach(func(ref id.Zid) {
+ ms.dead[ref] = ms.dead[ref].Remove(zidx.Zid)
+ })
+ newRefs.ForEach(func(ref id.Zid) {
+ ms.dead[ref] = ms.dead[ref].Add(zidx.Zid)
+ })
+}
+
+func (ms *mapStore) updateForwardBackwardReferences(zidx *store.ZettelIndex, zi *zettelData) *idset.Set {
+ // Must only be called if ms.mx is write-locked!
+ brefs := zidx.GetBackRefs()
+ newRefs, remRefs := zi.forward.Diff(brefs)
+ zi.forward = brefs
+
+ var toCheck *idset.Set
+ remRefs.ForEach(func(ref id.Zid) {
+ bzi := ms.getOrCreateEntry(ref)
+ bzi.backward = bzi.backward.Remove(zidx.Zid)
+ if bzi.meta == nil {
+ toCheck = toCheck.Add(ref)
+ }
+ })
+ newRefs.ForEach(func(ref id.Zid) {
+ bzi := ms.getOrCreateEntry(ref)
+ bzi.backward = bzi.backward.Add(zidx.Zid)
+ if bzi.meta == nil {
+ toCheck = toCheck.Add(ref)
+ }
+ })
+ return toCheck
+}
+
+func (ms *mapStore) updateMetadataReferences(zidx *store.ZettelIndex, zi *zettelData) *idset.Set {
+ // Must only be called if ms.mx is write-locked!
+ inverseRefs := zidx.GetInverseRefs()
+ for key, mr := range zi.otherRefs {
+ if _, ok := inverseRefs[key]; ok {
+ continue
+ }
+ ms.removeInverseMeta(zidx.Zid, key, mr.forward)
+ }
+ if zi.otherRefs == nil {
+ zi.otherRefs = make(map[string]bidiRefs)
+ }
+ var toCheck *idset.Set
+ for key, mrefs := range inverseRefs {
+ mr := zi.otherRefs[key]
+ newRefs, remRefs := mr.forward.Diff(mrefs)
+ mr.forward = mrefs
+ zi.otherRefs[key] = mr
+
+ newRefs.ForEach(func(ref id.Zid) {
+ bzi := ms.getOrCreateEntry(ref)
+ if bzi.otherRefs == nil {
+ bzi.otherRefs = make(map[string]bidiRefs)
+ }
+ bmr := bzi.otherRefs[key]
+ bmr.backward = bmr.backward.Add(zidx.Zid)
+ bzi.otherRefs[key] = bmr
+ if bzi.meta == nil {
+ toCheck = toCheck.Add(ref)
+ }
+ })
+
+ ms.removeInverseMeta(zidx.Zid, key, remRefs)
+ }
+ return toCheck
+}
+
+func updateStrings(zid id.Zid, srefs stringRefs, prev []string, next store.WordSet) []string {
+ newWords, removeWords := next.Diff(prev)
+ for _, word := range newWords {
+ srefs[word] = srefs[word].Add(zid)
+ }
+ for _, word := range removeWords {
+ refs, ok := srefs[word]
+ if !ok {
+ continue
+ }
+ refs = refs.Remove(zid)
+ if refs.IsEmpty() {
+ delete(srefs, word)
+ continue
+ }
+ srefs[word] = refs
+ }
+ return next.Words()
+}
+
+func (ms *mapStore) getOrCreateEntry(zid id.Zid) *zettelData {
+ // Must only be called if ms.mx is write-locked!
+ if zi, ok := ms.idx[zid]; ok {
+ return zi
+ }
+ zi := &zettelData{}
+ ms.idx[zid] = zi
+ return zi
+}
+
+func (ms *mapStore) DeleteZettel(_ context.Context, zid id.Zid) *idset.Set {
+ ms.mx.Lock()
+ defer ms.mx.Unlock()
+ return ms.doDeleteZettel(zid)
+}
+
+func (ms *mapStore) doDeleteZettel(zid id.Zid) *idset.Set {
+ // Must only be called if ms.mx is write-locked!
+ zi, ok := ms.idx[zid]
+ if !ok {
+ return nil
+ }
+
+ ms.deleteDeadSources(zid, zi)
+ toCheck := ms.deleteForwardBackward(zid, zi)
+ for key, mrefs := range zi.otherRefs {
+ ms.removeInverseMeta(zid, key, mrefs.forward)
+ }
+ deleteStrings(ms.words, zi.words, zid)
+ deleteStrings(ms.urls, zi.urls, zid)
+ delete(ms.idx, zid)
+ return toCheck
+}
+
+func (ms *mapStore) deleteDeadSources(zid id.Zid, zi *zettelData) {
+ // Must only be called if ms.mx is write-locked!
+ zi.dead.ForEach(func(ref id.Zid) {
+ if drefs, ok := ms.dead[ref]; ok {
+ if drefs = drefs.Remove(zid); drefs.IsEmpty() {
+ delete(ms.dead, ref)
+ } else {
+ ms.dead[ref] = drefs
+ }
+ }
+ })
+}
+
+func (ms *mapStore) deleteForwardBackward(zid id.Zid, zi *zettelData) *idset.Set {
+ // Must only be called if ms.mx is write-locked!
+ zi.forward.ForEach(func(ref id.Zid) {
+ if fzi, ok := ms.idx[ref]; ok {
+ fzi.backward = fzi.backward.Remove(zid)
+ }
+ })
+
+ var toCheck *idset.Set
+ zi.backward.ForEach(func(ref id.Zid) {
+ if bzi, ok := ms.idx[ref]; ok {
+ bzi.forward = bzi.forward.Remove(zid)
+ toCheck = toCheck.Add(ref)
+ }
+ })
+ return toCheck
+}
+
+func (ms *mapStore) removeInverseMeta(zid id.Zid, key string, forward *idset.Set) {
+ // Must only be called if ms.mx is write-locked!
+ forward.ForEach(func(ref id.Zid) {
+ bzi, ok := ms.idx[ref]
+ if !ok || bzi.otherRefs == nil {
+ return
+ }
+ bmr, ok := bzi.otherRefs[key]
+ if !ok {
+ return
+ }
+ bmr.backward = bmr.backward.Remove(zid)
+ if !bmr.backward.IsEmpty() || !bmr.forward.IsEmpty() {
+ bzi.otherRefs[key] = bmr
+ } else {
+ delete(bzi.otherRefs, key)
+ if len(bzi.otherRefs) == 0 {
+ bzi.otherRefs = nil
+ }
+ }
+ })
+}
+
+func deleteStrings(msStringMap stringRefs, curStrings []string, zid id.Zid) {
+ // Must only be called if ms.mx is write-locked!
+ for _, word := range curStrings {
+ refs, ok := msStringMap[word]
+ if !ok {
+ continue
+ }
+ refs = refs.Remove(zid)
+ if refs.IsEmpty() {
+ delete(msStringMap, word)
+ continue
+ }
+ msStringMap[word] = refs
+ }
+}
+
+func (ms *mapStore) Optimize() {
+ ms.mx.Lock()
+ defer ms.mx.Unlock()
+
+ // No need to optimize ms.idx: is already done via ms.UpdateReferences
+ for _, dead := range ms.dead {
+ dead.Optimize()
+ }
+ for _, s := range ms.words {
+ s.Optimize()
+ }
+ for _, s := range ms.urls {
+ s.Optimize()
+ }
+}
+
+func (ms *mapStore) ReadStats(st *store.Stats) {
+ ms.mx.RLock()
+ st.Zettel = len(ms.idx)
+ st.Words = uint64(len(ms.words))
+ st.Urls = uint64(len(ms.urls))
+ ms.mx.RUnlock()
+ ms.mxStats.Lock()
+ st.Updates = ms.updates
+ ms.mxStats.Unlock()
+}
+
+func (ms *mapStore) Dump(w io.Writer) {
+ ms.mx.RLock()
+ defer ms.mx.RUnlock()
+
+ _, _ = io.WriteString(w, "=== Dump\n")
+ ms.dumpIndex(w)
+ ms.dumpDead(w)
+ dumpStringRefs(w, "Words", "", "", ms.words)
+ dumpStringRefs(w, "URLs", "[[", "]]", ms.urls)
+}
+
+func (ms *mapStore) dumpIndex(w io.Writer) {
+ if len(ms.idx) == 0 {
+ return
+ }
+ _, _ = io.WriteString(w, "==== Zettel Index\n")
+ zids := make([]id.Zid, 0, len(ms.idx))
+ for id := range ms.idx {
+ zids = append(zids, id)
+ }
+ slices.Sort(zids)
+ for _, id := range zids {
+ _, _ = fmt.Fprintln(w, "=====", id)
+ zi := ms.idx[id]
+ if !zi.dead.IsEmpty() {
+ _, _ = fmt.Fprintln(w, "* Dead:", zi.dead)
+ }
+ dumpSet(w, "* Forward:", zi.forward)
+ dumpSet(w, "* Backward:", zi.backward)
+
+ otherRefs := make([]string, 0, len(zi.otherRefs))
+ for k := range zi.otherRefs {
+ otherRefs = append(otherRefs, k)
+ }
+ slices.Sort(otherRefs)
+ for _, k := range otherRefs {
+ _, _ = fmt.Fprintln(w, "* Meta", k)
+ dumpSet(w, "** Forward:", zi.otherRefs[k].forward)
+ dumpSet(w, "** Backward:", zi.otherRefs[k].backward)
+ }
+ dumpStrings(w, "* Words", "", "", zi.words)
+ dumpStrings(w, "* URLs", "[[", "]]", zi.urls)
+ }
+}
+
+func (ms *mapStore) dumpDead(w io.Writer) {
+ if len(ms.dead) == 0 {
+ return
+ }
+ _, _ = fmt.Fprintf(w, "==== Dead References\n")
+ zids := make([]id.Zid, 0, len(ms.dead))
+ for id := range ms.dead {
+ zids = append(zids, id)
+ }
+ slices.Sort(zids)
+ for _, id := range zids {
+ _, _ = fmt.Fprintln(w, ";", id)
+ _, _ = fmt.Fprintln(w, ":", ms.dead[id])
+ }
+}
+
+func dumpSet(w io.Writer, prefix string, s *idset.Set) {
+ if !s.IsEmpty() {
+ _, _ = io.WriteString(w, prefix)
+ s.ForEach(func(zid id.Zid) {
+ _, _ = io.WriteString(w, " ")
+ _, _ = w.Write(zid.Bytes())
+ })
+ _, _ = fmt.Fprintln(w)
+ }
+}
+func dumpStrings(w io.Writer, title, preString, postString string, slice []string) {
+ if len(slice) > 0 {
+ sl := make([]string, len(slice))
+ copy(sl, slice)
+ slices.Sort(sl)
+ _, _ = fmt.Fprintln(w, title)
+ for _, s := range sl {
+ _, _ = fmt.Fprintf(w, "** %s%s%s\n", preString, s, postString)
+ }
+ }
+}
+
+func dumpStringRefs(w io.Writer, title, preString, postString string, srefs stringRefs) {
+ if len(srefs) == 0 {
+ return
+ }
+ _, _ = fmt.Fprintln(w, "====", title)
+ for _, s := range slices.Sorted(maps.Keys(srefs)) {
+ _, _ = fmt.Fprintf(w, "; %s%s%s\n", preString, s, postString)
+ _, _ = fmt.Fprintln(w, ":", srefs[s])
+ }
+}
ADDED internal/box/manager/store/store.go
Index: internal/box/manager/store/store.go
==================================================================
--- /dev/null
+++ internal/box/manager/store/store.go
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package store contains general index data for storing a zettel index.
+package store
+
+import (
+ "context"
+ "io"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+ "t73f.de/r/zsc/domain/meta"
+
+ "zettelstore.de/z/internal/query"
+)
+
+// Stats records statistics about the store.
+type Stats struct {
+ // Zettel is the number of zettel managed by the indexer.
+ Zettel int
+
+ // Updates count the number of metadata updates.
+ Updates uint64
+
+ // Words count the different words stored in the store.
+ Words uint64
+
+ // Urls count the different URLs stored in the store.
+ Urls uint64
+}
+
+// Store all relevant zettel data. There may be multiple implementations, i.e.
+// memory-based, file-based, based on SQLite, ...
+type Store interface {
+ query.Searcher
+
+ // GetMeta returns the metadata of the zettel with the given identifier.
+ GetMeta(context.Context, id.Zid) (*meta.Meta, error)
+
+ // Entrich metadata with data from store.
+ Enrich(ctx context.Context, m *meta.Meta)
+
+ // UpdateReferences for a specific zettel.
+ // Returns set of zettel identifier that must also be checked for changes.
+ UpdateReferences(context.Context, *ZettelIndex) *idset.Set
+
+ // DeleteZettel removes index data for given zettel.
+ // Returns set of zettel identifier that must also be checked for changes.
+ DeleteZettel(context.Context, id.Zid) *idset.Set
+
+ // Optimize removes unneeded space.
+ Optimize()
+
+ // ReadStats populates st with store statistics.
+ ReadStats(st *Stats)
+
+ // Dump the content to a Writer.
+ Dump(io.Writer)
+}
ADDED internal/box/manager/store/wordset.go
Index: internal/box/manager/store/wordset.go
==================================================================
--- /dev/null
+++ internal/box/manager/store/wordset.go
@@ -0,0 +1,63 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package store
+
+// WordSet contains the set of all words, with the count of their occurrences.
+type WordSet map[string]int
+
+// NewWordSet returns a new WordSet.
+func NewWordSet() WordSet { return make(WordSet) }
+
+// Add one word to the set
+func (ws WordSet) Add(s string) {
+ ws[s] = ws[s] + 1
+}
+
+// Words gives the slice of all words in the set.
+func (ws WordSet) Words() []string {
+ if len(ws) == 0 {
+ return nil
+ }
+ words := make([]string, 0, len(ws))
+ for w := range ws {
+ words = append(words, w)
+ }
+ return words
+}
+
+// Diff calculates the word slice to be added and to be removed from oldWords
+// to get the given word set.
+func (ws WordSet) Diff(oldWords []string) (newWords, removeWords []string) {
+ if len(ws) == 0 {
+ return nil, oldWords
+ }
+ if len(oldWords) == 0 {
+ return ws.Words(), nil
+ }
+ oldSet := make(WordSet, len(oldWords))
+ for _, ow := range oldWords {
+ if _, ok := ws[ow]; ok {
+ oldSet[ow] = 1
+ continue
+ }
+ removeWords = append(removeWords, ow)
+ }
+ for w := range ws {
+ if _, ok := oldSet[w]; ok {
+ continue
+ }
+ newWords = append(newWords, w)
+ }
+ return newWords, removeWords
+}
ADDED internal/box/manager/store/wordset_test.go
Index: internal/box/manager/store/wordset_test.go
==================================================================
--- /dev/null
+++ internal/box/manager/store/wordset_test.go
@@ -0,0 +1,80 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package store_test
+
+import (
+ "slices"
+ "testing"
+
+ "zettelstore.de/z/internal/box/manager/store"
+)
+
+func equalWordList(exp, got []string) bool {
+ if len(exp) != len(got) {
+ return false
+ }
+ if len(got) == 0 {
+ return len(exp) == 0
+ }
+ slices.Sort(got)
+ for i, w := range exp {
+ if w != got[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func TestWordsWords(t *testing.T) {
+ t.Parallel()
+ testcases := []struct {
+ words store.WordSet
+ exp []string
+ }{
+ {nil, nil},
+ {store.WordSet{}, nil},
+ {store.WordSet{"a": 1, "b": 2}, []string{"a", "b"}},
+ }
+ for i, tc := range testcases {
+ got := tc.words.Words()
+ if !equalWordList(tc.exp, got) {
+ t.Errorf("%d: %v.Words() == %v, but got %v", i, tc.words, tc.exp, got)
+ }
+ }
+}
+
+func TestWordsDiff(t *testing.T) {
+ t.Parallel()
+ testcases := []struct {
+ cur store.WordSet
+ old []string
+ expN, expR []string
+ }{
+ {nil, nil, nil, nil},
+ {store.WordSet{}, []string{}, nil, nil},
+ {store.WordSet{"a": 1}, []string{}, []string{"a"}, nil},
+ {store.WordSet{"a": 1}, []string{"b"}, []string{"a"}, []string{"b"}},
+ {store.WordSet{}, []string{"b"}, nil, []string{"b"}},
+ {store.WordSet{"a": 1}, []string{"a"}, nil, nil},
+ }
+ for i, tc := range testcases {
+ gotN, gotR := tc.cur.Diff(tc.old)
+ if !equalWordList(tc.expN, gotN) {
+ t.Errorf("%d: %v.Diff(%v)->new %v, but got %v", i, tc.cur, tc.old, tc.expN, gotN)
+ }
+ if !equalWordList(tc.expR, gotR) {
+ t.Errorf("%d: %v.Diff(%v)->rem %v, but got %v", i, tc.cur, tc.old, tc.expR, gotR)
+ }
+ }
+}
ADDED internal/box/manager/store/zettel.go
Index: internal/box/manager/store/zettel.go
==================================================================
--- /dev/null
+++ internal/box/manager/store/zettel.go
@@ -0,0 +1,89 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package store
+
+import (
+ "maps"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/id/idset"
+ "t73f.de/r/zsc/domain/meta"
+)
+
+// ZettelIndex contains all index data of a zettel.
+type ZettelIndex struct {
+ Zid id.Zid // zid of the indexed zettel
+ meta *meta.Meta // full metadata
+ backrefs *idset.Set // set of back references
+ inverseRefs map[string]*idset.Set // references of inverse keys
+ deadrefs *idset.Set // set of dead references
+ words WordSet
+ urls WordSet
+}
+
+// NewZettelIndex creates a new zettel index.
+func NewZettelIndex(m *meta.Meta) *ZettelIndex {
+ return &ZettelIndex{
+ Zid: m.Zid,
+ meta: m,
+ backrefs: idset.New(),
+ inverseRefs: make(map[string]*idset.Set),
+ deadrefs: idset.New(),
+ }
+}
+
+// AddBackRef adds a reference to a zettel where the current zettel links to
+// without any more information.
+func (zi *ZettelIndex) AddBackRef(zid id.Zid) { zi.backrefs.Add(zid) }
+
+// AddInverseRef adds a named reference to a zettel. On that zettel, the given
+// metadata key should point back to the current zettel.
+func (zi *ZettelIndex) AddInverseRef(key string, zid id.Zid) {
+ if zids, ok := zi.inverseRefs[key]; ok {
+ zids.Add(zid)
+ return
+ }
+ zi.inverseRefs[key] = idset.New(zid)
+}
+
+// AddDeadRef adds a dead reference to a zettel.
+func (zi *ZettelIndex) AddDeadRef(zid id.Zid) {
+ zi.deadrefs.Add(zid)
+}
+
+// SetWords sets the words to the given value.
+func (zi *ZettelIndex) SetWords(words WordSet) { zi.words = words }
+
+// SetUrls sets the words to the given value.
+func (zi *ZettelIndex) SetUrls(urls WordSet) { zi.urls = urls }
+
+// GetDeadRefs returns all dead references as a sorted list.
+func (zi *ZettelIndex) GetDeadRefs() *idset.Set { return zi.deadrefs }
+
+// GetMeta return just the raw metadata.
+func (zi *ZettelIndex) GetMeta() *meta.Meta { return zi.meta }
+
+// GetBackRefs returns all back references as a sorted list.
+func (zi *ZettelIndex) GetBackRefs() *idset.Set { return zi.backrefs }
+
+// GetInverseRefs returns all inverse meta references as a map of strings to a sorted list of references
+func (zi *ZettelIndex) GetInverseRefs() map[string]*idset.Set {
+ return maps.Clone(zi.inverseRefs)
+}
+
+// GetWords returns a reference to the set of words. It must not be modified.
+func (zi *ZettelIndex) GetWords() WordSet { return zi.words }
+
+// GetUrls returns a reference to the set of URLs. It must not be modified.
+func (zi *ZettelIndex) GetUrls() WordSet { return zi.urls }
ADDED internal/box/membox/membox.go
Index: internal/box/membox/membox.go
==================================================================
--- /dev/null
+++ internal/box/membox/membox.go
@@ -0,0 +1,238 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package membox stores zettel volatile in main memory.
+package membox
+
+import (
+ "context"
+ "log/slog"
+ "net/url"
+ "sync"
+
+ "t73f.de/r/zsc/domain/id"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/box/manager"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/query"
+ "zettelstore.de/z/internal/zettel"
+)
+
+func init() {
+ manager.Register(
+ "mem",
+ func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) {
+ return &memBox{
+ logger: kernel.Main.GetLogger(kernel.BoxService).With("box", "mem", "boxnum", cdata.Number),
+ u: u,
+ cdata: *cdata,
+ maxZettel: box.GetQueryInt(u, "max-zettel", 0, 127, 65535),
+ maxBytes: box.GetQueryInt(u, "max-bytes", 0, 65535, (1024*1024*1024)-1),
+ }, nil
+ })
+}
+
+type memBox struct {
+ logger *slog.Logger
+ u *url.URL
+ cdata manager.ConnectData
+ maxZettel int
+ maxBytes int
+ mx sync.RWMutex // Protects the following fields
+ zettel map[id.Zid]zettel.Zettel
+ curBytes int
+}
+
+func (mb *memBox) notifyChanged(zid id.Zid, reason box.UpdateReason) {
+ if notify := mb.cdata.Notify; notify != nil {
+ notify(mb, zid, reason)
+ }
+}
+
+func (mb *memBox) Location() string {
+ return mb.u.String()
+}
+
+func (mb *memBox) State() box.StartState {
+ mb.mx.RLock()
+ defer mb.mx.RUnlock()
+ if mb.zettel == nil {
+ return box.StartStateStopped
+ }
+ return box.StartStateStarted
+}
+
+func (mb *memBox) Start(context.Context) error {
+ mb.mx.Lock()
+ mb.zettel = make(map[id.Zid]zettel.Zettel)
+ mb.curBytes = 0
+ mb.mx.Unlock()
+ logging.LogTrace(mb.logger, "Start box", "max-zettel", mb.maxZettel, "max-bytes", mb.maxBytes)
+ return nil
+}
+
+func (mb *memBox) Stop(context.Context) {
+ mb.mx.Lock()
+ mb.zettel = nil
+ mb.mx.Unlock()
+}
+
+func (mb *memBox) CanCreateZettel(context.Context) bool {
+ mb.mx.RLock()
+ defer mb.mx.RUnlock()
+ return len(mb.zettel) < mb.maxZettel
+}
+
+func (mb *memBox) CreateZettel(_ context.Context, zettel zettel.Zettel) (id.Zid, error) {
+ mb.mx.Lock()
+ newBytes := mb.curBytes + zettel.ByteSize()
+ if mb.maxZettel < len(mb.zettel) || mb.maxBytes < newBytes {
+ mb.mx.Unlock()
+ return id.Invalid, box.ErrCapacity
+ }
+ zid, err := box.GetNewZid(func(zid id.Zid) (bool, error) {
+ _, ok := mb.zettel[zid]
+ return !ok, nil
+ })
+ if err != nil {
+ mb.mx.Unlock()
+ return id.Invalid, err
+ }
+ meta := zettel.Meta.Clone()
+ meta.Zid = zid
+ zettel.Meta = meta
+ mb.zettel[zid] = zettel
+ mb.curBytes = newBytes
+ mb.mx.Unlock()
+
+ mb.notifyChanged(zid, box.OnZettel)
+ logging.LogTrace(mb.logger, "CreateZettel", "zid", zid)
+ return zid, nil
+}
+
+func (mb *memBox) GetZettel(_ context.Context, zid id.Zid) (zettel.Zettel, error) {
+ mb.mx.RLock()
+ z, ok := mb.zettel[zid]
+ mb.mx.RUnlock()
+ if !ok {
+ return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
+ }
+ z.Meta = z.Meta.Clone()
+ logging.LogTrace(mb.logger, "GetZettel")
+ return z, nil
+}
+
+func (mb *memBox) HasZettel(_ context.Context, zid id.Zid) bool {
+ mb.mx.RLock()
+ _, found := mb.zettel[zid]
+ mb.mx.RUnlock()
+ return found
+}
+
+func (mb *memBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint query.RetrievePredicate) error {
+ mb.mx.RLock()
+ defer mb.mx.RUnlock()
+ logging.LogTrace(mb.logger, "ApplyZid", "entries", len(mb.zettel))
+ for zid := range mb.zettel {
+ if constraint(zid) {
+ handle(zid)
+ }
+ }
+ return nil
+}
+
+func (mb *memBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint query.RetrievePredicate) error {
+ mb.mx.RLock()
+ defer mb.mx.RUnlock()
+ logging.LogTrace(mb.logger, "ApplyMeta", "entries", len(mb.zettel))
+ for zid, zettel := range mb.zettel {
+ if constraint(zid) {
+ m := zettel.Meta.Clone()
+ mb.cdata.Enricher.Enrich(ctx, m, mb.cdata.Number)
+ handle(m)
+ }
+ }
+ return nil
+}
+
+func (mb *memBox) CanUpdateZettel(_ context.Context, zettel zettel.Zettel) bool {
+ mb.mx.RLock()
+ defer mb.mx.RUnlock()
+ zid := zettel.Meta.Zid
+ if !zid.IsValid() {
+ return false
+ }
+
+ newBytes := mb.curBytes + zettel.ByteSize()
+ if prevZettel, found := mb.zettel[zid]; found {
+ newBytes -= prevZettel.ByteSize()
+ }
+ return newBytes < mb.maxBytes
+}
+
+func (mb *memBox) UpdateZettel(_ context.Context, zettel zettel.Zettel) error {
+ m := zettel.Meta.Clone()
+ if !m.Zid.IsValid() {
+ return box.ErrInvalidZid{Zid: m.Zid.String()}
+ }
+
+ mb.mx.Lock()
+ newBytes := mb.curBytes + zettel.ByteSize()
+ if prevZettel, found := mb.zettel[m.Zid]; found {
+ newBytes -= prevZettel.ByteSize()
+ }
+ if mb.maxBytes < newBytes {
+ mb.mx.Unlock()
+ return box.ErrCapacity
+ }
+
+ zettel.Meta = m
+ mb.zettel[m.Zid] = zettel
+ mb.curBytes = newBytes
+ mb.mx.Unlock()
+ mb.notifyChanged(m.Zid, box.OnZettel)
+ logging.LogTrace(mb.logger, "UpdateZettel")
+ return nil
+}
+
+func (mb *memBox) CanDeleteZettel(_ context.Context, zid id.Zid) bool {
+ mb.mx.RLock()
+ _, ok := mb.zettel[zid]
+ mb.mx.RUnlock()
+ return ok
+}
+
+func (mb *memBox) DeleteZettel(_ context.Context, zid id.Zid) error {
+ mb.mx.Lock()
+ oldZettel, found := mb.zettel[zid]
+ if !found {
+ mb.mx.Unlock()
+ return box.ErrZettelNotFound{Zid: zid}
+ }
+ delete(mb.zettel, zid)
+ mb.curBytes -= oldZettel.ByteSize()
+ mb.mx.Unlock()
+ mb.notifyChanged(zid, box.OnDelete)
+ logging.LogTrace(mb.logger, "DeleteZettel")
+ return nil
+}
+
+func (mb *memBox) ReadStats(st *box.ManagedBoxStats) {
+ st.ReadOnly = false
+ mb.mx.RLock()
+ st.Zettel = len(mb.zettel)
+ mb.mx.RUnlock()
+ logging.LogTrace(mb.logger, "ReadStats", "zettel", st.Zettel)
+}
ADDED internal/box/notify/directory.go
Index: internal/box/notify/directory.go
==================================================================
--- /dev/null
+++ internal/box/notify/directory.go
@@ -0,0 +1,581 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package notify
+
+import (
+ "errors"
+ "log/slog"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "sync"
+
+ "t73f.de/r/zero/set"
+ "t73f.de/r/zsc/domain/id"
+
+ "zettelstore.de/z/internal/box"
+ "zettelstore.de/z/internal/kernel"
+ "zettelstore.de/z/internal/logging"
+ "zettelstore.de/z/internal/parser"
+ "zettelstore.de/z/internal/query"
+)
+
+type entrySet map[id.Zid]*DirEntry
+
+// DirServiceState signal the internal state of the service.
+//
+// The following state transitions are possible:
+// --newDirService--> dsCreated
+// dsCreated --Start--> dsStarting
+// dsStarting --last list notification--> dsWorking
+// dsWorking --directory missing--> dsMissing
+// dsMissing --last list notification--> dsWorking
+// --Stop--> dsStopping
+type DirServiceState uint8
+
+// Constants for DirServiceState
+const (
+ DsCreated DirServiceState = iota
+ DsStarting // Reading inital scan
+ DsWorking // Initial scan complete, fully operational
+ DsMissing // Directory is missing
+ DsStopping // Service is shut down
+)
+
+// DirService specifies a directory service for file based zettel.
+type DirService struct {
+ box box.ManagedBox
+ logger *slog.Logger
+ dirPath string
+ notifier Notifier
+ infos box.UpdateNotifier
+ mx sync.RWMutex // protects status, entries
+ state DirServiceState
+ entries entrySet
+}
+
+// ErrNoDirectory signals missing directory data.
+var ErrNoDirectory = errors.New("unable to retrieve zettel directory information")
+
+// NewDirService creates a new directory service.
+func NewDirService(box box.ManagedBox, logger *slog.Logger, notifier Notifier, notify box.UpdateNotifier) *DirService {
+ return &DirService{
+ box: box,
+ logger: logger,
+ notifier: notifier,
+ infos: notify,
+ state: DsCreated,
+ }
+}
+
+// State the current service state.
+func (ds *DirService) State() DirServiceState {
+ ds.mx.RLock()
+ state := ds.state
+ ds.mx.RUnlock()
+ return state
+}
+
+// Start the directory service.
+func (ds *DirService) Start() {
+ ds.mx.Lock()
+ ds.state = DsStarting
+ ds.mx.Unlock()
+ var newEntries entrySet
+ go ds.updateEvents(newEntries)
+}
+
+// Refresh the directory entries.
+func (ds *DirService) Refresh() {
+ ds.notifier.Refresh()
+}
+
+// Stop the directory service.
+func (ds *DirService) Stop() {
+ ds.mx.Lock()
+ ds.state = DsStopping
+ ds.mx.Unlock()
+ ds.notifier.Close()
+}
+
+func (ds *DirService) logMissingEntry(action string) error {
+ err := ErrNoDirectory
+ ds.logger.Info("Unable to get directory information", "err", err, "action", action)
+ return err
+}
+
+// NumDirEntries returns the number of entries in the directory.
+func (ds *DirService) NumDirEntries() int {
+ ds.mx.RLock()
+ defer ds.mx.RUnlock()
+ if ds.entries == nil {
+ return 0
+ }
+ return len(ds.entries)
+}
+
+// GetDirEntries returns a list of directory entries, which satisfy the given constraint.
+func (ds *DirService) GetDirEntries(constraint query.RetrievePredicate) []*DirEntry {
+ ds.mx.RLock()
+ defer ds.mx.RUnlock()
+ if ds.entries == nil {
+ return nil
+ }
+ result := make([]*DirEntry, 0, len(ds.entries))
+ for zid, entry := range ds.entries {
+ if constraint(zid) {
+ copiedEntry := *entry
+ result = append(result, &copiedEntry)
+ }
+ }
+ return result
+}
+
+// GetDirEntry returns a directory entry with the given zid, or nil if not found.
+func (ds *DirService) GetDirEntry(zid id.Zid) *DirEntry {
+ ds.mx.RLock()
+ defer ds.mx.RUnlock()
+ if ds.entries == nil {
+ return nil
+ }
+ foundEntry := ds.entries[zid]
+ if foundEntry == nil {
+ return nil
+ }
+ result := *foundEntry
+ return &result
+}
+
+// SetNewDirEntry calculates an empty directory entry with an unused identifier and
+// stores it in the directory.
+func (ds *DirService) SetNewDirEntry() (id.Zid, error) {
+ ds.mx.Lock()
+ defer ds.mx.Unlock()
+ if ds.entries == nil {
+ return id.Invalid, ds.logMissingEntry("new")
+ }
+ zid, err := box.GetNewZid(func(zid id.Zid) (bool, error) {
+ _, found := ds.entries[zid]
+ return !found, nil
+ })
+ if err != nil {
+ return id.Invalid, err
+ }
+ ds.entries[zid] = &DirEntry{Zid: zid}
+ return zid, nil
+}
+
+// UpdateDirEntry updates an directory entry in place.
+func (ds *DirService) UpdateDirEntry(updatedEntry *DirEntry) error {
+ entry := *updatedEntry
+ ds.mx.Lock()
+ defer ds.mx.Unlock()
+ if ds.entries == nil {
+ return ds.logMissingEntry("update")
+ }
+ ds.entries[entry.Zid] = &entry
+ return nil
+}
+
+// DeleteDirEntry removes a entry from the directory.
+func (ds *DirService) DeleteDirEntry(zid id.Zid) error {
+ ds.mx.Lock()
+ defer ds.mx.Unlock()
+ if ds.entries == nil {
+ return ds.logMissingEntry("delete")
+ }
+ delete(ds.entries, zid)
+ return nil
+}
+
+func (ds *DirService) updateEvents(newEntries entrySet) {
+ // Something may panic. Ensure a running service.
+ defer func() {
+ if ri := recover(); ri != nil {
+ kernel.Main.LogRecover("DirectoryService", ri)
+ go ds.updateEvents(newEntries)
+ }
+ }()
+
+ for ev := range ds.notifier.Events() {
+ e, ok := ds.handleEvent(ev, newEntries)
+ if !ok {
+ break
+ }
+ newEntries = e
+ }
+}
+func (ds *DirService) handleEvent(ev Event, newEntries entrySet) (entrySet, bool) {
+ ds.mx.RLock()
+ state := ds.state
+ ds.mx.RUnlock()
+
+ logging.LogTrace(ds.logger, "notifyEvent", "state", state, "op", ev.Op, "name", ev.Name)
+ if state == DsStopping {
+ return nil, false
+ }
+
+ switch ev.Op {
+ case Error:
+ newEntries = nil
+ if state != DsMissing {
+ ds.logger.Error("Notifier confused", "state", state, logging.Err(ev.Err))
+ }
+ case Make:
+ newEntries = make(entrySet)
+ case List:
+ if ev.Name == "" {
+ zids := getNewZids(newEntries)
+ ds.mx.Lock()
+ fromMissing := ds.state == DsMissing
+ prevEntries := ds.entries
+ ds.entries = newEntries
+ ds.state = DsWorking
+ ds.mx.Unlock()
+ ds.onCreateDirectory(zids, prevEntries)
+ if fromMissing {
+ ds.logger.Info("Zettel directory found", "path", ds.dirPath)
+ }
+ return nil, true
+ }
+ if newEntries != nil {
+ ds.onUpdateFileEvent(newEntries, ev.Name)
+ }
+ case Destroy:
+ ds.onDestroyDirectory()
+ ds.logger.Error("Zettel directory missing", "path", ds.dirPath)
+ return nil, true
+ case Update:
+ ds.mx.Lock()
+ zid := ds.onUpdateFileEvent(ds.entries, ev.Name)
+ ds.mx.Unlock()
+ if zid != id.Invalid {
+ ds.notifyChange(zid, box.OnZettel)
+ }
+ case Delete:
+ ds.mx.Lock()
+ zid := ds.onDeleteFileEvent(ds.entries, ev.Name)
+ ds.mx.Unlock()
+ if zid != id.Invalid {
+ ds.notifyChange(zid, box.OnDelete)
+ }
+ default:
+ ds.logger.Error("Unknown zettel notification", "event", ev)
+ }
+ return newEntries, true
+}
+
+func getNewZids(entries entrySet) []id.Zid {
+ zids := make([]id.Zid, 0, len(entries))
+ for zid := range entries {
+ zids = append(zids, zid)
+ }
+ return zids
+}
+
+func (ds *DirService) onCreateDirectory(zids []id.Zid, prevEntries entrySet) {
+ for _, zid := range zids {
+ ds.notifyChange(zid, box.OnZettel)
+ delete(prevEntries, zid)
+ }
+
+ // These were previously stored, by are not found now.
+ // Notify system that these were deleted, e.g. for updating the index.
+ for zid := range prevEntries {
+ ds.notifyChange(zid, box.OnDelete)
+ }
+}
+
+func (ds *DirService) onDestroyDirectory() {
+ ds.mx.Lock()
+ entries := ds.entries
+ ds.entries = nil
+ ds.state = DsMissing
+ ds.mx.Unlock()
+ for zid := range entries {
+ ds.notifyChange(zid, box.OnDelete)
+ }
+}
+
+var validFileName = regexp.MustCompile(`^(\d{14})`)
+
+func matchValidFileName(name string) []string {
+ return validFileName.FindStringSubmatch(name)
+}
+
+func seekZid(name string) id.Zid {
+ match := matchValidFileName(name)
+ if len(match) == 0 {
+ return id.Invalid
+ }
+ zid, err := id.Parse(match[1])
+ if err != nil {
+ return id.Invalid
+ }
+ return zid
+}
+
+func fetchdirEntry(entries entrySet, zid id.Zid) *DirEntry {
+ if entry, found := entries[zid]; found {
+ return entry
+ }
+ entry := &DirEntry{Zid: zid}
+ entries[zid] = entry
+ return entry
+}
+
+func (ds *DirService) onUpdateFileEvent(entries entrySet, name string) id.Zid {
+ if entries == nil {
+ return id.Invalid
+ }
+ zid := seekZid(name)
+ if zid == id.Invalid {
+ return id.Invalid
+ }
+ entry := fetchdirEntry(entries, zid)
+ dupName1, dupName2 := ds.updateEntry(entry, name)
+ if dupName1 != "" {
+ ds.logger.Info("Duplicate content (is ignored)", "name", dupName1)
+ if dupName2 != "" {
+ ds.logger.Info("Duplicate content (is ignored)", "name", dupName2)
+ }
+ return id.Invalid
+ }
+ return zid
+}
+
+func (ds *DirService) onDeleteFileEvent(entries entrySet, name string) id.Zid {
+ if entries == nil {
+ return id.Invalid
+ }
+ zid := seekZid(name)
+ if zid == id.Invalid {
+ return id.Invalid
+ }
+ entry, found := entries[zid]
+ if !found {
+ return zid
+ }
+ for i, dupName := range entry.UselessFiles {
+ if dupName == name {
+ removeDuplicate(entry, i)
+ return zid
+ }
+ }
+ if name == entry.ContentName {
+ entry.ContentName = ""
+ entry.ContentExt = ""
+ ds.replayUpdateUselessFiles(entry)
+ } else if name == entry.MetaName {
+ entry.MetaName = ""
+ ds.replayUpdateUselessFiles(entry)
+ }
+ if entry.ContentName == "" && entry.MetaName == "" {
+ delete(entries, zid)
+ }
+ return zid
+}
+
+func removeDuplicate(entry *DirEntry, i int) {
+ if len(entry.UselessFiles) == 1 {
+ entry.UselessFiles = nil
+ return
+ }
+ entry.UselessFiles = entry.UselessFiles[:i+copy(entry.UselessFiles[i:], entry.UselessFiles[i+1:])]
+}
+
+func (ds *DirService) replayUpdateUselessFiles(entry *DirEntry) {
+ uselessFiles := entry.UselessFiles
+ if len(uselessFiles) == 0 {
+ return
+ }
+ entry.UselessFiles = make([]string, 0, len(uselessFiles))
+ for _, name := range uselessFiles {
+ ds.updateEntry(entry, name)
+ }
+ if len(uselessFiles) == len(entry.UselessFiles) {
+ return
+ }
+loop:
+ for _, prevName := range uselessFiles {
+ for _, newName := range entry.UselessFiles {
+ if prevName == newName {
+ continue loop
+ }
+ }
+ ds.logger.Info("Previous duplicate file becomes useful", "name", prevName)
+ }
+}
+
+func (ds *DirService) updateEntry(entry *DirEntry, name string) (string, string) {
+ ext := onlyExt(name)
+ if !extIsMetaAndContent(entry.ContentExt) {
+ if ext == "" {
+ return updateEntryMeta(entry, name), ""
+ }
+ if entry.MetaName == "" {
+ if nameWithoutExt(name, ext) == entry.ContentName {
+ // We have marked a file as content file, but it is a metadata file,
+ // because it is the same as the new file without extension.
+ entry.MetaName = entry.ContentName
+ entry.ContentName = ""
+ entry.ContentExt = ""
+ ds.replayUpdateUselessFiles(entry)
+ } else if entry.ContentName != "" && nameWithoutExt(entry.ContentName, entry.ContentExt) == name {
+ // We have already a valid content file, and new file should serve as metadata file,
+ // because it is the same as the content file without extension.
+ entry.MetaName = name
+ return "", ""
+ }
+ }
+ }
+ return updateEntryContent(entry, name, ext)
+}
+
+func nameWithoutExt(name, ext string) string {
+ return name[0 : len(name)-len(ext)-1]
+}
+
+func updateEntryMeta(entry *DirEntry, name string) string {
+ metaName := entry.MetaName
+ if metaName == "" {
+ entry.MetaName = name
+ return ""
+ }
+ if metaName == name {
+ return ""
+ }
+ if newNameIsBetter(metaName, name) {
+ entry.MetaName = name
+ return addUselessFile(entry, metaName)
+ }
+ return addUselessFile(entry, name)
+}
+
+func updateEntryContent(entry *DirEntry, name, ext string) (string, string) {
+ contentName := entry.ContentName
+ if contentName == "" {
+ entry.ContentName = name
+ entry.ContentExt = ext
+ return "", ""
+ }
+ if contentName == name {
+ return "", ""
+ }
+ contentExt := entry.ContentExt
+ if contentExt == ext {
+ if newNameIsBetter(contentName, name) {
+ entry.ContentName = name
+ return addUselessFile(entry, contentName), ""
+ }
+ return addUselessFile(entry, name), ""
+ }
+ if contentExt == extZettel {
+ return addUselessFile(entry, name), ""
+ }
+ if ext == extZettel {
+ entry.ContentName = name
+ entry.ContentExt = ext
+ contentName = addUselessFile(entry, contentName)
+ if metaName := entry.MetaName; metaName != "" {
+ metaName = addUselessFile(entry, metaName)
+ entry.MetaName = ""
+ return contentName, metaName
+ }
+ return contentName, ""
+ }
+ if newExtIsBetter(contentExt, ext) {
+ entry.ContentName = name
+ entry.ContentExt = ext
+ return addUselessFile(entry, contentName), ""
+ }
+ return addUselessFile(entry, name), ""
+}
+func addUselessFile(entry *DirEntry, name string) string {
+ if slices.Contains(entry.UselessFiles, name) {
+ return ""
+ }
+ entry.UselessFiles = append(entry.UselessFiles, name)
+ return name
+}
+
+func onlyExt(name string) string {
+ ext := filepath.Ext(name)
+ if ext == "" || ext[0] != '.' {
+ return ext
+ }
+ return ext[1:]
+}
+
+func newNameIsBetter(oldName, newName string) bool {
+ if len(oldName) < len(newName) {
+ return false
+ }
+ return oldName > newName
+}
+
+var supportedSyntax, primarySyntax *set.Set[string]
+
+func init() {
+ syntaxList := parser.GetSyntaxes()
+ supportedSyntax = set.New(syntaxList...)
+ primarySyntax = set.New[string]()
+ for _, syntax := range syntaxList {
+ if parser.Get(syntax).Name == syntax {
+ primarySyntax.Add(syntax)
+ }
+ }
+}
+func newExtIsBetter(oldExt, newExt string) bool {
+ oldSyntax := supportedSyntax.Contains(oldExt)
+ if oldSyntax != supportedSyntax.Contains(newExt) {
+ return !oldSyntax
+ }
+ if oldSyntax {
+ if oldExt == "zmk" {
+ return false
+ }
+ if newExt == "zmk" {
+ return true
+ }
+ oldInfo := parser.Get(oldExt)
+ newInfo := parser.Get(newExt)
+ if oldASTParser := oldInfo.IsASTParser; oldASTParser != newInfo.IsASTParser {
+ return !oldASTParser
+ }
+ if oldTextFormat := oldInfo.IsTextFormat; oldTextFormat != newInfo.IsTextFormat {
+ return !oldTextFormat
+ }
+ if oldImageFormat := oldInfo.IsImageFormat; oldImageFormat != newInfo.IsImageFormat {
+ return oldImageFormat
+ }
+ if oldPrimary := primarySyntax.Contains(oldExt); oldPrimary != primarySyntax.Contains(newExt) {
+ return !oldPrimary
+ }
+ }
+
+ oldLen := len(oldExt)
+ newLen := len(newExt)
+ if oldLen != newLen {
+ return newLen < oldLen
+ }
+ return newExt < oldExt
+}
+
+func (ds *DirService) notifyChange(zid id.Zid, reason box.UpdateReason) {
+ if notify := ds.infos; notify != nil {
+ logging.LogTrace(ds.logger, "notifychange", "zid", zid, "reason", reason)
+ notify(ds.box, zid, reason)
+ }
+}
ADDED internal/box/notify/directory_test.go
Index: internal/box/notify/directory_test.go
==================================================================
--- /dev/null
+++ internal/box/notify/directory_test.go
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2022-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2022-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package notify
+
+import (
+ "testing"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+)
+
+func TestSeekZid(t *testing.T) {
+ testcases := []struct {
+ name string
+ zid id.Zid
+ }{
+ {"", id.Invalid},
+ {"1", id.Invalid},
+ {"1234567890123", id.Invalid},
+ {" 12345678901234", id.Invalid},
+ {"12345678901234", id.Zid(12345678901234)},
+ {"12345678901234.ext", id.Zid(12345678901234)},
+ {"12345678901234 abc.ext", id.Zid(12345678901234)},
+ {"12345678901234.abc.ext", id.Zid(12345678901234)},
+ {"12345678901234 def", id.Zid(12345678901234)},
+ }
+ for _, tc := range testcases {
+ gotZid := seekZid(tc.name)
+ if gotZid != tc.zid {
+ t.Errorf("seekZid(%q) == %v, but got %v", tc.name, tc.zid, gotZid)
+ }
+ }
+}
+
+func TestNewExtIsBetter(t *testing.T) {
+ extVals := []string{
+ // Main Formats
+ meta.ValueSyntaxZmk, meta.ValueSyntaxDraw, meta.ValueSyntaxMarkdown, meta.ValueSyntaxMD,
+ // Other supported text formats
+ meta.ValueSyntaxCSS, meta.ValueSyntaxSxn, meta.ValueSyntaxTxt, meta.ValueSyntaxHTML,
+ meta.ValueSyntaxText, meta.ValueSyntaxPlain,
+ // Supported text graphics formats
+ meta.ValueSyntaxSVG,
+ meta.ValueSyntaxNone,
+ // Supported binary graphic formats
+ meta.ValueSyntaxGif, meta.ValueSyntaxPNG, meta.ValueSyntaxJPEG, meta.ValueSyntaxWebp, meta.ValueSyntaxJPG,
+
+ // Unsupported syntax values
+ "gz", "cpp", "tar", "cppc",
+ }
+ for oldI, oldExt := range extVals {
+ for newI, newExt := range extVals {
+ if oldI <= newI {
+ continue
+ }
+ if !newExtIsBetter(oldExt, newExt) {
+ t.Errorf("newExtIsBetter(%q, %q) == true, but got false", oldExt, newExt)
+ }
+ if newExtIsBetter(newExt, oldExt) {
+ t.Errorf("newExtIsBetter(%q, %q) == false, but got true", newExt, oldExt)
+ }
+ }
+ }
+}
ADDED internal/box/notify/entry.go
Index: internal/box/notify/entry.go
==================================================================
--- /dev/null
+++ internal/box/notify/entry.go
@@ -0,0 +1,122 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package notify
+
+import (
+ "path/filepath"
+
+ "slices"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "zettelstore.de/z/internal/parser"
+ "zettelstore.de/z/internal/zettel"
+)
+
+const (
+ extZettel = "zettel" // file contains metadata and content
+ extBin = "bin" // file contains binary content
+ extTxt = "txt" // file contains non-binary content
+)
+
+func extIsMetaAndContent(ext string) bool { return ext == extZettel }
+
+// DirEntry stores everything for a directory entry.
+type DirEntry struct {
+ Zid id.Zid
+ MetaName string // file name of meta information
+ ContentName string // file name of zettel content
+ ContentExt string // (normalized) file extension of zettel content
+ UselessFiles []string // list of other content files
+}
+
+// IsValid checks whether the entry is valid.
+func (e *DirEntry) IsValid() bool {
+ return e != nil && e.Zid.IsValid()
+}
+
+// HasMetaInContent returns true, if metadata will be stored in the content file.
+func (e *DirEntry) HasMetaInContent() bool {
+ return e.IsValid() && extIsMetaAndContent(e.ContentExt)
+}
+
+// SetupFromMetaContent fills entry data based on metadata and zettel content.
+func (e *DirEntry) SetupFromMetaContent(m *meta.Meta, content zettel.Content, getZettelFileSyntax func() []meta.Value) {
+ if e.Zid != m.Zid {
+ panic("Zid differ")
+ }
+ if contentName := e.ContentName; contentName != "" {
+ if !extIsMetaAndContent(e.ContentExt) && e.MetaName == "" {
+ e.MetaName = e.calcBaseName(contentName)
+ }
+ return
+ }
+
+ syntax := m.GetDefault(meta.KeySyntax, meta.DefaultSyntax)
+ ext := calcContentExt(syntax, m.YamlSep, getZettelFileSyntax)
+ metaName := e.MetaName
+ eimc := extIsMetaAndContent(ext)
+ if eimc {
+ if metaName != "" {
+ ext = contentExtWithMeta(syntax, content)
+ }
+ e.ContentName = e.calcBaseName(metaName) + "." + ext
+ e.ContentExt = ext
+ } else {
+ if len(content.AsBytes()) > 0 {
+ e.ContentName = e.calcBaseName(metaName) + "." + ext
+ e.ContentExt = ext
+ }
+ if metaName == "" {
+ e.MetaName = e.calcBaseName(e.ContentName)
+ }
+ }
+}
+
+func contentExtWithMeta(syntax meta.Value, content zettel.Content) string {
+ p := parser.Get(string(syntax))
+ if content.IsBinary() {
+ if p.IsImageFormat {
+ return string(syntax)
+ }
+ return extBin
+ }
+ if p.IsImageFormat {
+ return extTxt
+ }
+ return string(syntax)
+}
+
+func calcContentExt(syntax meta.Value, yamlSep bool, getZettelFileSyntax func() []meta.Value) string {
+ if yamlSep {
+ return extZettel
+ }
+ switch syntax {
+ case meta.ValueSyntaxNone, meta.ValueSyntaxZmk:
+ return extZettel
+ }
+ if slices.Contains(getZettelFileSyntax(), syntax) {
+ return extZettel
+ }
+ return string(syntax)
+
+}
+
+func (e *DirEntry) calcBaseName(name string) string {
+ if name == "" {
+ return e.Zid.String()
+ }
+ return name[0 : len(name)-len(filepath.Ext(name))]
+
+}
ADDED internal/box/notify/fsdir.go
Index: internal/box/notify/fsdir.go
==================================================================
--- /dev/null
+++ internal/box/notify/fsdir.go
@@ -0,0 +1,235 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package notify
+
+import (
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/fsnotify/fsnotify"
+
+ "zettelstore.de/z/internal/logging"
+)
+
+type fsdirNotifier struct {
+ logger *slog.Logger
+ events chan Event
+ done chan struct{}
+ refresh chan struct{}
+ base *fsnotify.Watcher
+ path string
+ fetcher EntryFetcher
+ parent string
+}
+
+// NewFSDirNotifier creates a directory based notifier that receives notifications
+// from the file system.
+func NewFSDirNotifier(logger *slog.Logger, path string) (Notifier, error) {
+ absPath, err := filepath.Abs(path)
+ if err != nil {
+ logger.Debug("Unable to create absolute path", "err", err, "path", path)
+ return nil, err
+ }
+ watcher, err := fsnotify.NewWatcher()
+ if err != nil {
+ logger.Debug("Unable to create watcher", "err", err, "absPath", absPath)
+ return nil, err
+ }
+ absParentDir := filepath.Dir(absPath)
+ errParent := watcher.Add(absParentDir)
+ err = watcher.Add(absPath)
+ if errParent != nil {
+ if err != nil {
+ logger.Error("Unable to access Zettel directory and its parent directory",
+ "parentDir", absParentDir, "errParent", errParent, "path", absPath, "err", err)
+ _ = watcher.Close()
+ return nil, err
+ }
+ logger.Info("Parent of Zettel directory cannot be supervised",
+ "parentDir", absParentDir, "err", errParent)
+ logger.Info("Zettelstore might not detect a deletion or movement of the Zettel directory",
+ "path", absPath)
+ } else if err != nil {
+ // Not a problem, if container is not available. It might become available later.
+ logger.Info("Zettel directory currently not available", "err", err, "path", absPath)
+ }
+
+ fsdn := &fsdirNotifier{
+ logger: logger,
+ events: make(chan Event),
+ refresh: make(chan struct{}),
+ done: make(chan struct{}),
+ base: watcher,
+ path: absPath,
+ fetcher: newDirPathFetcher(absPath),
+ parent: absParentDir,
+ }
+ go fsdn.eventLoop()
+ return fsdn, nil
+}
+
+func (fsdn *fsdirNotifier) Events() <-chan Event {
+ return fsdn.events
+}
+
+func (fsdn *fsdirNotifier) Refresh() {
+ fsdn.refresh <- struct{}{}
+}
+
+func (fsdn *fsdirNotifier) eventLoop() {
+ defer func() { _ = fsdn.base.Close() }()
+ defer close(fsdn.events)
+ defer close(fsdn.refresh)
+ if !listDirElements(fsdn.logger, fsdn.fetcher, fsdn.events, fsdn.done) {
+ return
+ }
+
+ for fsdn.readAndProcessEvent() {
+ }
+}
+
+func (fsdn *fsdirNotifier) readAndProcessEvent() bool {
+ select {
+ case <-fsdn.done:
+ fsdn.traceDone(1)
+ return false
+ default:
+ }
+ select {
+ case <-fsdn.done:
+ fsdn.traceDone(2)
+ return false
+ case <-fsdn.refresh:
+ logging.LogTrace(fsdn.logger, "refresh")
+ listDirElements(fsdn.logger, fsdn.fetcher, fsdn.events, fsdn.done)
+ case err, ok := <-fsdn.base.Errors:
+ logging.LogTrace(fsdn.logger, "got errors", "err", err, "ok", ok)
+ if !ok {
+ return false
+ }
+ select {
+ case fsdn.events <- Event{Op: Error, Err: err}:
+ case <-fsdn.done:
+ fsdn.traceDone(3)
+ return false
+ }
+ case ev, ok := <-fsdn.base.Events:
+ logging.LogTrace(fsdn.logger, "file event", "name", ev.Name, "op", ev.Op, "ok", ok)
+ if !ok {
+ return false
+ }
+ if !fsdn.processEvent(&ev) {
+ return false
+ }
+ }
+ return true
+}
+
+func (fsdn *fsdirNotifier) traceDone(pos int64) {
+ logging.LogTrace(fsdn.logger, "done with read and process events", "i", pos)
+}
+
+func (fsdn *fsdirNotifier) processEvent(ev *fsnotify.Event) bool {
+ if strings.HasPrefix(ev.Name, fsdn.path) {
+ if len(ev.Name) == len(fsdn.path) {
+ return fsdn.processDirEvent(ev)
+ }
+ return fsdn.processFileEvent(ev)
+ }
+ logging.LogTrace(fsdn.logger, "event does not match", "path", fsdn.path, "name", ev.Name, "op", ev.Op)
+ return true
+}
+
+func (fsdn *fsdirNotifier) processDirEvent(ev *fsnotify.Event) bool {
+ if ev.Has(fsnotify.Remove) || ev.Has(fsnotify.Rename) {
+ fsdn.logger.Debug("Directory removed", "name", fsdn.path)
+ _ = fsdn.base.Remove(fsdn.path)
+ select {
+ case fsdn.events <- Event{Op: Destroy}:
+ case <-fsdn.done:
+ logging.LogTrace(fsdn.logger, "done dir event processing", "i", 1)
+ return false
+ }
+ return true
+ }
+
+ if ev.Has(fsnotify.Create) {
+ err := fsdn.base.Add(fsdn.path)
+ if err != nil {
+ fsdn.logger.Error("Unable to add directory", "err", err, "name", fsdn.path)
+ select {
+ case fsdn.events <- Event{Op: Error, Err: err}:
+ case <-fsdn.done:
+ logging.LogTrace(fsdn.logger, "done dir event processing", "i", 2)
+ return false
+ }
+ }
+ fsdn.logger.Debug("Directory added", "name", fsdn.path)
+ return listDirElements(fsdn.logger, fsdn.fetcher, fsdn.events, fsdn.done)
+ }
+
+ logging.LogTrace(fsdn.logger, "Directory processed", "name", ev.Name, "op", ev.Op)
+ return true
+}
+
+func (fsdn *fsdirNotifier) processFileEvent(ev *fsnotify.Event) bool {
+ if ev.Has(fsnotify.Create) || ev.Has(fsnotify.Write) {
+ if fi, err := os.Lstat(ev.Name); err != nil || !fi.Mode().IsRegular() {
+ regular := err == nil && fi.Mode().IsRegular()
+ logging.LogTrace(fsdn.logger, "error with file",
+ "name", ev.Name, "op", ev.Op, logging.Err(err), "regular", regular)
+ return true
+ }
+ logging.LogTrace(fsdn.logger, "File updated", "name", ev.Name, "op", ev.Op)
+ return fsdn.sendEvent(Update, filepath.Base(ev.Name))
+ }
+
+ if ev.Has(fsnotify.Rename) {
+ fi, err := os.Lstat(ev.Name)
+ if err != nil {
+ logging.LogTrace(fsdn.logger, "File deleted", "name", ev.Name, "op", ev.Op)
+ return fsdn.sendEvent(Delete, filepath.Base(ev.Name))
+ }
+ if fi.Mode().IsRegular() {
+ logging.LogTrace(fsdn.logger, "File updated", "name", ev.Name, "op", ev.Op)
+ return fsdn.sendEvent(Update, filepath.Base(ev.Name))
+ }
+ logging.LogTrace(fsdn.logger, "File not regular", "name", ev.Name)
+ return true
+ }
+
+ if ev.Has(fsnotify.Remove) {
+ logging.LogTrace(fsdn.logger, "File deleted", "name", ev.Name, "op", ev.Op)
+ return fsdn.sendEvent(Delete, filepath.Base(ev.Name))
+ }
+
+ logging.LogTrace(fsdn.logger, "File processed", "name", ev.Name, "op", ev.Op)
+ return true
+}
+
+func (fsdn *fsdirNotifier) sendEvent(op EventOp, filename string) bool {
+ select {
+ case fsdn.events <- Event{Op: op, Name: filename}:
+ case <-fsdn.done:
+ logging.LogTrace(fsdn.logger, "done file event processing")
+ return false
+ }
+ return true
+}
+
+func (fsdn *fsdirNotifier) Close() {
+ close(fsdn.done)
+}
ADDED internal/box/notify/helper.go
Index: internal/box/notify/helper.go
==================================================================
--- /dev/null
+++ internal/box/notify/helper.go
@@ -0,0 +1,99 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package notify
+
+import (
+ "archive/zip"
+ "log/slog"
+ "os"
+
+ "zettelstore.de/z/internal/logging"
+)
+
+// EntryFetcher return a list of (file) names of an directory.
+type EntryFetcher interface {
+ Fetch() ([]string, error)
+}
+
+type dirPathFetcher struct {
+ dirPath string
+}
+
+func newDirPathFetcher(dirPath string) EntryFetcher { return &dirPathFetcher{dirPath} }
+
+func (dpf *dirPathFetcher) Fetch() ([]string, error) {
+ entries, err := os.ReadDir(dpf.dirPath)
+ if err != nil {
+ return nil, err
+ }
+ result := make([]string, 0, len(entries))
+ for _, entry := range entries {
+ if info, err1 := entry.Info(); err1 != nil || !info.Mode().IsRegular() {
+ continue
+ }
+ result = append(result, entry.Name())
+ }
+ return result, nil
+}
+
+type zipPathFetcher struct {
+ zipPath string
+}
+
+func newZipPathFetcher(zipPath string) EntryFetcher { return &zipPathFetcher{zipPath} }
+
+func (zpf *zipPathFetcher) Fetch() ([]string, error) {
+ reader, err := zip.OpenReader(zpf.zipPath)
+ if err != nil {
+ return nil, err
+ }
+ result := make([]string, 0, len(reader.File))
+ for _, f := range reader.File {
+ result = append(result, f.Name)
+ }
+ err = reader.Close()
+ return result, err
+}
+
+// listDirElements write all files within the directory path as events.
+func listDirElements(logger *slog.Logger, fetcher EntryFetcher, events chan<- Event, done <-chan struct{}) bool {
+ select {
+ case events <- Event{Op: Make}:
+ case <-done:
+ return false
+ }
+ entries, err := fetcher.Fetch()
+ if err != nil {
+ select {
+ case events <- Event{Op: Error, Err: err}:
+ case <-done:
+ return false
+ }
+ }
+ for _, name := range entries {
+ logging.LogTrace(logger, "File listed", "name", name)
+ select {
+ case events <- Event{Op: List, Name: name}:
+ case <-done:
+ return false
+ }
+ }
+
+ select {
+ case events <- Event{Op: List}:
+ case <-done:
+ return false
+ }
+ return true
+}
ADDED internal/box/notify/notify.go
Index: internal/box/notify/notify.go
==================================================================
--- /dev/null
+++ internal/box/notify/notify.go
@@ -0,0 +1,85 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package notify provides some notification services to be used by box services.
+package notify
+
+import "fmt"
+
+// Notifier send events about their container and content.
+type Notifier interface {
+ // Return the channel
+ Events() <-chan Event
+
+ // Signal a refresh of the container. This will result in some events.
+ Refresh()
+
+ // Close the notifier (and eventually the channel)
+ Close()
+}
+
+// EventOp describe a notification operation.
+type EventOp uint8
+
+// Valid constants for event operations.
+//
+// Error signals a detected error. Details are in Event.Err.
+//
+// Make signals that the container is detected. List events will follow.
+//
+// List signals a found file, if Event.Name is not empty. Otherwise it signals
+// the end of files within the container.
+//
+// Destroy signals that the container is not there any more. It might me Make later again.
+//
+// Update signals that file Event.Name was created/updated.
+// File name is relative to the container.
+//
+// Delete signals that file Event.Name was removed.
+// File name is relative to the container's name.
+const (
+ _ EventOp = iota
+ Error // Error while operating
+ Make // Make container
+ List // List container
+ Destroy // Destroy container
+ Update // Update element
+ Delete // Delete element
+)
+
+// String representation of operation code.
+func (c EventOp) String() string {
+ switch c {
+ case Error:
+ return "ERROR"
+ case Make:
+ return "MAKE"
+ case List:
+ return "LIST"
+ case Destroy:
+ return "DESTROY"
+ case Update:
+ return "UPDATE"
+ case Delete:
+ return "DELETE"
+ default:
+ return fmt.Sprintf("UNKNOWN(%d)", c)
+ }
+}
+
+// Event represents a single container / element event.
+type Event struct {
+ Op EventOp
+ Name string
+ Err error // Valid iff Op == Error
+}
ADDED internal/box/notify/simpledir.go
Index: internal/box/notify/simpledir.go
==================================================================
--- /dev/null
+++ internal/box/notify/simpledir.go
@@ -0,0 +1,87 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package notify
+
+import (
+ "log/slog"
+ "path/filepath"
+)
+
+type simpleDirNotifier struct {
+ logger *slog.Logger
+ events chan Event
+ done chan struct{}
+ refresh chan struct{}
+ fetcher EntryFetcher
+}
+
+// NewSimpleDirNotifier creates a directory based notifier that will not receive
+// any notifications from the operating system.
+func NewSimpleDirNotifier(logger *slog.Logger, path string) (Notifier, error) {
+ absPath, err := filepath.Abs(path)
+ if err != nil {
+ return nil, err
+ }
+ sdn := &simpleDirNotifier{
+ logger: logger,
+ events: make(chan Event),
+ done: make(chan struct{}),
+ refresh: make(chan struct{}),
+ fetcher: newDirPathFetcher(absPath),
+ }
+ go sdn.eventLoop()
+ return sdn, nil
+}
+
+// NewSimpleZipNotifier creates a zip-file based notifier that will not receive
+// any notifications from the operating system.
+func NewSimpleZipNotifier(logger *slog.Logger, zipPath string) Notifier {
+ sdn := &simpleDirNotifier{
+ logger: logger,
+ events: make(chan Event),
+ done: make(chan struct{}),
+ refresh: make(chan struct{}),
+ fetcher: newZipPathFetcher(zipPath),
+ }
+ go sdn.eventLoop()
+ return sdn
+}
+
+func (sdn *simpleDirNotifier) Events() <-chan Event {
+ return sdn.events
+}
+
+func (sdn *simpleDirNotifier) Refresh() {
+ sdn.refresh <- struct{}{}
+}
+
+func (sdn *simpleDirNotifier) eventLoop() {
+ defer close(sdn.events)
+ defer close(sdn.refresh)
+ if !listDirElements(sdn.logger, sdn.fetcher, sdn.events, sdn.done) {
+ return
+ }
+ for {
+ select {
+ case <-sdn.done:
+ return
+ case <-sdn.refresh:
+ listDirElements(sdn.logger, sdn.fetcher, sdn.events, sdn.done)
+ }
+ }
+}
+
+func (sdn *simpleDirNotifier) Close() {
+ close(sdn.done)
+}
ADDED internal/collect/collect.go
Index: internal/collect/collect.go
==================================================================
--- /dev/null
+++ internal/collect/collect.go
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package collect provides functions to collect items from a syntax tree.
+package collect
+
+import (
+ "iter"
+
+ "zettelstore.de/z/internal/ast"
+)
+
+type refYielder struct {
+ yield func(*ast.Reference) bool
+ stop bool
+}
+
+// ReferenceSeq returns an iterator of all references mentioned in the given
+// zettel. This also includes references to images.
+func ReferenceSeq(zn *ast.ZettelNode) iter.Seq[*ast.Reference] {
+ return func(yield func(*ast.Reference) bool) {
+ yielder := refYielder{yield, false}
+ ast.Walk(&yielder, &zn.BlocksAST)
+ }
+}
+
+// Visit all node to collect data for the summary.
+func (y *refYielder) Visit(node ast.Node) ast.Visitor {
+ if y.stop {
+ return nil
+ }
+ var stop bool
+ switch n := node.(type) {
+ case *ast.TranscludeNode:
+ stop = !y.yield(n.Ref)
+ case *ast.LinkNode:
+ stop = !y.yield(n.Ref)
+ case *ast.EmbedRefNode:
+ stop = !y.yield(n.Ref)
+ }
+ if stop {
+ y.stop = true
+ return nil
+ }
+ return y
+}
ADDED internal/collect/collect_test.go
Index: internal/collect/collect_test.go
==================================================================
--- /dev/null
+++ internal/collect/collect_test.go
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package collect_test provides some unit test for collectors.
+package collect_test
+
+import (
+ "slices"
+ "testing"
+
+ "zettelstore.de/z/internal/ast"
+ "zettelstore.de/z/internal/collect"
+)
+
+func parseRef(s string) *ast.Reference {
+ r := ast.ParseReference(s)
+ if !r.IsValid() {
+ panic(s)
+ }
+ return r
+}
+
+func TestReferenceSeq(t *testing.T) {
+ t.Parallel()
+ zn := &ast.ZettelNode{}
+ summary := slices.Collect(collect.ReferenceSeq(zn))
+ if len(summary) != 0 {
+ t.Error("No references expected, but got:", summary)
+ }
+
+ intNode := &ast.LinkNode{Ref: parseRef("01234567890123")}
+ para := ast.CreateParaNode(intNode, &ast.LinkNode{Ref: parseRef("https://zettelstore.de/z")})
+ zn.BlocksAST = ast.BlockSlice{para}
+ summary = slices.Collect(collect.ReferenceSeq(zn))
+ if len(summary) != 2 {
+ t.Error("2 refs expected, but got:", summary)
+ }
+
+ para.Inlines = append(para.Inlines, intNode)
+ summary = slices.Collect(collect.ReferenceSeq(zn))
+ if cnt := len(summary); cnt != 3 {
+ t.Error("Ref count does not work. Expected: 3, got", summary)
+ }
+
+ zn = &ast.ZettelNode{
+ BlocksAST: ast.BlockSlice{ast.CreateParaNode(&ast.EmbedRefNode{Ref: parseRef("12345678901234")})},
+ }
+ summary = slices.Collect(collect.ReferenceSeq(zn))
+ if len(summary) != 1 {
+ t.Error("Only one image ref expected, but got: ", summary)
+ }
+}
ADDED internal/collect/order.go
Index: internal/collect/order.go
==================================================================
--- /dev/null
+++ internal/collect/order.go
@@ -0,0 +1,73 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package collect provides functions to collect items from a syntax tree.
+package collect
+
+import "zettelstore.de/z/internal/ast"
+
+// Order of internal links within the given zettel.
+func Order(zn *ast.ZettelNode) (result []*ast.LinkNode) {
+ for _, bn := range zn.BlocksAST {
+ ln, ok := bn.(*ast.NestedListNode)
+ if !ok {
+ continue
+ }
+ switch ln.Kind {
+ case ast.NestedListOrdered, ast.NestedListUnordered:
+ for _, is := range ln.Items {
+ if ln := firstItemZettelLink(is); ln != nil {
+ result = append(result, ln)
+ }
+ }
+ }
+ }
+ return result
+}
+
+func firstItemZettelLink(is ast.ItemSlice) *ast.LinkNode {
+ for _, in := range is {
+ if pn, ok := in.(*ast.ParaNode); ok {
+ if ln := firstInlineZettelLink(pn.Inlines); ln != nil {
+ return ln
+ }
+ }
+ }
+ return nil
+}
+
+func firstInlineZettelLink(is ast.InlineSlice) (result *ast.LinkNode) {
+ for _, inl := range is {
+ switch in := inl.(type) {
+ case *ast.LinkNode:
+ return in
+ case *ast.EmbedRefNode:
+ result = firstInlineZettelLink(in.Inlines)
+ case *ast.EmbedBLOBNode:
+ result = firstInlineZettelLink(in.Inlines)
+ case *ast.CiteNode:
+ result = firstInlineZettelLink(in.Inlines)
+ case *ast.FootnoteNode:
+ // Ignore references in footnotes
+ continue
+ case *ast.FormatNode:
+ result = firstInlineZettelLink(in.Inlines)
+ default:
+ continue
+ }
+ if result != nil {
+ return result
+ }
+ }
+ return nil
+}
ADDED internal/config/config.go
Index: internal/config/config.go
==================================================================
--- /dev/null
+++ internal/config/config.go
@@ -0,0 +1,111 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package config provides functions to retrieve runtime configuration data.
+package config
+
+import (
+ "context"
+
+ "t73f.de/r/zsc/domain/meta"
+)
+
+// Key values that are supported by Config.Get
+const (
+ KeyFooterZettel = "footer-zettel"
+ KeyHomeZettel = "home-zettel"
+ KeyListsMenuZettel = "lists-menu-zettel"
+ KeyShowBackLinks = "show-back-links"
+ KeyShowFolgeLinks = "show-folge-links"
+ KeyShowSequelLinks = "show-sequel-links"
+ KeyShowSubordinateLinks = "show-subordinate-links"
+ // api.KeyLang
+)
+
+// Config allows to retrieve all defined configuration values that can be changed during runtime.
+type Config interface {
+ AuthConfig
+
+ // Get returns the value of the given key. It searches first in the given metadata,
+ // then in the data of the current user, and at last in the system-wide data.
+ Get(ctx context.Context, m *meta.Meta, key string) string
+
+ // AddDefaultValues enriches the given meta data with its default values.
+ AddDefaultValues(context.Context, *meta.Meta) *meta.Meta
+
+ // GetSiteName returns the current value of the "site-name" key.
+ GetSiteName() string
+
+ // GetHTMLInsecurity returns the current
+ GetHTMLInsecurity() HTMLInsecurity
+
+ // GetMaxTransclusions returns the maximum number of indirect transclusions.
+ GetMaxTransclusions() int
+
+ // GetYAMLHeader returns the current value of the "yaml-header" key.
+ GetYAMLHeader() bool
+
+ // GetZettelFileSyntax returns the current value of the "zettel-file-syntax" key.
+ GetZettelFileSyntax() []meta.Value
+}
+
+// AuthConfig are relevant configuration values for authentication.
+type AuthConfig interface {
+ // GetSimpleMode returns true if system tuns in simple-mode.
+ GetSimpleMode() bool
+
+ // GetExpertMode returns the current value of the "expert-mode" key.
+ GetExpertMode() bool
+
+ // GetVisibility returns the visibility value of the metadata.
+ GetVisibility(m *meta.Meta) meta.Visibility
+}
+
+// HTMLInsecurity states what kind of insecure HTML is allowed.
+// The lowest value is the most secure one (disallowing any HTML)
+type HTMLInsecurity uint8
+
+// Constant values for HTMLInsecurity:
+const (
+ NoHTML HTMLInsecurity = iota
+ SyntaxHTML
+ MarkdownHTML
+ ZettelmarkupHTML
+)
+
+func (hi HTMLInsecurity) String() string {
+ switch hi {
+ case SyntaxHTML:
+ return "html"
+ case MarkdownHTML:
+ return "markdown"
+ case ZettelmarkupHTML:
+ return "zettelmarkup"
+ }
+ return "secure"
+}
+
+// AllowHTML returns true, if the given HTML insecurity level matches the given syntax value.
+func (hi HTMLInsecurity) AllowHTML(syntax string) bool {
+ switch hi {
+ case SyntaxHTML:
+ return syntax == meta.ValueSyntaxHTML
+ case MarkdownHTML:
+ return syntax == meta.ValueSyntaxHTML || syntax == meta.ValueSyntaxMarkdown ||
+ syntax == meta.ValueSyntaxMD
+ case ZettelmarkupHTML:
+ return syntax == meta.ValueSyntaxZmk || syntax == meta.ValueSyntaxHTML ||
+ syntax == meta.ValueSyntaxMarkdown || syntax == meta.ValueSyntaxMD
+ }
+ return false
+}
ADDED internal/encoder/encoder.go
Index: internal/encoder/encoder.go
==================================================================
--- /dev/null
+++ internal/encoder/encoder.go
@@ -0,0 +1,81 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2020-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2020-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+// Package encoder provides a generic interface to encode the abstract syntax
+// tree into some text form.
+package encoder
+
+import (
+ "io"
+
+ "t73f.de/r/zsc/api"
+ "t73f.de/r/zsc/domain/meta"
+ "t73f.de/r/zsc/shtml"
+
+ "zettelstore.de/z/internal/ast"
+)
+
+// Encoder is an interface that allows to encode different parts of a zettel.
+type Encoder interface {
+ // WriteZettel encodes a whole zettel and writes it to the Writer.
+ WriteZettel(io.Writer, *ast.ZettelNode) (int, error)
+
+ // WriteMeta encodes just the metadata.
+ WriteMeta(io.Writer, *meta.Meta) (int, error)
+
+ // WiteBlocks encodes a block slice, i.e. the zettel content.
+ WriteBlocks(io.Writer, *ast.BlockSlice) (int, error)
+}
+
+// Create builds a new encoder with the given options.
+func Create(enc api.EncodingEnum, params *CreateParameter) Encoder {
+ switch enc {
+ case api.EncoderHTML:
+ // We need a new transformer every time, because tx.inVerse must be unique.
+ // If we can refactor it out, the transformer can be created only once.
+ return &htmlEncoder{
+ tx: NewSzTransformer(),
+ th: shtml.NewEvaluator(1),
+ lang: params.Lang,
+ }
+ case api.EncoderMD:
+ return &mdEncoder{lang: params.Lang}
+ case api.EncoderSHTML:
+ // We need a new transformer every time, because tx.inVerse must be unique.
+ // If we can refactor it out, the transformer can be created only once.
+ return &shtmlEncoder{
+ tx: NewSzTransformer(),
+ th: shtml.NewEvaluator(1),
+ lang: params.Lang,
+ }
+ case api.EncoderSz:
+ // We need a new transformer every time, because trans.inVerse must be unique.
+ // If we can refactor it out, the transformer can be created only once.
+ return &szEncoder{trans: NewSzTransformer()}
+ case api.EncoderText:
+ return (*TextEncoder)(nil)
+ case api.EncoderZmk:
+ return (*zmkEncoder)(nil)
+ }
+ return nil
+}
+
+// CreateParameter contains values that are needed to create some encoder.
+type CreateParameter struct {
+ Lang string // default language
+}
+
+// GetEncodings returns all registered encodings, ordered by encoding value.
+func GetEncodings() []api.EncodingEnum {
+ return []api.EncodingEnum{api.EncoderHTML, api.EncoderMD, api.EncoderSHTML, api.EncoderSz, api.EncoderText, api.EncoderZmk}
+}
ADDED internal/encoder/encoder_blob_test.go
Index: internal/encoder/encoder_blob_test.go
==================================================================
--- /dev/null
+++ internal/encoder/encoder_blob_test.go
@@ -0,0 +1,63 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package encoder_test
+
+import (
+ "testing"
+
+ "t73f.de/r/zsc/domain/id"
+ "t73f.de/r/zsc/domain/meta"
+ "t73f.de/r/zsx/input"
+
+ "zettelstore.de/z/internal/config"
+ "zettelstore.de/z/internal/parser"
+)
+
+type blobTestCase struct {
+ descr string
+ syntax string
+ blob []byte
+ expect expectMap
+}
+
+var pngTestCases = []blobTestCase{
+ {
+ descr: "Minimal PNG",
+ syntax: "png",
+ blob: []byte{
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x7e, 0x9b,
+ 0x55, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x62, 0x00, 0x00, 0x00,
+ 0x06, 0x00, 0x03, 0x36, 0x37, 0x7c, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
+ 0x42, 0x60, 0x82,
+ },
+ expect: expectMap{
+ encoderHTML: `
`,
+ encoderSz: `(BLOCK (BLOB () ((TEXT "Minimal PNG")) "png" "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg=="))`,
+ encoderSHTML: `((p (img (@ (alt . "Minimal PNG") (src . "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg==")))))`,
+ encoderText: "",
+ encoderZmk: `%% Unable to display BLOB with description 'Minimal PNG' and syntax 'png'.`,
+ },
+ },
+}
+
+func TestBlob(t *testing.T) {
+ m := meta.New(id.Invalid)
+ for testNum, tc := range pngTestCases {
+ m.Set(meta.KeyTitle, meta.Value(tc.descr))
+ inp := input.NewInput(tc.blob)
+ bs := parser.Parse(inp, m, tc.syntax, config.NoHTML)
+ checkEncodings(t, testNum, bs, false, tc.descr, tc.expect, "???")
+ }
+}
ADDED internal/encoder/encoder_block_test.go
Index: internal/encoder/encoder_block_test.go
==================================================================
--- /dev/null
+++ internal/encoder/encoder_block_test.go
@@ -0,0 +1,411 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package encoder_test
+
+var tcsBlock = []zmkTestCase{
+ {
+ descr: "Empty Zettelmarkup should produce near nothing",
+ zmk: "",
+ expect: expectMap{
+ encoderHTML: "",
+ encoderMD: "",
+ encoderSz: `(BLOCK)`,
+ encoderSHTML: `()`,
+ encoderText: "",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple text: Hello, world",
+ zmk: "Hello, world",
+ expect: expectMap{
+ encoderHTML: "Hello, world
",
+ encoderMD: "Hello, world",
+ encoderSz: `(BLOCK (PARA (TEXT "Hello, world")))`,
+ encoderSHTML: `((p "Hello, world"))`,
+ encoderText: "Hello, world",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple block comment",
+ zmk: "%%%\nNo\nrender\n%%%",
+ expect: expectMap{
+ encoderHTML: ``,
+ encoderMD: "",
+ encoderSz: `(BLOCK (VERBATIM-COMMENT () "No\nrender"))`,
+ encoderSHTML: `(())`,
+ encoderText: ``,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Rendered block comment",
+ zmk: "%%%{-}\nRender\n%%%",
+ expect: expectMap{
+ encoderHTML: "\n",
+ encoderMD: "",
+ encoderSz: `(BLOCK (VERBATIM-COMMENT (("-" . "")) "Render"))`,
+ encoderSHTML: "((@@@ \"Render\"))",
+ encoderText: ``,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Heading",
+ zmk: `=== Top Job`,
+ expect: expectMap{
+ encoderHTML: "Top Job
",
+ encoderMD: "# Top Job",
+ encoderSz: `(BLOCK (HEADING 1 () "top-job" "top-job" (TEXT "Top Job")))`,
+ encoderSHTML: `((h2 (@ (id . "top-job")) "Top Job"))`,
+ encoderText: `Top Job`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple List",
+ zmk: "* A\n* B\n* C",
+ expect: expectMap{
+ encoderHTML: "- A
- B
- C
",
+ encoderMD: "* A\n* B\n* C",
+ encoderSz: `(BLOCK (UNORDERED () (INLINE (TEXT "A")) (INLINE (TEXT "B")) (INLINE (TEXT "C"))))`,
+ encoderSHTML: `((ul (li "A") (li "B") (li "C")))`,
+ encoderText: "A\nB\nC",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Nested List",
+ zmk: "* T1\n*# T2\n* T3\n** T4\n** T5\n* T6",
+ expect: expectMap{
+ encoderHTML: `T1
- T2
T3
- T4
- T5
T6
`,
+ encoderMD: "* T1\n 1. T2\n* T3\n * T4\n * T5\n* T6",
+ encoderSz: `(BLOCK (UNORDERED () (BLOCK (PARA (TEXT "T1")) (ORDERED () (INLINE (TEXT "T2")))) (BLOCK (PARA (TEXT "T3")) (UNORDERED () (INLINE (TEXT "T4")) (INLINE (TEXT "T5")))) (BLOCK (PARA (TEXT "T6")))))`,
+ encoderSHTML: `((ul (li (p "T1") (ol (li "T2"))) (li (p "T3") (ul (li "T4") (li "T5"))) (li (p "T6"))))`,
+ encoderText: "T1\nT2\nT3\nT4\nT5\nT6",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Sequence of two lists",
+ zmk: "* Item1.1\n* Item1.2\n* Item1.3\n\n* Item2.1\n* Item2.2",
+ expect: expectMap{
+ encoderHTML: "- Item1.1
- Item1.2
- Item1.3
- Item2.1
- Item2.2
",
+ encoderMD: "* Item1.1\n* Item1.2\n* Item1.3\n* Item2.1\n* Item2.2",
+ encoderSz: `(BLOCK (UNORDERED () (INLINE (TEXT "Item1.1")) (INLINE (TEXT "Item1.2")) (INLINE (TEXT "Item1.3")) (INLINE (TEXT "Item2.1")) (INLINE (TEXT "Item2.2"))))`,
+ encoderSHTML: `((ul (li "Item1.1") (li "Item1.2") (li "Item1.3") (li "Item2.1") (li "Item2.2")))`,
+ encoderText: "Item1.1\nItem1.2\nItem1.3\nItem2.1\nItem2.2",
+ encoderZmk: "* Item1.1\n* Item1.2\n* Item1.3\n* Item2.1\n* Item2.2",
+ },
+ },
+ {
+ descr: "Simple horizontal rule",
+ zmk: `---`,
+ expect: expectMap{
+ encoderHTML: "
",
+ encoderMD: "---",
+ encoderSz: `(BLOCK (THEMATIC ()))`,
+ encoderSHTML: `((hr))`,
+ encoderText: ``,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Thematic break with attribute",
+ zmk: `---{lang="zmk"}`,
+ expect: expectMap{
+ encoderHTML: `
`,
+ encoderMD: "---",
+ encoderSz: `(BLOCK (THEMATIC (("lang" . "zmk"))))`,
+ encoderSHTML: `((hr (@ (lang . "zmk"))))`,
+ encoderText: ``,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "No list after paragraph",
+ zmk: "Text\n*abc",
+ expect: expectMap{
+ encoderHTML: "Text *abc
",
+ encoderMD: "Text\n*abc",
+ encoderSz: `(BLOCK (PARA (TEXT "Text") (SOFT) (TEXT "*abc")))`,
+ encoderSHTML: `((p "Text" " " "*abc"))`,
+ encoderText: `Text *abc`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "A list after paragraph",
+ zmk: "Text\n# abc",
+ expect: expectMap{
+ encoderHTML: "Text
- abc
",
+ encoderMD: "Text\n\n1. abc",
+ encoderSz: `(BLOCK (PARA (TEXT "Text")) (ORDERED () (INLINE (TEXT "abc"))))`,
+ encoderSHTML: `((p "Text") (ol (li "abc")))`,
+ encoderText: "Text\nabc",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple List Quote",
+ zmk: "> ToBeOrNotToBe",
+ expect: expectMap{
+ encoderHTML: "ToBeOrNotToBe
",
+ encoderMD: "> ToBeOrNotToBe",
+ encoderSz: `(BLOCK (QUOTATION () (INLINE (TEXT "ToBeOrNotToBe"))))`,
+ encoderSHTML: `((blockquote (@L "ToBeOrNotToBe")))`,
+ encoderText: "ToBeOrNotToBe",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Quote Block",
+ zmk: "<<<\nToBeOrNotToBe\n<<< Romeo Julia",
+ expect: expectMap{
+ encoderHTML: "ToBeOrNotToBe
Romeo Julia
",
+ encoderMD: "> ToBeOrNotToBe",
+ encoderSz: `(BLOCK (REGION-QUOTE () ((PARA (TEXT "ToBeOrNotToBe"))) (TEXT "Romeo Julia")))`,
+ encoderSHTML: `((blockquote (p "ToBeOrNotToBe") (cite "Romeo Julia")))`,
+ encoderText: "ToBeOrNotToBe\nRomeo Julia",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Quote Block with multiple paragraphs",
+ zmk: "<<<\nToBeOr\n\nNotToBe\n<<< Romeo",
+ expect: expectMap{
+ encoderHTML: "ToBeOr
NotToBe
Romeo
",
+ encoderMD: "> ToBeOr\n>\n> NotToBe",
+ encoderSz: `(BLOCK (REGION-QUOTE () ((PARA (TEXT "ToBeOr")) (PARA (TEXT "NotToBe"))) (TEXT "Romeo")))`,
+ encoderSHTML: `((blockquote (p "ToBeOr") (p "NotToBe") (cite "Romeo")))`,
+ encoderText: "ToBeOr\nNotToBe\nRomeo",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Verse block",
+ zmk: `"""
+A line
+ another line
+Back
+
+Paragraph
+
+ Spacy Para
+""" Author`,
+ expect: expectMap{
+ encoderHTML: "A\u00a0line
\u00a0\u00a0another\u00a0line
Back
Paragraph
\u00a0\u00a0\u00a0\u00a0Spacy\u00a0\u00a0Para
Author",
+ encoderMD: "",
+ encoderSz: "(BLOCK (REGION-VERSE () ((PARA (TEXT \"A\u00a0line\") (HARD) (TEXT \"\u00a0\u00a0another\u00a0line\") (HARD) (TEXT \"Back\")) (PARA (TEXT \"Paragraph\")) (PARA (TEXT \"\u00a0\u00a0\u00a0\u00a0Spacy\u00a0\u00a0Para\"))) (TEXT \"Author\")))",
+ encoderSHTML: "((div (p \"A\u00a0line\" (br) \"\u00a0\u00a0another\u00a0line\" (br) \"Back\") (p \"Paragraph\") (p \"\u00a0\u00a0\u00a0\u00a0Spacy\u00a0\u00a0Para\") (cite \"Author\")))",
+ encoderText: "A line\n another line\nBack\nParagraph\n Spacy Para\nAuthor",
+ encoderZmk: "\"\"\"\nA\u00a0line\\\n\u00a0\u00a0another\u00a0line\\\nBack\nParagraph\n\u00a0\u00a0\u00a0\u00a0Spacy\u00a0\u00a0Para\n\"\"\" Author",
+ },
+ },
+ {
+ descr: "Span Block",
+ zmk: `:::
+A simple
+ span
+and much more
+:::`,
+ expect: expectMap{
+ encoderHTML: "A simple span and much more
",
+ encoderMD: "",
+ encoderSz: `(BLOCK (REGION-BLOCK () ((PARA (TEXT "A simple") (SOFT) (TEXT " span") (SOFT) (TEXT "and much more")))))`,
+ encoderSHTML: `((div (p "A simple" " " " span" " " "and much more")))`,
+ encoderText: `A simple span and much more`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Verbatim Code",
+ zmk: "```\nHello\nWorld\n```",
+ expect: expectMap{
+ encoderHTML: "Hello\nWorld
",
+ encoderMD: " Hello\n World",
+ encoderSz: `(BLOCK (VERBATIM-CODE () "Hello\nWorld"))`,
+ encoderSHTML: `((pre (code "Hello\nWorld")))`,
+ encoderText: "Hello\nWorld",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Verbatim Code with visible spaces",
+ zmk: "```{-}\nHello World\n```",
+ expect: expectMap{
+ encoderHTML: "Hello\u2423World
",
+ encoderMD: " Hello World",
+ encoderSz: `(BLOCK (VERBATIM-CODE (("-" . "")) "Hello World"))`,
+ encoderSHTML: "((pre (code \"Hello\u2423World\")))",
+ encoderText: "Hello World",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Verbatim Eval",
+ zmk: "~~~\nHello\nWorld\n~~~",
+ expect: expectMap{
+ encoderHTML: "Hello\nWorld
",
+ encoderMD: "",
+ encoderSz: `(BLOCK (VERBATIM-EVAL () "Hello\nWorld"))`,
+ encoderSHTML: "((pre (code (@ (class . \"zs-eval\")) \"Hello\\nWorld\")))",
+ encoderText: "Hello\nWorld",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Verbatim Math",
+ zmk: "$$$\nHello\n\\LaTeX\n$$$",
+ expect: expectMap{
+ encoderHTML: "Hello\n\\LaTeX
",
+ encoderMD: "",
+ encoderSz: `(BLOCK (VERBATIM-MATH () "Hello\n\\LaTeX"))`,
+ encoderSHTML: "((pre (code (@ (class . \"zs-math\")) \"Hello\\n\\\\LaTeX\")))",
+ encoderText: "Hello\n\\LaTeX",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Description List",
+ zmk: "; Zettel\n: Paper\n: Note\n; Zettelkasten\n: Slip box",
+ expect: expectMap{
+ encoderHTML: "- Zettel
Paper
Note
- Zettelkasten
Slip box
",
+ encoderMD: "",
+ encoderSz: `(BLOCK (DESCRIPTION () ((TEXT "Zettel")) (BLOCK (BLOCK (PARA (TEXT "Paper"))) (BLOCK (PARA (TEXT "Note")))) ((TEXT "Zettelkasten")) (BLOCK (BLOCK (PARA (TEXT "Slip box"))))))`,
+ encoderSHTML: `((dl (dt "Zettel") (dd (p "Paper")) (dd (p "Note")) (dt "Zettelkasten") (dd (p "Slip box"))))`,
+ encoderText: "Zettel\nPaper\nNote\nZettelkasten\nSlip box",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Description List with paragraphs as item",
+ zmk: "; Zettel\n: Paper\n\n Note\n; Zettelkasten\n: Slip box",
+ expect: expectMap{
+ encoderHTML: "- Zettel
Paper
Note
- Zettelkasten
Slip box
",
+ encoderMD: "",
+ encoderSz: `(BLOCK (DESCRIPTION () ((TEXT "Zettel")) (BLOCK (BLOCK (PARA (TEXT "Paper")) (PARA (TEXT "Note")))) ((TEXT "Zettelkasten")) (BLOCK (BLOCK (PARA (TEXT "Slip box"))))))`,
+ encoderSHTML: `((dl (dt "Zettel") (dd (p "Paper") (p "Note")) (dt "Zettelkasten") (dd (p "Slip box"))))`,
+ encoderText: "Zettel\nPaper\nNote\nZettelkasten\nSlip box",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Description List with keys, but no descriptions",
+ zmk: "; K1\n: D11\n: D12\n; K2\n; K3\n: D31",
+ expect: expectMap{
+ encoderHTML: "- K1
D11
D12
- K2
- K3
D31
",
+ encoderMD: "",
+ encoderSz: `(BLOCK (DESCRIPTION () ((TEXT "K1")) (BLOCK (BLOCK (PARA (TEXT "D11"))) (BLOCK (PARA (TEXT "D12")))) ((TEXT "K2")) (BLOCK) ((TEXT "K3")) (BLOCK (BLOCK (PARA (TEXT "D31"))))))`,
+ encoderSHTML: `((dl (dt "K1") (dd (p "D11")) (dd (p "D12")) (dt "K2") (dt "K3") (dd (p "D31"))))`,
+ encoderText: "K1\nD11\nD12\nK2\nK3\nD31",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple Table",
+ zmk: "|c1|c2|c3\n|d1||d3",
+ expect: expectMap{
+ encoderHTML: `c1 c2 c3 d1 d3
`,
+ encoderMD: "",
+ encoderSz: `(BLOCK (TABLE () ((CELL () (TEXT "c1")) (CELL () (TEXT "c2")) (CELL () (TEXT "c3"))) ((CELL () (TEXT "d1")) (CELL ()) (CELL () (TEXT "d3")))))`,
+ encoderSHTML: `((table (tbody (tr (td "c1") (td "c2") (td "c3")) (tr (td "d1") (td) (td "d3")))))`,
+ encoderText: "c1 c2 c3\nd1 d3",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Table with alignment and comment",
+ zmk: `|h1>|=h2|h3:|
+|%--+---+---+
+|h1 h2 h3 c1 c2 c3 f1 f2 =f3 `,
+ encoderMD: "",
+ encoderSz: `(BLOCK (TABLE ((CELL ((align . "right")) (TEXT "h1")) (CELL () (TEXT "h2")) (CELL ((align . "center")) (TEXT "h3"))) ((CELL ((align . "left")) (TEXT "c1")) (CELL () (TEXT "c2")) (CELL ((align . "center")) (TEXT "c3"))) ((CELL ((align . "right")) (TEXT "f1")) (CELL () (TEXT "f2")) (CELL ((align . "center")) (TEXT "=f3")))))`,
+ encoderSHTML: `((table (thead (tr (th (@ (class . "right")) "h1") (th "h2") (th (@ (class . "center")) "h3"))) (tbody (tr (td (@ (class . "left")) "c1") (td "c2") (td (@ (class . "center")) "c3")) (tr (td (@ (class . "right")) "f1") (td "f2") (td (@ (class . "center")) "=f3")))))`,
+ encoderText: "h1 h2 h3\nc1 c2 c3\nf1 f2 =f3",
+ encoderZmk: /*`|=h1>|=h2|=h3:
+ |h1|=h2|=:h3
+|f1|f2|:=f3`,
+ },
+ },
+ {
+ descr: "Simple Endnote",
+ zmk: `Text[^Endnote]`,
+ expect: expectMap{
+ encoderHTML: "Text1
- Endnote \u21a9\ufe0e
",
+ encoderMD: "Text",
+ encoderSz: `(BLOCK (PARA (TEXT "Text") (ENDNOTE () (TEXT "Endnote"))))`,
+ encoderSHTML: "((p \"Text\" (sup (@ (id . \"fnref:1\")) (a (@ (class . \"zs-noteref\") (href . \"#fn:1\") (role . \"doc-noteref\")) \"1\"))))",
+ encoderText: "Text Endnote",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Nested Endnotes",
+ zmk: `Text[^Endnote[^Nested]]`,
+ expect: expectMap{
+ encoderHTML: "Text1
- Endnote2 \u21a9\ufe0e
- Nested \u21a9\ufe0e
",
+ encoderMD: "Text",
+ encoderSz: `(BLOCK (PARA (TEXT "Text") (ENDNOTE () (TEXT "Endnote") (ENDNOTE () (TEXT "Nested")))))`,
+ encoderSHTML: "((p \"Text\" (sup (@ (id . \"fnref:1\")) (a (@ (class . \"zs-noteref\") (href . \"#fn:1\") (role . \"doc-noteref\")) \"1\"))))",
+ encoderText: "Text Endnote Nested",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Transclusion",
+ zmk: `{{{http://example.com/image}}}{width="100px"}`,
+ expect: expectMap{
+ encoderHTML: `
`,
+ encoderMD: "",
+ encoderSz: `(BLOCK (TRANSCLUDE (("width" . "100px")) (EXTERNAL "http://example.com/image")))`,
+ encoderSHTML: `((p (img (@ (class . "external") (src . "http://example.com/image") (width . "100px")))))`,
+ encoderText: "",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "A paragraph with a inline comment only should be empty in HTML",
+ zmk: `%% Comment`,
+ expect: expectMap{
+ // encoderHTML: ``,
+ encoderSz: `(BLOCK (PARA (LITERAL-COMMENT () "Comment")))`,
+ // encoderSHTML: ``,
+ encoderText: "",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "",
+ zmk: ``,
+ expect: expectMap{
+ encoderHTML: ``,
+ encoderSz: `(BLOCK)`,
+ encoderSHTML: `()`,
+ encoderText: "",
+ encoderZmk: useZmk,
+ },
+ },
+}
+
+// func TestEncoderBlock(t *testing.T) {
+// executeTestCases(t, tcsBlock)
+// }
ADDED internal/encoder/encoder_inline_test.go
Index: internal/encoder/encoder_inline_test.go
==================================================================
--- /dev/null
+++ internal/encoder/encoder_inline_test.go
@@ -0,0 +1,652 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2021-present Detlef Stern
+//
+// This file is part of Zettelstore.
+//
+// Zettelstore is licensed under the latest version of the EUPL (European Union
+// Public License). Please see file LICENSE.txt for your rights and obligations
+// under this license.
+//
+// SPDX-License-Identifier: EUPL-1.2
+// SPDX-FileCopyrightText: 2021-present Detlef Stern
+//-----------------------------------------------------------------------------
+
+package encoder_test
+
+var tcsInline = []zmkTestCase{
+ {
+ descr: "Empty Zettelmarkup should produce near nothing (inline)",
+ zmk: "",
+ expect: expectMap{
+ encoderHTML: "",
+ encoderMD: "",
+ encoderSz: `(BLOCK)`,
+ encoderSHTML: `()`,
+ encoderText: "",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Simple text: Hello, world (inline)",
+ zmk: `Hello, world`,
+ expect: expectMap{
+ encoderHTML: "Hello, world
",
+ encoderMD: "Hello, world",
+ encoderSz: `(BLOCK (PARA (TEXT "Hello, world")))`,
+ encoderSHTML: `((p "Hello, world"))`,
+ encoderText: "Hello, world",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Soft Break",
+ zmk: "soft\nbreak",
+ expect: expectMap{
+ encoderHTML: "soft break
",
+ encoderMD: "soft\nbreak",
+ encoderSz: `(BLOCK (PARA (TEXT "soft") (SOFT) (TEXT "break")))`,
+ encoderSHTML: `((p "soft" " " "break"))`,
+ encoderText: "soft break",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Hard Break",
+ zmk: "hard\\\nbreak",
+ expect: expectMap{
+ encoderHTML: "hard
break
",
+ encoderMD: "hard\\\nbreak",
+ encoderSz: `(BLOCK (PARA (TEXT "hard") (HARD) (TEXT "break")))`,
+ encoderSHTML: `((p "hard" (br) "break"))`,
+ encoderText: "hard\nbreak",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Emphasized formatting",
+ zmk: "__emph__",
+ expect: expectMap{
+ encoderHTML: "emph
",
+ encoderMD: "*emph*",
+ encoderSz: `(BLOCK (PARA (FORMAT-EMPH () (TEXT "emph"))))`,
+ encoderSHTML: `((p (em "emph")))`,
+ encoderText: "emph",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Strong formatting",
+ zmk: "**strong**",
+ expect: expectMap{
+ encoderHTML: "strong
",
+ encoderMD: "__strong__",
+ encoderSz: `(BLOCK (PARA (FORMAT-STRONG () (TEXT "strong"))))`,
+ encoderSHTML: `((p (strong "strong")))`,
+ encoderText: "strong",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Insert formatting",
+ zmk: ">>insert>>",
+ expect: expectMap{
+ encoderHTML: "insert
",
+ encoderMD: "insert",
+ encoderSz: `(BLOCK (PARA (FORMAT-INSERT () (TEXT "insert"))))`,
+ encoderSHTML: `((p (ins "insert")))`,
+ encoderText: "insert",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Delete formatting",
+ zmk: "~~delete~~",
+ expect: expectMap{
+ encoderHTML: "delete
",
+ encoderMD: "delete",
+ encoderSz: `(BLOCK (PARA (FORMAT-DELETE () (TEXT "delete"))))`,
+ encoderSHTML: `((p (del "delete")))`,
+ encoderText: "delete",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Update formatting",
+ zmk: "~~old~~>>new>>",
+ expect: expectMap{
+ encoderHTML: "oldnew
",
+ encoderMD: "oldnew",
+ encoderSz: `(BLOCK (PARA (FORMAT-DELETE () (TEXT "old")) (FORMAT-INSERT () (TEXT "new"))))`,
+ encoderSHTML: `((p (del "old") (ins "new")))`,
+ encoderText: "oldnew",
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Superscript formatting",
+ zmk: "^^superscript^^",
+ expect: expectMap{
+ encoderHTML: `superscript
`,
+ encoderMD: "superscript",
+ encoderSz: `(BLOCK (PARA (FORMAT-SUPER () (TEXT "superscript"))))`,
+ encoderSHTML: `((p (sup "superscript")))`,
+ encoderText: `superscript`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Subscript formatting",
+ zmk: ",,subscript,,",
+ expect: expectMap{
+ encoderHTML: `subscript
`,
+ encoderMD: "subscript",
+ encoderSz: `(BLOCK (PARA (FORMAT-SUB () (TEXT "subscript"))))`,
+ encoderSHTML: `((p (sub "subscript")))`,
+ encoderText: `subscript`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Quotes formatting",
+ zmk: `""quotes""`,
+ expect: expectMap{
+ encoderHTML: "“quotes”
",
+ encoderMD: "“quotes”",
+ encoderSz: `(BLOCK (PARA (FORMAT-QUOTE () (TEXT "quotes"))))`,
+ encoderSHTML: `((p (@L (@H "“") "quotes" (@H "”"))))`,
+ encoderText: `quotes`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Quotes formatting (german)",
+ zmk: `""quotes""{lang=de}`,
+ expect: expectMap{
+ encoderHTML: `„quotes“
`,
+ encoderMD: "„quotes“",
+ encoderSz: `(BLOCK (PARA (FORMAT-QUOTE (("lang" . "de")) (TEXT "quotes"))))`,
+ encoderSHTML: `((p (span (@ (lang . "de")) (@H "„") "quotes" (@H "“"))))`,
+ encoderText: `quotes`,
+ encoderZmk: `""quotes""{lang="de"}`,
+ },
+ },
+ {
+ descr: "Empty quotes (default)",
+ zmk: `""""`,
+ expect: expectMap{
+ encoderHTML: `“”
`,
+ encoderMD: "“”",
+ encoderSz: `(BLOCK (PARA (FORMAT-QUOTE ())))`,
+ encoderSHTML: `((p (@L (@H "“" "”"))))`,
+ encoderText: ``,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Empty quotes (unknown)",
+ zmk: `""""{lang=unknown}`,
+ expect: expectMap{
+ encoderHTML: `""
`,
+ encoderMD: """",
+ encoderSz: `(BLOCK (PARA (FORMAT-QUOTE (("lang" . "unknown")))))`,
+ encoderSHTML: `((p (span (@ (lang . "unknown")) (@H """ """))))`,
+ encoderText: ``,
+ encoderZmk: `""""{lang="unknown"}`,
+ },
+ },
+ {
+ descr: "Nested quotes (default)",
+ zmk: `""say: ::""yes, ::""or?""::""::""`,
+ expect: expectMap{
+ encoderHTML: `“say: ‘yes, “or?”’”
`,
+ encoderMD: `“say: ‘yes, “or?”’”`,
+ encoderSz: `(BLOCK (PARA (FORMAT-QUOTE () (TEXT "say: ") (FORMAT-SPAN () (FORMAT-QUOTE () (TEXT "yes, ") (FORMAT-SPAN () (FORMAT-QUOTE () (TEXT "or?"))))))))`,
+ encoderSHTML: `((p (@L (@H "“") "say: " (span (@L (@H "‘") "yes, " (span (@L (@H "“") "or?" (@H "”"))) (@H "’"))) (@H "”"))))`,
+ encoderText: `say: yes, or?`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Two quotes",
+ zmk: `""yes"" or ""no""`,
+ expect: expectMap{
+ encoderHTML: `“yes” or “no”
`,
+ encoderMD: `“yes” or “no”`,
+ encoderSz: `(BLOCK (PARA (FORMAT-QUOTE () (TEXT "yes")) (TEXT " or ") (FORMAT-QUOTE () (TEXT "no"))))`,
+ encoderSHTML: `((p (@L (@H "“") "yes" (@H "”")) " or " (@L (@H "“") "no" (@H "”"))))`,
+ encoderText: `yes or no`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Mark formatting",
+ zmk: `##marked##`,
+ expect: expectMap{
+ encoderHTML: `marked
`,
+ encoderMD: "marked",
+ encoderSz: `(BLOCK (PARA (FORMAT-MARK () (TEXT "marked"))))`,
+ encoderSHTML: `((p (mark "marked")))`,
+ encoderText: `marked`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Span formatting",
+ zmk: `::span::`,
+ expect: expectMap{
+ encoderHTML: `span
`,
+ encoderMD: "span",
+ encoderSz: `(BLOCK (PARA (FORMAT-SPAN () (TEXT "span"))))`,
+ encoderSHTML: `((p (span "span")))`,
+ encoderText: `span`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Code formatting",
+ zmk: "``code``",
+ expect: expectMap{
+ encoderHTML: `code
`,
+ encoderMD: "`code`",
+ encoderSz: `(BLOCK (PARA (LITERAL-CODE () "code")))`,
+ encoderSHTML: `((p (code "code")))`,
+ encoderText: `code`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "Code formatting with visible space",
+ zmk: "``x y``{-}",
+ expect: expectMap{
+ encoderHTML: "x\u2423y
",
+ encoderMD: "`x y`",
+ encoderSz: `(BLOCK (PARA (LITERAL-CODE (("-" . "")) "x y")))`,
+ encoderSHTML: "((p (code \"x\u2423y\")))",
+ encoderText: `x y`,
+ encoderZmk: useZmk,
+ },
+ },
+ {
+ descr: "HTML in code formatting",
+ zmk: "``\nokay\n",
"html": "\nokay
\n",
- "example": 140,
- "start_line": 2411,
- "end_line": 2425,
+ "example": 170,
+ "start_line": 2756,
+ "end_line": 2770,
+ "section": "HTML blocks"
+ },
+ {
+ "markdown": "\n",
+ "html": "\n",
+ "example": 171,
+ "start_line": 2775,
+ "end_line": 2791,
"section": "HTML blocks"
},
{
"markdown": "\nokay\n",
"html": "\nokay
\n",
- "example": 141,
- "start_line": 2430,
- "end_line": 2446,
+ "example": 172,
+ "start_line": 2795,
+ "end_line": 2811,
"section": "HTML blocks"
},
{
"markdown": "\n*foo*\n",
"html": "\nfoo
\n",
- "example": 145,
- "start_line": 2495,
- "end_line": 2501,
+ "example": 176,
+ "start_line": 2860,
+ "end_line": 2866,
"section": "HTML blocks"
},
{
"markdown": "*bar*\n*baz*\n",
"html": "*bar*\nbaz
\n",
- "example": 146,
- "start_line": 2504,
- "end_line": 2510,
+ "example": 177,
+ "start_line": 2869,
+ "end_line": 2875,
"section": "HTML blocks"
},
{
"markdown": "1. *bar*\n",
"html": "1. *bar*\n",
- "example": 147,
- "start_line": 2516,
- "end_line": 2524,
+ "example": 178,
+ "start_line": 2881,
+ "end_line": 2889,
"section": "HTML blocks"
},
{
"markdown": "\nokay\n",
"html": "\nokay
\n",
- "example": 148,
- "start_line": 2529,
- "end_line": 2541,
+ "example": 179,
+ "start_line": 2894,
+ "end_line": 2906,
"section": "HTML blocks"
},
{
"markdown": "';\n\n?>\nokay\n",
"html": "';\n\n?>\nokay
\n",
- "example": 149,
- "start_line": 2547,
- "end_line": 2561,
+ "example": 180,
+ "start_line": 2912,
+ "end_line": 2926,
"section": "HTML blocks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 150,
- "start_line": 2566,
- "end_line": 2570,
+ "example": 181,
+ "start_line": 2931,
+ "end_line": 2935,
"section": "HTML blocks"
},
{
"markdown": "\nokay\n",
"html": "\nokay
\n",
- "example": 151,
- "start_line": 2575,
- "end_line": 2603,
+ "example": 182,
+ "start_line": 2940,
+ "end_line": 2968,
"section": "HTML blocks"
},
{
"markdown": " \n\n \n",
"html": " \n<!-- foo -->\n
\n",
- "example": 152,
- "start_line": 2608,
- "end_line": 2616,
+ "example": 183,
+ "start_line": 2974,
+ "end_line": 2982,
"section": "HTML blocks"
},
{
"markdown": " \n\n \n",
"html": " \n<div>\n
\n",
- "example": 153,
- "start_line": 2619,
- "end_line": 2627,
+ "example": 184,
+ "start_line": 2985,
+ "end_line": 2993,
"section": "HTML blocks"
},
{
"markdown": "Foo\n\nbar\n\n",
"html": "Foo
\n\nbar\n\n",
- "example": 154,
- "start_line": 2633,
- "end_line": 2643,
+ "example": 185,
+ "start_line": 2999,
+ "end_line": 3009,
"section": "HTML blocks"
},
{
"markdown": "\nbar\n\n*foo*\n",
"html": "\nbar\n\n*foo*\n",
- "example": 155,
- "start_line": 2650,
- "end_line": 2660,
+ "example": 186,
+ "start_line": 3016,
+ "end_line": 3026,
"section": "HTML blocks"
},
{
"markdown": "Foo\n\nbaz\n",
"html": "Foo\n\nbaz
\n",
- "example": 156,
- "start_line": 2665,
- "end_line": 2673,
+ "example": 187,
+ "start_line": 3031,
+ "end_line": 3039,
"section": "HTML blocks"
},
{
"markdown": "\n\n*Emphasized* text.\n\n\n",
"html": "\nEmphasized text.
\n\n",
- "example": 157,
- "start_line": 2706,
- "end_line": 2716,
+ "example": 188,
+ "start_line": 3072,
+ "end_line": 3082,
"section": "HTML blocks"
},
{
"markdown": "\n*Emphasized* text.\n\n",
"html": "\n*Emphasized* text.\n\n",
- "example": 158,
- "start_line": 2719,
- "end_line": 2727,
+ "example": 189,
+ "start_line": 3085,
+ "end_line": 3093,
"section": "HTML blocks"
},
{
"markdown": "\n\n\n\n\nHi\n \n\n \n\n
\n",
"html": "\n\n\nHi\n \n \n
\n",
- "example": 159,
- "start_line": 2741,
- "end_line": 2761,
+ "example": 190,
+ "start_line": 3107,
+ "end_line": 3127,
"section": "HTML blocks"
},
{
"markdown": "\n\n \n\n \n Hi\n \n\n \n\n
\n",
"html": "\n \n<td>\n Hi\n</td>\n
\n \n
\n",
- "example": 160,
- "start_line": 2768,
- "end_line": 2789,
+ "example": 191,
+ "start_line": 3134,
+ "end_line": 3155,
"section": "HTML blocks"
},
{
"markdown": "[foo]: /url \"title\"\n\n[foo]\n",
"html": "\n",
- "example": 161,
- "start_line": 2816,
- "end_line": 2822,
+ "example": 192,
+ "start_line": 3183,
+ "end_line": 3189,
"section": "Link reference definitions"
},
{
"markdown": " [foo]: \n /url \n 'the title' \n\n[foo]\n",
"html": "\n",
- "example": 162,
- "start_line": 2825,
- "end_line": 2833,
+ "example": 193,
+ "start_line": 3192,
+ "end_line": 3200,
"section": "Link reference definitions"
},
{
"markdown": "[Foo*bar\\]]:my_(url) 'title (with parens)'\n\n[Foo*bar\\]]\n",
"html": "\n",
- "example": 163,
- "start_line": 2836,
- "end_line": 2842,
+ "example": 194,
+ "start_line": 3203,
+ "end_line": 3209,
"section": "Link reference definitions"
},
{
"markdown": "[Foo bar]:\n\n'title'\n\n[Foo bar]\n",
"html": "\n",
- "example": 164,
- "start_line": 2845,
- "end_line": 2853,
+ "example": 195,
+ "start_line": 3212,
+ "end_line": 3220,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url '\ntitle\nline1\nline2\n'\n\n[foo]\n",
"html": "\n",
- "example": 165,
- "start_line": 2858,
- "end_line": 2872,
+ "example": 196,
+ "start_line": 3225,
+ "end_line": 3239,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url 'title\n\nwith blank line'\n\n[foo]\n",
"html": "[foo]: /url 'title
\nwith blank line'
\n[foo]
\n",
- "example": 166,
- "start_line": 2877,
- "end_line": 2887,
+ "example": 197,
+ "start_line": 3244,
+ "end_line": 3254,
"section": "Link reference definitions"
},
{
"markdown": "[foo]:\n/url\n\n[foo]\n",
"html": "\n",
- "example": 167,
- "start_line": 2892,
- "end_line": 2899,
+ "example": 198,
+ "start_line": 3259,
+ "end_line": 3266,
"section": "Link reference definitions"
},
{
"markdown": "[foo]:\n\n[foo]\n",
"html": "[foo]:
\n[foo]
\n",
- "example": 168,
- "start_line": 2904,
- "end_line": 2911,
+ "example": 199,
+ "start_line": 3271,
+ "end_line": 3278,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: <>\n\n[foo]\n",
"html": "\n",
- "example": 169,
- "start_line": 2916,
- "end_line": 2922,
+ "example": 200,
+ "start_line": 3283,
+ "end_line": 3289,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: (baz)\n\n[foo]\n",
"html": "[foo]: (baz)
\n[foo]
\n",
- "example": 170,
- "start_line": 2927,
- "end_line": 2934,
+ "example": 201,
+ "start_line": 3294,
+ "end_line": 3301,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url\\bar\\*baz \"foo\\\"bar\\baz\"\n\n[foo]\n",
"html": "\n",
- "example": 171,
- "start_line": 2940,
- "end_line": 2946,
+ "example": 202,
+ "start_line": 3307,
+ "end_line": 3313,
"section": "Link reference definitions"
},
{
"markdown": "[foo]\n\n[foo]: url\n",
"html": "\n",
- "example": 172,
- "start_line": 2951,
- "end_line": 2957,
+ "example": 203,
+ "start_line": 3318,
+ "end_line": 3324,
"section": "Link reference definitions"
},
{
"markdown": "[foo]\n\n[foo]: first\n[foo]: second\n",
"html": "\n",
- "example": 173,
- "start_line": 2963,
- "end_line": 2970,
+ "example": 204,
+ "start_line": 3330,
+ "end_line": 3337,
"section": "Link reference definitions"
},
{
"markdown": "[FOO]: /url\n\n[Foo]\n",
"html": "\n",
- "example": 174,
- "start_line": 2976,
- "end_line": 2982,
+ "example": 205,
+ "start_line": 3343,
+ "end_line": 3349,
"section": "Link reference definitions"
},
{
"markdown": "[ΑΓΩ]: /φου\n\n[αγω]\n",
"html": "\n",
- "example": 175,
- "start_line": 2985,
- "end_line": 2991,
+ "example": 206,
+ "start_line": 3352,
+ "end_line": 3358,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url\n",
"html": "",
- "example": 176,
- "start_line": 2997,
- "end_line": 3000,
+ "example": 207,
+ "start_line": 3367,
+ "end_line": 3370,
"section": "Link reference definitions"
},
{
"markdown": "[\nfoo\n]: /url\nbar\n",
"html": "bar
\n",
- "example": 177,
- "start_line": 3005,
- "end_line": 3012,
+ "example": 208,
+ "start_line": 3375,
+ "end_line": 3382,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url \"title\" ok\n",
"html": "[foo]: /url "title" ok
\n",
- "example": 178,
- "start_line": 3018,
- "end_line": 3022,
+ "example": 209,
+ "start_line": 3388,
+ "end_line": 3392,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url\n\"title\" ok\n",
"html": ""title" ok
\n",
- "example": 179,
- "start_line": 3027,
- "end_line": 3032,
+ "example": 210,
+ "start_line": 3397,
+ "end_line": 3402,
"section": "Link reference definitions"
},
{
"markdown": " [foo]: /url \"title\"\n\n[foo]\n",
"html": "[foo]: /url "title"\n
\n[foo]
\n",
- "example": 180,
- "start_line": 3038,
- "end_line": 3046,
+ "example": 211,
+ "start_line": 3408,
+ "end_line": 3416,
"section": "Link reference definitions"
},
{
"markdown": "```\n[foo]: /url\n```\n\n[foo]\n",
"html": "[foo]: /url\n
\n[foo]
\n",
- "example": 181,
- "start_line": 3052,
- "end_line": 3062,
+ "example": 212,
+ "start_line": 3422,
+ "end_line": 3432,
"section": "Link reference definitions"
},
{
"markdown": "Foo\n[bar]: /baz\n\n[bar]\n",
"html": "Foo\n[bar]: /baz
\n[bar]
\n",
- "example": 182,
- "start_line": 3067,
- "end_line": 3076,
+ "example": 213,
+ "start_line": 3437,
+ "end_line": 3446,
"section": "Link reference definitions"
},
{
"markdown": "# [Foo]\n[foo]: /url\n> bar\n",
"html": "Foo
\n\nbar
\n
\n",
- "example": 183,
- "start_line": 3082,
- "end_line": 3091,
+ "example": 214,
+ "start_line": 3452,
+ "end_line": 3461,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url\nbar\n===\n[foo]\n",
"html": "bar
\n\n",
- "example": 184,
- "start_line": 3093,
- "end_line": 3101,
+ "example": 215,
+ "start_line": 3463,
+ "end_line": 3471,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /url\n===\n[foo]\n",
"html": "===\nfoo
\n",
- "example": 185,
- "start_line": 3103,
- "end_line": 3110,
+ "example": 216,
+ "start_line": 3473,
+ "end_line": 3480,
"section": "Link reference definitions"
},
{
"markdown": "[foo]: /foo-url \"foo\"\n[bar]: /bar-url\n \"bar\"\n[baz]: /baz-url\n\n[foo],\n[bar],\n[baz]\n",
"html": "\n",
- "example": 186,
- "start_line": 3116,
- "end_line": 3129,
+ "example": 217,
+ "start_line": 3486,
+ "end_line": 3499,
"section": "Link reference definitions"
},
{
"markdown": "[foo]\n\n> [foo]: /url\n",
"html": "\n\n
\n",
- "example": 187,
- "start_line": 3137,
- "end_line": 3145,
- "section": "Link reference definitions"
- },
- {
- "markdown": "[foo]: /url\n",
- "html": "",
- "example": 188,
- "start_line": 3154,
- "end_line": 3157,
+ "example": 218,
+ "start_line": 3507,
+ "end_line": 3515,
"section": "Link reference definitions"
},
{
"markdown": "aaa\n\nbbb\n",
"html": "aaa
\nbbb
\n",
- "example": 189,
- "start_line": 3171,
- "end_line": 3178,
+ "example": 219,
+ "start_line": 3529,
+ "end_line": 3536,
"section": "Paragraphs"
},
{
"markdown": "aaa\nbbb\n\nccc\nddd\n",
"html": "aaa\nbbb
\nccc\nddd
\n",
- "example": 190,
- "start_line": 3183,
- "end_line": 3194,
+ "example": 220,
+ "start_line": 3541,
+ "end_line": 3552,
"section": "Paragraphs"
},
{
"markdown": "aaa\n\n\nbbb\n",
"html": "aaa
\nbbb
\n",
- "example": 191,
- "start_line": 3199,
- "end_line": 3207,
+ "example": 221,
+ "start_line": 3557,
+ "end_line": 3565,
"section": "Paragraphs"
},
{
"markdown": " aaa\n bbb\n",
"html": "aaa\nbbb
\n",
- "example": 192,
- "start_line": 3212,
- "end_line": 3218,
+ "example": 222,
+ "start_line": 3570,
+ "end_line": 3576,
"section": "Paragraphs"
},
{
"markdown": "aaa\n bbb\n ccc\n",
"html": "aaa\nbbb\nccc
\n",
- "example": 193,
- "start_line": 3224,
- "end_line": 3232,
+ "example": 223,
+ "start_line": 3582,
+ "end_line": 3590,
"section": "Paragraphs"
},
{
"markdown": " aaa\nbbb\n",
"html": "aaa\nbbb
\n",
- "example": 194,
- "start_line": 3238,
- "end_line": 3244,
+ "example": 224,
+ "start_line": 3596,
+ "end_line": 3602,
"section": "Paragraphs"
},
{
"markdown": " aaa\nbbb\n",
"html": "aaa\n
\nbbb
\n",
- "example": 195,
- "start_line": 3247,
- "end_line": 3254,
+ "example": 225,
+ "start_line": 3605,
+ "end_line": 3612,
"section": "Paragraphs"
},
{
"markdown": "aaa \nbbb \n",
"html": "aaa
\nbbb
\n",
- "example": 196,
- "start_line": 3261,
- "end_line": 3267,
+ "example": 226,
+ "start_line": 3619,
+ "end_line": 3625,
"section": "Paragraphs"
},
{
"markdown": " \n\naaa\n \n\n# aaa\n\n \n",
"html": "aaa
\naaa
\n",
- "example": 197,
- "start_line": 3278,
- "end_line": 3290,
+ "example": 227,
+ "start_line": 3636,
+ "end_line": 3648,
"section": "Blank lines"
},
{
"markdown": "> # Foo\n> bar\n> baz\n",
"html": "\nFoo
\nbar\nbaz
\n
\n",
- "example": 198,
- "start_line": 3344,
- "end_line": 3354,
+ "example": 228,
+ "start_line": 3704,
+ "end_line": 3714,
"section": "Block quotes"
},
{
"markdown": "># Foo\n>bar\n> baz\n",
"html": "\nFoo
\nbar\nbaz
\n
\n",
- "example": 199,
- "start_line": 3359,
- "end_line": 3369,
+ "example": 229,
+ "start_line": 3719,
+ "end_line": 3729,
"section": "Block quotes"
},
{
"markdown": " > # Foo\n > bar\n > baz\n",
"html": "\nFoo
\nbar\nbaz
\n
\n",
- "example": 200,
- "start_line": 3374,
- "end_line": 3384,
+ "example": 230,
+ "start_line": 3734,
+ "end_line": 3744,
"section": "Block quotes"
},
{
"markdown": " > # Foo\n > bar\n > baz\n",
"html": "> # Foo\n> bar\n> baz\n
\n",
- "example": 201,
- "start_line": 3389,
- "end_line": 3398,
+ "example": 231,
+ "start_line": 3749,
+ "end_line": 3758,
"section": "Block quotes"
},
{
"markdown": "> # Foo\n> bar\nbaz\n",
"html": "\nFoo
\nbar\nbaz
\n
\n",
- "example": 202,
- "start_line": 3404,
- "end_line": 3414,
+ "example": 232,
+ "start_line": 3764,
+ "end_line": 3774,
"section": "Block quotes"
},
{
"markdown": "> bar\nbaz\n> foo\n",
"html": "\nbar\nbaz\nfoo
\n
\n",
- "example": 203,
- "start_line": 3420,
- "end_line": 3430,
+ "example": 233,
+ "start_line": 3780,
+ "end_line": 3790,
"section": "Block quotes"
},
{
"markdown": "> foo\n---\n",
"html": "\nfoo
\n
\n
\n",
- "example": 204,
- "start_line": 3444,
- "end_line": 3452,
+ "example": 234,
+ "start_line": 3804,
+ "end_line": 3812,
"section": "Block quotes"
},
{
"markdown": "> - foo\n- bar\n",
"html": "\n\n- foo
\n
\n
\n\n- bar
\n
\n",
- "example": 205,
- "start_line": 3464,
- "end_line": 3476,
+ "example": 235,
+ "start_line": 3824,
+ "end_line": 3836,
"section": "Block quotes"
},
{
"markdown": "> foo\n bar\n",
"html": "\nfoo\n
\n
\nbar\n
\n",
- "example": 206,
- "start_line": 3482,
- "end_line": 3492,
+ "example": 236,
+ "start_line": 3842,
+ "end_line": 3852,
"section": "Block quotes"
},
{
"markdown": "> ```\nfoo\n```\n",
"html": "\n
\n
\nfoo
\n
\n",
- "example": 207,
- "start_line": 3495,
- "end_line": 3505,
+ "example": 237,
+ "start_line": 3855,
+ "end_line": 3865,
"section": "Block quotes"
},
{
"markdown": "> foo\n - bar\n",
"html": "\nfoo\n- bar
\n
\n",
- "example": 208,
- "start_line": 3511,
- "end_line": 3519,
+ "example": 238,
+ "start_line": 3871,
+ "end_line": 3879,
"section": "Block quotes"
},
{
"markdown": ">\n",
"html": "\n
\n",
- "example": 209,
- "start_line": 3535,
- "end_line": 3540,
+ "example": 239,
+ "start_line": 3895,
+ "end_line": 3900,
"section": "Block quotes"
},
{
"markdown": ">\n> \n> \n",
"html": "\n
\n",
- "example": 210,
- "start_line": 3543,
- "end_line": 3550,
+ "example": 240,
+ "start_line": 3903,
+ "end_line": 3910,
"section": "Block quotes"
},
{
"markdown": ">\n> foo\n> \n",
"html": "\nfoo
\n
\n",
- "example": 211,
- "start_line": 3555,
- "end_line": 3563,
+ "example": 241,
+ "start_line": 3915,
+ "end_line": 3923,
"section": "Block quotes"
},
{
"markdown": "> foo\n\n> bar\n",
"html": "\nfoo
\n
\n\nbar
\n
\n",
- "example": 212,
- "start_line": 3568,
- "end_line": 3579,
+ "example": 242,
+ "start_line": 3928,
+ "end_line": 3939,
"section": "Block quotes"
},
{
"markdown": "> foo\n> bar\n",
"html": "\nfoo\nbar
\n
\n",
- "example": 213,
- "start_line": 3590,
- "end_line": 3598,
+ "example": 243,
+ "start_line": 3950,
+ "end_line": 3958,
"section": "Block quotes"
},
{
"markdown": "> foo\n>\n> bar\n",
"html": "\nfoo
\nbar
\n
\n",
- "example": 214,
- "start_line": 3603,
- "end_line": 3612,
+ "example": 244,
+ "start_line": 3963,
+ "end_line": 3972,
"section": "Block quotes"
},
{
"markdown": "foo\n> bar\n",
"html": "foo
\n\nbar
\n
\n",
- "example": 215,
- "start_line": 3617,
- "end_line": 3625,
+ "example": 245,
+ "start_line": 3977,
+ "end_line": 3985,
"section": "Block quotes"
},
{
"markdown": "> aaa\n***\n> bbb\n",
"html": "\naaa
\n
\n
\n\nbbb
\n
\n",
- "example": 216,
- "start_line": 3631,
- "end_line": 3643,
+ "example": 246,
+ "start_line": 3991,
+ "end_line": 4003,
"section": "Block quotes"
},
{
"markdown": "> bar\nbaz\n",
"html": "\nbar\nbaz
\n
\n",
- "example": 217,
- "start_line": 3649,
- "end_line": 3657,
+ "example": 247,
+ "start_line": 4009,
+ "end_line": 4017,
"section": "Block quotes"
},
{
"markdown": "> bar\n\nbaz\n",
"html": "\nbar
\n
\nbaz
\n",
- "example": 218,
- "start_line": 3660,
- "end_line": 3669,
+ "example": 248,
+ "start_line": 4020,
+ "end_line": 4029,
"section": "Block quotes"
},
{
"markdown": "> bar\n>\nbaz\n",
"html": "\nbar
\n
\nbaz
\n",
- "example": 219,
- "start_line": 3672,
- "end_line": 3681,
+ "example": 249,
+ "start_line": 4032,
+ "end_line": 4041,
"section": "Block quotes"
},
{
"markdown": "> > > foo\nbar\n",
"html": "\n\n\nfoo\nbar
\n
\n
\n
\n",
- "example": 220,
- "start_line": 3688,
- "end_line": 3700,
+ "example": 250,
+ "start_line": 4048,
+ "end_line": 4060,
"section": "Block quotes"
},
{
"markdown": ">>> foo\n> bar\n>>baz\n",
"html": "\n\n\nfoo\nbar\nbaz
\n
\n
\n
\n",
- "example": 221,
- "start_line": 3703,
- "end_line": 3717,
+ "example": 251,
+ "start_line": 4063,
+ "end_line": 4077,
"section": "Block quotes"
},
{
"markdown": "> code\n\n> not code\n",
"html": "\ncode\n
\n
\n\nnot code
\n
\n",
- "example": 222,
- "start_line": 3725,
- "end_line": 3737,
+ "example": 252,
+ "start_line": 4085,
+ "end_line": 4097,
"section": "Block quotes"
},
{
"markdown": "A paragraph\nwith two lines.\n\n indented code\n\n> A block quote.\n",
"html": "A paragraph\nwith two lines.
\nindented code\n
\n\nA block quote.
\n
\n",
- "example": 223,
- "start_line": 3779,
- "end_line": 3794,
+ "example": 253,
+ "start_line": 4139,
+ "end_line": 4154,
"section": "List items"
},
{
"markdown": "1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
"html": "\n- \n
A paragraph\nwith two lines.
\nindented code\n
\n\nA block quote.
\n
\n \n
\n",
- "example": 224,
- "start_line": 3801,
- "end_line": 3820,
+ "example": 254,
+ "start_line": 4161,
+ "end_line": 4180,
"section": "List items"
},
{
"markdown": "- one\n\n two\n",
"html": "\n- one
\n
\ntwo
\n",
- "example": 225,
- "start_line": 3834,
- "end_line": 3843,
+ "example": 255,
+ "start_line": 4194,
+ "end_line": 4203,
"section": "List items"
},
{
"markdown": "- one\n\n two\n",
"html": "\n- \n
one
\ntwo
\n \n
\n",
- "example": 226,
- "start_line": 3846,
- "end_line": 3857,
+ "example": 256,
+ "start_line": 4206,
+ "end_line": 4217,
"section": "List items"
},
{
"markdown": " - one\n\n two\n",
"html": "\n- one
\n
\n two\n
\n",
- "example": 227,
- "start_line": 3860,
- "end_line": 3870,
+ "example": 257,
+ "start_line": 4220,
+ "end_line": 4230,
"section": "List items"
},
{
"markdown": " - one\n\n two\n",
"html": "\n- \n
one
\ntwo
\n \n
\n",
- "example": 228,
- "start_line": 3873,
- "end_line": 3884,
+ "example": 258,
+ "start_line": 4233,
+ "end_line": 4244,
"section": "List items"
},
{
"markdown": " > > 1. one\n>>\n>> two\n",
"html": "\n\n\n- \n
one
\ntwo
\n \n
\n
\n
\n",
- "example": 229,
- "start_line": 3895,
- "end_line": 3910,
+ "example": 259,
+ "start_line": 4255,
+ "end_line": 4270,
"section": "List items"
},
{
"markdown": ">>- one\n>>\n > > two\n",
"html": "\n\n\n- one
\n
\ntwo
\n
\n
\n",
- "example": 230,
- "start_line": 3922,
- "end_line": 3935,
+ "example": 260,
+ "start_line": 4282,
+ "end_line": 4295,
"section": "List items"
},
{
"markdown": "-one\n\n2.two\n",
"html": "-one
\n2.two
\n",
- "example": 231,
- "start_line": 3941,
- "end_line": 3948,
+ "example": 261,
+ "start_line": 4301,
+ "end_line": 4308,
"section": "List items"
},
{
"markdown": "- foo\n\n\n bar\n",
"html": "\n- \n
foo
\nbar
\n \n
\n",
- "example": 232,
- "start_line": 3954,
- "end_line": 3966,
+ "example": 262,
+ "start_line": 4314,
+ "end_line": 4326,
"section": "List items"
},
{
"markdown": "1. foo\n\n ```\n bar\n ```\n\n baz\n\n > bam\n",
"html": "\n- \n
foo
\nbar\n
\nbaz
\n\nbam
\n
\n \n
\n",
- "example": 233,
- "start_line": 3971,
- "end_line": 3993,
+ "example": 263,
+ "start_line": 4331,
+ "end_line": 4353,
"section": "List items"
},
{
"markdown": "- Foo\n\n bar\n\n\n baz\n",
"html": "\n- \n
Foo
\nbar\n\n\nbaz\n
\n \n
\n",
- "example": 234,
- "start_line": 3999,
- "end_line": 4017,
+ "example": 264,
+ "start_line": 4359,
+ "end_line": 4377,
"section": "List items"
},
{
"markdown": "123456789. ok\n",
"html": "\n- ok
\n
\n",
- "example": 235,
- "start_line": 4021,
- "end_line": 4027,
+ "example": 265,
+ "start_line": 4381,
+ "end_line": 4387,
"section": "List items"
},
{
"markdown": "1234567890. not ok\n",
"html": "1234567890. not ok
\n",
- "example": 236,
- "start_line": 4030,
- "end_line": 4034,
+ "example": 266,
+ "start_line": 4390,
+ "end_line": 4394,
"section": "List items"
},
{
"markdown": "0. ok\n",
"html": "\n- ok
\n
\n",
- "example": 237,
- "start_line": 4039,
- "end_line": 4045,
+ "example": 267,
+ "start_line": 4399,
+ "end_line": 4405,
"section": "List items"
},
{
"markdown": "003. ok\n",
"html": "\n- ok
\n
\n",
- "example": 238,
- "start_line": 4048,
- "end_line": 4054,
+ "example": 268,
+ "start_line": 4408,
+ "end_line": 4414,
"section": "List items"
},
{
"markdown": "-1. not ok\n",
"html": "-1. not ok
\n",
- "example": 239,
- "start_line": 4059,
- "end_line": 4063,
+ "example": 269,
+ "start_line": 4419,
+ "end_line": 4423,
"section": "List items"
},
{
"markdown": "- foo\n\n bar\n",
"html": "\n- \n
foo
\nbar\n
\n \n
\n",
- "example": 240,
- "start_line": 4082,
- "end_line": 4094,
+ "example": 270,
+ "start_line": 4442,
+ "end_line": 4454,
"section": "List items"
},
{
"markdown": " 10. foo\n\n bar\n",
"html": "\n- \n
foo
\nbar\n
\n \n
\n",
- "example": 241,
- "start_line": 4099,
- "end_line": 4111,
+ "example": 271,
+ "start_line": 4459,
+ "end_line": 4471,
"section": "List items"
},
{
"markdown": " indented code\n\nparagraph\n\n more code\n",
"html": "indented code\n
\nparagraph
\nmore code\n
\n",
- "example": 242,
- "start_line": 4118,
- "end_line": 4130,
+ "example": 272,
+ "start_line": 4478,
+ "end_line": 4490,
"section": "List items"
},
{
"markdown": "1. indented code\n\n paragraph\n\n more code\n",
"html": "\n- \n
indented code\n
\nparagraph
\nmore code\n
\n \n
\n",
- "example": 243,
- "start_line": 4133,
- "end_line": 4149,
+ "example": 273,
+ "start_line": 4493,
+ "end_line": 4509,
"section": "List items"
},
{
"markdown": "1. indented code\n\n paragraph\n\n more code\n",
"html": "\n- \n
indented code\n
\nparagraph
\nmore code\n
\n \n
\n",
- "example": 244,
- "start_line": 4155,
- "end_line": 4171,
+ "example": 274,
+ "start_line": 4515,
+ "end_line": 4531,
"section": "List items"
},
{
"markdown": " foo\n\nbar\n",
"html": "foo
\nbar
\n",
- "example": 245,
- "start_line": 4182,
- "end_line": 4189,
+ "example": 275,
+ "start_line": 4542,
+ "end_line": 4549,
"section": "List items"
},
{
"markdown": "- foo\n\n bar\n",
"html": "\n- foo
\n
\nbar
\n",
- "example": 246,
- "start_line": 4192,
- "end_line": 4201,
+ "example": 276,
+ "start_line": 4552,
+ "end_line": 4561,
"section": "List items"
},
{
"markdown": "- foo\n\n bar\n",
"html": "\n- \n
foo
\nbar
\n \n
\n",
- "example": 247,
- "start_line": 4209,
- "end_line": 4220,
+ "example": 277,
+ "start_line": 4569,
+ "end_line": 4580,
"section": "List items"
},
{
"markdown": "-\n foo\n-\n ```\n bar\n ```\n-\n baz\n",
"html": "\n- foo
\n- \n
bar\n
\n \n- \n
baz\n
\n \n
\n",
- "example": 248,
- "start_line": 4237,
- "end_line": 4258,
+ "example": 278,
+ "start_line": 4596,
+ "end_line": 4617,
"section": "List items"
},
{
"markdown": "- \n foo\n",
"html": "\n- foo
\n
\n",
- "example": 249,
- "start_line": 4263,
- "end_line": 4270,
+ "example": 279,
+ "start_line": 4622,
+ "end_line": 4629,
"section": "List items"
},
{
"markdown": "-\n\n foo\n",
"html": "\n\n
\nfoo
\n",
- "example": 250,
- "start_line": 4277,
- "end_line": 4286,
+ "example": 280,
+ "start_line": 4636,
+ "end_line": 4645,
"section": "List items"
},
{
"markdown": "- foo\n-\n- bar\n",
"html": "\n- foo
\n\n- bar
\n
\n",
- "example": 251,
- "start_line": 4291,
- "end_line": 4301,
+ "example": 281,
+ "start_line": 4650,
+ "end_line": 4660,
"section": "List items"
},
{
"markdown": "- foo\n- \n- bar\n",
"html": "\n- foo
\n\n- bar
\n
\n",
- "example": 252,
- "start_line": 4306,
- "end_line": 4316,
+ "example": 282,
+ "start_line": 4665,
+ "end_line": 4675,
"section": "List items"
},
{
"markdown": "1. foo\n2.\n3. bar\n",
"html": "\n- foo
\n\n- bar
\n
\n",
- "example": 253,
- "start_line": 4321,
- "end_line": 4331,
+ "example": 283,
+ "start_line": 4680,
+ "end_line": 4690,
"section": "List items"
},
{
"markdown": "*\n",
"html": "\n\n
\n",
- "example": 254,
- "start_line": 4336,
- "end_line": 4342,
+ "example": 284,
+ "start_line": 4695,
+ "end_line": 4701,
"section": "List items"
},
{
"markdown": "foo\n*\n\nfoo\n1.\n",
"html": "foo\n*
\nfoo\n1.
\n",
- "example": 255,
- "start_line": 4346,
- "end_line": 4357,
+ "example": 285,
+ "start_line": 4705,
+ "end_line": 4716,
"section": "List items"
},
{
"markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
"html": "\n- \n
A paragraph\nwith two lines.
\nindented code\n
\n\nA block quote.
\n
\n \n
\n",
- "example": 256,
- "start_line": 4368,
- "end_line": 4387,
+ "example": 286,
+ "start_line": 4727,
+ "end_line": 4746,
"section": "List items"
},
{
"markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
"html": "\n- \n
A paragraph\nwith two lines.
\nindented code\n
\n\nA block quote.
\n
\n \n
\n",
- "example": 257,
- "start_line": 4392,
- "end_line": 4411,
+ "example": 287,
+ "start_line": 4751,
+ "end_line": 4770,
"section": "List items"
},
{
"markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
"html": "\n- \n
A paragraph\nwith two lines.
\nindented code\n
\n\nA block quote.
\n
\n \n
\n",
- "example": 258,
- "start_line": 4416,
- "end_line": 4435,
+ "example": 288,
+ "start_line": 4775,
+ "end_line": 4794,
"section": "List items"
},
{
"markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
"html": "1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n
\n",
- "example": 259,
- "start_line": 4440,
- "end_line": 4455,
+ "example": 289,
+ "start_line": 4799,
+ "end_line": 4814,
"section": "List items"
},
{
"markdown": " 1. A paragraph\nwith two lines.\n\n indented code\n\n > A block quote.\n",
"html": "\n- \n
A paragraph\nwith two lines.
\nindented code\n
\n\nA block quote.
\n
\n \n
\n",
- "example": 260,
- "start_line": 4470,
- "end_line": 4489,
+ "example": 290,
+ "start_line": 4829,
+ "end_line": 4848,
"section": "List items"
},
{
"markdown": " 1. A paragraph\n with two lines.\n",
"html": "\n- A paragraph\nwith two lines.
\n
\n",
- "example": 261,
- "start_line": 4494,
- "end_line": 4502,
+ "example": 291,
+ "start_line": 4853,
+ "end_line": 4861,
"section": "List items"
},
{
"markdown": "> 1. > Blockquote\ncontinued here.\n",
"html": "\n\n- \n
\nBlockquote\ncontinued here.
\n
\n \n
\n
\n",
- "example": 262,
- "start_line": 4507,
- "end_line": 4521,
+ "example": 292,
+ "start_line": 4866,
+ "end_line": 4880,
"section": "List items"
},
{
"markdown": "> 1. > Blockquote\n> continued here.\n",
"html": "\n\n- \n
\nBlockquote\ncontinued here.
\n
\n \n
\n
\n",
- "example": 263,
- "start_line": 4524,
- "end_line": 4538,
+ "example": 293,
+ "start_line": 4883,
+ "end_line": 4897,
"section": "List items"
},
{
"markdown": "- foo\n - bar\n - baz\n - boo\n",
"html": "\n- foo\n
\n- bar\n
\n- baz\n
\n- boo
\n
\n \n
\n \n
\n \n
\n",
- "example": 264,
- "start_line": 4552,
- "end_line": 4573,
+ "example": 294,
+ "start_line": 4911,
+ "end_line": 4932,
"section": "List items"
},
{
"markdown": "- foo\n - bar\n - baz\n - boo\n",
"html": "\n- foo
\n- bar
\n- baz
\n- boo
\n
\n",
- "example": 265,
- "start_line": 4578,
- "end_line": 4590,
+ "example": 295,
+ "start_line": 4937,
+ "end_line": 4949,
"section": "List items"
},
{
"markdown": "10) foo\n - bar\n",
"html": "\n- foo\n
\n- bar
\n
\n \n
\n",
- "example": 266,
- "start_line": 4595,
- "end_line": 4606,
+ "example": 296,
+ "start_line": 4954,
+ "end_line": 4965,
"section": "List items"
},
{
"markdown": "10) foo\n - bar\n",
"html": "\n- foo
\n
\n\n- bar
\n
\n",
- "example": 267,
- "start_line": 4611,
- "end_line": 4621,
+ "example": 297,
+ "start_line": 4970,
+ "end_line": 4980,
"section": "List items"
},
{
"markdown": "- - foo\n",
"html": "\n- \n
\n- foo
\n
\n \n
\n",
- "example": 268,
- "start_line": 4626,
- "end_line": 4636,
+ "example": 298,
+ "start_line": 4985,
+ "end_line": 4995,
"section": "List items"
},
{
"markdown": "1. - 2. foo\n",
"html": "\n- \n
\n- \n
\n- foo
\n
\n \n
\n \n
\n",
- "example": 269,
- "start_line": 4639,
- "end_line": 4653,
+ "example": 299,
+ "start_line": 4998,
+ "end_line": 5012,
"section": "List items"
},
{
"markdown": "- # Foo\n- Bar\n ---\n baz\n",
"html": "\n- \n
Foo
\n \n- \n
Bar
\nbaz \n
\n",
- "example": 270,
- "start_line": 4658,
- "end_line": 4672,
+ "example": 300,
+ "start_line": 5017,
+ "end_line": 5031,
"section": "List items"
},
{
"markdown": "- foo\n- bar\n+ baz\n",
"html": "\n- foo
\n- bar
\n
\n\n- baz
\n
\n",
- "example": 271,
- "start_line": 4894,
- "end_line": 4906,
+ "example": 301,
+ "start_line": 5253,
+ "end_line": 5265,
"section": "Lists"
},
{
"markdown": "1. foo\n2. bar\n3) baz\n",
"html": "\n- foo
\n- bar
\n
\n\n- baz
\n
\n",
- "example": 272,
- "start_line": 4909,
- "end_line": 4921,
+ "example": 302,
+ "start_line": 5268,
+ "end_line": 5280,
"section": "Lists"
},
{
"markdown": "Foo\n- bar\n- baz\n",
"html": "Foo
\n\n- bar
\n- baz
\n
\n",
- "example": 273,
- "start_line": 4928,
- "end_line": 4938,
+ "example": 303,
+ "start_line": 5287,
+ "end_line": 5297,
"section": "Lists"
},
{
"markdown": "The number of windows in my house is\n14. The number of doors is 6.\n",
"html": "The number of windows in my house is\n14. The number of doors is 6.
\n",
- "example": 274,
- "start_line": 5005,
- "end_line": 5011,
+ "example": 304,
+ "start_line": 5364,
+ "end_line": 5370,
"section": "Lists"
},
{
"markdown": "The number of windows in my house is\n1. The number of doors is 6.\n",
"html": "The number of windows in my house is
\n\n- The number of doors is 6.
\n
\n",
- "example": 275,
- "start_line": 5015,
- "end_line": 5023,
+ "example": 305,
+ "start_line": 5374,
+ "end_line": 5382,
"section": "Lists"
},
{
"markdown": "- foo\n\n- bar\n\n\n- baz\n",
"html": "\n- \n
foo
\n \n- \n
bar
\n \n- \n
baz
\n \n
\n",
- "example": 276,
- "start_line": 5029,
- "end_line": 5048,
+ "example": 306,
+ "start_line": 5388,
+ "end_line": 5407,
"section": "Lists"
},
{
"markdown": "- foo\n - bar\n - baz\n\n\n bim\n",
"html": "\n- foo\n
\n- bar\n
\n- \n
baz
\nbim
\n \n
\n \n
\n \n
\n",
- "example": 277,
- "start_line": 5050,
- "end_line": 5072,
+ "example": 307,
+ "start_line": 5409,
+ "end_line": 5431,
"section": "Lists"
},
{
"markdown": "- foo\n- bar\n\n\n\n- baz\n- bim\n",
"html": "\n- foo
\n- bar
\n
\n\n\n- baz
\n- bim
\n
\n",
- "example": 278,
- "start_line": 5080,
- "end_line": 5098,
+ "example": 308,
+ "start_line": 5439,
+ "end_line": 5457,
"section": "Lists"
},
{
"markdown": "- foo\n\n notcode\n\n- foo\n\n\n\n code\n",
"html": "\n- \n
foo
\nnotcode
\n \n- \n
foo
\n \n
\n\ncode\n
\n",
- "example": 279,
- "start_line": 5101,
- "end_line": 5124,
+ "example": 309,
+ "start_line": 5460,
+ "end_line": 5483,
"section": "Lists"
},
{
"markdown": "- a\n - b\n - c\n - d\n - e\n - f\n- g\n",
"html": "\n- a
\n- b
\n- c
\n- d
\n- e
\n- f
\n- g
\n
\n",
- "example": 280,
- "start_line": 5132,
- "end_line": 5150,
+ "example": 310,
+ "start_line": 5491,
+ "end_line": 5509,
"section": "Lists"
},
{
"markdown": "1. a\n\n 2. b\n\n 3. c\n",
"html": "\n- \n
a
\n \n- \n
b
\n \n- \n
c
\n \n
\n",
- "example": 281,
- "start_line": 5153,
- "end_line": 5171,
+ "example": 311,
+ "start_line": 5512,
+ "end_line": 5530,
"section": "Lists"
},
{
"markdown": "- a\n - b\n - c\n - d\n - e\n",
"html": "\n- a
\n- b
\n- c
\n- d\n- e
\n
\n",
- "example": 282,
- "start_line": 5177,
- "end_line": 5191,
+ "example": 312,
+ "start_line": 5536,
+ "end_line": 5550,
"section": "Lists"
},
{
"markdown": "1. a\n\n 2. b\n\n 3. c\n",
"html": "\n- \n
a
\n \n- \n
b
\n \n
\n3. c\n
\n",
- "example": 283,
- "start_line": 5197,
- "end_line": 5214,
+ "example": 313,
+ "start_line": 5556,
+ "end_line": 5573,
"section": "Lists"
},
{
"markdown": "- a\n- b\n\n- c\n",
"html": "\n- \n
a
\n \n- \n
b
\n \n- \n
c
\n \n
\n",
- "example": 284,
- "start_line": 5220,
- "end_line": 5237,
+ "example": 314,
+ "start_line": 5579,
+ "end_line": 5596,
"section": "Lists"
},
{
"markdown": "* a\n*\n\n* c\n",
"html": "\n- \n
a
\n \n\n- \n
c
\n \n
\n",
- "example": 285,
- "start_line": 5242,
- "end_line": 5257,
+ "example": 315,
+ "start_line": 5601,
+ "end_line": 5616,
"section": "Lists"
},
{
"markdown": "- a\n- b\n\n c\n- d\n",
"html": "\n- \n
a
\n \n- \n
b
\nc
\n \n- \n
d
\n \n
\n",
- "example": 286,
- "start_line": 5264,
- "end_line": 5283,
+ "example": 316,
+ "start_line": 5623,
+ "end_line": 5642,
"section": "Lists"
},
{
"markdown": "- a\n- b\n\n [ref]: /url\n- d\n",
"html": "\n- \n
a
\n \n- \n
b
\n \n- \n
d
\n \n
\n",
- "example": 287,
- "start_line": 5286,
- "end_line": 5304,
+ "example": 317,
+ "start_line": 5645,
+ "end_line": 5663,
"section": "Lists"
},
{
"markdown": "- a\n- ```\n b\n\n\n ```\n- c\n",
"html": "\n- a
\n- \n
b\n\n\n
\n \n- c
\n
\n",
- "example": 288,
- "start_line": 5309,
- "end_line": 5328,
+ "example": 318,
+ "start_line": 5668,
+ "end_line": 5687,
"section": "Lists"
},
{
"markdown": "- a\n - b\n\n c\n- d\n",
"html": "\n- a\n
\n- \n
b
\nc
\n \n
\n \n- d
\n
\n",
- "example": 289,
- "start_line": 5335,
- "end_line": 5353,
+ "example": 319,
+ "start_line": 5694,
+ "end_line": 5712,
"section": "Lists"
},
{
"markdown": "* a\n > b\n >\n* c\n",
"html": "\n- a\n
\nb
\n
\n \n- c
\n
\n",
- "example": 290,
- "start_line": 5359,
- "end_line": 5373,
+ "example": 320,
+ "start_line": 5718,
+ "end_line": 5732,
"section": "Lists"
},
{
"markdown": "- a\n > b\n ```\n c\n ```\n- d\n",
"html": "\n- a\n
\nb
\n
\nc\n
\n \n- d
\n
\n",
- "example": 291,
- "start_line": 5379,
- "end_line": 5397,
+ "example": 321,
+ "start_line": 5738,
+ "end_line": 5756,
"section": "Lists"
},
{
"markdown": "- a\n",
"html": "\n- a
\n
\n",
- "example": 292,
- "start_line": 5402,
- "end_line": 5408,
+ "example": 322,
+ "start_line": 5761,
+ "end_line": 5767,
"section": "Lists"
},
{
"markdown": "- a\n - b\n",
"html": "\n- a\n
\n- b
\n
\n \n
\n",
- "example": 293,
- "start_line": 5411,
- "end_line": 5422,
+ "example": 323,
+ "start_line": 5770,
+ "end_line": 5781,
"section": "Lists"
},
{
"markdown": "1. ```\n foo\n ```\n\n bar\n",
"html": "\n- \n
foo\n
\nbar
\n \n
\n",
- "example": 294,
- "start_line": 5428,
- "end_line": 5442,
+ "example": 324,
+ "start_line": 5787,
+ "end_line": 5801,
"section": "Lists"
},
{
"markdown": "* foo\n * bar\n\n baz\n",
"html": "\n- \n
foo
\n\n- bar
\n
\nbaz
\n \n
\n",
- "example": 295,
- "start_line": 5447,
- "end_line": 5462,
+ "example": 325,
+ "start_line": 5806,
+ "end_line": 5821,
"section": "Lists"
},
{
"markdown": "- a\n - b\n - c\n\n- d\n - e\n - f\n",
"html": "\n- \n
a
\n\n- b
\n- c
\n
\n \n- \n
d
\n\n- e
\n- f
\n
\n \n
\n",
- "example": 296,
- "start_line": 5465,
- "end_line": 5490,
+ "example": 326,
+ "start_line": 5824,
+ "end_line": 5849,
"section": "Lists"
},
{
"markdown": "`hi`lo`\n",
"html": "hi
lo`
\n",
- "example": 297,
- "start_line": 5499,
- "end_line": 5503,
- "section": "Inlines"
- },
- {
- "markdown": "\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\n",
- "html": "!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~
\n",
- "example": 298,
- "start_line": 5513,
- "end_line": 5517,
- "section": "Backslash escapes"
- },
- {
- "markdown": "\\\t\\A\\a\\ \\3\\φ\\«\n",
- "html": "\\\t\\A\\a\\ \\3\\φ\\«
\n",
- "example": 299,
- "start_line": 5523,
- "end_line": 5527,
- "section": "Backslash escapes"
- },
- {
- "markdown": "\\*not emphasized*\n\\
not a tag\n\\[not a link](/foo)\n\\`not code`\n1\\. not a list\n\\* not a list\n\\# not a heading\n\\[foo]: /url \"not a reference\"\n\\ö not a character entity\n",
- "html": "*not emphasized*\n<br/> not a tag\n[not a link](/foo)\n`not code`\n1. not a list\n* not a list\n# not a heading\n[foo]: /url "not a reference"\nö not a character entity
\n",
- "example": 300,
- "start_line": 5533,
- "end_line": 5553,
- "section": "Backslash escapes"
- },
- {
- "markdown": "\\\\*emphasis*\n",
- "html": "\\emphasis
\n",
- "example": 301,
- "start_line": 5558,
- "end_line": 5562,
- "section": "Backslash escapes"
- },
- {
- "markdown": "foo\\\nbar\n",
- "html": "foo
\nbar
\n",
- "example": 302,
- "start_line": 5567,
- "end_line": 5573,
- "section": "Backslash escapes"
- },
- {
- "markdown": "`` \\[\\` ``\n",
- "html": "\\[\\`
\n",
- "example": 303,
- "start_line": 5579,
- "end_line": 5583,
- "section": "Backslash escapes"
- },
- {
- "markdown": " \\[\\]\n",
- "html": "\\[\\]\n
\n",
- "example": 304,
- "start_line": 5586,
- "end_line": 5591,
- "section": "Backslash escapes"
- },
- {
- "markdown": "~~~\n\\[\\]\n~~~\n",
- "html": "\\[\\]\n
\n",
- "example": 305,
- "start_line": 5594,
- "end_line": 5601,
- "section": "Backslash escapes"
- },
- {
- "markdown": "\n",
- "html": "\n",
- "example": 306,
- "start_line": 5604,
- "end_line": 5608,
- "section": "Backslash escapes"
- },
- {
- "markdown": "\n",
- "html": "\n",
- "example": 307,
- "start_line": 5611,
- "end_line": 5615,
- "section": "Backslash escapes"
- },
- {
- "markdown": "[foo](/bar\\* \"ti\\*tle\")\n",
- "html": "\n",
- "example": 308,
- "start_line": 5621,
- "end_line": 5625,
- "section": "Backslash escapes"
- },
- {
- "markdown": "[foo]\n\n[foo]: /bar\\* \"ti\\*tle\"\n",
- "html": "\n",
- "example": 309,
- "start_line": 5628,
- "end_line": 5634,
- "section": "Backslash escapes"
- },
- {
- "markdown": "``` foo\\+bar\nfoo\n```\n",
- "html": "foo\n
\n",
- "example": 310,
- "start_line": 5637,
- "end_line": 5644,
- "section": "Backslash escapes"
- },
- {
- "markdown": " & © Æ Ď\n¾ ℋ ⅆ\n∲ ≧̸\n",
- "html": " & © Æ Ď\n¾ ℋ ⅆ\n∲ ≧̸
\n",
- "example": 311,
- "start_line": 5674,
- "end_line": 5682,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "# Ӓ Ϡ \n",
- "html": "# Ӓ Ϡ �
\n",
- "example": 312,
- "start_line": 5693,
- "end_line": 5697,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "" ആ ಫ\n",
- "html": "" ആ ಫ
\n",
- "example": 313,
- "start_line": 5706,
- "end_line": 5710,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "  &x; \n\nabcdef0;\n&ThisIsNotDefined; &hi?;\n",
- "html": "  &x; &#; &#x;\n�\n&#abcdef0;\n&ThisIsNotDefined; &hi?;
\n",
- "example": 314,
- "start_line": 5715,
- "end_line": 5725,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "©\n",
- "html": "©
\n",
- "example": 315,
- "start_line": 5732,
- "end_line": 5736,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "&MadeUpEntity;\n",
- "html": "&MadeUpEntity;
\n",
- "example": 316,
- "start_line": 5742,
- "end_line": 5746,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "\n",
- "html": "\n",
- "example": 317,
- "start_line": 5753,
- "end_line": 5757,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "[foo](/föö \"föö\")\n",
- "html": "\n",
- "example": 318,
- "start_line": 5760,
- "end_line": 5764,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "[foo]\n\n[foo]: /föö \"föö\"\n",
- "html": "\n",
- "example": 319,
- "start_line": 5767,
- "end_line": 5773,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "``` föö\nfoo\n```\n",
- "html": "foo\n
\n",
- "example": 320,
- "start_line": 5776,
- "end_line": 5783,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "`föö`\n",
- "html": "föö
\n",
- "example": 321,
- "start_line": 5789,
- "end_line": 5793,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": " föfö\n",
- "html": "föfö\n
\n",
- "example": 322,
- "start_line": 5796,
- "end_line": 5801,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "*foo*\n*foo*\n",
- "html": "*foo*\nfoo
\n",
- "example": 323,
- "start_line": 5808,
- "end_line": 5814,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "* foo\n\n* foo\n",
- "html": "* foo
\n\n- foo
\n
\n",
- "example": 324,
- "start_line": 5816,
- "end_line": 5825,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "foo
bar\n",
- "html": "foo\n\nbar
\n",
- "example": 325,
- "start_line": 5827,
- "end_line": 5833,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": " foo\n",
- "html": "\tfoo
\n",
- "example": 326,
- "start_line": 5835,
- "end_line": 5839,
- "section": "Entity and numeric character references"
- },
- {
- "markdown": "[a](url "tit")\n",
- "html": "[a](url "tit")
\n",
"example": 327,
- "start_line": 5842,
- "end_line": 5846,
- "section": "Entity and numeric character references"
+ "start_line": 5858,
+ "end_line": 5862,
+ "section": "Inlines"
},
{
"markdown": "`foo`\n",
"html": "foo
\n",
"example": 328,
- "start_line": 5870,
- "end_line": 5874,
+ "start_line": 5890,
+ "end_line": 5894,
"section": "Code spans"
},
{
"markdown": "`` foo ` bar ``\n",
"html": "foo ` bar
\n",
"example": 329,
- "start_line": 5881,
- "end_line": 5885,
+ "start_line": 5901,
+ "end_line": 5905,
"section": "Code spans"
},
{
"markdown": "` `` `\n",
"html": "``
\n",
"example": 330,
- "start_line": 5891,
- "end_line": 5895,
+ "start_line": 5911,
+ "end_line": 5915,
"section": "Code spans"
},
{
"markdown": "` `` `\n",
"html": " ``
\n",
"example": 331,
- "start_line": 5899,
- "end_line": 5903,
+ "start_line": 5919,
+ "end_line": 5923,
"section": "Code spans"
},
{
"markdown": "` a`\n",
"html": " a
\n",
"example": 332,
- "start_line": 5908,
- "end_line": 5912,
+ "start_line": 5928,
+ "end_line": 5932,
"section": "Code spans"
},
{
"markdown": "` b `\n",
"html": " b
\n",
"example": 333,
- "start_line": 5917,
- "end_line": 5921,
+ "start_line": 5937,
+ "end_line": 5941,
"section": "Code spans"
},
{
"markdown": "` `\n` `\n",
"html": "
\n
\n",
"example": 334,
- "start_line": 5925,
- "end_line": 5931,
+ "start_line": 5945,
+ "end_line": 5951,
"section": "Code spans"
},
{
"markdown": "``\nfoo\nbar \nbaz\n``\n",
"html": "foo bar baz
\n",
"example": 335,
- "start_line": 5936,
- "end_line": 5944,
+ "start_line": 5956,
+ "end_line": 5964,
"section": "Code spans"
},
{
"markdown": "``\nfoo \n``\n",
"html": "foo
\n",
"example": 336,
- "start_line": 5946,
- "end_line": 5952,
+ "start_line": 5966,
+ "end_line": 5972,
"section": "Code spans"
},
{
"markdown": "`foo bar \nbaz`\n",
"html": "foo bar baz
\n",
"example": 337,
- "start_line": 5957,
- "end_line": 5962,
+ "start_line": 5977,
+ "end_line": 5982,
"section": "Code spans"
},
{
"markdown": "`foo\\`bar`\n",
"html": "foo\\
bar`
\n",
"example": 338,
- "start_line": 5974,
- "end_line": 5978,
+ "start_line": 5994,
+ "end_line": 5998,
"section": "Code spans"
},
{
"markdown": "``foo`bar``\n",
"html": "foo`bar
\n",
"example": 339,
- "start_line": 5985,
- "end_line": 5989,
+ "start_line": 6005,
+ "end_line": 6009,
"section": "Code spans"
},
{
"markdown": "` foo `` bar `\n",
"html": "foo `` bar
\n",
"example": 340,
- "start_line": 5991,
- "end_line": 5995,
+ "start_line": 6011,
+ "end_line": 6015,
"section": "Code spans"
},
{
"markdown": "*foo`*`\n",
"html": "*foo*
\n",
"example": 341,
- "start_line": 6003,
- "end_line": 6007,
+ "start_line": 6023,
+ "end_line": 6027,
"section": "Code spans"
},
{
"markdown": "[not a `link](/foo`)\n",
"html": "[not a link](/foo
)
\n",
"example": 342,
- "start_line": 6012,
- "end_line": 6016,
+ "start_line": 6032,
+ "end_line": 6036,
"section": "Code spans"
},
{
"markdown": "``\n",
"html": "<a href="
">`
\n",
"example": 343,
- "start_line": 6022,
- "end_line": 6026,
+ "start_line": 6042,
+ "end_line": 6046,
"section": "Code spans"
},
{
"markdown": "`\n",
"html": "\n",
"example": 344,
- "start_line": 6031,
- "end_line": 6035,
+ "start_line": 6051,
+ "end_line": 6055,
"section": "Code spans"
},
{
"markdown": "``\n",
"html": "<http://foo.bar.
baz>`
\n",
"example": 345,
- "start_line": 6040,
- "end_line": 6044,
+ "start_line": 6060,
+ "end_line": 6064,
"section": "Code spans"
},
{
"markdown": "`\n",
"html": "\n",
"example": 346,
- "start_line": 6049,
- "end_line": 6053,
+ "start_line": 6069,
+ "end_line": 6073,
"section": "Code spans"
},
{
"markdown": "```foo``\n",
"html": "```foo``
\n",
"example": 347,
- "start_line": 6059,
- "end_line": 6063,
+ "start_line": 6079,
+ "end_line": 6083,
"section": "Code spans"
},
{
"markdown": "`foo\n",
"html": "`foo
\n",
"example": 348,
- "start_line": 6066,
- "end_line": 6070,
+ "start_line": 6086,
+ "end_line": 6090,
"section": "Code spans"
},
{
"markdown": "`foo``bar``\n",
"html": "`foobar
\n",
"example": 349,
- "start_line": 6075,
- "end_line": 6079,
+ "start_line": 6095,
+ "end_line": 6099,
"section": "Code spans"
},
{
"markdown": "*foo bar*\n",
"html": "foo bar
\n",
"example": 350,
- "start_line": 6292,
- "end_line": 6296,
+ "start_line": 6312,
+ "end_line": 6316,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "a * foo bar*\n",
"html": "a * foo bar*
\n",
"example": 351,
- "start_line": 6302,
- "end_line": 6306,
+ "start_line": 6322,
+ "end_line": 6326,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "a*\"foo\"*\n",
"html": "a*"foo"*
\n",
"example": 352,
- "start_line": 6313,
- "end_line": 6317,
+ "start_line": 6333,
+ "end_line": 6337,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "* a *\n",
"html": "* a *
\n",
"example": 353,
- "start_line": 6322,
- "end_line": 6326,
+ "start_line": 6342,
+ "end_line": 6346,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo*bar*\n",
"html": "foobar
\n",
"example": 354,
- "start_line": 6331,
- "end_line": 6335,
+ "start_line": 6351,
+ "end_line": 6355,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "5*6*78\n",
"html": "5678
\n",
"example": 355,
- "start_line": 6338,
- "end_line": 6342,
+ "start_line": 6358,
+ "end_line": 6362,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo bar_\n",
"html": "foo bar
\n",
"example": 356,
- "start_line": 6347,
- "end_line": 6351,
+ "start_line": 6367,
+ "end_line": 6371,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_ foo bar_\n",
"html": "_ foo bar_
\n",
"example": 357,
- "start_line": 6357,
- "end_line": 6361,
+ "start_line": 6377,
+ "end_line": 6381,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "a_\"foo\"_\n",
"html": "a_"foo"_
\n",
"example": 358,
- "start_line": 6367,
- "end_line": 6371,
+ "start_line": 6387,
+ "end_line": 6391,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo_bar_\n",
"html": "foo_bar_
\n",
"example": 359,
- "start_line": 6376,
- "end_line": 6380,
+ "start_line": 6396,
+ "end_line": 6400,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "5_6_78\n",
"html": "5_6_78
\n",
"example": 360,
- "start_line": 6383,
- "end_line": 6387,
+ "start_line": 6403,
+ "end_line": 6407,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "пристаням_стремятся_\n",
"html": "пристаням_стремятся_
\n",
"example": 361,
- "start_line": 6390,
- "end_line": 6394,
+ "start_line": 6410,
+ "end_line": 6414,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "aa_\"bb\"_cc\n",
"html": "aa_"bb"_cc
\n",
"example": 362,
- "start_line": 6400,
- "end_line": 6404,
+ "start_line": 6420,
+ "end_line": 6424,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo-_(bar)_\n",
"html": "foo-(bar)
\n",
"example": 363,
- "start_line": 6411,
- "end_line": 6415,
+ "start_line": 6431,
+ "end_line": 6435,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo*\n",
"html": "_foo*
\n",
"example": 364,
- "start_line": 6423,
- "end_line": 6427,
+ "start_line": 6443,
+ "end_line": 6447,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo bar *\n",
"html": "*foo bar *
\n",
"example": 365,
- "start_line": 6433,
- "end_line": 6437,
+ "start_line": 6453,
+ "end_line": 6457,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo bar\n*\n",
"html": "*foo bar\n*
\n",
"example": 366,
- "start_line": 6442,
- "end_line": 6448,
+ "start_line": 6462,
+ "end_line": 6468,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*(*foo)\n",
"html": "*(*foo)
\n",
"example": 367,
- "start_line": 6455,
- "end_line": 6459,
+ "start_line": 6475,
+ "end_line": 6479,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*(*foo*)*\n",
"html": "(foo)
\n",
"example": 368,
- "start_line": 6465,
- "end_line": 6469,
+ "start_line": 6485,
+ "end_line": 6489,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo*bar\n",
"html": "foobar
\n",
"example": 369,
- "start_line": 6474,
- "end_line": 6478,
+ "start_line": 6494,
+ "end_line": 6498,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo bar _\n",
"html": "_foo bar _
\n",
"example": 370,
- "start_line": 6487,
- "end_line": 6491,
+ "start_line": 6507,
+ "end_line": 6511,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_(_foo)\n",
"html": "_(_foo)
\n",
"example": 371,
- "start_line": 6497,
- "end_line": 6501,
+ "start_line": 6517,
+ "end_line": 6521,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_(_foo_)_\n",
"html": "(foo)
\n",
"example": 372,
- "start_line": 6506,
- "end_line": 6510,
+ "start_line": 6526,
+ "end_line": 6530,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo_bar\n",
"html": "_foo_bar
\n",
"example": 373,
- "start_line": 6515,
- "end_line": 6519,
+ "start_line": 6535,
+ "end_line": 6539,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_пристаням_стремятся\n",
"html": "_пристаням_стремятся
\n",
"example": 374,
- "start_line": 6522,
- "end_line": 6526,
+ "start_line": 6542,
+ "end_line": 6546,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo_bar_baz_\n",
"html": "foo_bar_baz
\n",
"example": 375,
- "start_line": 6529,
- "end_line": 6533,
+ "start_line": 6549,
+ "end_line": 6553,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_(bar)_.\n",
"html": "(bar).
\n",
"example": 376,
- "start_line": 6540,
- "end_line": 6544,
+ "start_line": 6560,
+ "end_line": 6564,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo bar**\n",
"html": "foo bar
\n",
"example": 377,
- "start_line": 6549,
- "end_line": 6553,
+ "start_line": 6569,
+ "end_line": 6573,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "** foo bar**\n",
"html": "** foo bar**
\n",
"example": 378,
- "start_line": 6559,
- "end_line": 6563,
+ "start_line": 6579,
+ "end_line": 6583,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "a**\"foo\"**\n",
"html": "a**"foo"**
\n",
"example": 379,
- "start_line": 6570,
- "end_line": 6574,
+ "start_line": 6590,
+ "end_line": 6594,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo**bar**\n",
"html": "foobar
\n",
"example": 380,
- "start_line": 6579,
- "end_line": 6583,
+ "start_line": 6599,
+ "end_line": 6603,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo bar__\n",
"html": "foo bar
\n",
"example": 381,
- "start_line": 6588,
- "end_line": 6592,
+ "start_line": 6608,
+ "end_line": 6612,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__ foo bar__\n",
"html": "__ foo bar__
\n",
"example": 382,
- "start_line": 6598,
- "end_line": 6602,
+ "start_line": 6618,
+ "end_line": 6622,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__\nfoo bar__\n",
"html": "__\nfoo bar__
\n",
"example": 383,
- "start_line": 6606,
- "end_line": 6612,
+ "start_line": 6626,
+ "end_line": 6632,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "a__\"foo\"__\n",
"html": "a__"foo"__
\n",
"example": 384,
- "start_line": 6618,
- "end_line": 6622,
+ "start_line": 6638,
+ "end_line": 6642,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo__bar__\n",
"html": "foo__bar__
\n",
"example": 385,
- "start_line": 6627,
- "end_line": 6631,
+ "start_line": 6647,
+ "end_line": 6651,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "5__6__78\n",
"html": "5__6__78
\n",
"example": 386,
- "start_line": 6634,
- "end_line": 6638,
+ "start_line": 6654,
+ "end_line": 6658,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "пристаням__стремятся__\n",
"html": "пристаням__стремятся__
\n",
"example": 387,
- "start_line": 6641,
- "end_line": 6645,
+ "start_line": 6661,
+ "end_line": 6665,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo, __bar__, baz__\n",
"html": "foo, bar, baz
\n",
"example": 388,
- "start_line": 6648,
- "end_line": 6652,
+ "start_line": 6668,
+ "end_line": 6672,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo-__(bar)__\n",
"html": "foo-(bar)
\n",
"example": 389,
- "start_line": 6659,
- "end_line": 6663,
+ "start_line": 6679,
+ "end_line": 6683,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo bar **\n",
"html": "**foo bar **
\n",
"example": 390,
- "start_line": 6672,
- "end_line": 6676,
+ "start_line": 6692,
+ "end_line": 6696,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**(**foo)\n",
"html": "**(**foo)
\n",
"example": 391,
- "start_line": 6685,
- "end_line": 6689,
+ "start_line": 6705,
+ "end_line": 6709,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*(**foo**)*\n",
"html": "(foo)
\n",
"example": 392,
- "start_line": 6695,
- "end_line": 6699,
+ "start_line": 6715,
+ "end_line": 6719,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**Gomphocarpus (*Gomphocarpus physocarpus*, syn.\n*Asclepias physocarpa*)**\n",
"html": "Gomphocarpus (Gomphocarpus physocarpus, syn.\nAsclepias physocarpa)
\n",
"example": 393,
- "start_line": 6702,
- "end_line": 6708,
+ "start_line": 6722,
+ "end_line": 6728,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo \"*bar*\" foo**\n",
"html": "foo "bar" foo
\n",
"example": 394,
- "start_line": 6711,
- "end_line": 6715,
+ "start_line": 6731,
+ "end_line": 6735,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo**bar\n",
"html": "foobar
\n",
"example": 395,
- "start_line": 6720,
- "end_line": 6724,
+ "start_line": 6740,
+ "end_line": 6744,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo bar __\n",
"html": "__foo bar __
\n",
"example": 396,
- "start_line": 6732,
- "end_line": 6736,
+ "start_line": 6752,
+ "end_line": 6756,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__(__foo)\n",
"html": "__(__foo)
\n",
"example": 397,
- "start_line": 6742,
- "end_line": 6746,
+ "start_line": 6762,
+ "end_line": 6766,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_(__foo__)_\n",
"html": "(foo)
\n",
"example": 398,
- "start_line": 6752,
- "end_line": 6756,
+ "start_line": 6772,
+ "end_line": 6776,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo__bar\n",
"html": "__foo__bar
\n",
"example": 399,
- "start_line": 6761,
- "end_line": 6765,
+ "start_line": 6781,
+ "end_line": 6785,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__пристаням__стремятся\n",
"html": "__пристаням__стремятся
\n",
"example": 400,
- "start_line": 6768,
- "end_line": 6772,
+ "start_line": 6788,
+ "end_line": 6792,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo__bar__baz__\n",
"html": "foo__bar__baz
\n",
"example": 401,
- "start_line": 6775,
- "end_line": 6779,
+ "start_line": 6795,
+ "end_line": 6799,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__(bar)__.\n",
"html": "(bar).
\n",
"example": 402,
- "start_line": 6786,
- "end_line": 6790,
+ "start_line": 6806,
+ "end_line": 6810,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo [bar](/url)*\n",
"html": "foo bar
\n",
"example": 403,
- "start_line": 6798,
- "end_line": 6802,
+ "start_line": 6818,
+ "end_line": 6822,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo\nbar*\n",
"html": "foo\nbar
\n",
"example": 404,
- "start_line": 6805,
- "end_line": 6811,
+ "start_line": 6825,
+ "end_line": 6831,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo __bar__ baz_\n",
"html": "foo bar baz
\n",
"example": 405,
- "start_line": 6817,
- "end_line": 6821,
+ "start_line": 6837,
+ "end_line": 6841,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo _bar_ baz_\n",
"html": "foo bar baz
\n",
"example": 406,
- "start_line": 6824,
- "end_line": 6828,
+ "start_line": 6844,
+ "end_line": 6848,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo_ bar_\n",
"html": "foo bar
\n",
"example": 407,
- "start_line": 6831,
- "end_line": 6835,
+ "start_line": 6851,
+ "end_line": 6855,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo *bar**\n",
"html": "foo bar
\n",
"example": 408,
- "start_line": 6838,
- "end_line": 6842,
+ "start_line": 6858,
+ "end_line": 6862,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo **bar** baz*\n",
"html": "foo bar baz
\n",
"example": 409,
- "start_line": 6845,
- "end_line": 6849,
+ "start_line": 6865,
+ "end_line": 6869,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo**bar**baz*\n",
"html": "foobarbaz
\n",
"example": 410,
- "start_line": 6851,
- "end_line": 6855,
+ "start_line": 6871,
+ "end_line": 6875,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo**bar*\n",
"html": "foo**bar
\n",
"example": 411,
- "start_line": 6875,
- "end_line": 6879,
+ "start_line": 6895,
+ "end_line": 6899,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "***foo** bar*\n",
"html": "foo bar
\n",
"example": 412,
- "start_line": 6888,
- "end_line": 6892,
+ "start_line": 6908,
+ "end_line": 6912,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo **bar***\n",
"html": "foo bar
\n",
"example": 413,
- "start_line": 6895,
- "end_line": 6899,
+ "start_line": 6915,
+ "end_line": 6919,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo**bar***\n",
"html": "foobar
\n",
"example": 414,
- "start_line": 6902,
- "end_line": 6906,
+ "start_line": 6922,
+ "end_line": 6926,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo***bar***baz\n",
"html": "foobarbaz
\n",
"example": 415,
- "start_line": 6913,
- "end_line": 6917,
+ "start_line": 6933,
+ "end_line": 6937,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo******bar*********baz\n",
"html": "foobar***baz
\n",
"example": 416,
- "start_line": 6919,
- "end_line": 6923,
+ "start_line": 6939,
+ "end_line": 6943,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo **bar *baz* bim** bop*\n",
"html": "foo bar baz bim bop
\n",
"example": 417,
- "start_line": 6928,
- "end_line": 6932,
+ "start_line": 6948,
+ "end_line": 6952,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo [*bar*](/url)*\n",
"html": "foo bar
\n",
"example": 418,
- "start_line": 6935,
- "end_line": 6939,
+ "start_line": 6955,
+ "end_line": 6959,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "** is not an empty emphasis\n",
"html": "** is not an empty emphasis
\n",
"example": 419,
- "start_line": 6944,
- "end_line": 6948,
+ "start_line": 6964,
+ "end_line": 6968,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**** is not an empty strong emphasis\n",
"html": "**** is not an empty strong emphasis
\n",
"example": 420,
- "start_line": 6951,
- "end_line": 6955,
+ "start_line": 6971,
+ "end_line": 6975,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo [bar](/url)**\n",
"html": "foo bar
\n",
"example": 421,
- "start_line": 6964,
- "end_line": 6968,
+ "start_line": 6984,
+ "end_line": 6988,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo\nbar**\n",
"html": "foo\nbar
\n",
"example": 422,
- "start_line": 6971,
- "end_line": 6977,
+ "start_line": 6991,
+ "end_line": 6997,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo _bar_ baz__\n",
"html": "foo bar baz
\n",
"example": 423,
- "start_line": 6983,
- "end_line": 6987,
+ "start_line": 7003,
+ "end_line": 7007,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo __bar__ baz__\n",
"html": "foo bar baz
\n",
"example": 424,
- "start_line": 6990,
- "end_line": 6994,
+ "start_line": 7010,
+ "end_line": 7014,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "____foo__ bar__\n",
"html": "foo bar
\n",
"example": 425,
- "start_line": 6997,
- "end_line": 7001,
+ "start_line": 7017,
+ "end_line": 7021,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo **bar****\n",
"html": "foo bar
\n",
"example": 426,
- "start_line": 7004,
- "end_line": 7008,
+ "start_line": 7024,
+ "end_line": 7028,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo *bar* baz**\n",
"html": "foo bar baz
\n",
"example": 427,
- "start_line": 7011,
- "end_line": 7015,
+ "start_line": 7031,
+ "end_line": 7035,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo*bar*baz**\n",
"html": "foobarbaz
\n",
"example": 428,
- "start_line": 7018,
- "end_line": 7022,
+ "start_line": 7038,
+ "end_line": 7042,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "***foo* bar**\n",
"html": "foo bar
\n",
"example": 429,
- "start_line": 7025,
- "end_line": 7029,
+ "start_line": 7045,
+ "end_line": 7049,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo *bar***\n",
"html": "foo bar
\n",
"example": 430,
- "start_line": 7032,
- "end_line": 7036,
+ "start_line": 7052,
+ "end_line": 7056,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo *bar **baz**\nbim* bop**\n",
"html": "foo bar baz\nbim bop
\n",
"example": 431,
- "start_line": 7041,
- "end_line": 7047,
+ "start_line": 7061,
+ "end_line": 7067,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo [*bar*](/url)**\n",
"html": "foo bar
\n",
"example": 432,
- "start_line": 7050,
- "end_line": 7054,
+ "start_line": 7070,
+ "end_line": 7074,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__ is not an empty emphasis\n",
"html": "__ is not an empty emphasis
\n",
"example": 433,
- "start_line": 7059,
- "end_line": 7063,
+ "start_line": 7079,
+ "end_line": 7083,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "____ is not an empty strong emphasis\n",
"html": "____ is not an empty strong emphasis
\n",
"example": 434,
- "start_line": 7066,
- "end_line": 7070,
+ "start_line": 7086,
+ "end_line": 7090,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo ***\n",
"html": "foo ***
\n",
"example": 435,
- "start_line": 7076,
- "end_line": 7080,
+ "start_line": 7096,
+ "end_line": 7100,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo *\\**\n",
"html": "foo *
\n",
"example": 436,
- "start_line": 7083,
- "end_line": 7087,
+ "start_line": 7103,
+ "end_line": 7107,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo *_*\n",
"html": "foo _
\n",
"example": 437,
- "start_line": 7090,
- "end_line": 7094,
+ "start_line": 7110,
+ "end_line": 7114,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo *****\n",
"html": "foo *****
\n",
"example": 438,
- "start_line": 7097,
- "end_line": 7101,
+ "start_line": 7117,
+ "end_line": 7121,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo **\\***\n",
"html": "foo *
\n",
"example": 439,
- "start_line": 7104,
- "end_line": 7108,
+ "start_line": 7124,
+ "end_line": 7128,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo **_**\n",
"html": "foo _
\n",
"example": 440,
- "start_line": 7111,
- "end_line": 7115,
+ "start_line": 7131,
+ "end_line": 7135,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo*\n",
"html": "*foo
\n",
"example": 441,
- "start_line": 7122,
- "end_line": 7126,
+ "start_line": 7142,
+ "end_line": 7146,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo**\n",
"html": "foo*
\n",
"example": 442,
- "start_line": 7129,
- "end_line": 7133,
+ "start_line": 7149,
+ "end_line": 7153,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "***foo**\n",
"html": "*foo
\n",
"example": 443,
- "start_line": 7136,
- "end_line": 7140,
+ "start_line": 7156,
+ "end_line": 7160,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "****foo*\n",
"html": "***foo
\n",
"example": 444,
- "start_line": 7143,
- "end_line": 7147,
+ "start_line": 7163,
+ "end_line": 7167,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo***\n",
"html": "foo*
\n",
"example": 445,
- "start_line": 7150,
- "end_line": 7154,
+ "start_line": 7170,
+ "end_line": 7174,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo****\n",
"html": "foo***
\n",
"example": 446,
- "start_line": 7157,
- "end_line": 7161,
+ "start_line": 7177,
+ "end_line": 7181,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo ___\n",
"html": "foo ___
\n",
"example": 447,
- "start_line": 7167,
- "end_line": 7171,
+ "start_line": 7187,
+ "end_line": 7191,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo _\\__\n",
"html": "foo _
\n",
"example": 448,
- "start_line": 7174,
- "end_line": 7178,
+ "start_line": 7194,
+ "end_line": 7198,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo _*_\n",
"html": "foo *
\n",
"example": 449,
- "start_line": 7181,
- "end_line": 7185,
+ "start_line": 7201,
+ "end_line": 7205,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo _____\n",
"html": "foo _____
\n",
"example": 450,
- "start_line": 7188,
- "end_line": 7192,
+ "start_line": 7208,
+ "end_line": 7212,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo __\\___\n",
"html": "foo _
\n",
"example": 451,
- "start_line": 7195,
- "end_line": 7199,
+ "start_line": 7215,
+ "end_line": 7219,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "foo __*__\n",
"html": "foo *
\n",
"example": 452,
- "start_line": 7202,
- "end_line": 7206,
+ "start_line": 7222,
+ "end_line": 7226,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo_\n",
"html": "_foo
\n",
"example": 453,
- "start_line": 7209,
- "end_line": 7213,
+ "start_line": 7229,
+ "end_line": 7233,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo__\n",
"html": "foo_
\n",
"example": 454,
- "start_line": 7220,
- "end_line": 7224,
+ "start_line": 7240,
+ "end_line": 7244,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "___foo__\n",
"html": "_foo
\n",
"example": 455,
- "start_line": 7227,
- "end_line": 7231,
+ "start_line": 7247,
+ "end_line": 7251,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "____foo_\n",
"html": "___foo
\n",
"example": 456,
- "start_line": 7234,
- "end_line": 7238,
+ "start_line": 7254,
+ "end_line": 7258,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo___\n",
"html": "foo_
\n",
"example": 457,
- "start_line": 7241,
- "end_line": 7245,
+ "start_line": 7261,
+ "end_line": 7265,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo____\n",
"html": "foo___
\n",
"example": 458,
- "start_line": 7248,
- "end_line": 7252,
+ "start_line": 7268,
+ "end_line": 7272,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo**\n",
"html": "foo
\n",
"example": 459,
- "start_line": 7258,
- "end_line": 7262,
+ "start_line": 7278,
+ "end_line": 7282,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*_foo_*\n",
"html": "foo
\n",
"example": 460,
- "start_line": 7265,
- "end_line": 7269,
+ "start_line": 7285,
+ "end_line": 7289,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__foo__\n",
"html": "foo
\n",
"example": 461,
- "start_line": 7272,
- "end_line": 7276,
+ "start_line": 7292,
+ "end_line": 7296,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_*foo*_\n",
"html": "foo
\n",
"example": 462,
- "start_line": 7279,
- "end_line": 7283,
+ "start_line": 7299,
+ "end_line": 7303,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "****foo****\n",
"html": "foo
\n",
"example": 463,
- "start_line": 7289,
- "end_line": 7293,
+ "start_line": 7309,
+ "end_line": 7313,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "____foo____\n",
"html": "foo
\n",
"example": 464,
- "start_line": 7296,
- "end_line": 7300,
+ "start_line": 7316,
+ "end_line": 7320,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "******foo******\n",
"html": "foo
\n",
"example": 465,
- "start_line": 7307,
- "end_line": 7311,
+ "start_line": 7327,
+ "end_line": 7331,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "***foo***\n",
"html": "foo
\n",
"example": 466,
- "start_line": 7316,
- "end_line": 7320,
+ "start_line": 7336,
+ "end_line": 7340,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_____foo_____\n",
"html": "foo
\n",
"example": 467,
- "start_line": 7323,
- "end_line": 7327,
+ "start_line": 7343,
+ "end_line": 7347,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo _bar* baz_\n",
"html": "foo _bar baz_
\n",
"example": 468,
- "start_line": 7332,
- "end_line": 7336,
+ "start_line": 7352,
+ "end_line": 7356,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo __bar *baz bim__ bam*\n",
"html": "foo bar *baz bim bam
\n",
"example": 469,
- "start_line": 7339,
- "end_line": 7343,
+ "start_line": 7359,
+ "end_line": 7363,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**foo **bar baz**\n",
"html": "**foo bar baz
\n",
"example": 470,
- "start_line": 7348,
- "end_line": 7352,
+ "start_line": 7368,
+ "end_line": 7372,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*foo *bar baz*\n",
"html": "*foo bar baz
\n",
"example": 471,
- "start_line": 7355,
- "end_line": 7359,
+ "start_line": 7375,
+ "end_line": 7379,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*[bar*](/url)\n",
"html": "*bar*
\n",
"example": 472,
- "start_line": 7364,
- "end_line": 7368,
+ "start_line": 7384,
+ "end_line": 7388,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_foo [bar_](/url)\n",
"html": "_foo bar_
\n",
"example": 473,
- "start_line": 7371,
- "end_line": 7375,
+ "start_line": 7391,
+ "end_line": 7395,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*
\n",
"html": "*
\n",
"example": 474,
- "start_line": 7378,
- "end_line": 7382,
+ "start_line": 7398,
+ "end_line": 7402,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**\n",
"html": "\n",
"example": 475,
- "start_line": 7385,
- "end_line": 7389,
+ "start_line": 7405,
+ "end_line": 7409,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__\n",
"html": "\n",
"example": 476,
- "start_line": 7392,
- "end_line": 7396,
+ "start_line": 7412,
+ "end_line": 7416,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "*a `*`*\n",
"html": "a *
\n",
"example": 477,
- "start_line": 7399,
- "end_line": 7403,
+ "start_line": 7419,
+ "end_line": 7423,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "_a `_`_\n",
"html": "a _
\n",
"example": 478,
- "start_line": 7406,
- "end_line": 7410,
+ "start_line": 7426,
+ "end_line": 7430,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "**a\n",
"html": "\n",
"example": 479,
- "start_line": 7413,
- "end_line": 7417,
+ "start_line": 7433,
+ "end_line": 7437,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "__a\n",
"html": "\n",
"example": 480,
- "start_line": 7420,
- "end_line": 7424,
+ "start_line": 7440,
+ "end_line": 7444,
"section": "Emphasis and strong emphasis"
},
{
"markdown": "[link](/uri \"title\")\n",
"html": "\n",
"example": 481,
- "start_line": 7503,
- "end_line": 7507,
+ "start_line": 7528,
+ "end_line": 7532,
"section": "Links"
},
{
"markdown": "[link](/uri)\n",
"html": "\n",
"example": 482,
- "start_line": 7512,
- "end_line": 7516,
+ "start_line": 7538,
+ "end_line": 7542,
+ "section": "Links"
+ },
+ {
+ "markdown": "[](./target.md)\n",
+ "html": "\n",
+ "example": 483,
+ "start_line": 7544,
+ "end_line": 7548,
"section": "Links"
},
{
"markdown": "[link]()\n",
"html": "\n",
- "example": 483,
- "start_line": 7521,
- "end_line": 7525,
+ "example": 484,
+ "start_line": 7551,
+ "end_line": 7555,
"section": "Links"
},
{
"markdown": "[link](<>)\n",
"html": "\n",
- "example": 484,
- "start_line": 7528,
- "end_line": 7532,
+ "example": 485,
+ "start_line": 7558,
+ "end_line": 7562,
+ "section": "Links"
+ },
+ {
+ "markdown": "[]()\n",
+ "html": "\n",
+ "example": 486,
+ "start_line": 7565,
+ "end_line": 7569,
"section": "Links"
},
{
"markdown": "[link](/my uri)\n",
"html": "[link](/my uri)
\n",
- "example": 485,
- "start_line": 7537,
- "end_line": 7541,
+ "example": 487,
+ "start_line": 7574,
+ "end_line": 7578,
"section": "Links"
},
{
"markdown": "[link]( )\n",
"html": "\n",
- "example": 486,
- "start_line": 7543,
- "end_line": 7547,
+ "example": 488,
+ "start_line": 7580,
+ "end_line": 7584,
"section": "Links"
},
{
"markdown": "[link](foo\nbar)\n",
"html": "[link](foo\nbar)
\n",
- "example": 487,
- "start_line": 7552,
- "end_line": 7558,
+ "example": 489,
+ "start_line": 7589,
+ "end_line": 7595,
"section": "Links"
},
{
"markdown": "[link]()\n",
"html": "[link]()
\n",
- "example": 488,
- "start_line": 7560,
- "end_line": 7566,
+ "example": 490,
+ "start_line": 7597,
+ "end_line": 7603,
"section": "Links"
},
{
"markdown": "[a]()\n",
"html": "\n",
- "example": 489,
- "start_line": 7571,
- "end_line": 7575,
+ "example": 491,
+ "start_line": 7608,
+ "end_line": 7612,
"section": "Links"
},
{
"markdown": "[link]()\n",
"html": "[link](<foo>)
\n",
- "example": 490,
- "start_line": 7579,
- "end_line": 7583,
+ "example": 492,
+ "start_line": 7616,
+ "end_line": 7620,
"section": "Links"
},
{
"markdown": "[a](\n[a](c)\n",
"html": "[a](<b)c\n[a](<b)c>\n[a](c)
\n",
- "example": 491,
- "start_line": 7588,
- "end_line": 7596,
+ "example": 493,
+ "start_line": 7625,
+ "end_line": 7633,
"section": "Links"
},
{
"markdown": "[link](\\(foo\\))\n",
"html": "\n",
- "example": 492,
- "start_line": 7600,
- "end_line": 7604,
+ "example": 494,
+ "start_line": 7637,
+ "end_line": 7641,
"section": "Links"
},
{
"markdown": "[link](foo(and(bar)))\n",
"html": "\n",
- "example": 493,
- "start_line": 7609,
- "end_line": 7613,
+ "example": 495,
+ "start_line": 7646,
+ "end_line": 7650,
+ "section": "Links"
+ },
+ {
+ "markdown": "[link](foo(and(bar))\n",
+ "html": "[link](foo(and(bar))
\n",
+ "example": 496,
+ "start_line": 7655,
+ "end_line": 7659,
"section": "Links"
},
{
"markdown": "[link](foo\\(and\\(bar\\))\n",
"html": "\n",
- "example": 494,
- "start_line": 7618,
- "end_line": 7622,
+ "example": 497,
+ "start_line": 7662,
+ "end_line": 7666,
"section": "Links"
},
{
"markdown": "[link]()\n",
"html": "\n",
- "example": 495,
- "start_line": 7625,
- "end_line": 7629,
+ "example": 498,
+ "start_line": 7669,
+ "end_line": 7673,
"section": "Links"
},
{
"markdown": "[link](foo\\)\\:)\n",
"html": "\n",
- "example": 496,
- "start_line": 7635,
- "end_line": 7639,
+ "example": 499,
+ "start_line": 7679,
+ "end_line": 7683,
"section": "Links"
},
{
"markdown": "[link](#fragment)\n\n[link](http://example.com#fragment)\n\n[link](http://example.com?foo=3#frag)\n",
"html": "\n\n\n",
- "example": 497,
- "start_line": 7644,
- "end_line": 7654,
+ "example": 500,
+ "start_line": 7688,
+ "end_line": 7698,
"section": "Links"
},
{
"markdown": "[link](foo\\bar)\n",
"html": "\n",
- "example": 498,
- "start_line": 7660,
- "end_line": 7664,
+ "example": 501,
+ "start_line": 7704,
+ "end_line": 7708,
"section": "Links"
},
{
"markdown": "[link](foo%20bä)\n",
"html": "\n",
- "example": 499,
- "start_line": 7676,
- "end_line": 7680,
+ "example": 502,
+ "start_line": 7720,
+ "end_line": 7724,
"section": "Links"
},
{
"markdown": "[link](\"title\")\n",
"html": "\n",
- "example": 500,
- "start_line": 7687,
- "end_line": 7691,
+ "example": 503,
+ "start_line": 7731,
+ "end_line": 7735,
"section": "Links"
},
{
"markdown": "[link](/url \"title\")\n[link](/url 'title')\n[link](/url (title))\n",
"html": "\n",
- "example": 501,
- "start_line": 7696,
- "end_line": 7704,
+ "example": 504,
+ "start_line": 7740,
+ "end_line": 7748,
"section": "Links"
},
{
"markdown": "[link](/url \"title \\\""\")\n",
"html": "\n",
- "example": 502,
- "start_line": 7710,
- "end_line": 7714,
+ "example": 505,
+ "start_line": 7754,
+ "end_line": 7758,
"section": "Links"
},
{
"markdown": "[link](/url \"title\")\n",
"html": "\n",
- "example": 503,
- "start_line": 7720,
- "end_line": 7724,
+ "example": 506,
+ "start_line": 7765,
+ "end_line": 7769,
"section": "Links"
},
{
"markdown": "[link](/url \"title \"and\" title\")\n",
"html": "[link](/url "title "and" title")
\n",
- "example": 504,
- "start_line": 7729,
- "end_line": 7733,
+ "example": 507,
+ "start_line": 7774,
+ "end_line": 7778,
"section": "Links"
},
{
"markdown": "[link](/url 'title \"and\" title')\n",
"html": "\n",
- "example": 505,
- "start_line": 7738,
- "end_line": 7742,
- "section": "Links"
- },
- {
- "markdown": "[link]( /uri\n \"title\" )\n",
- "html": "\n",
- "example": 506,
- "start_line": 7762,
- "end_line": 7767,
- "section": "Links"
- },
- {
- "markdown": "[link] (/uri)\n",
- "html": "[link] (/uri)
\n",
- "example": 507,
- "start_line": 7773,
- "end_line": 7777,
- "section": "Links"
- },
- {
- "markdown": "[link [foo [bar]]](/uri)\n",
- "html": "\n",
"example": 508,
"start_line": 7783,
"end_line": 7787,
"section": "Links"
},
+ {
+ "markdown": "[link]( /uri\n \"title\" )\n",
+ "html": "\n",
+ "example": 509,
+ "start_line": 7808,
+ "end_line": 7813,
+ "section": "Links"
+ },
+ {
+ "markdown": "[link] (/uri)\n",
+ "html": "[link] (/uri)
\n",
+ "example": 510,
+ "start_line": 7819,
+ "end_line": 7823,
+ "section": "Links"
+ },
+ {
+ "markdown": "[link [foo [bar]]](/uri)\n",
+ "html": "\n",
+ "example": 511,
+ "start_line": 7829,
+ "end_line": 7833,
+ "section": "Links"
+ },
{
"markdown": "[link] bar](/uri)\n",
"html": "[link] bar](/uri)
\n",
- "example": 509,
- "start_line": 7790,
- "end_line": 7794,
+ "example": 512,
+ "start_line": 7836,
+ "end_line": 7840,
"section": "Links"
},
{
"markdown": "[link [bar](/uri)\n",
"html": "[link bar
\n",
- "example": 510,
- "start_line": 7797,
- "end_line": 7801,
+ "example": 513,
+ "start_line": 7843,
+ "end_line": 7847,
"section": "Links"
},
{
"markdown": "[link \\[bar](/uri)\n",
"html": "\n",
- "example": 511,
- "start_line": 7804,
- "end_line": 7808,
+ "example": 514,
+ "start_line": 7850,
+ "end_line": 7854,
"section": "Links"
},
{
"markdown": "[link *foo **bar** `#`*](/uri)\n",
"html": "\n",
- "example": 512,
- "start_line": 7813,
- "end_line": 7817,
+ "example": 515,
+ "start_line": 7859,
+ "end_line": 7863,
"section": "Links"
},
{
"markdown": "[](/uri)\n",
"html": "\n",
- "example": 513,
- "start_line": 7820,
- "end_line": 7824,
+ "example": 516,
+ "start_line": 7866,
+ "end_line": 7870,
"section": "Links"
},
{
"markdown": "[foo [bar](/uri)](/uri)\n",
"html": "[foo bar](/uri)
\n",
- "example": 514,
- "start_line": 7829,
- "end_line": 7833,
+ "example": 517,
+ "start_line": 7875,
+ "end_line": 7879,
"section": "Links"
},
{
"markdown": "[foo *[bar [baz](/uri)](/uri)*](/uri)\n",
"html": "[foo [bar baz](/uri)](/uri)
\n",
- "example": 515,
- "start_line": 7836,
- "end_line": 7840,
+ "example": 518,
+ "start_line": 7882,
+ "end_line": 7886,
"section": "Links"
},
{
"markdown": "](uri2)](uri3)\n",
"html": "\"](\"uri3\")
\n",
- "example": 516,
- "start_line": 7843,
- "end_line": 7847,
+ "example": 519,
+ "start_line": 7889,
+ "end_line": 7893,
"section": "Links"
},
{
"markdown": "*[foo*](/uri)\n",
"html": "*foo*
\n",
- "example": 517,
- "start_line": 7853,
- "end_line": 7857,
+ "example": 520,
+ "start_line": 7899,
+ "end_line": 7903,
"section": "Links"
},
{
"markdown": "[foo *bar](baz*)\n",
"html": "\n",
- "example": 518,
- "start_line": 7860,
- "end_line": 7864,
+ "example": 521,
+ "start_line": 7906,
+ "end_line": 7910,
"section": "Links"
},
{
"markdown": "*foo [bar* baz]\n",
"html": "foo [bar baz]
\n",
- "example": 519,
- "start_line": 7870,
- "end_line": 7874,
+ "example": 522,
+ "start_line": 7916,
+ "end_line": 7920,
"section": "Links"
},
{
"markdown": "[foo \n",
"html": "[foo
\n",
- "example": 520,
- "start_line": 7880,
- "end_line": 7884,
+ "example": 523,
+ "start_line": 7926,
+ "end_line": 7930,
"section": "Links"
},
{
"markdown": "[foo`](/uri)`\n",
"html": "[foo](/uri)
\n",
- "example": 521,
- "start_line": 7887,
- "end_line": 7891,
+ "example": 524,
+ "start_line": 7933,
+ "end_line": 7937,
"section": "Links"
},
{
"markdown": "[foo\n",
"html": "[foohttp://example.com/?search=](uri)
\n",
- "example": 522,
- "start_line": 7894,
- "end_line": 7898,
+ "example": 525,
+ "start_line": 7940,
+ "end_line": 7944,
"section": "Links"
},
{
"markdown": "[foo][bar]\n\n[bar]: /url \"title\"\n",
"html": "\n",
- "example": 523,
- "start_line": 7932,
- "end_line": 7938,
+ "example": 526,
+ "start_line": 7978,
+ "end_line": 7984,
"section": "Links"
},
{
"markdown": "[link [foo [bar]]][ref]\n\n[ref]: /uri\n",
"html": "\n",
- "example": 524,
- "start_line": 7947,
- "end_line": 7953,
+ "example": 527,
+ "start_line": 7993,
+ "end_line": 7999,
"section": "Links"
},
{
"markdown": "[link \\[bar][ref]\n\n[ref]: /uri\n",
"html": "\n",
- "example": 525,
- "start_line": 7956,
- "end_line": 7962,
+ "example": 528,
+ "start_line": 8002,
+ "end_line": 8008,
"section": "Links"
},
{
"markdown": "[link *foo **bar** `#`*][ref]\n\n[ref]: /uri\n",
"html": "\n",
- "example": 526,
- "start_line": 7967,
- "end_line": 7973,
+ "example": 529,
+ "start_line": 8013,
+ "end_line": 8019,
"section": "Links"
},
{
"markdown": "[][ref]\n\n[ref]: /uri\n",
"html": "\n",
- "example": 527,
- "start_line": 7976,
- "end_line": 7982,
+ "example": 530,
+ "start_line": 8022,
+ "end_line": 8028,
"section": "Links"
},
{
"markdown": "[foo [bar](/uri)][ref]\n\n[ref]: /uri\n",
"html": "\n",
- "example": 528,
- "start_line": 7987,
- "end_line": 7993,
+ "example": 531,
+ "start_line": 8033,
+ "end_line": 8039,
"section": "Links"
},
{
"markdown": "[foo *bar [baz][ref]*][ref]\n\n[ref]: /uri\n",
"html": "\n",
- "example": 529,
- "start_line": 7996,
- "end_line": 8002,
+ "example": 532,
+ "start_line": 8042,
+ "end_line": 8048,
"section": "Links"
},
{
"markdown": "*[foo*][ref]\n\n[ref]: /uri\n",
"html": "*foo*
\n",
- "example": 530,
- "start_line": 8011,
- "end_line": 8017,
+ "example": 533,
+ "start_line": 8057,
+ "end_line": 8063,
"section": "Links"
},
{
- "markdown": "[foo *bar][ref]\n\n[ref]: /uri\n",
- "html": "\n",
- "example": 531,
- "start_line": 8020,
- "end_line": 8026,
+ "markdown": "[foo *bar][ref]*\n\n[ref]: /uri\n",
+ "html": "\n",
+ "example": 534,
+ "start_line": 8066,
+ "end_line": 8072,
"section": "Links"
},
{
"markdown": "[foo \n\n[ref]: /uri\n",
"html": "[foo
\n",
- "example": 532,
- "start_line": 8032,
- "end_line": 8038,
+ "example": 535,
+ "start_line": 8078,
+ "end_line": 8084,
"section": "Links"
},
{
"markdown": "[foo`][ref]`\n\n[ref]: /uri\n",
"html": "[foo][ref]
\n",
- "example": 533,
- "start_line": 8041,
- "end_line": 8047,
+ "example": 536,
+ "start_line": 8087,
+ "end_line": 8093,
"section": "Links"
},
{
"markdown": "[foo\n\n[ref]: /uri\n",
"html": "[foohttp://example.com/?search=][ref]
\n",
- "example": 534,
- "start_line": 8050,
- "end_line": 8056,
+ "example": 537,
+ "start_line": 8096,
+ "end_line": 8102,
"section": "Links"
},
{
"markdown": "[foo][BaR]\n\n[bar]: /url \"title\"\n",
"html": "\n",
- "example": 535,
- "start_line": 8061,
- "end_line": 8067,
+ "example": 538,
+ "start_line": 8107,
+ "end_line": 8113,
"section": "Links"
},
{
- "markdown": "[Толпой][Толпой] is a Russian word.\n\n[ТОЛПОЙ]: /url\n",
- "html": "Толпой is a Russian word.
\n",
- "example": 536,
- "start_line": 8072,
- "end_line": 8078,
+ "markdown": "[ẞ]\n\n[SS]: /url\n",
+ "html": "\n",
+ "example": 539,
+ "start_line": 8118,
+ "end_line": 8124,
"section": "Links"
},
{
"markdown": "[Foo\n bar]: /url\n\n[Baz][Foo bar]\n",
"html": "\n",
- "example": 537,
- "start_line": 8084,
- "end_line": 8091,
+ "example": 540,
+ "start_line": 8130,
+ "end_line": 8137,
"section": "Links"
},
{
"markdown": "[foo] [bar]\n\n[bar]: /url \"title\"\n",
"html": "[foo] bar
\n",
- "example": 538,
- "start_line": 8097,
- "end_line": 8103,
+ "example": 541,
+ "start_line": 8143,
+ "end_line": 8149,
"section": "Links"
},
{
"markdown": "[foo]\n[bar]\n\n[bar]: /url \"title\"\n",
"html": "[foo]\nbar
\n",
- "example": 539,
- "start_line": 8106,
- "end_line": 8114,
+ "example": 542,
+ "start_line": 8152,
+ "end_line": 8160,
"section": "Links"
},
{
"markdown": "[foo]: /url1\n\n[foo]: /url2\n\n[bar][foo]\n",
"html": "\n",
- "example": 540,
- "start_line": 8147,
- "end_line": 8155,
+ "example": 543,
+ "start_line": 8193,
+ "end_line": 8201,
"section": "Links"
},
{
"markdown": "[bar][foo\\!]\n\n[foo!]: /url\n",
"html": "[bar][foo!]
\n",
- "example": 541,
- "start_line": 8162,
- "end_line": 8168,
+ "example": 544,
+ "start_line": 8208,
+ "end_line": 8214,
"section": "Links"
},
{
"markdown": "[foo][ref[]\n\n[ref[]: /uri\n",
"html": "[foo][ref[]
\n[ref[]: /uri
\n",
- "example": 542,
- "start_line": 8174,
- "end_line": 8181,
+ "example": 545,
+ "start_line": 8220,
+ "end_line": 8227,
"section": "Links"
},
{
"markdown": "[foo][ref[bar]]\n\n[ref[bar]]: /uri\n",
"html": "[foo][ref[bar]]
\n[ref[bar]]: /uri
\n",
- "example": 543,
- "start_line": 8184,
- "end_line": 8191,
+ "example": 546,
+ "start_line": 8230,
+ "end_line": 8237,
"section": "Links"
},
{
"markdown": "[[[foo]]]\n\n[[[foo]]]: /url\n",
"html": "[[[foo]]]
\n[[[foo]]]: /url
\n",
- "example": 544,
- "start_line": 8194,
- "end_line": 8201,
+ "example": 547,
+ "start_line": 8240,
+ "end_line": 8247,
"section": "Links"
},
{
"markdown": "[foo][ref\\[]\n\n[ref\\[]: /uri\n",
"html": "\n",
- "example": 545,
- "start_line": 8204,
- "end_line": 8210,
+ "example": 548,
+ "start_line": 8250,
+ "end_line": 8256,
"section": "Links"
},
{
"markdown": "[bar\\\\]: /uri\n\n[bar\\\\]\n",
"html": "\n",
- "example": 546,
- "start_line": 8215,
- "end_line": 8221,
+ "example": 549,
+ "start_line": 8261,
+ "end_line": 8267,
"section": "Links"
},
{
"markdown": "[]\n\n[]: /uri\n",
"html": "[]
\n[]: /uri
\n",
- "example": 547,
- "start_line": 8226,
- "end_line": 8233,
+ "example": 550,
+ "start_line": 8273,
+ "end_line": 8280,
"section": "Links"
},
{
"markdown": "[\n ]\n\n[\n ]: /uri\n",
"html": "[\n]
\n[\n]: /uri
\n",
- "example": 548,
- "start_line": 8236,
- "end_line": 8247,
+ "example": 551,
+ "start_line": 8283,
+ "end_line": 8294,
"section": "Links"
},
{
"markdown": "[foo][]\n\n[foo]: /url \"title\"\n",
"html": "\n",
- "example": 549,
- "start_line": 8259,
- "end_line": 8265,
+ "example": 552,
+ "start_line": 8306,
+ "end_line": 8312,
"section": "Links"
},
{
"markdown": "[*foo* bar][]\n\n[*foo* bar]: /url \"title\"\n",
"html": "\n",
- "example": 550,
- "start_line": 8268,
- "end_line": 8274,
+ "example": 553,
+ "start_line": 8315,
+ "end_line": 8321,
"section": "Links"
},
{
"markdown": "[Foo][]\n\n[foo]: /url \"title\"\n",
"html": "\n",
- "example": 551,
- "start_line": 8279,
- "end_line": 8285,
+ "example": 554,
+ "start_line": 8326,
+ "end_line": 8332,
"section": "Links"
},
{
"markdown": "[foo] \n[]\n\n[foo]: /url \"title\"\n",
"html": "foo\n[]
\n",
- "example": 552,
- "start_line": 8292,
- "end_line": 8300,
+ "example": 555,
+ "start_line": 8339,
+ "end_line": 8347,
"section": "Links"
},
{
"markdown": "[foo]\n\n[foo]: /url \"title\"\n",
"html": "\n",
- "example": 553,
- "start_line": 8312,
- "end_line": 8318,
+ "example": 556,
+ "start_line": 8359,
+ "end_line": 8365,
"section": "Links"
},
{
"markdown": "[*foo* bar]\n\n[*foo* bar]: /url \"title\"\n",
"html": "\n",
- "example": 554,
- "start_line": 8321,
- "end_line": 8327,
+ "example": 557,
+ "start_line": 8368,
+ "end_line": 8374,
"section": "Links"
},
{
"markdown": "[[*foo* bar]]\n\n[*foo* bar]: /url \"title\"\n",
"html": "[foo bar]
\n",
- "example": 555,
- "start_line": 8330,
- "end_line": 8336,
+ "example": 558,
+ "start_line": 8377,
+ "end_line": 8383,
"section": "Links"
},
{
"markdown": "[[bar [foo]\n\n[foo]: /url\n",
"html": "[[bar foo
\n",
- "example": 556,
- "start_line": 8339,
- "end_line": 8345,
+ "example": 559,
+ "start_line": 8386,
+ "end_line": 8392,
"section": "Links"
},
{
"markdown": "[Foo]\n\n[foo]: /url \"title\"\n",
"html": "\n",
- "example": 557,
- "start_line": 8350,
- "end_line": 8356,
+ "example": 560,
+ "start_line": 8397,
+ "end_line": 8403,
"section": "Links"
},
{
"markdown": "[foo] bar\n\n[foo]: /url\n",
"html": "foo bar
\n",
- "example": 558,
- "start_line": 8361,
- "end_line": 8367,
+ "example": 561,
+ "start_line": 8408,
+ "end_line": 8414,
"section": "Links"
},
{
"markdown": "\\[foo]\n\n[foo]: /url \"title\"\n",
"html": "[foo]
\n",
- "example": 559,
- "start_line": 8373,
- "end_line": 8379,
+ "example": 562,
+ "start_line": 8420,
+ "end_line": 8426,
"section": "Links"
},
{
"markdown": "[foo*]: /url\n\n*[foo*]\n",
"html": "*foo*
\n",
- "example": 560,
- "start_line": 8385,
- "end_line": 8391,
+ "example": 563,
+ "start_line": 8432,
+ "end_line": 8438,
"section": "Links"
},
{
"markdown": "[foo][bar]\n\n[foo]: /url1\n[bar]: /url2\n",
"html": "\n",
- "example": 561,
- "start_line": 8397,
- "end_line": 8404,
+ "example": 564,
+ "start_line": 8444,
+ "end_line": 8451,
"section": "Links"
},
{
"markdown": "[foo][]\n\n[foo]: /url1\n",
"html": "\n",
- "example": 562,
- "start_line": 8406,
- "end_line": 8412,
+ "example": 565,
+ "start_line": 8453,
+ "end_line": 8459,
"section": "Links"
},
{
"markdown": "[foo]()\n\n[foo]: /url1\n",
"html": "\n",
- "example": 563,
- "start_line": 8416,
- "end_line": 8422,
+ "example": 566,
+ "start_line": 8463,
+ "end_line": 8469,
"section": "Links"
},
{
"markdown": "[foo](not a link)\n\n[foo]: /url1\n",
"html": "foo(not a link)
\n",
- "example": 564,
- "start_line": 8424,
- "end_line": 8430,
+ "example": 567,
+ "start_line": 8471,
+ "end_line": 8477,
"section": "Links"
},
{
"markdown": "[foo][bar][baz]\n\n[baz]: /url\n",
"html": "[foo]bar
\n",
- "example": 565,
- "start_line": 8435,
- "end_line": 8441,
+ "example": 568,
+ "start_line": 8482,
+ "end_line": 8488,
"section": "Links"
},
{
"markdown": "[foo][bar][baz]\n\n[baz]: /url1\n[bar]: /url2\n",
"html": "\n",
- "example": 566,
- "start_line": 8447,
- "end_line": 8454,
+ "example": 569,
+ "start_line": 8494,
+ "end_line": 8501,
"section": "Links"
},
{
"markdown": "[foo][bar][baz]\n\n[baz]: /url1\n[foo]: /url2\n",
"html": "[foo]bar
\n",
- "example": 567,
- "start_line": 8460,
- "end_line": 8467,
+ "example": 570,
+ "start_line": 8507,
+ "end_line": 8514,
"section": "Links"
},
{
"markdown": "\n",
"html": "
\n",
- "example": 568,
- "start_line": 8483,
- "end_line": 8487,
+ "example": 571,
+ "start_line": 8530,
+ "end_line": 8534,
"section": "Images"
},
{
"markdown": "![foo *bar*]\n\n[foo *bar*]: train.jpg \"train & tracks\"\n",
"html": "
\n",
- "example": 569,
- "start_line": 8490,
- "end_line": 8496,
+ "example": 572,
+ "start_line": 8537,
+ "end_line": 8543,
"section": "Images"
},
{
"markdown": "](/url2)\n",
"html": "
\n",
- "example": 570,
- "start_line": 8499,
- "end_line": 8503,
+ "example": 573,
+ "start_line": 8546,
+ "end_line": 8550,
"section": "Images"
},
{
"markdown": "](/url2)\n",
"html": "
\n",
- "example": 571,
- "start_line": 8506,
- "end_line": 8510,
+ "example": 574,
+ "start_line": 8553,
+ "end_line": 8557,
"section": "Images"
},
{
"markdown": "![foo *bar*][]\n\n[foo *bar*]: train.jpg \"train & tracks\"\n",
"html": "
\n",
- "example": 572,
- "start_line": 8520,
- "end_line": 8526,
+ "example": 575,
+ "start_line": 8567,
+ "end_line": 8573,
"section": "Images"
},
{
"markdown": "![foo *bar*][foobar]\n\n[FOOBAR]: train.jpg \"train & tracks\"\n",
"html": "
\n",
- "example": 573,
- "start_line": 8529,
- "end_line": 8535,
+ "example": 576,
+ "start_line": 8576,
+ "end_line": 8582,
"section": "Images"
},
{
"markdown": "\n",
"html": "
\n",
- "example": 574,
- "start_line": 8538,
- "end_line": 8542,
+ "example": 577,
+ "start_line": 8585,
+ "end_line": 8589,
"section": "Images"
},
{
"markdown": "My \n",
"html": "My 
\n",
- "example": 575,
- "start_line": 8545,
- "end_line": 8549,
+ "example": 578,
+ "start_line": 8592,
+ "end_line": 8596,
"section": "Images"
},
{
"markdown": "![foo]()\n",
"html": "
\n",
- "example": 576,
- "start_line": 8552,
- "end_line": 8556,
+ "example": 579,
+ "start_line": 8599,
+ "end_line": 8603,
"section": "Images"
},
{
"markdown": "\n",
"html": "
\n",
- "example": 577,
- "start_line": 8559,
- "end_line": 8563,
+ "example": 580,
+ "start_line": 8606,
+ "end_line": 8610,
"section": "Images"
},
{
"markdown": "![foo][bar]\n\n[bar]: /url\n",
"html": "
\n",
- "example": 578,
- "start_line": 8568,
- "end_line": 8574,
+ "example": 581,
+ "start_line": 8615,
+ "end_line": 8621,
"section": "Images"
},
{
"markdown": "![foo][bar]\n\n[BAR]: /url\n",
"html": "
\n",
- "example": 579,
- "start_line": 8577,
- "end_line": 8583,
+ "example": 582,
+ "start_line": 8624,
+ "end_line": 8630,
"section": "Images"
},
{
"markdown": "![foo][]\n\n[foo]: /url \"title\"\n",
"html": "
\n",
- "example": 580,
- "start_line": 8588,
- "end_line": 8594,
+ "example": 583,
+ "start_line": 8635,
+ "end_line": 8641,
"section": "Images"
},
{
"markdown": "![*foo* bar][]\n\n[*foo* bar]: /url \"title\"\n",
"html": "
\n",
- "example": 581,
- "start_line": 8597,
- "end_line": 8603,
+ "example": 584,
+ "start_line": 8644,
+ "end_line": 8650,
"section": "Images"
},
{
"markdown": "![Foo][]\n\n[foo]: /url \"title\"\n",
"html": "
\n",
- "example": 582,
- "start_line": 8608,
- "end_line": 8614,
+ "example": 585,
+ "start_line": 8655,
+ "end_line": 8661,
"section": "Images"
},
{
"markdown": "![foo] \n[]\n\n[foo]: /url \"title\"\n",
"html": "
\n[]
\n",
- "example": 583,
- "start_line": 8620,
- "end_line": 8628,
+ "example": 586,
+ "start_line": 8667,
+ "end_line": 8675,
"section": "Images"
},
{
"markdown": "![foo]\n\n[foo]: /url \"title\"\n",
"html": "
\n",
- "example": 584,
- "start_line": 8633,
- "end_line": 8639,
+ "example": 587,
+ "start_line": 8680,
+ "end_line": 8686,
"section": "Images"
},
{
"markdown": "![*foo* bar]\n\n[*foo* bar]: /url \"title\"\n",
"html": "
\n",
- "example": 585,
- "start_line": 8642,
- "end_line": 8648,
+ "example": 588,
+ "start_line": 8689,
+ "end_line": 8695,
"section": "Images"
},
{
"markdown": "![[foo]]\n\n[[foo]]: /url \"title\"\n",
"html": "![[foo]]
\n[[foo]]: /url "title"
\n",
- "example": 586,
- "start_line": 8653,
- "end_line": 8660,
+ "example": 589,
+ "start_line": 8700,
+ "end_line": 8707,
"section": "Images"
},
{
"markdown": "![Foo]\n\n[foo]: /url \"title\"\n",
"html": "
\n",
- "example": 587,
- "start_line": 8665,
- "end_line": 8671,
+ "example": 590,
+ "start_line": 8712,
+ "end_line": 8718,
"section": "Images"
},
{
"markdown": "!\\[foo]\n\n[foo]: /url \"title\"\n",
"html": "![foo]
\n",
- "example": 588,
- "start_line": 8677,
- "end_line": 8683,
+ "example": 591,
+ "start_line": 8724,
+ "end_line": 8730,
"section": "Images"
},
{
"markdown": "\\![foo]\n\n[foo]: /url \"title\"\n",
"html": "!foo
\n",
- "example": 589,
- "start_line": 8689,
- "end_line": 8695,
+ "example": 592,
+ "start_line": 8736,
+ "end_line": 8742,
"section": "Images"
},
{
"markdown": "\n",
"html": "\n",
- "example": 590,
- "start_line": 8722,
- "end_line": 8726,
+ "example": 593,
+ "start_line": 8769,
+ "end_line": 8773,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "http://foo.bar.baz/test?q=hello&id=22&boolean
\n",
- "example": 591,
- "start_line": 8729,
- "end_line": 8733,
+ "example": 594,
+ "start_line": 8776,
+ "end_line": 8780,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 592,
- "start_line": 8736,
- "end_line": 8740,
+ "example": 595,
+ "start_line": 8783,
+ "end_line": 8787,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 593,
- "start_line": 8745,
- "end_line": 8749,
+ "example": 596,
+ "start_line": 8792,
+ "end_line": 8796,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 594,
- "start_line": 8757,
- "end_line": 8761,
+ "example": 597,
+ "start_line": 8804,
+ "end_line": 8808,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 595,
- "start_line": 8764,
- "end_line": 8768,
+ "example": 598,
+ "start_line": 8811,
+ "end_line": 8815,
"section": "Autolinks"
},
{
"markdown": " \n",
"html": "\n",
- "example": 596,
- "start_line": 8771,
- "end_line": 8775,
+ "example": 599,
+ "start_line": 8818,
+ "end_line": 8822,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 597,
- "start_line": 8778,
- "end_line": 8782,
+ "example": 600,
+ "start_line": 8825,
+ "end_line": 8829,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "<http://foo.bar/baz bim>
\n",
- "example": 598,
- "start_line": 8787,
- "end_line": 8791,
+ "example": 601,
+ "start_line": 8834,
+ "end_line": 8838,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 599,
- "start_line": 8796,
- "end_line": 8800,
+ "example": 602,
+ "start_line": 8843,
+ "end_line": 8847,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 600,
- "start_line": 8818,
- "end_line": 8822,
+ "example": 603,
+ "start_line": 8865,
+ "end_line": 8869,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 601,
- "start_line": 8825,
- "end_line": 8829,
+ "example": 604,
+ "start_line": 8872,
+ "end_line": 8876,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "<foo+@bar.example.com>
\n",
- "example": 602,
- "start_line": 8834,
- "end_line": 8838,
+ "example": 605,
+ "start_line": 8881,
+ "end_line": 8885,
"section": "Autolinks"
},
{
"markdown": "<>\n",
"html": "<>
\n",
- "example": 603,
- "start_line": 8843,
- "end_line": 8847,
+ "example": 606,
+ "start_line": 8890,
+ "end_line": 8894,
"section": "Autolinks"
},
{
"markdown": "< http://foo.bar >\n",
"html": "< http://foo.bar >
\n",
- "example": 604,
- "start_line": 8850,
- "end_line": 8854,
+ "example": 607,
+ "start_line": 8897,
+ "end_line": 8901,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "<m:abc>
\n",
- "example": 605,
- "start_line": 8857,
- "end_line": 8861,
+ "example": 608,
+ "start_line": 8904,
+ "end_line": 8908,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "<foo.bar.baz>
\n",
- "example": 606,
- "start_line": 8864,
- "end_line": 8868,
+ "example": 609,
+ "start_line": 8911,
+ "end_line": 8915,
"section": "Autolinks"
},
{
"markdown": "http://example.com\n",
"html": "http://example.com
\n",
- "example": 607,
- "start_line": 8871,
- "end_line": 8875,
+ "example": 610,
+ "start_line": 8918,
+ "end_line": 8922,
"section": "Autolinks"
},
{
"markdown": "foo@bar.example.com\n",
"html": "foo@bar.example.com
\n",
- "example": 608,
- "start_line": 8878,
- "end_line": 8882,
+ "example": 611,
+ "start_line": 8925,
+ "end_line": 8929,
"section": "Autolinks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 609,
- "start_line": 8960,
- "end_line": 8964,
+ "example": 612,
+ "start_line": 9006,
+ "end_line": 9010,
"section": "Raw HTML"
},
{
"markdown": " \n",
"html": "\n",
- "example": 610,
- "start_line": 8969,
- "end_line": 8973,
+ "example": 613,
+ "start_line": 9015,
+ "end_line": 9019,
"section": "Raw HTML"
},
{
"markdown": "\n",
"html": "\n",
- "example": 611,
- "start_line": 8978,
- "end_line": 8984,
+ "example": 614,
+ "start_line": 9024,
+ "end_line": 9030,
"section": "Raw HTML"
},
{
"markdown": "\n",
"html": "\n",
- "example": 612,
- "start_line": 8989,
- "end_line": 8995,
+ "example": 615,
+ "start_line": 9035,
+ "end_line": 9041,
"section": "Raw HTML"
},
{
"markdown": "Foo \n",
"html": "Foo
\n",
- "example": 613,
- "start_line": 9000,
- "end_line": 9004,
+ "example": 616,
+ "start_line": 9046,
+ "end_line": 9050,
"section": "Raw HTML"
},
{
"markdown": "<33> <__>\n",
"html": "<33> <__>
\n",
- "example": 614,
- "start_line": 9009,
- "end_line": 9013,
+ "example": 617,
+ "start_line": 9055,
+ "end_line": 9059,
"section": "Raw HTML"
},
{
"markdown": "\n",
"html": "<a h*#ref="hi">
\n",
- "example": 615,
- "start_line": 9018,
- "end_line": 9022,
+ "example": 618,
+ "start_line": 9064,
+ "end_line": 9068,
"section": "Raw HTML"
},
{
"markdown": " \n",
"html": "<a href="hi'> <a href=hi'>
\n",
- "example": 616,
- "start_line": 9027,
- "end_line": 9031,
+ "example": 619,
+ "start_line": 9073,
+ "end_line": 9077,
"section": "Raw HTML"
},
{
"markdown": "< a><\nfoo>\n \n",
"html": "< a><\nfoo><bar/ >\n<foo bar=baz\nbim!bop />
\n",
- "example": 617,
- "start_line": 9036,
- "end_line": 9046,
+ "example": 620,
+ "start_line": 9082,
+ "end_line": 9092,
"section": "Raw HTML"
},
{
"markdown": "\n",
"html": "<a href='bar'title=title>
\n",
- "example": 618,
- "start_line": 9051,
- "end_line": 9055,
+ "example": 621,
+ "start_line": 9097,
+ "end_line": 9101,
"section": "Raw HTML"
},
{
"markdown": " \n",
"html": " \n",
- "example": 619,
- "start_line": 9060,
- "end_line": 9064,
+ "example": 622,
+ "start_line": 9106,
+ "end_line": 9110,
"section": "Raw HTML"
},
{
"markdown": "\n",
"html": "</a href="foo">
\n",
- "example": 620,
- "start_line": 9069,
- "end_line": 9073,
+ "example": 623,
+ "start_line": 9115,
+ "end_line": 9119,
"section": "Raw HTML"
},
{
"markdown": "foo \n",
"html": "foo
\n",
- "example": 621,
- "start_line": 9078,
- "end_line": 9084,
+ "example": 624,
+ "start_line": 9124,
+ "end_line": 9130,
"section": "Raw HTML"
},
{
"markdown": "foo \n",
"html": "foo <!-- not a comment -- two hyphens -->
\n",
- "example": 622,
- "start_line": 9087,
- "end_line": 9091,
+ "example": 625,
+ "start_line": 9133,
+ "end_line": 9137,
"section": "Raw HTML"
},
{
"markdown": "foo foo -->\n\nfoo \n",
"html": "foo <!--> foo -->
\nfoo <!-- foo--->
\n",
- "example": 623,
- "start_line": 9096,
- "end_line": 9103,
+ "example": 626,
+ "start_line": 9142,
+ "end_line": 9149,
"section": "Raw HTML"
},
{
"markdown": "foo \n",
"html": "foo
\n",
- "example": 624,
- "start_line": 9108,
- "end_line": 9112,
+ "example": 627,
+ "start_line": 9154,
+ "end_line": 9158,
"section": "Raw HTML"
},
{
"markdown": "foo \n",
"html": "foo
\n",
- "example": 625,
- "start_line": 9117,
- "end_line": 9121,
+ "example": 628,
+ "start_line": 9163,
+ "end_line": 9167,
"section": "Raw HTML"
},
{
"markdown": "foo &<]]>\n",
"html": "foo &<]]>
\n",
- "example": 626,
- "start_line": 9126,
- "end_line": 9130,
+ "example": 629,
+ "start_line": 9172,
+ "end_line": 9176,
"section": "Raw HTML"
},
{
"markdown": "foo \n",
"html": "\n",
- "example": 627,
- "start_line": 9136,
- "end_line": 9140,
+ "example": 630,
+ "start_line": 9182,
+ "end_line": 9186,
"section": "Raw HTML"
},
{
"markdown": "foo \n",
"html": "\n",
- "example": 628,
- "start_line": 9145,
- "end_line": 9149,
+ "example": 631,
+ "start_line": 9191,
+ "end_line": 9195,
"section": "Raw HTML"
},
{
"markdown": "\n",
"html": "<a href=""">
\n",
- "example": 629,
- "start_line": 9152,
- "end_line": 9156,
+ "example": 632,
+ "start_line": 9198,
+ "end_line": 9202,
"section": "Raw HTML"
},
{
"markdown": "foo \nbaz\n",
"html": "foo
\nbaz
\n",
- "example": 630,
- "start_line": 9166,
- "end_line": 9172,
+ "example": 633,
+ "start_line": 9212,
+ "end_line": 9218,
"section": "Hard line breaks"
},
{
"markdown": "foo\\\nbaz\n",
"html": "foo
\nbaz
\n",
- "example": 631,
- "start_line": 9178,
- "end_line": 9184,
+ "example": 634,
+ "start_line": 9224,
+ "end_line": 9230,
"section": "Hard line breaks"
},
{
"markdown": "foo \nbaz\n",
"html": "foo
\nbaz
\n",
- "example": 632,
- "start_line": 9189,
- "end_line": 9195,
+ "example": 635,
+ "start_line": 9235,
+ "end_line": 9241,
"section": "Hard line breaks"
},
{
"markdown": "foo \n bar\n",
"html": "foo
\nbar
\n",
- "example": 633,
- "start_line": 9200,
- "end_line": 9206,
+ "example": 636,
+ "start_line": 9246,
+ "end_line": 9252,
"section": "Hard line breaks"
},
{
"markdown": "foo\\\n bar\n",
"html": "foo
\nbar
\n",
- "example": 634,
- "start_line": 9209,
- "end_line": 9215,
+ "example": 637,
+ "start_line": 9255,
+ "end_line": 9261,
"section": "Hard line breaks"
},
{
"markdown": "*foo \nbar*\n",
"html": "foo
\nbar
\n",
- "example": 635,
- "start_line": 9221,
- "end_line": 9227,
+ "example": 638,
+ "start_line": 9267,
+ "end_line": 9273,
"section": "Hard line breaks"
},
{
"markdown": "*foo\\\nbar*\n",
"html": "foo
\nbar
\n",
- "example": 636,
- "start_line": 9230,
- "end_line": 9236,
+ "example": 639,
+ "start_line": 9276,
+ "end_line": 9282,
"section": "Hard line breaks"
},
{
- "markdown": "`code \nspan`\n",
- "html": "code span
\n",
- "example": 637,
- "start_line": 9241,
- "end_line": 9246,
+ "markdown": "`code \nspan`\n",
+ "html": "code span
\n",
+ "example": 640,
+ "start_line": 9287,
+ "end_line": 9292,
"section": "Hard line breaks"
},
{
"markdown": "`code\\\nspan`\n",
"html": "code\\ span
\n",
- "example": 638,
- "start_line": 9249,
- "end_line": 9254,
+ "example": 641,
+ "start_line": 9295,
+ "end_line": 9300,
"section": "Hard line breaks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 639,
- "start_line": 9259,
- "end_line": 9265,
+ "example": 642,
+ "start_line": 9305,
+ "end_line": 9311,
"section": "Hard line breaks"
},
{
"markdown": "\n",
"html": "\n",
- "example": 640,
- "start_line": 9268,
- "end_line": 9274,
+ "example": 643,
+ "start_line": 9314,
+ "end_line": 9320,
"section": "Hard line breaks"
},
{
"markdown": "foo\\\n",
"html": "foo\\
\n",
- "example": 641,
- "start_line": 9281,
- "end_line": 9285,
+ "example": 644,
+ "start_line": 9327,
+ "end_line": 9331,
"section": "Hard line breaks"
},
{
"markdown": "foo \n",
"html": "foo
\n",
- "example": 642,
- "start_line": 9288,
- "end_line": 9292,
+ "example": 645,
+ "start_line": 9334,
+ "end_line": 9338,
"section": "Hard line breaks"
},
{
"markdown": "### foo\\\n",
"html": "foo\\
\n",
- "example": 643,
- "start_line": 9295,
- "end_line": 9299,
+ "example": 646,
+ "start_line": 9341,
+ "end_line": 9345,
"section": "Hard line breaks"
},
{
"markdown": "### foo \n",
"html": "foo
\n",
- "example": 644,
- "start_line": 9302,
- "end_line": 9306,
+ "example": 647,
+ "start_line": 9348,
+ "end_line": 9352,
"section": "Hard line breaks"
},
{
"markdown": "foo\nbaz\n",
"html": "foo\nbaz
\n",
- "example": 645,
- "start_line": 9317,
- "end_line": 9323,
+ "example": 648,
+ "start_line": 9363,
+ "end_line": 9369,
"section": "Soft line breaks"
},
{
"markdown": "foo \n baz\n",
"html": "foo\nbaz
\n",
- "example": 646,
- "start_line": 9329,
- "end_line": 9335,
+ "example": 649,
+ "start_line": 9375,
+ "end_line": 9381,
"section": "Soft line breaks"
},
{
"markdown": "hello $.;'there\n",
"html": "hello $.;'there
\n",
- "example": 647,
- "start_line": 9349,
- "end_line": 9353,
+ "example": 650,
+ "start_line": 9395,
+ "end_line": 9399,
"section": "Textual content"
},
{
"markdown": "Foo χρῆν\n",
"html": "Foo χρῆν
\n",
- "example": 648,
- "start_line": 9356,
- "end_line": 9360,
+ "example": 651,
+ "start_line": 9402,
+ "end_line": 9406,
"section": "Textual content"
},
{
"markdown": "Multiple spaces\n",
"html": "Multiple spaces
\n",
- "example": 649,
- "start_line": 9365,
- "end_line": 9369,
+ "example": 652,
+ "start_line": 9411,
+ "end_line": 9415,
"section": "Textual content"
}
]
Index: testdata/meta/title/20200310110300.zettel
==================================================================
--- testdata/meta/title/20200310110300.zettel
+++ testdata/meta/title/20200310110300.zettel
@@ -1,1 +1,1 @@
-title: A ""Title"" with //Markup//, ``Zettelmarkup``{=zmk}
+title: A ""Title"" with __Markup__, ``Zettelmarkup``{=zmk}
DELETED testdata/mustache/comments.json
Index: testdata/mustache/comments.json
==================================================================
--- testdata/mustache/comments.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Comment tags represent content that should never appear in the resulting\noutput.\n\nThe tag's content may contain any substring (including newlines) EXCEPT the\nclosing delimiter.\n\nComment tags SHOULD be treated as standalone when appropriate.\n","tests":[{"name":"Inline","data":{},"expected":"1234567890","template":"12345{{! Comment Block! }}67890","desc":"Comment blocks should be removed from the template."},{"name":"Multiline","data":{},"expected":"1234567890\n","template":"12345{{!\n This is a\n multi-line comment...\n}}67890\n","desc":"Multiline comments should be permitted."},{"name":"Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n{{! Comment Block! }}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Indented Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n {{! Indented Comment Block! }}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Standalone Line Endings","data":{},"expected":"|\r\n|","template":"|\r\n{{! Standalone Comment }}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{},"expected":"!","template":" {{! I'm Still Standalone }}\n!","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{},"expected":"!\n","template":"!\n {{! I'm Still Standalone }}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Multiline Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n{{!\nSomething's going on here...\n}}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Indented Multiline Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n {{!\n Something's going on here...\n }}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Indented Inline","data":{},"expected":" 12 \n","template":" 12 {{! 34 }}\n","desc":"Inline comments should not strip whitespace"},{"name":"Surrounding Whitespace","data":{},"expected":"12345 67890","template":"12345 {{! Comment Block! }} 67890","desc":"Comment removal should preserve surrounding whitespace."}]}
DELETED testdata/mustache/delimiters.json
Index: testdata/mustache/delimiters.json
==================================================================
--- testdata/mustache/delimiters.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Set Delimiter tags are used to change the tag delimiters for all content\nfollowing the tag in the current compilation unit.\n\nThe tag's content MUST be any two non-whitespace sequences (separated by\nwhitespace) EXCEPT an equals sign ('=') followed by the current closing\ndelimiter.\n\nSet Delimiter tags SHOULD be treated as standalone when appropriate.\n","tests":[{"name":"Pair Behavior","data":{"text":"Hey!"},"expected":"(Hey!)","template":"{{=<% %>=}}(<%text%>)","desc":"The equals sign (used on both sides) should permit delimiter changes."},{"name":"Special Characters","data":{"text":"It worked!"},"expected":"(It worked!)","template":"({{=[ ]=}}[text])","desc":"Characters with special meaning regexen should be valid delimiters."},{"name":"Sections","data":{"section":true,"data":"I got interpolated."},"expected":"[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n","template":"[\n{{#section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|#section|\n {{data}}\n |data|\n|/section|\n]\n","desc":"Delimiters set outside sections should persist."},{"name":"Inverted Sections","data":{"section":false,"data":"I got interpolated."},"expected":"[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n","template":"[\n{{^section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|^section|\n {{data}}\n |data|\n|/section|\n]\n","desc":"Delimiters set outside inverted sections should persist."},{"name":"Partial Inheritence","data":{"value":"yes"},"expected":"[ .yes. ]\n[ .yes. ]\n","template":"[ {{>include}} ]\n{{= | | =}}\n[ |>include| ]\n","desc":"Delimiters set in a parent template should not affect a partial.","partials":{"include":".{{value}}."}},{"name":"Post-Partial Behavior","data":{"value":"yes"},"expected":"[ .yes. .yes. ]\n[ .yes. .|value|. ]\n","template":"[ {{>include}} ]\n[ .{{value}}. .|value|. ]\n","desc":"Delimiters set in a partial should not affect the parent template.","partials":{"include":".{{value}}. {{= | | =}} .|value|."}},{"name":"Surrounding Whitespace","data":{},"expected":"| |","template":"| {{=@ @=}} |","desc":"Surrounding whitespace should be left untouched."},{"name":"Outlying Whitespace (Inline)","data":{},"expected":" | \n","template":" | {{=@ @=}}\n","desc":"Whitespace should be left untouched."},{"name":"Standalone Tag","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n{{=@ @=}}\nEnd.\n","desc":"Standalone lines should be removed from the template."},{"name":"Indented Standalone Tag","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n {{=@ @=}}\nEnd.\n","desc":"Indented standalone lines should be removed from the template."},{"name":"Standalone Line Endings","data":{},"expected":"|\r\n|","template":"|\r\n{{= @ @ =}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{},"expected":"=","template":" {{=@ @=}}\n=","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{},"expected":"=\n","template":"=\n {{=@ @=}}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Pair with Padding","data":{},"expected":"||","template":"|{{= @ @ =}}|","desc":"Superfluous in-tag whitespace should be ignored."}]}
DELETED testdata/mustache/interpolation.json
Index: testdata/mustache/interpolation.json
==================================================================
--- testdata/mustache/interpolation.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Interpolation tags are used to integrate dynamic content into the template.\n\nThe tag's content MUST be a non-whitespace character sequence NOT containing\nthe current closing delimiter.\n\nThis tag's content names the data to replace the tag. A single period (`.`)\nindicates that the item currently sitting atop the context stack should be\nused; otherwise, name resolution is as follows:\n 1) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 2) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 3) If the context is a hash, the data is the value associated with the\n name.\n 4) If the context is an object, the data is the value returned by the\n method with the given name.\n 5) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\nData should be coerced into a string (and escaped, if appropriate) before\ninterpolation.\n\nThe Interpolation tags MUST NOT be treated as standalone.\n","tests":[{"name":"No Interpolation","data":{},"expected":"Hello from {Mustache}!\n","template":"Hello from {Mustache}!\n","desc":"Mustache-free templates should render as-is."},{"name":"Basic Interpolation","data":{"subject":"world"},"expected":"Hello, world!\n","template":"Hello, {{subject}}!\n","desc":"Unadorned tags should interpolate content into the template."},{"name":"HTML Escaping","data":{"forbidden":"& \" < >"},"expected":"These characters should be HTML escaped: & " < >\n","template":"These characters should be HTML escaped: {{forbidden}}\n","desc":"Basic interpolation should be HTML escaped."},{"name":"Triple Mustache","data":{"forbidden":"& \" < >"},"expected":"These characters should not be HTML escaped: & \" < >\n","template":"These characters should not be HTML escaped: {{{forbidden}}}\n","desc":"Triple mustaches should interpolate without HTML escaping."},{"name":"Ampersand","data":{"forbidden":"& \" < >"},"expected":"These characters should not be HTML escaped: & \" < >\n","template":"These characters should not be HTML escaped: {{&forbidden}}\n","desc":"Ampersand should interpolate without HTML escaping."},{"name":"Basic Integer Interpolation","data":{"mph":85},"expected":"\"85 miles an hour!\"","template":"\"{{mph}} miles an hour!\"","desc":"Integers should interpolate seamlessly."},{"name":"Triple Mustache Integer Interpolation","data":{"mph":85},"expected":"\"85 miles an hour!\"","template":"\"{{{mph}}} miles an hour!\"","desc":"Integers should interpolate seamlessly."},{"name":"Ampersand Integer Interpolation","data":{"mph":85},"expected":"\"85 miles an hour!\"","template":"\"{{&mph}} miles an hour!\"","desc":"Integers should interpolate seamlessly."},{"name":"Basic Decimal Interpolation","data":{"power":1.21},"expected":"\"1.21 jiggawatts!\"","template":"\"{{power}} jiggawatts!\"","desc":"Decimals should interpolate seamlessly with proper significance."},{"name":"Triple Mustache Decimal Interpolation","data":{"power":1.21},"expected":"\"1.21 jiggawatts!\"","template":"\"{{{power}}} jiggawatts!\"","desc":"Decimals should interpolate seamlessly with proper significance."},{"name":"Ampersand Decimal Interpolation","data":{"power":1.21},"expected":"\"1.21 jiggawatts!\"","template":"\"{{&power}} jiggawatts!\"","desc":"Decimals should interpolate seamlessly with proper significance."},{"name":"Basic Context Miss Interpolation","data":{},"expected":"I () be seen!","template":"I ({{cannot}}) be seen!","desc":"Failed context lookups should default to empty strings."},{"name":"Triple Mustache Context Miss Interpolation","data":{},"expected":"I () be seen!","template":"I ({{{cannot}}}) be seen!","desc":"Failed context lookups should default to empty strings."},{"name":"Ampersand Context Miss Interpolation","data":{},"expected":"I () be seen!","template":"I ({{&cannot}}) be seen!","desc":"Failed context lookups should default to empty strings."},{"name":"Dotted Names - Basic Interpolation","data":{"person":{"name":"Joe"}},"expected":"\"Joe\" == \"Joe\"","template":"\"{{person.name}}\" == \"{{#person}}{{name}}{{/person}}\"","desc":"Dotted names should be considered a form of shorthand for sections."},{"name":"Dotted Names - Triple Mustache Interpolation","data":{"person":{"name":"Joe"}},"expected":"\"Joe\" == \"Joe\"","template":"\"{{{person.name}}}\" == \"{{#person}}{{{name}}}{{/person}}\"","desc":"Dotted names should be considered a form of shorthand for sections."},{"name":"Dotted Names - Ampersand Interpolation","data":{"person":{"name":"Joe"}},"expected":"\"Joe\" == \"Joe\"","template":"\"{{&person.name}}\" == \"{{#person}}{{&name}}{{/person}}\"","desc":"Dotted names should be considered a form of shorthand for sections."},{"name":"Dotted Names - Arbitrary Depth","data":{"a":{"b":{"c":{"d":{"e":{"name":"Phil"}}}}}},"expected":"\"Phil\" == \"Phil\"","template":"\"{{a.b.c.d.e.name}}\" == \"Phil\"","desc":"Dotted names should be functional to any level of nesting."},{"name":"Dotted Names - Broken Chains","data":{"a":{}},"expected":"\"\" == \"\"","template":"\"{{a.b.c}}\" == \"\"","desc":"Any falsey value prior to the last part of the name should yield ''."},{"name":"Dotted Names - Broken Chain Resolution","data":{"a":{"b":{}},"c":{"name":"Jim"}},"expected":"\"\" == \"\"","template":"\"{{a.b.c.name}}\" == \"\"","desc":"Each part of a dotted name should resolve only against its parent."},{"name":"Dotted Names - Initial Resolution","data":{"a":{"b":{"c":{"d":{"e":{"name":"Phil"}}}}},"b":{"c":{"d":{"e":{"name":"Wrong"}}}}},"expected":"\"Phil\" == \"Phil\"","template":"\"{{#a}}{{b.c.d.e.name}}{{/a}}\" == \"Phil\"","desc":"The first part of a dotted name should resolve as any other name."},{"name":"Interpolation - Surrounding Whitespace","data":{"string":"---"},"expected":"| --- |","template":"| {{string}} |","desc":"Interpolation should not alter surrounding whitespace."},{"name":"Triple Mustache - Surrounding Whitespace","data":{"string":"---"},"expected":"| --- |","template":"| {{{string}}} |","desc":"Interpolation should not alter surrounding whitespace."},{"name":"Ampersand - Surrounding Whitespace","data":{"string":"---"},"expected":"| --- |","template":"| {{&string}} |","desc":"Interpolation should not alter surrounding whitespace."},{"name":"Interpolation - Standalone","data":{"string":"---"},"expected":" ---\n","template":" {{string}}\n","desc":"Standalone interpolation should not alter surrounding whitespace."},{"name":"Triple Mustache - Standalone","data":{"string":"---"},"expected":" ---\n","template":" {{{string}}}\n","desc":"Standalone interpolation should not alter surrounding whitespace."},{"name":"Ampersand - Standalone","data":{"string":"---"},"expected":" ---\n","template":" {{&string}}\n","desc":"Standalone interpolation should not alter surrounding whitespace."},{"name":"Interpolation With Padding","data":{"string":"---"},"expected":"|---|","template":"|{{ string }}|","desc":"Superfluous in-tag whitespace should be ignored."},{"name":"Triple Mustache With Padding","data":{"string":"---"},"expected":"|---|","template":"|{{{ string }}}|","desc":"Superfluous in-tag whitespace should be ignored."},{"name":"Ampersand With Padding","data":{"string":"---"},"expected":"|---|","template":"|{{& string }}|","desc":"Superfluous in-tag whitespace should be ignored."}]}
DELETED testdata/mustache/inverted.json
Index: testdata/mustache/inverted.json
==================================================================
--- testdata/mustache/inverted.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Inverted Section tags and End Section tags are used in combination to wrap a\nsection of the template.\n\nThese tags' content MUST be a non-whitespace character sequence NOT\ncontaining the current closing delimiter; each Inverted Section tag MUST be\nfollowed by an End Section tag with the same content within the same\nsection.\n\nThis tag's content names the data to replace the tag. Name resolution is as\nfollows:\n 1) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 2) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 3) If the context is a hash, the data is the value associated with the\n name.\n 4) If the context is an object and the method with the given name has an\n arity of 1, the method SHOULD be called with a String containing the\n unprocessed contents of the sections; the data is the value returned.\n 5) Otherwise, the data is the value returned by calling the method with\n the given name.\n 6) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\nIf the data is not of a list type, it is coerced into a list as follows: if\nthe data is truthy (e.g. `!!data == true`), use a single-element list\ncontaining the data, otherwise use an empty list.\n\nThis section MUST NOT be rendered unless the data list is empty.\n\nInverted Section and End Section tags SHOULD be treated as standalone when\nappropriate.\n","tests":[{"name":"Falsey","data":{"boolean":false},"expected":"\"This should be rendered.\"","template":"\"{{^boolean}}This should be rendered.{{/boolean}}\"","desc":"Falsey sections should have their contents rendered."},{"name":"Truthy","data":{"boolean":true},"expected":"\"\"","template":"\"{{^boolean}}This should not be rendered.{{/boolean}}\"","desc":"Truthy sections should have their contents omitted."},{"name":"Context","data":{"context":{"name":"Joe"}},"expected":"\"\"","template":"\"{{^context}}Hi {{name}}.{{/context}}\"","desc":"Objects and hashes should behave like truthy values."},{"name":"List","data":{"list":[{"n":1},{"n":2},{"n":3}]},"expected":"\"\"","template":"\"{{^list}}{{n}}{{/list}}\"","desc":"Lists should behave like truthy values."},{"name":"Empty List","data":{"list":[]},"expected":"\"Yay lists!\"","template":"\"{{^list}}Yay lists!{{/list}}\"","desc":"Empty lists should behave like falsey values."},{"name":"Doubled","data":{"two":"second","bool":false},"expected":"* first\n* second\n* third\n","template":"{{^bool}}\n* first\n{{/bool}}\n* {{two}}\n{{^bool}}\n* third\n{{/bool}}\n","desc":"Multiple inverted sections per template should be permitted."},{"name":"Nested (Falsey)","data":{"bool":false},"expected":"| A B C D E |","template":"| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested falsey sections should have their contents rendered."},{"name":"Nested (Truthy)","data":{"bool":true},"expected":"| A E |","template":"| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested truthy sections should be omitted."},{"name":"Context Misses","data":{},"expected":"[Cannot find key 'missing'!]","template":"[{{^missing}}Cannot find key 'missing'!{{/missing}}]","desc":"Failed context lookups should be considered falsey."},{"name":"Dotted Names - Truthy","data":{"a":{"b":{"c":true}}},"expected":"\"\" == \"\"","template":"\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"\"","desc":"Dotted names should be valid for Inverted Section tags."},{"name":"Dotted Names - Falsey","data":{"a":{"b":{"c":false}}},"expected":"\"Not Here\" == \"Not Here\"","template":"\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"","desc":"Dotted names should be valid for Inverted Section tags."},{"name":"Dotted Names - Broken Chains","data":{"a":{}},"expected":"\"Not Here\" == \"Not Here\"","template":"\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"","desc":"Dotted names that cannot be resolved should be considered falsey."},{"name":"Surrounding Whitespace","data":{"boolean":false},"expected":" | \t|\t | \n","template":" | {{^boolean}}\t|\t{{/boolean}} | \n","desc":"Inverted sections should not alter surrounding whitespace."},{"name":"Internal Whitespace","data":{"boolean":false},"expected":" | \n | \n","template":" | {{^boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n","desc":"Inverted should not alter internal whitespace."},{"name":"Indented Inline Sections","data":{"boolean":false},"expected":" NO\n WAY\n","template":" {{^boolean}}NO{{/boolean}}\n {{^boolean}}WAY{{/boolean}}\n","desc":"Single-line sections should not alter surrounding whitespace."},{"name":"Standalone Lines","data":{"boolean":false},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n{{^boolean}}\n|\n{{/boolean}}\n| A Line\n","desc":"Standalone lines should be removed from the template."},{"name":"Standalone Indented Lines","data":{"boolean":false},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n {{^boolean}}\n|\n {{/boolean}}\n| A Line\n","desc":"Standalone indented lines should be removed from the template."},{"name":"Standalone Line Endings","data":{"boolean":false},"expected":"|\r\n|","template":"|\r\n{{^boolean}}\r\n{{/boolean}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{"boolean":false},"expected":"^\n/","template":" {{^boolean}}\n^{{/boolean}}\n/","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{"boolean":false},"expected":"^\n/\n","template":"^{{^boolean}}\n/\n {{/boolean}}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Padding","data":{"boolean":false},"expected":"|=|","template":"|{{^ boolean }}={{/ boolean }}|","desc":"Superfluous in-tag whitespace should be ignored."}]}
DELETED testdata/mustache/partials.json
Index: testdata/mustache/partials.json
==================================================================
--- testdata/mustache/partials.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Partial tags are used to expand an external template into the current\ntemplate.\n\nThe tag's content MUST be a non-whitespace character sequence NOT containing\nthe current closing delimiter.\n\nThis tag's content names the partial to inject. Set Delimiter tags MUST NOT\naffect the parsing of a partial. The partial MUST be rendered against the\ncontext stack local to the tag. If the named partial cannot be found, the\nempty string SHOULD be used instead, as in interpolations.\n\nPartial tags SHOULD be treated as standalone when appropriate. If this tag\nis used standalone, any whitespace preceding the tag should treated as\nindentation, and prepended to each line of the partial before rendering.\n","tests":[{"name":"Basic Behavior","data":{},"expected":"\"from partial\"","template":"\"{{>text}}\"","desc":"The greater-than operator should expand to the named partial.","partials":{"text":"from partial"}},{"name":"Failed Lookup","data":{},"expected":"\"\"","template":"\"{{>text}}\"","desc":"The empty string should be used when the named partial is not found.","partials":{}},{"name":"Context","data":{"text":"content"},"expected":"\"*content*\"","template":"\"{{>partial}}\"","desc":"The greater-than operator should operate within the current context.","partials":{"partial":"*{{text}}*"}},{"name":"Recursion","data":{"content":"X","nodes":[{"content":"Y","nodes":[]}]},"expected":"X>","template":"{{>node}}","desc":"The greater-than operator should properly recurse.","partials":{"node":"{{content}}<{{#nodes}}{{>node}}{{/nodes}}>"}},{"name":"Surrounding Whitespace","data":{},"expected":"| \t|\t |","template":"| {{>partial}} |","desc":"The greater-than operator should not alter surrounding whitespace.","partials":{"partial":"\t|\t"}},{"name":"Inline Indentation","data":{"data":"|"},"expected":" | >\n>\n","template":" {{data}} {{> partial}}\n","desc":"Whitespace should be left untouched.","partials":{"partial":">\n>"}},{"name":"Standalone Line Endings","data":{},"expected":"|\r\n>|","template":"|\r\n{{>partial}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags.","partials":{"partial":">"}},{"name":"Standalone Without Previous Line","data":{},"expected":" >\n >>","template":" {{>partial}}\n>","desc":"Standalone tags should not require a newline to precede them.","partials":{"partial":">\n>"}},{"name":"Standalone Without Newline","data":{},"expected":">\n >\n >","template":">\n {{>partial}}","desc":"Standalone tags should not require a newline to follow them.","partials":{"partial":">\n>"}},{"name":"Standalone Indentation","data":{"content":"<\n->"},"expected":"\\\n |\n <\n->\n |\n/\n","template":"\\\n {{>partial}}\n/\n","desc":"Each line of the partial should be indented before rendering.","partials":{"partial":"|\n{{{content}}}\n|\n"}},{"name":"Padding Whitespace","data":{"boolean":true},"expected":"|[]|","template":"|{{> partial }}|","desc":"Superfluous in-tag whitespace should be ignored.","partials":{"partial":"[]"}}]}
DELETED testdata/mustache/sections.json
Index: testdata/mustache/sections.json
==================================================================
--- testdata/mustache/sections.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Section tags and End Section tags are used in combination to wrap a section\nof the template for iteration\n\nThese tags' content MUST be a non-whitespace character sequence NOT\ncontaining the current closing delimiter; each Section tag MUST be followed\nby an End Section tag with the same content within the same section.\n\nThis tag's content names the data to replace the tag. Name resolution is as\nfollows:\n 1) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 2) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 3) If the context is a hash, the data is the value associated with the\n name.\n 4) If the context is an object and the method with the given name has an\n arity of 1, the method SHOULD be called with a String containing the\n unprocessed contents of the sections; the data is the value returned.\n 5) Otherwise, the data is the value returned by calling the method with\n the given name.\n 6) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\nIf the data is not of a list type, it is coerced into a list as follows: if\nthe data is truthy (e.g. `!!data == true`), use a single-element list\ncontaining the data, otherwise use an empty list.\n\nFor each element in the data list, the element MUST be pushed onto the\ncontext stack, the section MUST be rendered, and the element MUST be popped\noff the context stack.\n\nSection and End Section tags SHOULD be treated as standalone when\nappropriate.\n","tests":[{"name":"Truthy","data":{"boolean":true},"expected":"\"This should be rendered.\"","template":"\"{{#boolean}}This should be rendered.{{/boolean}}\"","desc":"Truthy sections should have their contents rendered."},{"name":"Falsey","data":{"boolean":false},"expected":"\"\"","template":"\"{{#boolean}}This should not be rendered.{{/boolean}}\"","desc":"Falsey sections should have their contents omitted."},{"name":"Context","data":{"context":{"name":"Joe"}},"expected":"\"Hi Joe.\"","template":"\"{{#context}}Hi {{name}}.{{/context}}\"","desc":"Objects and hashes should be pushed onto the context stack."},{"name":"Deeply Nested Contexts","data":{"a":{"one":1},"b":{"two":2},"c":{"three":3},"d":{"four":4},"e":{"five":5}},"expected":"1\n121\n12321\n1234321\n123454321\n1234321\n12321\n121\n1\n","template":"{{#a}}\n{{one}}\n{{#b}}\n{{one}}{{two}}{{one}}\n{{#c}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{#d}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{#e}}\n{{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}}\n{{/e}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{/d}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{/c}}\n{{one}}{{two}}{{one}}\n{{/b}}\n{{one}}\n{{/a}}\n","desc":"All elements on the context stack should be accessible."},{"name":"List","data":{"list":[{"item":1},{"item":2},{"item":3}]},"expected":"\"123\"","template":"\"{{#list}}{{item}}{{/list}}\"","desc":"Lists should be iterated; list items should visit the context stack."},{"name":"Empty List","data":{"list":[]},"expected":"\"\"","template":"\"{{#list}}Yay lists!{{/list}}\"","desc":"Empty lists should behave like falsey values."},{"name":"Doubled","data":{"two":"second","bool":true},"expected":"* first\n* second\n* third\n","template":"{{#bool}}\n* first\n{{/bool}}\n* {{two}}\n{{#bool}}\n* third\n{{/bool}}\n","desc":"Multiple sections per template should be permitted."},{"name":"Nested (Truthy)","data":{"bool":true},"expected":"| A B C D E |","template":"| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested truthy sections should have their contents rendered."},{"name":"Nested (Falsey)","data":{"bool":false},"expected":"| A E |","template":"| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested falsey sections should be omitted."},{"name":"Context Misses","data":{},"expected":"[]","template":"[{{#missing}}Found key 'missing'!{{/missing}}]","desc":"Failed context lookups should be considered falsey."},{"name":"Implicit Iterator - String","data":{"list":["a","b","c","d","e"]},"expected":"\"(a)(b)(c)(d)(e)\"","template":"\"{{#list}}({{.}}){{/list}}\"","desc":"Implicit iterators should directly interpolate strings."},{"name":"Implicit Iterator - Integer","data":{"list":[1,2,3,4,5]},"expected":"\"(1)(2)(3)(4)(5)\"","template":"\"{{#list}}({{.}}){{/list}}\"","desc":"Implicit iterators should cast integers to strings and interpolate."},{"name":"Implicit Iterator - Decimal","data":{"list":[1.1,2.2,3.3,4.4,5.5]},"expected":"\"(1.1)(2.2)(3.3)(4.4)(5.5)\"","template":"\"{{#list}}({{.}}){{/list}}\"","desc":"Implicit iterators should cast decimals to strings and interpolate."},{"name":"Implicit Iterator - Array","desc":"Implicit iterators should allow iterating over nested arrays.","data":{"list":[[1,2,3],["a","b","c"]]},"template":"\"{{#list}}({{#.}}{{.}}{{/.}}){{/list}}\"","expected":"\"(123)(abc)\""},{"name":"Dotted Names - Truthy","data":{"a":{"b":{"c":true}}},"expected":"\"Here\" == \"Here\"","template":"\"{{#a.b.c}}Here{{/a.b.c}}\" == \"Here\"","desc":"Dotted names should be valid for Section tags."},{"name":"Dotted Names - Falsey","data":{"a":{"b":{"c":false}}},"expected":"\"\" == \"\"","template":"\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"","desc":"Dotted names should be valid for Section tags."},{"name":"Dotted Names - Broken Chains","data":{"a":{}},"expected":"\"\" == \"\"","template":"\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"","desc":"Dotted names that cannot be resolved should be considered falsey."},{"name":"Surrounding Whitespace","data":{"boolean":true},"expected":" | \t|\t | \n","template":" | {{#boolean}}\t|\t{{/boolean}} | \n","desc":"Sections should not alter surrounding whitespace."},{"name":"Internal Whitespace","data":{"boolean":true},"expected":" | \n | \n","template":" | {{#boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n","desc":"Sections should not alter internal whitespace."},{"name":"Indented Inline Sections","data":{"boolean":true},"expected":" YES\n GOOD\n","template":" {{#boolean}}YES{{/boolean}}\n {{#boolean}}GOOD{{/boolean}}\n","desc":"Single-line sections should not alter surrounding whitespace."},{"name":"Standalone Lines","data":{"boolean":true},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n{{#boolean}}\n|\n{{/boolean}}\n| A Line\n","desc":"Standalone lines should be removed from the template."},{"name":"Indented Standalone Lines","data":{"boolean":true},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n {{#boolean}}\n|\n {{/boolean}}\n| A Line\n","desc":"Indented standalone lines should be removed from the template."},{"name":"Standalone Line Endings","data":{"boolean":true},"expected":"|\r\n|","template":"|\r\n{{#boolean}}\r\n{{/boolean}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{"boolean":true},"expected":"#\n/","template":" {{#boolean}}\n#{{/boolean}}\n/","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{"boolean":true},"expected":"#\n/\n","template":"#{{#boolean}}\n/\n {{/boolean}}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Padding","data":{"boolean":true},"expected":"|=|","template":"|{{# boolean }}={{/ boolean }}|","desc":"Superfluous in-tag whitespace should be ignored."}]}
DELETED testdata/mustache/~lambdas.json
Index: testdata/mustache/~lambdas.json
==================================================================
--- testdata/mustache/~lambdas.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Lambdas are a special-cased data type for use in interpolations and\nsections.\n\nWhen used as the data value for an Interpolation tag, the lambda MUST be\ntreatable as an arity 0 function, and invoked as such. The returned value\nMUST be rendered against the default delimiters, then interpolated in place\nof the lambda.\n\nWhen used as the data value for a Section tag, the lambda MUST be treatable\nas an arity 1 function, and invoked as such (passing a String containing the\nunprocessed section contents). The returned value MUST be rendered against\nthe current delimiters, then interpolated in place of the section.\n","tests":[{"name":"Interpolation","data":{"lambda":{"php":"return \"world\";","clojure":"(fn [] \"world\")","__tag__":"code","perl":"sub { \"world\" }","python":"lambda: \"world\"","ruby":"proc { \"world\" }","js":"function() { return \"world\" }"}},"expected":"Hello, world!","template":"Hello, {{lambda}}!","desc":"A lambda's return value should be interpolated."},{"name":"Interpolation - Expansion","data":{"planet":"world","lambda":{"php":"return \"{{planet}}\";","clojure":"(fn [] \"{{planet}}\")","__tag__":"code","perl":"sub { \"{{planet}}\" }","python":"lambda: \"{{planet}}\"","ruby":"proc { \"{{planet}}\" }","js":"function() { return \"{{planet}}\" }"}},"expected":"Hello, world!","template":"Hello, {{lambda}}!","desc":"A lambda's return value should be parsed."},{"name":"Interpolation - Alternate Delimiters","data":{"planet":"world","lambda":{"php":"return \"|planet| => {{planet}}\";","clojure":"(fn [] \"|planet| => {{planet}}\")","__tag__":"code","perl":"sub { \"|planet| => {{planet}}\" }","python":"lambda: \"|planet| => {{planet}}\"","ruby":"proc { \"|planet| => {{planet}}\" }","js":"function() { return \"|planet| => {{planet}}\" }"}},"expected":"Hello, (|planet| => world)!","template":"{{= | | =}}\nHello, (|&lambda|)!","desc":"A lambda's return value should parse with the default delimiters."},{"name":"Interpolation - Multiple Calls","data":{"lambda":{"php":"global $calls; return ++$calls;","clojure":"(def g (atom 0)) (fn [] (swap! g inc))","__tag__":"code","perl":"sub { no strict; $calls += 1 }","python":"lambda: globals().update(calls=globals().get(\"calls\",0)+1) or calls","ruby":"proc { $calls ||= 0; $calls += 1 }","js":"function() { return (g=(function(){return this})()).calls=(g.calls||0)+1 }"}},"expected":"1 == 2 == 3","template":"{{lambda}} == {{{lambda}}} == {{lambda}}","desc":"Interpolated lambdas should not be cached."},{"name":"Escaping","data":{"lambda":{"php":"return \">\";","clojure":"(fn [] \">\")","__tag__":"code","perl":"sub { \">\" }","python":"lambda: \">\"","ruby":"proc { \">\" }","js":"function() { return \">\" }"}},"expected":"<>>","template":"<{{lambda}}{{{lambda}}}","desc":"Lambda results should be appropriately escaped."},{"name":"Section","data":{"x":"Error!","lambda":{"php":"return ($text == \"{{x}}\") ? \"yes\" : \"no\";","clojure":"(fn [text] (if (= text \"{{x}}\") \"yes\" \"no\"))","__tag__":"code","perl":"sub { $_[0] eq \"{{x}}\" ? \"yes\" : \"no\" }","python":"lambda text: text == \"{{x}}\" and \"yes\" or \"no\"","ruby":"proc { |text| text == \"{{x}}\" ? \"yes\" : \"no\" }","js":"function(txt) { return (txt == \"{{x}}\" ? \"yes\" : \"no\") }"}},"expected":"","template":"<{{#lambda}}{{x}}{{/lambda}}>","desc":"Lambdas used for sections should receive the raw section string."},{"name":"Section - Expansion","data":{"planet":"Earth","lambda":{"php":"return $text . \"{{planet}}\" . $text;","clojure":"(fn [text] (str text \"{{planet}}\" text))","__tag__":"code","perl":"sub { $_[0] . \"{{planet}}\" . $_[0] }","python":"lambda text: \"%s{{planet}}%s\" % (text, text)","ruby":"proc { |text| \"#{text}{{planet}}#{text}\" }","js":"function(txt) { return txt + \"{{planet}}\" + txt }"}},"expected":"<-Earth->","template":"<{{#lambda}}-{{/lambda}}>","desc":"Lambdas used for sections should have their results parsed."},{"name":"Section - Alternate Delimiters","data":{"planet":"Earth","lambda":{"php":"return $text . \"{{planet}} => |planet|\" . $text;","clojure":"(fn [text] (str text \"{{planet}} => |planet|\" text))","__tag__":"code","perl":"sub { $_[0] . \"{{planet}} => |planet|\" . $_[0] }","python":"lambda text: \"%s{{planet}} => |planet|%s\" % (text, text)","ruby":"proc { |text| \"#{text}{{planet}} => |planet|#{text}\" }","js":"function(txt) { return txt + \"{{planet}} => |planet|\" + txt }"}},"expected":"<-{{planet}} => Earth->","template":"{{= | | =}}<|#lambda|-|/lambda|>","desc":"Lambdas used for sections should parse with the current delimiters."},{"name":"Section - Multiple Calls","data":{"lambda":{"php":"return \"__\" . $text . \"__\";","clojure":"(fn [text] (str \"__\" text \"__\"))","__tag__":"code","perl":"sub { \"__\" . $_[0] . \"__\" }","python":"lambda text: \"__%s__\" % (text)","ruby":"proc { |text| \"__#{text}__\" }","js":"function(txt) { return \"__\" + txt + \"__\" }"}},"expected":"__FILE__ != __LINE__","template":"{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}","desc":"Lambdas used for sections should not be cached."},{"name":"Inverted Section","data":{"static":"static","lambda":{"php":"return false;","clojure":"(fn [text] false)","__tag__":"code","perl":"sub { 0 }","python":"lambda text: 0","ruby":"proc { |text| false }","js":"function(txt) { return false }"}},"expected":"<>","template":"<{{^lambda}}{{static}}{{/lambda}}>","desc":"Lambdas used for inverted sections should be considered truthy."}]}
ADDED testdata/naughty/LICENSE
Index: testdata/naughty/LICENSE
==================================================================
--- /dev/null
+++ testdata/naughty/LICENSE
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-2020 Max Woolf
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
ADDED testdata/naughty/README.md
Index: testdata/naughty/README.md
==================================================================
--- /dev/null
+++ testdata/naughty/README.md
@@ -0,0 +1,6 @@
+# Big List of Naughty Strings
+
+A list of strings which have a high probability of causing issues when used as user-input data.
+
+* Source: https://github.com/minimaxir/big-list-of-naughty-strings
+* License: MIT, (c) 2015-2020 Max Woolf (see file LICENSE)
ADDED testdata/naughty/blns.txt
Index: testdata/naughty/blns.txt
==================================================================
--- /dev/null
+++ testdata/naughty/blns.txt
@@ -0,0 +1,742 @@
+# Reserved Strings
+#
+# Strings which may be used elsewhere in code
+
+undefined
+undef
+null
+NULL
+(null)
+nil
+NIL
+true
+false
+True
+False
+TRUE
+FALSE
+None
+hasOwnProperty
+then
+constructor
+\
+\\
+
+# Numeric Strings
+#
+# Strings which can be interpreted as numeric
+
+0
+1
+1.00
+$1.00
+1/2
+1E2
+1E02
+1E+02
+-1
+-1.00
+-$1.00
+-1/2
+-1E2
+-1E02
+-1E+02
+1/0
+0/0
+-2147483648/-1
+-9223372036854775808/-1
+-0
+-0.0
++0
++0.0
+0.00
+0..0
+.
+0.0.0
+0,00
+0,,0
+,
+0,0,0
+0.0/0
+1.0/0.0
+0.0/0.0
+1,0/0,0
+0,0/0,0
+--1
+-
+-.
+-,
+999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
+NaN
+Infinity
+-Infinity
+INF
+1#INF
+-1#IND
+1#QNAN
+1#SNAN
+1#IND
+0x0
+0xffffffff
+0xffffffffffffffff
+0xabad1dea
+123456789012345678901234567890123456789
+1,000.00
+1 000.00
+1'000.00
+1,000,000.00
+1 000 000.00
+1'000'000.00
+1.000,00
+1 000,00
+1'000,00
+1.000.000,00
+1 000 000,00
+1'000'000,00
+01000
+08
+09
+2.2250738585072011e-308
+
+# Special Characters
+#
+# ASCII punctuation. All of these characters may need to be escaped in some
+# contexts. Divided into three groups based on (US-layout) keyboard position.
+
+,./;'[]\-=
+<>?:"{}|_+
+!@#$%^&*()`~
+
+# Non-whitespace C0 controls: U+0001 through U+0008, U+000E through U+001F,
+# and U+007F (DEL)
+# Often forbidden to appear in various text-based file formats (e.g. XML),
+# or reused for internal delimiters on the theory that they should never
+# appear in input.
+# The next line may appear to be blank or mojibake in some viewers.
+
+
+# Non-whitespace C1 controls: U+0080 through U+0084 and U+0086 through U+009F.
+# Commonly misinterpreted as additional graphic characters.
+# The next line may appear to be blank, mojibake, or dingbats in some viewers.
+
+
+# Whitespace: all of the characters with category Zs, Zl, or Zp (in Unicode
+# version 8.0.0), plus U+0009 (HT), U+000B (VT), U+000C (FF), U+0085 (NEL),
+# and U+200B (ZERO WIDTH SPACE), which are in the C categories but are often
+# treated as whitespace in some contexts.
+# This file unfortunately cannot express strings containing
+# U+0000, U+000A, or U+000D (NUL, LF, CR).
+# The next line may appear to be blank or mojibake in some viewers.
+# The next line may be flagged for "trailing whitespace" in some viewers.
+
+
+# Unicode additional control characters: all of the characters with
+# general category Cf (in Unicode 8.0.0).
+# The next line may appear to be blank or mojibake in some viewers.
+
+
+# "Byte order marks", U+FEFF and U+FFFE, each on its own line.
+# The next two lines may appear to be blank or mojibake in some viewers.
+
+
+
+# Unicode Symbols
+#
+# Strings which contain common unicode symbols (e.g. smart quotes)
+
+Ω≈ç√∫˜µ≤≥÷
+åß∂ƒ©˙∆˚¬…æ
+œ∑´®†¥¨ˆøπ“‘
+¡™£¢∞§¶•ªº–≠
+¸˛Ç◊ı˜Â¯˘¿
+ÅÍÎÏ˝ÓÔÒÚÆ☃
+Œ„´‰ˇÁ¨ˆØ∏”’
+`⁄€‹›fifl‡°·‚—±
+⅛⅜⅝⅞
+ЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя
+٠١٢٣٤٥٦٧٨٩
+
+# Unicode Subscript/Superscript/Accents
+#
+# Strings which contain unicode subscripts/superscripts; can cause rendering issues
+
+⁰⁴⁵
+₀₁₂
+⁰⁴⁵₀₁₂
+ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็ ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็
+
+# Quotation Marks
+#
+# Strings which contain misplaced quotation marks; can cause encoding errors
+
+'
+"
+''
+""
+'"'
+"''''"'"
+"'"'"''''"
+
+
+
+
+
+# Two-Byte Characters
+#
+# Strings which contain two-byte characters: can cause rendering issues or character-length issues
+
+田中さんにあげて下さい
+パーティーへ行かないか
+和製漢語
+部落格
+사회과학원 어학연구소
+찦차를 타고 온 펲시맨과 쑛다리 똠방각하
+社會科學院語學研究所
+울란바토르
+𠜎𠜱𠝹𠱓𠱸𠲖𠳏
+
+# Strings which contain two-byte letters: can cause issues with naïve UTF-16 capitalizers which think that 16 bits == 1 character
+
+𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆
+
+# Special Unicode Characters Union
+#
+# A super string recommended by VMware Inc. Globalization Team: can effectively cause rendering issues or character-length issues to validate product globalization readiness.
+#
+# 表 CJK_UNIFIED_IDEOGRAPHS (U+8868)
+# ポ KATAKANA LETTER PO (U+30DD)
+# あ HIRAGANA LETTER A (U+3042)
+# A LATIN CAPITAL LETTER A (U+0041)
+# 鷗 CJK_UNIFIED_IDEOGRAPHS (U+9DD7)
+# Œ LATIN SMALL LIGATURE OE (U+0153)
+# é LATIN SMALL LETTER E WITH ACUTE (U+00E9)
+# B FULLWIDTH LATIN CAPITAL LETTER B (U+FF22)
+# 逍 CJK_UNIFIED_IDEOGRAPHS (U+900D)
+# Ü LATIN SMALL LETTER U WITH DIAERESIS (U+00FC)
+# ß LATIN SMALL LETTER SHARP S (U+00DF)
+# ª FEMININE ORDINAL INDICATOR (U+00AA)
+# ą LATIN SMALL LETTER A WITH OGONEK (U+0105)
+# ñ LATIN SMALL LETTER N WITH TILDE (U+00F1)
+# 丂 CJK_UNIFIED_IDEOGRAPHS (U+4E02)
+# 㐀 CJK Ideograph Extension A, First (U+3400)
+# 𠀀 CJK Ideograph Extension B, First (U+20000)
+
+表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀
+
+# Changing length when lowercased
+#
+# Characters which increase in length (2 to 3 bytes) when lowercased
+# Credit: https://twitter.com/jifa/status/625776454479970304
+
+Ⱥ
+Ⱦ
+
+# Japanese Emoticons
+#
+# Strings which consists of Japanese-style emoticons which are popular on the web
+
+ヽ༼ຈل͜ຈ༽ノ ヽ༼ຈل͜ຈ༽ノ
+(。◕ ∀ ◕。)
+`ィ(´∀`∩
+__ロ(,_,*)
+・( ̄∀ ̄)・:*:
+゚・✿ヾ╲(。◕‿◕。)╱✿・゚
+,。・:*:・゜’( ☻ ω ☻ )。・:*:・゜’
+(╯°□°)╯︵ ┻━┻)
+(ノಥ益ಥ)ノ ┻━┻
+┬─┬ノ( º _ ºノ)
+( ͡° ͜ʖ ͡°)
+¯\_(ツ)_/¯
+
+# Emoji
+#
+# Strings which contain Emoji; should be the same behavior as two-byte characters, but not always
+
+😍
+👩🏽
+👨🦰 👨🏿🦰 👨🦱 👨🏿🦱 🦹🏿♂️
+👾 🙇 💁 🙅 🙆 🙋 🙎 🙍
+🐵 🙈 🙉 🙊
+❤️ 💔 💌 💕 💞 💓 💗 💖 💘 💝 💟 💜 💛 💚 💙
+✋🏿 💪🏿 👐🏿 🙌🏿 👏🏿 🙏🏿
+👨👩👦 👨👩👧👦 👨👨👦 👩👩👧 👨👦 👨👧👦 👩👦 👩👧👦
+🚾 🆒 🆓 🆕 🆖 🆗 🆙 🏧
+0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣ 7️⃣ 8️⃣ 9️⃣ 🔟
+
+# Regional Indicator Symbols
+#
+# Regional Indicator Symbols can be displayed differently across
+# fonts, and have a number of special behaviors
+
+🇺🇸🇷🇺🇸 🇦🇫🇦🇲🇸
+🇺🇸🇷🇺🇸🇦🇫🇦🇲
+🇺🇸🇷🇺🇸🇦
+
+# Unicode Numbers
+#
+# Strings which contain unicode numbers; if the code is localized, it should see the input as numeric
+
+123
+١٢٣
+
+# Right-To-Left Strings
+#
+# Strings which contain text that should be rendered RTL if possible (e.g. Arabic, Hebrew)
+
+ثم نفس سقطت وبالتحديد،, جزيرتي باستخدام أن دنو. إذ هنا؟ الستار وتنصيب كان. أهّل ايطاليا، بريطانيا-فرنسا قد أخذ. سليمان، إتفاقية بين ما, يذكر الحدود أي بعد, معاملة بولندا، الإطلاق عل إيو.
+בְּרֵאשִׁית, בָּרָא אֱלֹהִים, אֵת הַשָּׁמַיִם, וְאֵת הָאָרֶץ
+הָיְתָהtestالصفحات التّحول
+﷽
+ﷺ
+مُنَاقَشَةُ سُبُلِ اِسْتِخْدَامِ اللُّغَةِ فِي النُّظُمِ الْقَائِمَةِ وَفِيم يَخُصَّ التَّطْبِيقَاتُ الْحاسُوبِيَّةُ،
+الكل في المجمو عة (5)
+
+# Ogham Text
+#
+# The only unicode alphabet to use a space which isn't empty but should still act like a space.
+
+᚛ᚄᚓᚐᚋᚒᚄ ᚑᚄᚂᚑᚏᚅ᚜
+᚛ ᚜
+
+# Trick Unicode
+#
+# Strings which contain unicode with unusual properties (e.g. Right-to-left override) (c.f. http://www.unicode.org/charts/PDF/U2000.pdf)
+
+test
+test
+
test
+testtest
+test
+
+# Zalgo Text
+#
+# Strings which contain "corrupted" text. The corruption will not appear in non-HTML text, however. (via http://www.eeemo.net)
+
+Ṱ̺̺̕o͞ ̷i̲̬͇̪͙n̝̗͕v̟̜̘̦͟o̶̙̰̠kè͚̮̺̪̹̱̤ ̖t̝͕̳̣̻̪͞h̼͓̲̦̳̘̲e͇̣̰̦̬͎ ̢̼̻̱̘h͚͎͙̜̣̲ͅi̦̲̣̰̤v̻͍e̺̭̳̪̰-m̢iͅn̖̺̞̲̯̰d̵̼̟͙̩̼̘̳ ̞̥̱̳̭r̛̗̘e͙p͠r̼̞̻̭̗e̺̠̣͟s̘͇̳͍̝͉e͉̥̯̞̲͚̬͜ǹ̬͎͎̟̖͇̤t͍̬̤͓̼̭͘ͅi̪̱n͠g̴͉ ͏͉ͅc̬̟h͡a̫̻̯͘o̫̟̖͍̙̝͉s̗̦̲.̨̹͈̣
+̡͓̞ͅI̗̘̦͝n͇͇͙v̮̫ok̲̫̙͈i̖͙̭̹̠̞n̡̻̮̣̺g̲͈͙̭͙̬͎ ̰t͔̦h̞̲e̢̤ ͍̬̲͖f̴̘͕̣è͖ẹ̥̩l͖͔͚i͓͚̦͠n͖͍̗͓̳̮g͍ ̨o͚̪͡f̘̣̬ ̖̘͖̟͙̮c҉͔̫͖͓͇͖ͅh̵̤̣͚͔á̗̼͕ͅo̼̣̥s̱͈̺̖̦̻͢.̛̖̞̠̫̰
+̗̺͖̹̯͓Ṯ̤͍̥͇͈h̲́e͏͓̼̗̙̼̣͔ ͇̜̱̠͓͍ͅN͕͠e̗̱z̘̝̜̺͙p̤̺̹͍̯͚e̠̻̠͜r̨̤͍̺̖͔̖̖d̠̟̭̬̝͟i̦͖̩͓͔̤a̠̗̬͉̙n͚͜ ̻̞̰͚ͅh̵͉i̳̞v̢͇ḙ͎͟-҉̭̩̼͔m̤̭̫i͕͇̝̦n̗͙ḍ̟ ̯̲͕͞ǫ̟̯̰̲͙̻̝f ̪̰̰̗̖̭̘͘c̦͍̲̞͍̩̙ḥ͚a̮͎̟̙͜ơ̩̹͎s̤.̝̝ ҉Z̡̖̜͖̰̣͉̜a͖̰͙̬͡l̲̫̳͍̩g̡̟̼̱͚̞̬ͅo̗͜.̟
+̦H̬̤̗̤͝e͜ ̜̥̝̻͍̟́w̕h̖̯͓o̝͙̖͎̱̮ ҉̺̙̞̟͈W̷̼̭a̺̪͍į͈͕̭͙̯̜t̶̼̮s̘͙͖̕ ̠̫̠B̻͍͙͉̳ͅe̵h̵̬͇̫͙i̹͓̳̳̮͎̫̕n͟d̴̪̜̖ ̰͉̩͇͙̲͞ͅT͖̼͓̪͢h͏͓̮̻e̬̝̟ͅ ̤̹̝W͙̞̝͔͇͝ͅa͏͓͔̹̼̣l̴͔̰̤̟͔ḽ̫.͕
+Z̮̞̠͙͔ͅḀ̗̞͈̻̗Ḷ͙͎̯̹̞͓G̻O̭̗̮
+
+# Unicode Upsidedown
+#
+# Strings which contain unicode with an "upsidedown" effect (via http://www.upsidedowntext.com)
+
+˙ɐnbᴉlɐ ɐuƃɐɯ ǝɹolop ʇǝ ǝɹoqɐl ʇn ʇunpᴉpᴉɔuᴉ ɹodɯǝʇ poɯsnᴉǝ op pǝs 'ʇᴉlǝ ƃuᴉɔsᴉdᴉpɐ ɹnʇǝʇɔǝsuoɔ 'ʇǝɯɐ ʇᴉs ɹolop ɯnsdᴉ ɯǝɹo˥
+00˙Ɩ$-
+
+# Unicode font
+#
+# Strings which contain bold/italic/etc. versions of normal characters
+
+The quick brown fox jumps over the lazy dog
+𝐓𝐡𝐞 𝐪𝐮𝐢𝐜𝐤 𝐛𝐫𝐨𝐰𝐧 𝐟𝐨𝐱 𝐣𝐮𝐦𝐩𝐬 𝐨𝐯𝐞𝐫 𝐭𝐡𝐞 𝐥𝐚𝐳𝐲 𝐝𝐨𝐠
+𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐 𝖇𝖗𝖔𝖜𝖓 𝖋𝖔𝖝 𝖏𝖚𝖒𝖕𝖘 𝖔𝖛𝖊𝖗 𝖙𝖍𝖊 𝖑𝖆𝖟𝖞 𝖉𝖔𝖌
+𝑻𝒉𝒆 𝒒𝒖𝒊𝒄𝒌 𝒃𝒓𝒐𝒘𝒏 𝒇𝒐𝒙 𝒋𝒖𝒎𝒑𝒔 𝒐𝒗𝒆𝒓 𝒕𝒉𝒆 𝒍𝒂𝒛𝒚 𝒅𝒐𝒈
+𝓣𝓱𝓮 𝓺𝓾𝓲𝓬𝓴 𝓫𝓻𝓸𝔀𝓷 𝓯𝓸𝔁 𝓳𝓾𝓶𝓹𝓼 𝓸𝓿𝓮𝓻 𝓽𝓱𝓮 𝓵𝓪𝔃𝔂 𝓭𝓸𝓰
+𝕋𝕙𝕖 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨𝕟 𝕗𝕠𝕩 𝕛𝕦𝕞𝕡𝕤 𝕠𝕧𝕖𝕣 𝕥𝕙𝕖 𝕝𝕒𝕫𝕪 𝕕𝕠𝕘
+𝚃𝚑𝚎 𝚚𝚞𝚒𝚌𝚔 𝚋𝚛𝚘𝚠𝚗 𝚏𝚘𝚡 𝚓𝚞𝚖𝚙𝚜 𝚘𝚟𝚎𝚛 𝚝𝚑𝚎 𝚕𝚊𝚣𝚢 𝚍𝚘𝚐
+⒯⒣⒠ ⒬⒰⒤⒞⒦ ⒝⒭⒪⒲⒩ ⒡⒪⒳ ⒥⒰⒨⒫⒮ ⒪⒱⒠⒭ ⒯⒣⒠ ⒧⒜⒵⒴ ⒟⒪⒢
+
+# Script Injection
+#
+# Strings which attempt to invoke a benign script injection; shows vulnerability to XSS
+
+
+<script>alert('1');</script>
+
+