Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
Comment: | Initial version of zmk->Sx parser |
---|---|
Timelines: | family | ancestors | descendants | both | trunk |
Files: | files | file ages | folders |
SHA3-256: |
955147c904a352ad6637743e41b84685 |
User & Date: | stern 2024-05-31 15:48:07 |
Context
2024-06-30
| ||
19:00 | Add some predefined zettel IDs ... (Leaf check-in: ca0a0b5289 user: stern tags: trunk) | |
2024-06-20
| ||
10:55 | Remove '(SPACE ...)' node from sx-AST ... (check-in: 9860f59f2d user: stern tags: nospace) | |
2024-05-31
| ||
15:48 | Initial version of zmk->Sx parser ... (check-in: 955147c904 user: stern tags: trunk) | |
15:46 | Merge from trunk ... (Leaf check-in: 9aec1d38bb user: stern tags: zmk) | |
2024-04-22
| ||
14:51 | Package sxhtml was renamed to sxwebs/sxhtml ... (check-in: 3bbfcfd939 user: stern tags: trunk) | |
Changes
Added sz/parser.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | //----------------------------------------------------------------------------- // Copyright (c) 2024-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 sz import ( "t73f.de/r/sx" "t73f.de/r/zsc/api" "t73f.de/r/zsc/input" ) // --- Contains some simple parsers // ---- Syntax: none // ParseNoneBlocks parses no block. func ParseNoneBlocks(*input.Input) *sx.Pair { return nil } // ParseNoneInlines skips to the end of line and parses no inline. func ParseNoneInlines(inp *input.Input) *sx.Pair { inp.SkipToEOL() return nil } // ---- Some plain text syntaxes // ParsePlainBlocks parses the block as plain text with the given syntax. func ParsePlainBlocks(inp *input.Input, syntax string) *sx.Pair { var sym *sx.Symbol if syntax == api.ValueSyntaxHTML { sym = SymVerbatimHTML } else { sym = SymVerbatimProg } return sx.MakeList( sym, sx.MakeList(sx.Cons(sx.MakeString(""), sx.MakeString(syntax))), sx.MakeString(string(inp.ScanLineContent())), ) } // ParsePlainInlines parses the inline as plain text with the given syntax. func ParsePlainInlines(inp *input.Input, syntax string) *sx.Pair { var sym *sx.Symbol if syntax == api.ValueSyntaxHTML { sym = SymLiteralHTML } else { sym = SymLiteralProg } pos := inp.Pos inp.SkipToEOL() return sx.MakeList( sym, sx.MakeList(sx.Cons(sx.MakeString(""), sx.MakeString(syntax))), sx.MakeString(string(inp.Src[pos:inp.Pos])), ) } |
Added sz/parser_test.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | //----------------------------------------------------------------------------- // Copyright (c) 2024-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 sz_test import ( "testing" "t73f.de/r/zsc/input" "t73f.de/r/zsc/sz" ) func TestParseNone(t *testing.T) { if got := sz.ParseNoneBlocks(nil); got != nil { t.Error("GOTB", got) } inp := input.NewInput([]byte("1234\n6789")) if got := sz.ParseNoneInlines(inp); got != nil { t.Error("GOTI", got) } if got := inp.Pos; got != 4 { t.Errorf("input should be on position 4, but is %d", got) } if got := inp.Ch; got != '\n' { t.Errorf("input character should be 10, but is %d", got) } } func TestParsePlani(t *testing.T) { testcases := []struct { src string syntax string expBlocks string expInlines string }{ {"abc", "html", "(VERBATIM-HTML ((\"\" . \"html\")) \"abc\")", "(LITERAL-HTML ((\"\" . \"html\")) \"abc\")"}, {"abc\ndef", "html", "(VERBATIM-HTML ((\"\" . \"html\")) \"abc\\ndef\")", "(LITERAL-HTML ((\"\" . \"html\")) \"abc\")"}, {"abc", "text", "(VERBATIM-CODE ((\"\" . \"text\")) \"abc\")", "(LITERAL-CODE ((\"\" . \"text\")) \"abc\")"}, {"abc\nDEF", "text", "(VERBATIM-CODE ((\"\" . \"text\")) \"abc\\nDEF\")", "(LITERAL-CODE ((\"\" . \"text\")) \"abc\")"}, } for i, tc := range testcases { t.Run(tc.syntax+":"+tc.src, func(t *testing.T) { inp := input.NewInput([]byte(tc.src)) if got := sz.ParsePlainBlocks(inp, tc.syntax).String(); tc.expBlocks != got { t.Errorf("%d: %q/%v\nexpected: %q\ngot : %q", i, tc.src, tc.syntax, tc.expBlocks, got) } inp.SetPos(0) if got := sz.ParsePlainInlines(inp, tc.syntax).String(); tc.expInlines != got { t.Errorf("%d: %q/%v\nexpected: %q\ngot : %q", i, tc.src, tc.syntax, tc.expInlines, got) } }) } } |
Changes to sz/sz.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //----------------------------------------------------------------------------- // Copyright (c) 2022-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 sz import ( "t73f.de/r/sx" "t73f.de/r/zsc/attrs" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //----------------------------------------------------------------------------- // Copyright (c) 2022-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 sz contains zettel data handling as sx expressions. package sz import ( "t73f.de/r/sx" "t73f.de/r/zsc/attrs" ) |
︙ | ︙ | |||
121 122 123 124 125 126 127 | if mv, found := m[key]; found { if pair, isPair := sx.GetPair(mv.Value); isPair { return pair } } return nil } | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | if mv, found := m[key]; found { if pair, isPair := sx.GetPair(mv.Value); isPair { return pair } } return nil } // MapRefStateToLinkEmbed maps a reference state symbol to a link symbol or to // an embed symbol, depending on 'forLink'. func MapRefStateToLinkEmbed(symRefState *sx.Symbol, forLink bool) *sx.Symbol { if !forLink { return SymEmbed } if sym, found := mapRefStateLink[symRefState.GetValue()]; found { return sym } return SymLinkInvalid } var mapRefStateLink = map[string]*sx.Symbol{ NameRefStateInvalid: SymLinkInvalid, NameRefStateZettel: SymLinkZettel, NameRefStateSelf: SymLinkSelf, NameRefStateFound: SymLinkFound, NameRefStateBroken: SymLinkBroken, NameRefStateHosted: SymLinkHosted, NameRefStateBased: SymLinkBased, NameRefStateQuery: SymLinkQuery, NameRefStateExternal: SymLinkExternal, } // IsBreakSym return true if the object is either a soft or a hard break symbol. func IsBreakSym(obj sx.Object) bool { return SymSoft.IsEqual(obj) || SymHard.IsEqual(obj) } |
Added sz/walk.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | //----------------------------------------------------------------------------- // Copyright (c) 2024-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 sz import "t73f.de/r/sx" // Visitor is walking the sx-based AST. type Visitor interface { Visit(node *sx.Pair, env *sx.Pair) sx.Object } // Walk a sx-based AST through a Visitor. func Walk(v Visitor, node *sx.Pair, env *sx.Pair) *sx.Pair { if node == nil { return nil } if result, isPair := sx.GetPair(v.Visit(node, env)); isPair { return result } if sym, isSymbol := sx.GetSymbol(node.Car()); isSymbol { symVal := sym.GetValue() if fn, found := mapChildrenWalk[symVal]; found { return fn(v, node, env) } return node } panic(node) } var mapChildrenWalk map[string]func(Visitor, *sx.Pair, *sx.Pair) *sx.Pair func init() { mapChildrenWalk = map[string]func(Visitor, *sx.Pair, *sx.Pair) *sx.Pair{ NameBlock: walkChildrenTail, NamePara: walkChildrenTail, NameRegionBlock: walkChildrenRegion, NameRegionQuote: walkChildrenRegion, NameRegionVerse: walkChildrenRegion, NameHeading: walkChildrenHeading, NameListOrdered: walkChildrenTail, NameListUnordered: walkChildrenTail, NameListQuote: walkChildrenTail, NameDescription: walkChildrenDescription, NameTable: walkChildrenTable, NameInline: walkChildrenTail, NameEndnote: walkChildrenInlines3, NameMark: walkChildrenMark, NameLinkBased: walkChildrenInlines4, NameLinkBroken: walkChildrenInlines4, NameLinkExternal: walkChildrenInlines4, NameLinkFound: walkChildrenInlines4, NameLinkHosted: walkChildrenInlines4, NameLinkInvalid: walkChildrenInlines4, NameLinkQuery: walkChildrenInlines4, NameLinkSelf: walkChildrenInlines4, NameLinkZettel: walkChildrenInlines4, NameEmbed: walkChildrenInlines4, NameCite: walkChildrenInlines4, NameFormatDelete: walkChildrenInlines3, NameFormatEmph: walkChildrenInlines3, NameFormatInsert: walkChildrenInlines3, NameFormatMark: walkChildrenInlines3, NameFormatQuote: walkChildrenInlines3, NameFormatStrong: walkChildrenInlines3, NameFormatSpan: walkChildrenInlines3, NameFormatSub: walkChildrenInlines3, NameFormatSuper: walkChildrenInlines3, } } func walkChildrenTail(v Visitor, node *sx.Pair, env *sx.Pair) *sx.Pair { hasNil := false for n := node.Tail(); n != nil; n = n.Tail() { obj := Walk(v, n.Head(), env) if sx.IsNil(obj) { hasNil = true } n.SetCar(obj) } if !hasNil { return node } for n := node; ; { next := n.Tail() if next == nil { break } if sx.IsNil(next.Car()) { n.SetCdr(next.Cdr()) continue } n = next } return node } func walkChildrenList(v Visitor, lst *sx.Pair, env *sx.Pair) *sx.Pair { hasNil := false for n := lst; n != nil; n = n.Tail() { obj := Walk(v, n.Head(), env) if sx.IsNil(obj) { hasNil = true } n.SetCar(obj) } if !hasNil { return lst } var result sx.ListBuilder for n := lst; n != nil; n = n.Tail() { obj := n.Car() if !sx.IsNil(obj) { result.Add(obj) } } return result.List() } func walkChildrenRegion(v Visitor, node *sx.Pair, env *sx.Pair) *sx.Pair { // sym := node.Car() next := node.Tail() // attrs := next.Car() next = next.Tail() next.SetCar(walkChildrenList(v, next.Head(), env)) next.SetCdr(walkChildrenList(v, next.Tail(), env)) return node } func walkChildrenHeading(v Visitor, node *sx.Pair, env *sx.Pair) *sx.Pair { // sym := node.Car() next := node.Tail() // level := next.Car() next = next.Tail() // attrs := next.Car() next = next.Tail() // slug := next.Car() next = next.Tail() // fragment := next.Car() next.SetCdr(walkChildrenList(v, next.Tail(), env)) return node } func walkChildrenDescription(v Visitor, dn *sx.Pair, env *sx.Pair) *sx.Pair { for n := dn.Tail(); n != nil; n = n.Tail() { n.SetCar(walkChildrenList(v, n.Head(), env)) n = n.Tail() if n == nil { break } n.SetCar(Walk(v, n.Head(), env)) } return dn } func walkChildrenTable(v Visitor, tn *sx.Pair, env *sx.Pair) *sx.Pair { header := tn.Tail() header.SetCar(walkChildrenList(v, header.Tail(), env)) for row := header.Tail(); row != nil; row = row.Tail() { row.SetCar(walkChildrenList(v, row.Head(), env)) } return tn } func walkChildrenMark(v Visitor, mn *sx.Pair, env *sx.Pair) *sx.Pair { // sym := mn.Car() next := mn.Tail() // mark := next.Car() next = next.Tail() // slug := next.Car() next = next.Tail() // fragment := next.Car() next.SetCdr(walkChildrenList(v, next.Tail(), env)) return mn } func walkChildrenInlines4(v Visitor, ln *sx.Pair, env *sx.Pair) *sx.Pair { // sym := ln.Car() next := ln.Tail() // attrs := next.Car() next = next.Tail() // val3 := next.Car() next.SetCdr(walkChildrenList(v, next.Tail(), env)) return ln } func walkChildrenInlines3(v Visitor, node *sx.Pair, env *sx.Pair) *sx.Pair { // sym := node.Car() next := node.Tail() // Attrs // attrs := next.Car() next.SetCdr(walkChildrenList(v, next.Tail(), env)) return node } |
Added sz/zmk/block.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | //----------------------------------------------------------------------------- // Copyright (c) 2020-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk import ( "fmt" "t73f.de/r/sx" "t73f.de/r/zsc/input" "t73f.de/r/zsc/sz" ) // parseBlock parses one block. func (cp *zmkP) parseBlock(lastPara *sx.Pair) (res *sx.Pair, cont bool) { inp := cp.inp pos := inp.Pos if cp.nestingLevel <= maxNestingLevel { cp.nestingLevel++ defer func() { cp.nestingLevel-- }() var bn *sx.Pair success := false switch inp.Ch { case input.EOS: return nil, false case '\n', '\r': inp.EatEOL() cp.cleanupListsAfterEOL() return nil, false case ':': bn, success = cp.parseColon() case '@', '`', runeModGrave, '%', '~', '$': cp.clearStacked() bn, success = cp.parseVerbatim() case '"', '<': cp.clearStacked() bn, success = cp.parseRegion() case '=': cp.clearStacked() bn, success = cp.parseHeading() case '-': cp.clearStacked() bn, success = cp.parseHRule() case '*', '#', '>': cp.lastRow = nil cp.descrl = nil bn, success = cp.parseNestedList() case ';': cp.lists = nil cp.lastRow = nil bn, success = cp.parseDefTerm() case ' ': cp.lastRow = nil bn, success = nil, cp.parseIndent() case '|': cp.lists = nil cp.descrl = nil bn, success = cp.parseRow(), true case '{': cp.clearStacked() bn, success = cp.parseTransclusion() } if success { return bn, false } } inp.SetPos(pos) cp.clearStacked() ins := cp.parsePara() if startsWithSpaceSoftBreak(ins) { ins = ins[2:] } else if lastPara != nil { lastPair := lastPara.LastPair() lastPair.ExtendBang(sx.MakeList(ins...)) return nil, true } return sx.MakeList(ins...).Cons(sz.SymPara), false } func startsWithSpaceSoftBreak(ins sx.Vector) bool { if len(ins) < 2 { return false } pair0, isPair0 := sx.GetPair(ins[0]) pair1, isPair1 := sx.GetPair(ins[0]) if !isPair0 || !isPair1 { return false } car1 := pair1.Car() return pair0.Car().IsEqual(sz.SymSpace) && sz.IsBreakSym(car1) } var symSeparator = sx.MakeSymbol("sEpArAtOr") func (cp *zmkP) cleanupListsAfterEOL() { for _, l := range cp.lists { l.LastPair().Head().LastPair().AppendBang(sx.Cons(symSeparator, nil)) } if descrl := cp.descrl; descrl != nil { if lastPair, pos := lastPairPos(descrl); pos > 1 && pos%2 == 0 { lastPair.Head().LastPair().AppendBang(sx.Cons(symSeparator, nil)) } } } // parseColon determines which element should be parsed. func (cp *zmkP) parseColon() (*sx.Pair, bool) { inp := cp.inp if inp.PeekN(1) == ':' { cp.clearStacked() return cp.parseRegion() } return cp.parseDefDescr() } // parsePara parses paragraphed inline material as a sx.Vector. func (cp *zmkP) parsePara() (result sx.Vector) { for { in := cp.parseInline() if in == nil { return result } result = append(result, in) if sz.IsBreakSym(in.Car()) { ch := cp.inp.Ch switch ch { // Must contain all cases from above switch in parseBlock. case input.EOS, '\n', '\r', '@', '`', runeModGrave, '%', '~', '$', '"', '<', '=', '-', '*', '#', '>', ';', ':', ' ', '|', '{': return result } } } } // countDelim read from input until a non-delimiter is found and returns number of delimiter chars. func (cp *zmkP) countDelim(delim rune) int { inp := cp.inp cnt := 0 for inp.Ch == delim { cnt++ inp.Next() } return cnt } // parseVerbatim parses a verbatim block. func (cp *zmkP) parseVerbatim() (rn *sx.Pair, success bool) { inp := cp.inp fch := inp.Ch cnt := cp.countDelim(fch) if cnt < 3 { return nil, false } attrs := cp.parseBlockAttributes() inp.SkipToEOL() if inp.Ch == input.EOS { return nil, false } var sym *sx.Symbol switch fch { case '@': sym = sz.SymVerbatimZettel case '`', runeModGrave: sym = sz.SymVerbatimProg case '%': sym = sz.SymVerbatimComment case '~': sym = sz.SymVerbatimEval case '$': sym = sz.SymVerbatimMath default: panic(fmt.Sprintf("%q is not a verbatim char", fch)) } content := make([]byte, 0, 512) for { inp.EatEOL() posL := inp.Pos switch inp.Ch { case fch: if cp.countDelim(fch) >= cnt { inp.SkipToEOL() rn = sx.MakeList(sym, attrs, sx.MakeString(string(content))) return rn, true } inp.SetPos(posL) case input.EOS: return nil, false } inp.SkipToEOL() if len(content) > 0 { content = append(content, '\n') } content = append(content, inp.Src[posL:inp.Pos]...) } } // parseRegion parses a block region. func (cp *zmkP) parseRegion() (rn *sx.Pair, success bool) { inp := cp.inp fch := inp.Ch cnt := cp.countDelim(fch) if cnt < 3 { return nil, false } var sym *sx.Symbol oldInVerse := cp.inVerse defer func() { cp.inVerse = oldInVerse }() switch fch { case ':': sym = sz.SymRegionBlock case '<': sym = sz.SymRegionQuote case '"': sym = sz.SymRegionVerse cp.inVerse = true default: panic(fmt.Sprintf("%q is not a region char", fch)) } attrs := cp.parseBlockAttributes() inp.SkipToEOL() if inp.Ch == input.EOS { return nil, false } var blocksBuilder sx.ListBuilder var lastPara *sx.Pair inp.EatEOL() for { posL := inp.Pos switch inp.Ch { case fch: if cp.countDelim(fch) >= cnt { ins := cp.parseRegionLastLine() rn = ins.Cons(blocksBuilder.List()).Cons(attrs).Cons(sym) return rn, true } inp.SetPos(posL) case input.EOS: return nil, false } bn, cont := cp.parseBlock(lastPara) if bn != nil { blocksBuilder.Add(bn) } if !cont { lastPara = bn } } } // parseRegionLastLine parses the last line of a region and returns its inline text. func (cp *zmkP) parseRegionLastLine() *sx.Pair { cp.clearStacked() // remove any lists defined in the region cp.skipSpace() var region sx.ListBuilder for { switch cp.inp.Ch { case input.EOS, '\n', '\r': return region.List() } in := cp.parseInline() if in == nil { return region.List() } region.Add(in) } } // parseHeading parses a head line. func (cp *zmkP) parseHeading() (hn *sx.Pair, success bool) { inp := cp.inp delims := cp.countDelim(inp.Ch) if delims < 3 { return nil, false } if inp.Ch != ' ' { return nil, false } inp.Next() cp.skipSpace() if delims > 7 { delims = 7 } level := int64(delims - 2) var attrs *sx.Pair var text sx.ListBuilder for { if input.IsEOLEOS(inp.Ch) { return createHeading(level, attrs, text.List()), true } in := cp.parseInline() if in == nil { return createHeading(level, attrs, text.List()), true } text.Add(in) if inp.Ch == '{' && inp.Peek() != '{' { attrs = cp.parseBlockAttributes() inp.SkipToEOL() return createHeading(level, attrs, text.List()), true } } } func createHeading(level int64, attrs, text *sx.Pair) *sx.Pair { return text. Cons(sx.MakeString("")). // Fragment Cons(sx.MakeString("")). // Slug Cons(attrs). Cons(sx.Int64(level)). Cons(sz.SymHeading) } // parseHRule parses a horizontal rule. func (cp *zmkP) parseHRule() (hn *sx.Pair, success bool) { inp := cp.inp if cp.countDelim(inp.Ch) < 3 { return nil, false } attrs := cp.parseBlockAttributes() inp.SkipToEOL() return sx.MakeList(sz.SymThematic, attrs), true } // parseNestedList parses a list. func (cp *zmkP) parseNestedList() (res *sx.Pair, success bool) { kinds := cp.parseNestedListKinds() if len(kinds) == 0 { return nil, false } cp.skipSpace() if !kinds[len(kinds)-1].IsEqual(sz.SymListQuote) && input.IsEOLEOS(cp.inp.Ch) { return nil, false } if len(kinds) < len(cp.lists) { cp.lists = cp.lists[:len(kinds)] } ln, newLnCount := cp.buildNestedList(kinds) pv := cp.parseLinePara() bn := sx.Cons(sz.SymBlock, nil) if len(pv) != 0 { bn.AppendBang(pv.MakeList().Cons(sz.SymPara)) } lastItemPair := ln.LastPair() lastItemPair.AppendBang(bn) return cp.cleanupParsedNestedList(newLnCount) } func (cp *zmkP) parseNestedListKinds() []*sx.Symbol { inp := cp.inp result := make([]*sx.Symbol, 0, 8) for { var sym *sx.Symbol switch inp.Ch { case '*': sym = sz.SymListUnordered case '#': sym = sz.SymListOrdered case '>': sym = sz.SymListQuote default: panic(fmt.Sprintf("%q is not a region char", inp.Ch)) } result = append(result, sym) switch inp.Next() { case '*', '#', '>': case ' ', input.EOS, '\n', '\r': return result default: return nil } } } func (cp *zmkP) buildNestedList(kinds []*sx.Symbol) (ln *sx.Pair, newLnCount int) { for i, kind := range kinds { if i < len(cp.lists) { if !cp.lists[i].Car().IsEqual(kind) { ln = sx.Cons(kind, nil) newLnCount++ cp.lists[i] = ln cp.lists = cp.lists[:i+1] } else { ln = cp.lists[i] } } else { ln = sx.Cons(kind, nil) newLnCount++ cp.lists = append(cp.lists, ln) } } return ln, newLnCount } func (cp *zmkP) cleanupParsedNestedList(newLnCount int) (res *sx.Pair, success bool) { childPos := len(cp.lists) - 1 parentPos := childPos - 1 for i := 0; i < newLnCount; i++ { if parentPos < 0 { return cp.lists[0], true } parentLn := cp.lists[parentPos] childLn := cp.lists[childPos] if firstParent := parentLn.Tail(); firstParent != nil { // Add list to last item of the parent list lastParent := firstParent.LastPair() lastParent.Head().LastPair().AppendBang(childLn) } else { // Set list to first child of parent. childBlock := sx.MakeList(sz.SymBlock, cp.lists[childPos]) parentLn.LastPair().AppendBang(childBlock) } childPos-- parentPos-- } return nil, true } // parseDefTerm parses a term of a definition list. func (cp *zmkP) parseDefTerm() (res *sx.Pair, success bool) { inp := cp.inp if inp.Next() != ' ' { return nil, false } inp.Next() cp.skipSpace() descrl := cp.descrl if descrl == nil { descrl = sx.Cons(sz.SymDescription, nil) cp.descrl = descrl res = descrl } lastPair, pos := lastPairPos(descrl) for { in := cp.parseInline() if in == nil { if pos%2 == 0 { // lastPair is either the empty description list or the last block of definitions return nil, false } // lastPair is the definition term return res, true } if pos%2 == 0 { // lastPair is either the empty description list or the last block of definitions lastPair = lastPair.AppendBang(sx.Cons(in, nil)) pos++ } else { // lastPair is the term part and we need to append the inline list just read lastPair.Head().LastPair().AppendBang(in) } if sz.IsBreakSym(in.Car()) { return res, true } } } // parseDefDescr parses a description of a definition list. func (cp *zmkP) parseDefDescr() (res *sx.Pair, success bool) { inp := cp.inp if inp.Next() != ' ' { return nil, false } inp.Next() cp.skipSpace() descrl := cp.descrl lastPair, pos := lastPairPos(descrl) if descrl == nil || pos <= 0 { // No term given return nil, false } pn := cp.parseLinePara() if len(pn) == 0 { return nil, false } newDef := sx.MakeList(sz.SymBlock, pn.MakeList().Cons(sz.SymPara)) if pos%2 == 1 { // Just a term, but no definitions lastPair.AppendBang(sx.MakeList(sz.SymBlock, newDef)) } else { // lastPara points a the last definition lastPair.Head().LastPair().AppendBang(newDef) } return nil, true } func lastPairPos(p *sx.Pair) (*sx.Pair, int) { cnt := 0 for node := p; node != nil; { next := node.Tail() if next == nil { return node, cnt } node = next cnt++ } return nil, -1 } // parseIndent parses initial spaces to continue a list. func (cp *zmkP) parseIndent() bool { inp := cp.inp cnt := 0 for { if inp.Next() != ' ' { break } cnt++ } if cp.lists != nil { return cp.parseIndentForList(cnt) } if cp.descrl != nil { return cp.parseIndentForDescription(cnt) } return false } func (cp *zmkP) parseIndentForList(cnt int) bool { if len(cp.lists) < cnt { cnt = len(cp.lists) } cp.lists = cp.lists[:cnt] if cnt == 0 { return false } pv := cp.parseLinePara() if len(pv) == 0 { return false } ln := cp.lists[cnt-1] lbn := ln.LastPair().Head() lpn := lbn.LastPair().Head() pvList := pv.MakeList() if lpn.Car().IsEqual(sz.SymPara) { lpn.LastPair().SetCdr(pvList) } else { lbn.LastPair().AppendBang(pvList.Cons(sz.SymPara)) } return true } func (cp *zmkP) parseIndentForDescription(cnt int) bool { descrl := cp.descrl lastPair, pos := lastPairPos(descrl) if cnt < 1 || pos < 1 { return false } if pos%2 == 1 { // Continuation of a definition term for { in := cp.parseInline() if in == nil { return true } lastPair.Head().LastPair().AppendBang(in) if sz.IsBreakSym(in.Car()) { return true } } } // Continuation of a definition description pn := cp.parseLinePara() if len(pn) == 0 { return false } bn := lastPair.Head() para := bn.LastPair().Head().LastPair().Head() pnList := pn.MakeList() if para.Car().IsEqual(sz.SymPara) { para.LastPair().SetCdr(pnList) } else { bn.LastPair().AppendBang(pnList.Cons(sz.SymPara)) } return true } // parseLinePara parses one paragraph of inline material. func (cp *zmkP) parseLinePara() sx.Vector { var ins sx.Vector for { in := cp.parseInline() if in == nil { return ins } ins = append(ins, in) if sz.IsBreakSym(in.Car()) { return ins } } } // parseRow parse one table row. func (cp *zmkP) parseRow() *sx.Pair { inp := cp.inp if inp.Peek() == '%' { inp.SkipToEOL() return nil } //var row, curr *sx.Pair var row sx.ListBuilder for { inp.Next() cell := cp.parseCell() if cell != nil { row.Add(cell) } switch inp.Ch { case '\n', '\r': inp.EatEOL() fallthrough case input.EOS: // add to table if cp.lastRow == nil { if row.IsEmpty() { return nil } cp.lastRow = sx.Cons(row.List(), nil) return cp.lastRow.Cons(nil).Cons(sz.SymTable) } cp.lastRow = cp.lastRow.AppendBang(row.List()) return nil } // inp.Ch must be '|' } } // parseCell parses one single cell of a table row. func (cp *zmkP) parseCell() *sx.Pair { inp := cp.inp var cell sx.ListBuilder for { if input.IsEOLEOS(inp.Ch) { if cell.IsEmpty() { return nil } return cell.List().Cons(sz.SymCell) } if inp.Ch == '|' { return cell.List().Cons(sz.SymCell) } in := cp.parseInline() cell.Add(in) } } // parseTransclusion parses '{' '{' '{' ZID '}' '}' '}' func (cp *zmkP) parseTransclusion() (*sx.Pair, bool) { if cp.countDelim('{') != 3 { return nil, false } inp := cp.inp posA, posE := inp.Pos, 0 loop: for { switch inp.Ch { case input.EOS: return nil, false case '\n', '\r', ' ', '\t': if !hasQueryPrefix(inp.Src[posA:]) { return nil, false } case '\\': switch inp.Next() { case input.EOS, '\n', '\r': return nil, false } case '}': posE = inp.Pos if posA >= posE { return nil, false } if inp.Next() != '}' { continue } if inp.Next() != '}' { continue } break loop } inp.Next() } inp.Next() // consume last '}' a := cp.parseBlockAttributes() inp.SkipToEOL() refText := string(inp.Src[posA:posE]) ref := ParseReference(refText) return sx.MakeList(sz.SymTransclude, a, ref), true } |
Added sz/zmk/inline.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | //----------------------------------------------------------------------------- // Copyright (c) 2020-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk import ( "fmt" "strings" "unicode/utf8" "t73f.de/r/sx" "t73f.de/r/zsc/api" "t73f.de/r/zsc/input" "t73f.de/r/zsc/sz" ) func (cp *zmkP) parseInline() *sx.Pair { inp := cp.inp pos := inp.Pos if cp.nestingLevel <= maxNestingLevel { cp.nestingLevel++ defer func() { cp.nestingLevel-- }() var in *sx.Pair success := false switch inp.Ch { case input.EOS: return nil case '\n', '\r': return cp.parseSoftBreak() case ' ', '\t': return cp.parseSpace() case '[': switch inp.Next() { case '[': in, success = cp.parseLinkEmbed('[', ']', true) case '@': in, success = cp.parseCite() case '^': in, success = cp.parseEndnote() case '!': in, success = cp.parseMark() } case '{': if inp.Next() == '{' { in, success = cp.parseLinkEmbed('{', '}', false) } case '%': in, success = cp.parseComment() case '_', '*', '>', '~', '^', ',', '"', '#', ':': in, success = cp.parseFormat() case '@', '\'', '`', '=', runeModGrave: in, success = cp.parseLiteral() case '$': in, success = cp.parseLiteralMath() case '\\': return cp.parseBackslash() case '-': in, success = cp.parseNdash() case '&': in, success = cp.parseEntity() } if success { return in } } inp.SetPos(pos) return cp.parseText() } func (cp *zmkP) parseText() *sx.Pair { return sx.MakeList(sz.SymText, cp.parseString()) } func (cp *zmkP) parseString() sx.String { inp := cp.inp pos := inp.Pos if inp.Ch == '\\' { cp.inp.Next() return cp.parseBackslashRest() } for { switch inp.Next() { // The following case must contain all runes that occur in parseInline! // Plus the closing brackets ] and } and ) and the middle | case input.EOS, '\n', '\r', ' ', '\t', '[', ']', '{', '}', '(', ')', '|', '%', '_', '*', '>', '~', '^', ',', '"', '#', ':', '\'', '@', '`', runeModGrave, '$', '=', '\\', '-', '&': return sx.MakeString(string(inp.Src[pos:inp.Pos])) } } } func (cp *zmkP) parseBackslash() *sx.Pair { inp := cp.inp switch inp.Next() { case '\n', '\r': inp.EatEOL() return sx.MakeList(sz.SymHard) default: return sx.MakeList(sz.SymText, cp.parseBackslashRest()) } } func (cp *zmkP) parseBackslashRest() sx.String { inp := cp.inp if input.IsEOLEOS(inp.Ch) { return sx.MakeString("\\") } if inp.Ch == ' ' { inp.Next() return sx.MakeString("\u00a0") } pos := inp.Pos inp.Next() return sx.MakeString(string(inp.Src[pos:inp.Pos])) } func (cp *zmkP) parseSpace() *sx.Pair { inp := cp.inp pos := inp.Pos for { switch inp.Next() { case ' ', '\t': default: if cp.inVerse { spaces := utf8.RuneCount(inp.Src[pos:inp.Pos]) s := strings.Repeat("\u00a0", spaces) return sx.MakeList(sz.SymSpace, sx.MakeString(s)) } return sx.MakeList(sz.SymSpace) } } } func (cp *zmkP) parseSoftBreak() *sx.Pair { cp.inp.EatEOL() return sx.MakeList(sz.SymSoft) } func (cp *zmkP) parseLinkEmbed(openCh, closeCh rune, forLink bool) (*sx.Pair, bool) { if refString, text, ok := cp.parseReference(openCh, closeCh); ok { attrs := cp.parseInlineAttributes() if len(refString) > 0 { ref := ParseReference(refString) refSym, _ := sx.GetSymbol(ref.Car()) sym := sz.MapRefStateToLinkEmbed(refSym, forLink) ln := text. Cons(ref.Tail().Car()). // reference value Cons(attrs). Cons(sym) return ln, true } } return nil, false } func hasQueryPrefix(src []byte) bool { return len(src) > len(api.QueryPrefix) && string(src[:len(api.QueryPrefix)]) == api.QueryPrefix } func (cp *zmkP) parseReference(openCh, closeCh rune) (ref string, text *sx.Pair, _ bool) { inp := cp.inp inp.Next() cp.skipSpace() if inp.Ch == openCh { // Additional opening chars result in a fail return "", nil, false } var is sx.Vector pos := inp.Pos if !hasQueryPrefix(inp.Src[pos:]) { hasSpace, ok := cp.readReferenceToSep(closeCh) if !ok { return "", nil, false } if inp.Ch == '|' { // First part must be inline text if pos == inp.Pos { // [[| or {{| return "", nil, false } cp.inp = input.NewInput(inp.Src[pos:inp.Pos]) for { in := cp.parseInline() if in == nil { break } is = append(is, in) } cp.inp = inp inp.Next() } else { if hasSpace { return "", nil, false } inp.SetPos(pos) } } cp.skipSpace() pos = inp.Pos if !cp.readReferenceToClose(closeCh) { return "", nil, false } ref = strings.TrimSpace(string(inp.Src[pos:inp.Pos])) if inp.Next() != closeCh { return "", nil, false } inp.Next() if len(is) == 0 { return ref, nil, true } return ref, sx.MakeList(is...), true } func (cp *zmkP) readReferenceToSep(closeCh rune) (bool, bool) { hasSpace := false inp := cp.inp for { switch inp.Ch { case input.EOS: return false, false case '\n', '\r', ' ': hasSpace = true case '|': return hasSpace, true case '\\': switch inp.Next() { case input.EOS: return false, false case '\n', '\r': hasSpace = true } case '%': if inp.Next() == '%' { inp.SkipToEOL() } continue case closeCh: if inp.Next() == closeCh { return hasSpace, true } continue } inp.Next() } } func (cp *zmkP) readReferenceToClose(closeCh rune) bool { inp := cp.inp pos := inp.Pos for { switch inp.Ch { case input.EOS: return false case '\t', '\r', '\n', ' ': if !hasQueryPrefix(inp.Src[pos:]) { return false } case '\\': switch inp.Next() { case input.EOS, '\n', '\r': return false } case closeCh: return true } inp.Next() } } func (cp *zmkP) parseCite() (*sx.Pair, bool) { inp := cp.inp switch inp.Next() { case ' ', ',', '|', ']', '\n', '\r': return nil, false } pos := inp.Pos loop: for { switch inp.Ch { case input.EOS: return nil, false case ' ', ',', '|', ']', '\n', '\r': break loop } inp.Next() } posL := inp.Pos switch inp.Ch { case ' ', ',', '|': inp.Next() } ins, ok := cp.parseLinkLikeRest() if !ok { return nil, false } attrs := cp.parseInlineAttributes() cn := ins.Cons(sx.MakeString(string(inp.Src[pos:posL]))).Cons(attrs).Cons(sz.SymCite) return cn, true } func (cp *zmkP) parseEndnote() (*sx.Pair, bool) { cp.inp.Next() ins, ok := cp.parseLinkLikeRest() if !ok { return nil, false } attrs := cp.parseInlineAttributes() return ins.Cons(attrs).Cons(sz.SymEndnote), true } func (cp *zmkP) parseMark() (*sx.Pair, bool) { inp := cp.inp inp.Next() pos := inp.Pos for inp.Ch != '|' && inp.Ch != ']' { if !isNameRune(inp.Ch) { return nil, false } inp.Next() } mark := inp.Src[pos:inp.Pos] var ins *sx.Pair if inp.Ch == '|' { inp.Next() var ok bool ins, ok = cp.parseLinkLikeRest() if !ok { return nil, false } } else { inp.Next() } mn := ins. Cons(sx.MakeString("")). // Fragment Cons(sx.MakeString("")). // Slug Cons(sx.MakeString(string(mark))). Cons(sz.SymMark) return mn, true // Problematisch ist, dass hier noch nicht mn.Fragment und mn.Slug gesetzt werden. // Evtl. muss es ein PreMark-Symbol geben } func (cp *zmkP) parseLinkLikeRest() (*sx.Pair, bool) { cp.skipSpace() var ins sx.Vector inp := cp.inp for inp.Ch != ']' { in := cp.parseInline() if in == nil { return nil, false } ins = append(ins, in) if input.IsEOLEOS(inp.Ch) && sz.IsBreakSym(in.Car()) { return nil, false } } inp.Next() if len(ins) == 0 { return nil, true } return sx.MakeList(ins...), true } func (cp *zmkP) parseComment() (res *sx.Pair, success bool) { inp := cp.inp if inp.Next() != '%' { return nil, false } for inp.Ch == '%' { inp.Next() } attrs := cp.parseInlineAttributes() cp.skipSpace() pos := inp.Pos for { if input.IsEOLEOS(inp.Ch) { return sx.MakeList( sz.SymLiteralComment, attrs, sx.MakeString(string(inp.Src[pos:inp.Pos])), ), true } inp.Next() } } var mapRuneFormat = map[rune]*sx.Symbol{ '_': sz.SymFormatEmph, '*': sz.SymFormatStrong, '>': sz.SymFormatInsert, '~': sz.SymFormatDelete, '^': sz.SymFormatSuper, ',': sz.SymFormatSub, '"': sz.SymFormatQuote, '#': sz.SymFormatMark, ':': sz.SymFormatSpan, } func (cp *zmkP) parseFormat() (res *sx.Pair, success bool) { inp := cp.inp fch := inp.Ch symFormat, ok := mapRuneFormat[fch] if !ok { panic(fmt.Sprintf("%q is not a formatting char", fch)) } // read 2nd formatting character if inp.Next() != fch { return nil, false } inp.Next() var inlines sx.Vector for { if inp.Ch == input.EOS { return nil, false } if inp.Ch == fch { if inp.Next() == fch { inp.Next() attrs := cp.parseInlineAttributes() fn := sx.MakeList(inlines...).Cons(attrs).Cons(symFormat) return fn, true } inlines = append(inlines, sx.MakeList(sz.SymText, sx.MakeString(string(fch)))) } else if in := cp.parseInline(); in != nil { if input.IsEOLEOS(inp.Ch) && sz.IsBreakSym(in.Car()) { return nil, false } inlines = append(inlines, in) } } } var mapRuneLiteral = map[rune]*sx.Symbol{ '@': sz.SymLiteralZettel, '`': sz.SymLiteralProg, runeModGrave: sz.SymLiteralProg, '\'': sz.SymLiteralInput, '=': sz.SymLiteralOutput, // No '$': sz.SymLiteralMath, because pairing literal math is a little different } func (cp *zmkP) parseLiteral() (res *sx.Pair, success bool) { inp := cp.inp fch := inp.Ch symLiteral, ok := mapRuneLiteral[fch] if !ok { panic(fmt.Sprintf("%q is not a formatting char", fch)) } // read 2nd formatting character if inp.Next() != fch { return nil, false } inp.Next() var sb strings.Builder for { if inp.Ch == input.EOS { return nil, false } if inp.Ch == fch { if inp.Peek() == fch { inp.Next() inp.Next() return createLiteralNode(symLiteral, cp.parseInlineAttributes(), sb.String()), true } sb.WriteRune(fch) inp.Next() } else { s := cp.parseString() sb.WriteString(s.GetValue()) } } } func createLiteralNode(sym *sx.Symbol, attrs *sx.Pair, content string) *sx.Pair { if sym.IsEqual(sz.SymLiteralZettel) { if p := attrs.Assoc(sx.MakeString("")); p != nil { if val, isString := sx.GetString(p.Cdr()); isString && val.GetValue() == api.ValueSyntaxHTML { sym = sz.SymLiteralHTML attrs = attrs.RemoveAssoc(sx.MakeString("")) } } } return sx.MakeList(sym, attrs, sx.MakeString(content)) } func (cp *zmkP) parseLiteralMath() (res *sx.Pair, success bool) { inp := cp.inp // read 2nd formatting character if inp.Next() != '$' { return nil, false } inp.Next() pos := inp.Pos for { if inp.Ch == input.EOS { return nil, false } if inp.Ch == '$' && inp.Peek() == '$' { content := append([]byte{}, inp.Src[pos:inp.Pos]...) inp.Next() inp.Next() fn := sx.MakeList(sz.SymLiteralMath, cp.parseInlineAttributes(), sx.MakeString(string(content))) return fn, true } inp.Next() } } func (cp *zmkP) parseNdash() (res *sx.Pair, success bool) { inp := cp.inp if inp.Peek() != inp.Ch { return nil, false } inp.Next() inp.Next() return sx.MakeList(sz.SymText, sx.MakeString("\u2013")), true } func (cp *zmkP) parseEntity() (res *sx.Pair, success bool) { if text, ok := cp.inp.ScanEntity(); ok { return sx.MakeList(sz.SymText, sx.MakeString(text)), true } return nil, false } |
Added sz/zmk/post-processor.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | //----------------------------------------------------------------------------- // Copyright (c) 2020-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk import ( "t73f.de/r/sx" "t73f.de/r/zsc/sz" ) var symInVerse = sx.MakeSymbol("in-verse") var symNoBlock = sx.MakeSymbol("no-block") type postProcessor struct{} func (pp *postProcessor) Visit(lst *sx.Pair, env *sx.Pair) sx.Object { if lst == nil { return nil } sym, isSym := sx.GetSymbol(lst.Car()) if !isSym { panic(lst) } symVal := sym.GetValue() if fn, found := symMap[symVal]; found { return fn(pp, lst, env) } return sx.Int64(0) } func (pp *postProcessor) visitPairList(lst *sx.Pair, env *sx.Pair) *sx.Pair { var pList sx.ListBuilder for node := lst; node != nil; node = node.Tail() { if elem := sz.Walk(pp, node.Head(), env); elem != nil { pList.Add(elem) } } return pList.List() } var symMap map[string]func(*postProcessor, *sx.Pair, *sx.Pair) *sx.Pair func init() { symMap = map[string]func(*postProcessor, *sx.Pair, *sx.Pair) *sx.Pair{ sz.NameBlock: postProcessBlockList, sz.NamePara: postProcessInlineList, sz.NameRegionBlock: postProcessRegion, sz.NameRegionQuote: postProcessRegion, sz.NameRegionVerse: postProcessRegionVerse, sz.NameVerbatimComment: postProcessVerbatim, sz.NameVerbatimEval: postProcessVerbatim, sz.NameVerbatimMath: postProcessVerbatim, sz.NameVerbatimProg: postProcessVerbatim, sz.NameVerbatimZettel: postProcessVerbatim, sz.NameHeading: postProcessHeading, sz.NameListOrdered: postProcessItemList, sz.NameListUnordered: postProcessItemList, sz.NameListQuote: postProcessQuoteList, sz.NameDescription: postProcessDescription, sz.NameTable: postProcessTable, sz.NameInline: postProcessInlineList, sz.NameText: postProcessText, sz.NameSoft: postProcessSoft, sz.NameEndnote: postProcessEndnote, sz.NameMark: postProcessMark, sz.NameLinkBased: postProcessInlines4, sz.NameLinkBroken: postProcessInlines4, sz.NameLinkExternal: postProcessInlines4, sz.NameLinkFound: postProcessInlines4, sz.NameLinkHosted: postProcessInlines4, sz.NameLinkInvalid: postProcessInlines4, sz.NameLinkQuery: postProcessInlines4, sz.NameLinkSelf: postProcessInlines4, sz.NameLinkZettel: postProcessInlines4, sz.NameEmbed: postProcessInlines4, sz.NameCite: postProcessInlines4, sz.NameFormatDelete: postProcessFormat, sz.NameFormatEmph: postProcessFormat, sz.NameFormatInsert: postProcessFormat, sz.NameFormatMark: postProcessFormat, sz.NameFormatQuote: postProcessFormat, sz.NameFormatStrong: postProcessFormat, sz.NameFormatSpan: postProcessFormat, sz.NameFormatSub: postProcessFormat, sz.NameFormatSuper: postProcessFormat, symSeparator.GetValue(): ignoreProcess, } } func ignoreProcess(*postProcessor, *sx.Pair, *sx.Pair) *sx.Pair { return nil } func postProcessBlockList(pp *postProcessor, lst *sx.Pair, env *sx.Pair) *sx.Pair { result := pp.visitPairList(lst.Tail(), env) if result == nil { if noBlockPair := env.Assoc(symNoBlock); noBlockPair == nil || sx.IsTrue(noBlockPair.Cdr()) { return nil } } return result.Cons(lst.Car()) } func postProcessInlineList(pp *postProcessor, lst *sx.Pair, env *sx.Pair) *sx.Pair { sym := lst.Car() if rest := pp.visitInlines(lst.Tail(), env); rest != nil { return rest.Cons(sym) } return nil } func postProcessRegion(pp *postProcessor, rn *sx.Pair, env *sx.Pair) *sx.Pair { sym := rn.Car() next := rn.Tail() attrs := next.Car() next = next.Tail() blocks := pp.visitPairList(next.Head(), env) text := pp.visitInlines(next.Tail(), env) if blocks == nil && text == nil { return nil } return text.Cons(blocks).Cons(attrs).Cons(sym) } func postProcessRegionVerse(pp *postProcessor, rn *sx.Pair, env *sx.Pair) *sx.Pair { return postProcessRegion(pp, rn, env.Cons(sx.Cons(symInVerse, nil))) } func postProcessVerbatim(_ *postProcessor, verb *sx.Pair, _ *sx.Pair) *sx.Pair { if content, isString := sx.GetString(verb.Tail().Tail().Car()); isString && content.GetValue() != "" { return verb } return nil } func postProcessHeading(pp *postProcessor, hn *sx.Pair, env *sx.Pair) *sx.Pair { sym := hn.Car() next := hn.Tail() level := next.Car() next = next.Tail() attrs := next.Car() next = next.Tail() slug := next.Car() next = next.Tail() fragment := next.Car() if text := pp.visitInlines(next.Tail(), env); text != nil { return text.Cons(fragment).Cons(slug).Cons(attrs).Cons(level).Cons(sym) } return nil } func postProcessItemList(pp *postProcessor, ln *sx.Pair, env *sx.Pair) *sx.Pair { elems := pp.visitListElems(ln, env) if elems == nil { return nil } return elems.Cons(ln.Car()) } func postProcessQuoteList(pp *postProcessor, ln *sx.Pair, env *sx.Pair) *sx.Pair { elems := pp.visitListElems(ln, env.Cons(sx.Cons(symNoBlock, nil))) // Collect multiple paragraph items into one item. var newElems sx.ListBuilder var newPara sx.ListBuilder addtoParagraph := func() { if !newPara.IsEmpty() { newElems.Add(sx.MakeList(sz.SymBlock, newPara.List().Cons(sz.SymPara))) } } for node := elems; node != nil; node = node.Tail() { item := node.Head() if !item.Car().IsEqual(sz.SymBlock) { continue } itemTail := item.Tail() if itemTail == nil || itemTail.Tail() != nil { addtoParagraph() newElems.Add(item) continue } if pn := itemTail.Head(); pn.Car().IsEqual(sz.SymPara) { if !newPara.IsEmpty() { newPara.Add(sx.Cons(sz.SymSoft, nil)) } newPara.ExtendBang(pn.Tail()) continue } addtoParagraph() newElems.Add(item) } addtoParagraph() return newElems.List().Cons(ln.Car()) } func (pp *postProcessor) visitListElems(ln *sx.Pair, env *sx.Pair) *sx.Pair { var pList sx.ListBuilder for node := ln.Tail(); node != nil; node = node.Tail() { if elem := sz.Walk(pp, node.Head(), env); elem != nil { pList.Add(elem) } } return pList.List() } func postProcessDescription(pp *postProcessor, dl *sx.Pair, env *sx.Pair) *sx.Pair { var dList sx.ListBuilder isTerm := false for node := dl.Tail(); node != nil; node = node.Tail() { isTerm = !isTerm if isTerm { dList.Add(pp.visitInlines(node.Head(), env)) } else { dList.Add(sz.Walk(pp, node.Head(), env)) } } return dList.List().Cons(dl.Car()) } func postProcessTable(pp *postProcessor, tbl *sx.Pair, env *sx.Pair) *sx.Pair { sym := tbl.Car() next := tbl.Tail() header := next.Head() if header != nil { // Already post-processed return tbl } rows, width := pp.visitRows(next.Tail(), env) if rows == nil { // Header and row are nil -> no table return nil } header, rows, align := splitTableHeader(rows, width) alignRow(header, align) for node := rows; node != nil; node = node.Tail() { alignRow(node.Head(), align) } return rows.Cons(header).Cons(sym) } func (pp *postProcessor) visitRows(rows *sx.Pair, env *sx.Pair) (*sx.Pair, int) { maxWidth := 0 var pRows sx.ListBuilder for node := rows; node != nil; node = node.Tail() { row := node.Head() row, width := pp.visitCells(row, env) if maxWidth < width { maxWidth = width } pRows.Add(row) } return pRows.List(), maxWidth } func (pp *postProcessor) visitCells(cells *sx.Pair, env *sx.Pair) (*sx.Pair, int) { width := 0 var pCells sx.ListBuilder for node := cells; node != nil; node = node.Tail() { cell := node.Head() ins := pp.visitInlines(cell.Tail(), env) newCell := ins.Cons(cell.Car()) pCells.Add(newCell) width++ } return pCells.List(), width } func splitTableHeader(rows *sx.Pair, width int) (header, realRows *sx.Pair, align []*sx.Symbol) { align = make([]*sx.Symbol, width) foundHeader := false cellCount := 0 // assert: rows != nil (checked in postProcessTable) for node := rows.Head(); node != nil; node = node.Tail() { cellCount++ cell := node.Head() cellTail := cell.Tail() if cellTail == nil { continue } // elem is first cell inline element elem := cellTail.Head() if elem.Car().IsEqual(sz.SymText) { if s, isString := sx.GetString(elem.Tail().Car()); isString && s.GetValue() != "" { str := s.GetValue() if str[0] == '=' { foundHeader = true elem.SetCdr(sx.Cons(sx.MakeString(str[1:]), nil)) } } } // move to the last cell inline element for { next := cellTail.Tail() if next == nil { break } cellTail = next } elem = cellTail.Head() if elem.Car().IsEqual(sz.SymText) { if s, isString := sx.GetString(elem.Tail().Car()); isString && s.GetValue() != "" { str := s.GetValue() cellAlign := getCellAlignment(str[len(str)-1]) if !cellAlign.IsEqual(sz.SymCell) { elem.SetCdr(sx.Cons(sx.MakeString(str[0:len(str)-1]), nil)) } align[cellCount-1] = cellAlign cell.SetCar(cellAlign) } } } if !foundHeader { for i := 0; i < width; i++ { align[i] = sz.SymCell // Default alignment } return nil, rows, align } for i := 0; i < width; i++ { if align[i] == nil { align[i] = sz.SymCell // Default alignment } } return rows.Head(), rows.Tail(), align } func alignRow(row *sx.Pair, align []*sx.Symbol) { if row == nil { return } var lastCellNode *sx.Pair cellCount := 0 for node := row; node != nil; node = node.Tail() { lastCellNode = node cell := node.Head() cell.SetCar(align[cellCount]) cellCount++ cellTail := cell.Tail() if cellTail == nil { continue } // elem is first cell inline element elem := cellTail.Head() if elem.Car().IsEqual(sz.SymText) { if s, isString := sx.GetString(elem.Tail().Car()); isString && s.GetValue() != "" { str := s.GetValue() cellAlign := getCellAlignment(str[0]) if !cellAlign.IsEqual(sz.SymCell) { elem.SetCdr(sx.Cons(sx.MakeString(str[1:]), nil)) cell.SetCar(cellAlign) } } } } for cellCount < len(align) { lastCellNode = lastCellNode.AppendBang(sx.Cons(align[cellCount], nil)) cellCount++ } } func getCellAlignment(ch byte) *sx.Symbol { switch ch { case ':': return sz.SymCellCenter case '<': return sz.SymCellLeft case '>': return sz.SymCellRight default: return sz.SymCell } } func (pp *postProcessor) visitInlines(lst *sx.Pair, env *sx.Pair) *sx.Pair { length := lst.Length() if length <= 0 { return nil } inVerse := env.Assoc(symInVerse) != nil vector := make([]*sx.Pair, 0, length) // 1st phase: process all childs, ignore SPACE at start, and merge some elements for node := lst; node != nil; node = node.Tail() { elem := sz.Walk(pp, node.Head(), env) if elem == nil { continue } elemSym := elem.Car() if len(vector) == 0 { // The 1st element is always moved, except for a SPACE outside a verse block if !inVerse && elemSym.IsEqual(sz.SymSpace) { continue } vector = append(vector, elem) continue } last := vector[len(vector)-1] lastSym := last.Car() if lastSym.IsEqual(sz.SymText) && elemSym.IsEqual(sz.SymText) { // Merge two TEXT elements into one lastText := last.Tail().Car().(sx.String).GetValue() elemText := elem.Tail().Car().(sx.String).GetValue() last.SetCdr(sx.Cons(sx.MakeString(lastText+elemText), sx.Nil())) continue } if lastSym.IsEqual(sz.SymSpace) && elemSym.IsEqual(sz.SymSoft) { // Merge (SPACE) (SOFT) to (HARD) vector[len(vector)-1] = sx.Cons(sz.SymHard, sx.Nil()) continue } vector = append(vector, elem) } if len(vector) == 0 { return nil } // 2nd phase: remove (SOFT), (HARD), (SPACE) at the end lastPos := len(vector) - 1 for lastPos >= 0 { elem := vector[lastPos] elemSym := elem.Car() if !elemSym.IsEqual(sz.SymSpace) && !sz.IsBreakSym(elemSym) { break } lastPos-- } if lastPos < 0 { return nil } result := sx.Cons(vector[0], nil) curr := result for i := 1; i <= lastPos; i++ { curr = curr.AppendBang(vector[i]) } return result } func postProcessText(_ *postProcessor, txt *sx.Pair, _ *sx.Pair) *sx.Pair { if tail := txt.Tail(); tail != nil { if content, isString := sx.GetString(tail.Car()); isString && content.GetValue() != "" { return txt } } return nil } func postProcessSoft(_ *postProcessor, sn *sx.Pair, env *sx.Pair) *sx.Pair { if env.Assoc(symInVerse) == nil { return sn } return sx.Cons(sz.SymHard, nil) } func postProcessEndnote(pp *postProcessor, en *sx.Pair, env *sx.Pair) *sx.Pair { sym := en.Car() next := en.Tail() attrs := next.Car() if text := pp.visitInlines(next.Tail(), env); text != nil { return text.Cons(attrs).Cons(sym) } return sx.MakeList(sym, attrs) } func postProcessMark(pp *postProcessor, en *sx.Pair, env *sx.Pair) *sx.Pair { sym := en.Car() next := en.Tail() mark := next.Car() next = next.Tail() slug := next.Car() next = next.Tail() fragment := next.Car() text := pp.visitInlines(next.Tail(), env) return text.Cons(fragment).Cons(slug).Cons(mark).Cons(sym) } func postProcessInlines4(pp *postProcessor, ln *sx.Pair, env *sx.Pair) *sx.Pair { sym := ln.Car() next := ln.Tail() attrs := next.Car() next = next.Tail() val3 := next.Car() text := pp.visitInlines(next.Tail(), env) return text.Cons(val3).Cons(attrs).Cons(sym) } func postProcessFormat(pp *postProcessor, fn *sx.Pair, env *sx.Pair) *sx.Pair { symFormat := fn.Car() next := fn.Tail() // Attrs attrs := next.Car() next = next.Tail() // Possible inlines if next == nil { return fn } inlines := pp.visitInlines(next, env) return inlines.Cons(attrs).Cons(symFormat) } |
Added sz/zmk/ref.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | // ----------------------------------------------------------------------------- // Copyright (c) 2020-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk import ( "net/url" "strings" "t73f.de/r/sx" "t73f.de/r/zsc/api" "t73f.de/r/zsc/sz" ) // ParseReference parses a string and returns a reference. func ParseReference(s string) *sx.Pair { if invalidReference(s) { return makePairRef(sz.SymRefStateInvalid, s) } if strings.HasPrefix(s, api.QueryPrefix) { return makePairRef(sz.SymRefStateQuery, s[len(api.QueryPrefix):]) } if state, ok := localState(s); ok { if state.IsEqual(sz.SymRefStateBased) { s = s[1:] } _, err := url.Parse(s) if err == nil { return makePairRef(state, s) } } u, err := url.Parse(s) if err != nil { return makePairRef(sz.SymRefStateInvalid, s) } if !externalURL(u) { zid := api.ZettelID(u.Path) if zid.IsValid() { return makePairRef(sz.SymRefStateZettel, s) } if u.Path == "" && u.Fragment != "" { return makePairRef(sz.SymRefStateSelf, s) } } return makePairRef(sz.SymRefStateExternal, s) } func makePairRef(sym *sx.Symbol, val string) *sx.Pair { return sx.MakeList(sym, sx.MakeString(val)) } 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) (*sx.Symbol, bool) { if len(path) > 0 && path[0] == '/' { if len(path) > 1 && path[1] == '/' { return sz.SymRefStateBased, true } return sz.SymRefStateHosted, true } if len(path) > 1 && path[0] == '.' { if len(path) > 2 && path[1] == '.' && path[2] == '/' { return sz.SymRefStateHosted, true } return sz.SymRefStateHosted, path[1] == '/' } return sz.SymRefStateInvalid, false } // ReferenceIsValid returns true if reference is valid func ReferenceIsValid(ref *sx.Pair) bool { return !ref.Car().IsEqual(sz.SymRefStateInvalid) } // ReferenceIsZettel returns true if it is a reference to a local zettel. func ReferenceIsZettel(ref *sx.Pair) bool { state := ref.Car() return state.IsEqual(sz.SymRefStateZettel) || state.IsEqual(sz.SymRefStateSelf) || state.IsEqual(sz.SymRefStateFound) || state.IsEqual(sz.SymRefStateBroken) } // ReferenceIsLocal returns true if reference is local func ReferenceIsLocal(ref *sx.Pair) bool { state := ref.Car() return state.IsEqual(sz.SymRefStateHosted) || state.IsEqual(sz.SymRefStateBased) } // ReferenceIsExternal returns true if it is a reference to external material. func ReferenceIsExternal(ref *sx.Pair) bool { return ref.Car().IsEqual(sz.SymRefStateExternal) } |
Added sz/zmk/ref_test.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | // ----------------------------------------------------------------------------- // Copyright (c) 2020-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk_test import ( "testing" "t73f.de/r/zsc/sz/zmk" ) func TestParseReference(t *testing.T) { t.Parallel() testcases := []struct { link string err bool exp string }{ {"", true, ""}, {"12345678901234", false, "(ZETTEL \"12345678901234\")"}, {"123", false, "(EXTERNAL \"123\")"}, {",://", true, ""}, } for i, tc := range testcases { got := zmk.ParseReference(tc.link) gotIsValid := zmk.ReferenceIsValid(got) if gotIsValid == tc.err { t.Errorf( "TC=%d, expected parse error of %q: %v, but got %q", i, tc.link, tc.err, got) } if gotIsValid && 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 := zmk.ParseReference(tc.link) isZettel := zmk.ReferenceIsZettel(ref) if isZettel != tc.isZettel { t.Errorf( "TC=%d, Reference %q isZettel=%v expected, but got %v", i, tc.link, tc.isZettel, isZettel) } isLocal := zmk.ReferenceIsLocal(ref) if isLocal != tc.isLocal { t.Errorf( "TC=%d, Reference %q isLocal=%v expected, but got %v", i, tc.link, tc.isLocal, isLocal) } isExternal := zmk.ReferenceIsExternal(ref) if isExternal != tc.isExternal { t.Errorf( "TC=%d, Reference %q isExternal=%v expected, but got %v", i, tc.link, tc.isExternal, isExternal) } } } |
Added sz/zmk/zmk.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | //----------------------------------------------------------------------------- // Copyright (c) 2020-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk provides a parser for zettelmarkup. package zmk import ( "slices" "strings" "unicode" "t73f.de/r/sx" "t73f.de/r/zsc/input" "t73f.de/r/zsc/sz" ) func ParseBlocks(inp *input.Input) *sx.Pair { parser := zmkP{inp: inp} var lastPara *sx.Pair var blkBuild sx.ListBuilder for inp.Ch != input.EOS { bn, cont := parser.parseBlock(lastPara) if bn != nil { blkBuild.Add(bn) } if !cont { if bn.Car().IsEqual(sz.SymPara) { lastPara = bn } else { lastPara = nil } } } if parser.nestingLevel != 0 { panic("Nesting level was not decremented") } bnl := blkBuild.List() var pp postProcessor if bs := pp.visitPairList(bnl, nil); bs != nil { return bs.Cons(sz.SymBlock) } return nil } func ParseInlines(inp *input.Input) *sx.Pair { parser := zmkP{inp: inp} var ins sx.Vector for inp.Ch != input.EOS { in := parser.parseInline() if in == nil { break } ins = append(ins, in) } inl := ins.MakeList().Cons(sz.SymInline) var pp postProcessor return sz.Walk(&pp, inl, nil) } type zmkP struct { inp *input.Input // Input stream lists []*sx.Pair // Stack of lists lastRow *sx.Pair // Last row of table, or nil if not in table. descrl *sx.Pair // Current description list nestingLevel int // Count nesting of block and inline elements inVerse bool // Currently in a vers region? } // runeModGrave is Unicode code point U+02CB (715) called "MODIFIER LETTER // GRAVE ACCENT". On the iPad it is much more easier to type in this code point // than U+0060 (96) "Grave accent" (aka backtick). Therefore, U+02CB will be // considered equivalent to U+0060. const runeModGrave = 'Ë‹' // This is NOT '`'! const maxNestingLevel = 50 // clearStacked removes all multi-line nodes from parser. func (cp *zmkP) clearStacked() { cp.lists = nil cp.lastRow = nil cp.descrl = nil } type attrMap map[string]string func (attrs attrMap) updateAttrs(key, val string) { if prevVal := attrs[key]; len(prevVal) > 0 { attrs[key] = prevVal + " " + val } else { attrs[key] = val } } func (attrs attrMap) asPairAssoc() *sx.Pair { names := make([]string, 0, len(attrs)) for n := range attrs { names = append(names, n) } slices.Sort(names) var assoc *sx.Pair = nil for i := len(names) - 1; i >= 0; i-- { n := names[i] assoc = assoc.Cons(sx.Cons(sx.MakeString(n), sx.MakeString(attrs[n]))) } return assoc } func (cp *zmkP) parseNormalAttribute(attrs attrMap) bool { inp := cp.inp posK := inp.Pos for isNameRune(inp.Ch) { inp.Next() } if posK == inp.Pos { return false } key := string(inp.Src[posK:inp.Pos]) if inp.Ch != '=' { attrs[key] = "" return true } return cp.parseAttributeValue(key, attrs) } func (cp *zmkP) parseAttributeValue(key string, attrs attrMap) bool { inp := cp.inp if inp.Next() == '"' { return cp.parseQuotedAttributeValue(key, attrs) } posV := inp.Pos for { switch inp.Ch { case input.EOS: return false case '\n', '\r', ' ', ',', '}': attrs.updateAttrs(key, string(inp.Src[posV:inp.Pos])) return true } inp.Next() } } func (cp *zmkP) parseQuotedAttributeValue(key string, attrs attrMap) bool { inp := cp.inp inp.Next() var sb strings.Builder for { switch inp.Ch { case input.EOS: return false case '"': attrs.updateAttrs(key, sb.String()) inp.Next() return true case '\\': switch inp.Next() { case input.EOS, '\n', '\r': return false } fallthrough default: sb.WriteRune(inp.Ch) inp.Next() } } } func (cp *zmkP) parseBlockAttributes() *sx.Pair { inp := cp.inp pos := inp.Pos for isNameRune(inp.Ch) { inp.Next() } if pos < inp.Pos { return attrMap{"": string(inp.Src[pos:inp.Pos])}.asPairAssoc() } // No immediate name: skip spaces cp.skipSpace() return cp.parseInlineAttributes() } func (cp *zmkP) parseInlineAttributes() *sx.Pair { inp := cp.inp pos := inp.Pos if attrs, success := cp.doParseAttributes(); success { return attrs } inp.SetPos(pos) return nil } // doParseAttributes reads attributes. func (cp *zmkP) doParseAttributes() (res *sx.Pair, success bool) { inp := cp.inp if inp.Ch != '{' { return nil, false } inp.Next() a := attrMap{} if !cp.parseAttributeValues(a) { return nil, false } inp.Next() return a.asPairAssoc(), true } func (cp *zmkP) parseAttributeValues(a attrMap) bool { inp := cp.inp for { cp.skipSpaceLine() switch inp.Ch { case input.EOS: return false case '}': return true case '.': inp.Next() posC := inp.Pos for isNameRune(inp.Ch) { inp.Next() } if posC == inp.Pos { return false } a.updateAttrs("class", string(inp.Src[posC:inp.Pos])) case '=': delete(a, "") if !cp.parseAttributeValue("", a) { return false } default: if !cp.parseNormalAttribute(a) { return false } } switch inp.Ch { case '}': return true case '\n', '\r': case ' ', ',': inp.Next() default: return false } } } func (cp *zmkP) skipSpaceLine() { for inp := cp.inp; ; { switch inp.Ch { case ' ': inp.Next() case '\n', '\r': inp.EatEOL() default: return } } } func (cp *zmkP) skipSpace() { for inp := cp.inp; inp.Ch == ' '; { inp.Next() } } func isNameRune(ch rune) bool { return unicode.IsLetter(ch) || unicode.IsDigit(ch) || ch == '-' || ch == '_' } |
Added sz/zmk/zmk_fuzz_test.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //----------------------------------------------------------------------------- // Copyright (c) 2022-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk_test import ( "testing" "t73f.de/r/zsc/input" "t73f.de/r/zsc/sz/zmk" ) func FuzzParseBlocks(f *testing.F) { f.Fuzz(func(t *testing.T, src []byte) { t.Parallel() inp := input.NewInput(src) zmk.ParseBlocks(inp) }) } |
Added sz/zmk/zmk_test.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 | //----------------------------------------------------------------------------- // Copyright (c) 2020-present Detlef Stern // // This file is part of zettelstore-client. // // Zettelstore client 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 zmk_test provides some tests for the zettelmarkup parser. package zmk_test import ( "fmt" "strings" "testing" "t73f.de/r/sx" "t73f.de/r/zsc/input" "t73f.de/r/zsc/sz" "t73f.de/r/zsc/sz/zmk" ) type TestCase struct{ source, want string } type TestCases []TestCase type symbolMap map[string]*sx.Symbol func replace(s string, sm symbolMap, tcs TestCases) TestCases { var sym string if len(sm) > 0 { sym = sm[s].GetValue() } var testCases TestCases for _, tc := range tcs { source := strings.ReplaceAll(tc.source, "$", s) want := tc.want if sym != "" { want = strings.ReplaceAll(want, "$%", sym) } want = strings.ReplaceAll(want, "$", s) testCases = append(testCases, TestCase{source, want}) } return testCases } func checkTcs(t *testing.T, isBlock bool, tcs TestCases) { t.Helper() for tcn, tc := range tcs { t.Run(fmt.Sprintf("TC=%02d,src=%q", tcn, tc.source), func(st *testing.T) { st.Helper() ast := parseInput(tc.source, isBlock) got := ast.String() if tc.want != got { st.Errorf("\nwant=%q\n got=%q", tc.want, got) } }) } } func parseInput(src string, asBlock bool) sx.Sequence { inp := input.NewInput([]byte(src)) if asBlock { bl := zmk.ParseBlocks(inp) return bl } il := zmk.ParseInlines(inp) return il } func TestEOL(t *testing.T) { t.Parallel() for _, isBlock := range []bool{true, false} { checkTcs(t, isBlock, TestCases{ {"", "()"}, {"\n", "()"}, {"\r", "()"}, {"\r\n", "()"}, {"\n\n", "()"}, }) } } func TestText(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"abcd", "(INLINE (TEXT \"abcd\"))"}, {"ab cd", "(INLINE (TEXT \"ab\") (SPACE) (TEXT \"cd\"))"}, {"abcd ", "(INLINE (TEXT \"abcd\"))"}, {" abcd", "(INLINE (TEXT \"abcd\"))"}, {"\\", "(INLINE (TEXT \"\\\\\"))"}, {"\\\n", "()"}, {"\\\ndef", "(INLINE (HARD) (TEXT \"def\"))"}, {"\\\r", "()"}, {"\\\rdef", "(INLINE (HARD) (TEXT \"def\"))"}, {"\\\r\n", "()"}, {"\\\r\ndef", "(INLINE (HARD) (TEXT \"def\"))"}, {"\\a", "(INLINE (TEXT \"a\"))"}, {"\\aa", "(INLINE (TEXT \"aa\"))"}, {"a\\a", "(INLINE (TEXT \"aa\"))"}, {"\\+", "(INLINE (TEXT \"+\"))"}, {"\\ ", "(INLINE (TEXT \"\u00a0\"))"}, {"http://a, http://b", "(INLINE (TEXT \"http://a,\") (SPACE) (TEXT \"http://b\"))"}, }) } func TestSpace(t *testing.T) { t.Parallel() for _, isBlock := range []bool{true, false} { checkTcs(t, isBlock, TestCases{ {" ", "()"}, {"\t", "()"}, {" ", "()"}, }) } } func TestSoftBreak(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"x\ny", "(INLINE (TEXT \"x\") (SOFT) (TEXT \"y\"))"}, {"z\n", "(INLINE (TEXT \"z\"))"}, {" \n ", "()"}, {" \n", "()"}, }) } func TestHardBreak(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"x \ny", "(INLINE (TEXT \"x\") (HARD) (TEXT \"y\"))"}, {"z \n", "(INLINE (TEXT \"z\"))"}, {" \n ", "()"}, {" \n", "()"}, }) } func TestLink(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"[", "(INLINE (TEXT \"[\"))"}, {"[[", "(INLINE (TEXT \"[[\"))"}, {"[[|", "(INLINE (TEXT \"[[|\"))"}, {"[[]", "(INLINE (TEXT \"[[]\"))"}, {"[[|]", "(INLINE (TEXT \"[[|]\"))"}, {"[[]]", "(INLINE (TEXT \"[[]]\"))"}, {"[[|]]", "(INLINE (TEXT \"[[|]]\"))"}, {"[[ ]]", "(INLINE (TEXT \"[[\") (SPACE) (TEXT \"]]\"))"}, {"[[\n]]", "(INLINE (TEXT \"[[\") (SOFT) (TEXT \"]]\"))"}, {"[[ a]]", "(INLINE (LINK-EXTERNAL () \"a\"))"}, {"[[a ]]", "(INLINE (TEXT \"[[a\") (SPACE) (TEXT \"]]\"))"}, {"[[a\n]]", "(INLINE (TEXT \"[[a\") (SOFT) (TEXT \"]]\"))"}, {"[[a]]", "(INLINE (LINK-EXTERNAL () \"a\"))"}, {"[[12345678901234]]", "(INLINE (LINK-ZETTEL () \"12345678901234\"))"}, {"[[a]", "(INLINE (TEXT \"[[a]\"))"}, {"[[|a]]", "(INLINE (TEXT \"[[|a]]\"))"}, {"[[b|]]", "(INLINE (TEXT \"[[b|]]\"))"}, {"[[b|a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"b\")))"}, {"[[b| a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"b\")))"}, {"[[b%c|a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"b%c\")))"}, {"[[b%%c|a]]", "(INLINE (TEXT \"[[b\") (LITERAL-COMMENT () \"c|a]]\"))"}, {"[[b|a]", "(INLINE (TEXT \"[[b|a]\"))"}, {"[[b\nc|a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"b\") (SOFT) (TEXT \"c\")))"}, {"[[b c|a#n]]", "(INLINE (LINK-EXTERNAL () \"a#n\" (TEXT \"b\") (SPACE) (TEXT \"c\")))"}, {"[[a]]go", "(INLINE (LINK-EXTERNAL () \"a\") (TEXT \"go\"))"}, {"[[b|a]]{go}", "(INLINE (LINK-EXTERNAL ((\"go\" . \"\")) \"a\" (TEXT \"b\")))"}, {"[[[[a]]|b]]", "(INLINE (TEXT \"[[\") (LINK-EXTERNAL () \"a\") (TEXT \"|b]]\"))"}, {"[[a[b]c|d]]", "(INLINE (LINK-EXTERNAL () \"d\" (TEXT \"a[b]c\")))"}, {"[[[b]c|d]]", "(INLINE (TEXT \"[\") (LINK-EXTERNAL () \"d\" (TEXT \"b]c\")))"}, {"[[a[]c|d]]", "(INLINE (LINK-EXTERNAL () \"d\" (TEXT \"a[]c\")))"}, {"[[a[b]|d]]", "(INLINE (LINK-EXTERNAL () \"d\" (TEXT \"a[b]\")))"}, {"[[\\|]]", "(INLINE (LINK-EXTERNAL () \"\\\\|\"))"}, {"[[\\||a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"|\")))"}, {"[[b\\||a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"b|\")))"}, {"[[b\\|c|a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"b|c\")))"}, {"[[\\]]]", "(INLINE (LINK-EXTERNAL () \"\\\\]\"))"}, {"[[\\]|a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"]\")))"}, {"[[b\\]|a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"b]\")))"}, {"[[\\]\\||a]]", "(INLINE (LINK-EXTERNAL () \"a\" (TEXT \"]|\")))"}, {"[[http://a]]", "(INLINE (LINK-EXTERNAL () \"http://a\"))"}, {"[[http://a|http://a]]", "(INLINE (LINK-EXTERNAL () \"http://a\" (TEXT \"http://a\")))"}, {"[[[[a]]]]", "(INLINE (TEXT \"[[\") (LINK-EXTERNAL () \"a\") (TEXT \"]]\"))"}, {"[[query:title]]", "(INLINE (LINK-QUERY () \"title\"))"}, {"[[query:title syntax]]", "(INLINE (LINK-QUERY () \"title syntax\"))"}, {"[[query:title | action]]", "(INLINE (LINK-QUERY () \"title | action\"))"}, {"[[Text|query:title]]", "(INLINE (LINK-QUERY () \"title\" (TEXT \"Text\")))"}, {"[[Text|query:title syntax]]", "(INLINE (LINK-QUERY () \"title syntax\" (TEXT \"Text\")))"}, {"[[Text|query:title | action]]", "(INLINE (LINK-QUERY () \"title | action\" (TEXT \"Text\")))"}, }) } func TestEmbed(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"{", "(INLINE (TEXT \"{\"))"}, {"{{", "(INLINE (TEXT \"{{\"))"}, {"{{|", "(INLINE (TEXT \"{{|\"))"}, {"{{}", "(INLINE (TEXT \"{{}\"))"}, {"{{|}", "(INLINE (TEXT \"{{|}\"))"}, {"{{}}", "(INLINE (TEXT \"{{}}\"))"}, {"{{|}}", "(INLINE (TEXT \"{{|}}\"))"}, {"{{ }}", "(INLINE (TEXT \"{{\") (SPACE) (TEXT \"}}\"))"}, {"{{\n}}", "(INLINE (TEXT \"{{\") (SOFT) (TEXT \"}}\"))"}, {"{{a }}", "(INLINE (TEXT \"{{a\") (SPACE) (TEXT \"}}\"))"}, {"{{a\n}}", "(INLINE (TEXT \"{{a\") (SOFT) (TEXT \"}}\"))"}, {"{{a}}", "(INLINE (EMBED () \"a\"))"}, {"{{12345678901234}}", "(INLINE (EMBED () \"12345678901234\"))"}, {"{{ a}}", "(INLINE (EMBED () \"a\"))"}, {"{{a}", "(INLINE (TEXT \"{{a}\"))"}, {"{{|a}}", "(INLINE (TEXT \"{{|a}}\"))"}, {"{{b|}}", "(INLINE (TEXT \"{{b|}}\"))"}, {"{{b|a}}", "(INLINE (EMBED () \"a\" (TEXT \"b\")))"}, {"{{b| a}}", "(INLINE (EMBED () \"a\" (TEXT \"b\")))"}, {"{{b|a}", "(INLINE (TEXT \"{{b|a}\"))"}, {"{{b\nc|a}}", "(INLINE (EMBED () \"a\" (TEXT \"b\") (SOFT) (TEXT \"c\")))"}, {"{{b c|a#n}}", "(INLINE (EMBED () \"a#n\" (TEXT \"b\") (SPACE) (TEXT \"c\")))"}, {"{{a}}{go}", "(INLINE (EMBED ((\"go\" . \"\")) \"a\"))"}, {"{{{{a}}|b}}", "(INLINE (TEXT \"{{\") (EMBED () \"a\") (TEXT \"|b}}\"))"}, {"{{\\|}}", "(INLINE (EMBED () \"\\\\|\"))"}, {"{{\\||a}}", "(INLINE (EMBED () \"a\" (TEXT \"|\")))"}, {"{{b\\||a}}", "(INLINE (EMBED () \"a\" (TEXT \"b|\")))"}, {"{{b\\|c|a}}", "(INLINE (EMBED () \"a\" (TEXT \"b|c\")))"}, {"{{\\}}}", "(INLINE (EMBED () \"\\\\}\"))"}, {"{{\\}|a}}", "(INLINE (EMBED () \"a\" (TEXT \"}\")))"}, {"{{b\\}|a}}", "(INLINE (EMBED () \"a\" (TEXT \"b}\")))"}, {"{{\\}\\||a}}", "(INLINE (EMBED () \"a\" (TEXT \"}|\")))"}, {"{{http://a}}", "(INLINE (EMBED () \"http://a\"))"}, {"{{http://a|http://a}}", "(INLINE (EMBED () \"http://a\" (TEXT \"http://a\")))"}, {"{{{{a}}}}", "(INLINE (TEXT \"{{\") (EMBED () \"a\") (TEXT \"}}\"))"}, }) } func TestCite(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"[@", "(INLINE (TEXT \"[@\"))"}, {"[@]", "(INLINE (TEXT \"[@]\"))"}, {"[@a]", "(INLINE (CITE () \"a\"))"}, {"[@ a]", "(INLINE (TEXT \"[@\") (SPACE) (TEXT \"a]\"))"}, {"[@a ]", "(INLINE (CITE () \"a\"))"}, {"[@a\n]", "(INLINE (CITE () \"a\"))"}, {"[@a\nx]", "(INLINE (CITE () \"a\" (SOFT) (TEXT \"x\")))"}, {"[@a\n\n]", "(INLINE (TEXT \"[@a\") (SOFT) (SOFT) (TEXT \"]\"))"}, {"[@a,\n]", "(INLINE (CITE () \"a\"))"}, {"[@a,n]", "(INLINE (CITE () \"a\" (TEXT \"n\")))"}, {"[@a| n]", "(INLINE (CITE () \"a\" (TEXT \"n\")))"}, {"[@a|n ]", "(INLINE (CITE () \"a\" (TEXT \"n\")))"}, {"[@a,[@b]]", "(INLINE (CITE () \"a\" (CITE () \"b\")))"}, {"[@a]{color=green}", "(INLINE (CITE ((\"color\" . \"green\")) \"a\"))"}, }) checkTcs(t, true, TestCases{ {"[@a\n\n]", "(BLOCK (PARA (TEXT \"[@a\")) (PARA (TEXT \"]\")))"}, }) } func TestEndnote(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"[^", "(INLINE (TEXT \"[^\"))"}, {"[^]", "(INLINE (ENDNOTE ()))"}, {"[^abc]", "(INLINE (ENDNOTE () (TEXT \"abc\")))"}, {"[^abc ]", "(INLINE (ENDNOTE () (TEXT \"abc\")))"}, {"[^abc\ndef]", "(INLINE (ENDNOTE () (TEXT \"abc\") (SOFT) (TEXT \"def\")))"}, {"[^abc\n\ndef]", "(INLINE (TEXT \"[^abc\") (SOFT) (SOFT) (TEXT \"def]\"))"}, {"[^abc[^def]]", "(INLINE (ENDNOTE () (TEXT \"abc\") (ENDNOTE () (TEXT \"def\"))))"}, {"[^abc]{-}", "(INLINE (ENDNOTE ((\"-\" . \"\")) (TEXT \"abc\")))"}, }) checkTcs(t, true, TestCases{ {"[^abc\n\ndef]", "(BLOCK (PARA (TEXT \"[^abc\")) (PARA (TEXT \"def]\")))"}, }) } func TestMark(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"[!", "(INLINE (TEXT \"[!\"))"}, {"[!\n", "(INLINE (TEXT \"[!\"))"}, {"[!]", "(INLINE (MARK \"\" \"\" \"\"))"}, {"[!][!]", "(INLINE (MARK \"\" \"\" \"\") (MARK \"\" \"\" \"\"))"}, {"[! ]", "(INLINE (TEXT \"[!\") (SPACE) (TEXT \"]\"))"}, {"[!a]", "(INLINE (MARK \"a\" \"\" \"\"))"}, {"[!a][!a]", "(INLINE (MARK \"a\" \"\" \"\") (MARK \"a\" \"\" \"\"))"}, {"[!a ]", "(INLINE (TEXT \"[!a\") (SPACE) (TEXT \"]\"))"}, {"[!a_]", "(INLINE (MARK \"a_\" \"\" \"\"))"}, {"[!a_][!a]", "(INLINE (MARK \"a_\" \"\" \"\") (MARK \"a\" \"\" \"\"))"}, {"[!a-b]", "(INLINE (MARK \"a-b\" \"\" \"\"))"}, {"[!a|b]", "(INLINE (MARK \"a\" \"\" \"\" (TEXT \"b\")))"}, {"[!a|]", "(INLINE (MARK \"a\" \"\" \"\"))"}, {"[!|b]", "(INLINE (MARK \"\" \"\" \"\" (TEXT \"b\")))"}, {"[!|b ]", "(INLINE (MARK \"\" \"\" \"\" (TEXT \"b\")))"}, {"[!|b c]", "(INLINE (MARK \"\" \"\" \"\" (TEXT \"b\") (SPACE) (TEXT \"c\")))"}, }) } func TestComment(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"%", "(INLINE (TEXT \"%\"))"}, {"%%", "(INLINE (LITERAL-COMMENT () \"\"))"}, {"%\n", "(INLINE (TEXT \"%\"))"}, {"%%\n", "(INLINE (LITERAL-COMMENT () \"\"))"}, {"%%a", "(INLINE (LITERAL-COMMENT () \"a\"))"}, {"%%%a", "(INLINE (LITERAL-COMMENT () \"a\"))"}, {"%% a", "(INLINE (LITERAL-COMMENT () \"a\"))"}, {"%%% a", "(INLINE (LITERAL-COMMENT () \"a\"))"}, {"%% % a", "(INLINE (LITERAL-COMMENT () \"% a\"))"}, {"%%a", "(INLINE (LITERAL-COMMENT () \"a\"))"}, {"a%%b", "(INLINE (TEXT \"a\") (LITERAL-COMMENT () \"b\"))"}, {"a %%b", "(INLINE (TEXT \"a\") (SPACE) (LITERAL-COMMENT () \"b\"))"}, {" %%b", "(INLINE (LITERAL-COMMENT () \"b\"))"}, {"%%b ", "(INLINE (LITERAL-COMMENT () \"b \"))"}, {"100%", "(INLINE (TEXT \"100%\"))"}, {"%%{=}a", "(INLINE (LITERAL-COMMENT ((\"\" . \"\")) \"a\"))"}, }) } func TestFormat(t *testing.T) { symMap := symbolMap{ "_": sz.SymFormatEmph, "*": sz.SymFormatStrong, ">": sz.SymFormatInsert, "~": sz.SymFormatDelete, "^": sz.SymFormatSuper, ",": sz.SymFormatSub, "#": sz.SymFormatMark, ":": sz.SymFormatSpan, } t.Parallel() // Not for Insert / '>', because collision with quoted list // Not for Quote / '"', because escaped representation. for _, ch := range []string{"_", "*", "~", "^", ",", "#", ":"} { checkTcs(t, false, replace(ch, symMap, TestCases{ {"$", "(INLINE (TEXT \"$\"))"}, {"$$", "(INLINE (TEXT \"$$\"))"}, {"$$$", "(INLINE (TEXT \"$$$\"))"}, {"$$$$", "(INLINE ($% ()))"}, })) } // Not for Quote / '"', because escaped representation. for _, ch := range []string{"_", "*", ">", "~", "^", ",", "#", ":"} { checkTcs(t, false, replace(ch, symMap, TestCases{ {"$$a$$", "(INLINE ($% () (TEXT \"a\")))"}, {"$$a$$$", "(INLINE ($% () (TEXT \"a\")) (TEXT \"$\"))"}, {"$$$a$$", "(INLINE ($% () (TEXT \"$a\")))"}, {"$$$a$$$", "(INLINE ($% () (TEXT \"$a\")) (TEXT \"$\"))"}, {"$\\$", "(INLINE (TEXT \"$$\"))"}, {"$\\$$", "(INLINE (TEXT \"$$$\"))"}, {"$$\\$", "(INLINE (TEXT \"$$$\"))"}, {"$$a\\$$", "(INLINE (TEXT \"$$a$$\"))"}, {"$$a$\\$", "(INLINE (TEXT \"$$a$$\"))"}, {"$$a\\$$$", "(INLINE ($% () (TEXT \"a$\")))"}, {"$$a\na$$", "(INLINE ($% () (TEXT \"a\") (SOFT) (TEXT \"a\")))"}, {"$$a\n\na$$", "(INLINE (TEXT \"$$a\") (SOFT) (SOFT) (TEXT \"a$$\"))"}, {"$$a$${go}", "(INLINE ($% ((\"go\" . \"\")) (TEXT \"a\")))"}, })) checkTcs(t, true, replace(ch, symMap, TestCases{ {"$$a\n\na$$", "(BLOCK (PARA (TEXT \"$$a\")) (PARA (TEXT \"a$$\")))"}, })) } checkTcs(t, false, replace(`"`, symbolMap{`"`: sz.SymFormatQuote}, TestCases{ {"$", "(INLINE (TEXT \"\\\"\"))"}, {"$$", "(INLINE (TEXT \"\\\"\\\"\"))"}, {"$$$", "(INLINE (TEXT \"\\\"\\\"\\\"\"))"}, {"$$$$", "(INLINE ($% ()))"}, {"$$a$$", "(INLINE ($% () (TEXT \"a\")))"}, {"$$a$$$", "(INLINE ($% () (TEXT \"a\")) (TEXT \"\\\"\"))"}, {"$$$a$$", "(INLINE ($% () (TEXT \"\\\"a\")))"}, {"$$$a$$$", "(INLINE ($% () (TEXT \"\\\"a\")) (TEXT \"\\\"\"))"}, {"$\\$", "(INLINE (TEXT \"\\\"\\\"\"))"}, {"$\\$$", "(INLINE (TEXT \"\\\"\\\"\\\"\"))"}, {"$$\\$", "(INLINE (TEXT \"\\\"\\\"\\\"\"))"}, {"$$a\\$$", "(INLINE (TEXT \"\\\"\\\"a\\\"\\\"\"))"}, {"$$a$\\$", "(INLINE (TEXT \"\\\"\\\"a\\\"\\\"\"))"}, {"$$a\\$$$", "(INLINE ($% () (TEXT \"a\\\"\")))"}, {"$$a\na$$", "(INLINE ($% () (TEXT \"a\") (SOFT) (TEXT \"a\")))"}, {"$$a\n\na$$", "(INLINE (TEXT \"\\\"\\\"a\") (SOFT) (SOFT) (TEXT \"a\\\"\\\"\"))"}, {"$$a$${go}", "(INLINE ($% ((\"go\" . \"\")) (TEXT \"a\")))"}, })) checkTcs(t, false, TestCases{ {"__****__", "(INLINE (FORMAT-EMPH () (FORMAT-STRONG ())))"}, {"__**a**__", "(INLINE (FORMAT-EMPH () (FORMAT-STRONG () (TEXT \"a\"))))"}, {"__**__**", "(INLINE (TEXT \"__\") (FORMAT-STRONG () (TEXT \"__\")))"}, }) } func TestLiteral(t *testing.T) { symMap := symbolMap{ "@": sz.SymLiteralZettel, "`": sz.SymLiteralProg, "'": sz.SymLiteralInput, "=": sz.SymLiteralOutput, } t.Parallel() for _, ch := range []string{"@", "`", "'", "="} { checkTcs(t, false, replace(ch, symMap, TestCases{ {"$", "(INLINE (TEXT \"$\"))"}, {"$$", "(INLINE (TEXT \"$$\"))"}, {"$$$", "(INLINE (TEXT \"$$$\"))"}, {"$$$$", "(INLINE ($% () \"\"))"}, {"$$a$$", "(INLINE ($% () \"a\"))"}, {"$$a$$$", "(INLINE ($% () \"a\") (TEXT \"$\"))"}, {"$$$a$$", "(INLINE ($% () \"$a\"))"}, {"$$$a$$$", "(INLINE ($% () \"$a\") (TEXT \"$\"))"}, {"$\\$", "(INLINE (TEXT \"$$\"))"}, {"$\\$$", "(INLINE (TEXT \"$$$\"))"}, {"$$\\$", "(INLINE (TEXT \"$$$\"))"}, {"$$a\\$$", "(INLINE (TEXT \"$$a$$\"))"}, {"$$a$\\$", "(INLINE (TEXT \"$$a$$\"))"}, {"$$a\\$$$", "(INLINE ($% () \"a$\"))"}, {"$$a$${go}", "(INLINE ($% ((\"go\" . \"\")) \"a\"))"}, })) } checkTcs(t, false, TestCases{ {"''````''", "(INLINE (LITERAL-INPUT () \"````\"))"}, {"''``a``''", "(INLINE (LITERAL-INPUT () \"``a``\"))"}, {"''``''``", "(INLINE (LITERAL-INPUT () \"``\") (TEXT \"``\"))"}, {"''\\'''", "(INLINE (LITERAL-INPUT () \"'\"))"}, }) checkTcs(t, false, TestCases{ {"@@HTML@@{=html}", "(INLINE (LITERAL-HTML () \"HTML\"))"}, {"@@HTML@@{=html lang=en}", "(INLINE (LITERAL-HTML ((\"lang\" . \"en\")) \"HTML\"))"}, {"@@HTML@@{=html,lang=en}", "(INLINE (LITERAL-HTML ((\"lang\" . \"en\")) \"HTML\"))"}, }) } func TestLiteralMath(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"$", "(INLINE (TEXT \"$\"))"}, {"$$", "(INLINE (TEXT \"$$\"))"}, {"$$$", "(INLINE (TEXT \"$$$\"))"}, {"$$$$", "(INLINE (LITERAL-MATH () \"\"))"}, {"$$a$$", "(INLINE (LITERAL-MATH () \"a\"))"}, {"$$a$$$", "(INLINE (LITERAL-MATH () \"a\") (TEXT \"$\"))"}, {"$$$a$$", "(INLINE (LITERAL-MATH () \"$a\"))"}, {"$$$a$$$", "(INLINE (LITERAL-MATH () \"$a\") (TEXT \"$\"))"}, {`$\$`, "(INLINE (TEXT \"$$\"))"}, {`$\$$`, "(INLINE (TEXT \"$$$\"))"}, {`$$\$`, "(INLINE (TEXT \"$$$\"))"}, {`$$a\$$`, "(INLINE (LITERAL-MATH () \"a\\\\\"))"}, {`$$a$\$`, "(INLINE (TEXT \"$$a$$\"))"}, {`$$a\$$$`, "(INLINE (LITERAL-MATH () \"a\\\\\") (TEXT \"$\"))"}, {"$$a$${go}", "(INLINE (LITERAL-MATH ((\"go\" . \"\")) \"a\"))"}, }) } func TestMixFormatCode(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"__abc__\n**def**", "(INLINE (FORMAT-EMPH () (TEXT \"abc\")) (SOFT) (FORMAT-STRONG () (TEXT \"def\")))"}, {"''abc''\n==def==", "(INLINE (LITERAL-INPUT () \"abc\") (SOFT) (LITERAL-OUTPUT () \"def\"))"}, {"__abc__\n==def==", "(INLINE (FORMAT-EMPH () (TEXT \"abc\")) (SOFT) (LITERAL-OUTPUT () \"def\"))"}, {"__abc__\n``def``", "(INLINE (FORMAT-EMPH () (TEXT \"abc\")) (SOFT) (LITERAL-CODE () \"def\"))"}, { "\"\"ghi\"\"\n::abc::\n``def``\n", "(INLINE (FORMAT-QUOTE () (TEXT \"ghi\")) (SOFT) (FORMAT-SPAN () (TEXT \"abc\")) (SOFT) (LITERAL-CODE () \"def\"))", }, }) } func TestNDash(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"--", "(INLINE (TEXT \"\u2013\"))"}, {"a--b", "(INLINE (TEXT \"a\u2013b\"))"}, }) } func TestEntity(t *testing.T) { t.Parallel() checkTcs(t, false, TestCases{ {"&", "(INLINE (TEXT \"&\"))"}, {"&;", "(INLINE (TEXT \"&;\"))"}, {"&#;", "(INLINE (TEXT \"&#;\"))"}, {"a;", "(INLINE (TEXT \"a;\"))"}, {"&#x;", "(INLINE (TEXT \"&#x;\"))"}, {"�z;", "(INLINE (TEXT \"�z;\"))"}, {"&1;", "(INLINE (TEXT \"&1;\"))"}, {"	", "(INLINE (TEXT \"	\"))"}, // Numeric entities below space are not allowed. {"", "(INLINE (TEXT \"\"))"}, // Good cases {"<", "(INLINE (TEXT \"<\"))"}, {"0", "(INLINE (TEXT \"0\"))"}, {"J", "(INLINE (TEXT \"J\"))"}, {"J", "(INLINE (TEXT \"J\"))"}, {"…", "(INLINE (TEXT \"\u2026\"))"}, {" ", "(INLINE (TEXT \"\u00a0\"))"}, {"E: &,?;c.", "(INLINE (TEXT \"E:\") (SPACE) (TEXT \"&,?;c.\"))"}, }) } func TestVerbatimZettel(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"@@@\n@@@", "()"}, {"@@@\nabc\n@@@", "(BLOCK (VERBATIM-ZETTEL () \"abc\"))"}, {"@@@@def\nabc\n@@@@", "(BLOCK (VERBATIM-ZETTEL ((\"\" . \"def\")) \"abc\"))"}, }) } func TestVerbatimCode(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"```\n```", "()"}, {"```\nabc\n```", "(BLOCK (VERBATIM-CODE () \"abc\"))"}, {"```\nabc\n````", "(BLOCK (VERBATIM-CODE () \"abc\"))"}, {"````\nabc\n````", "(BLOCK (VERBATIM-CODE () \"abc\"))"}, {"````\nabc\n```\n````", "(BLOCK (VERBATIM-CODE () \"abc\\n```\"))"}, {"````go\nabc\n````", "(BLOCK (VERBATIM-CODE ((\"\" . \"go\")) \"abc\"))"}, }) } func TestVerbatimEval(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"~~~\n~~~", "()"}, {"~~~\nabc\n~~~", "(BLOCK (VERBATIM-EVAL () \"abc\"))"}, {"~~~\nabc\n~~~~", "(BLOCK (VERBATIM-EVAL () \"abc\"))"}, {"~~~~\nabc\n~~~~", "(BLOCK (VERBATIM-EVAL () \"abc\"))"}, {"~~~~\nabc\n~~~\n~~~~", "(BLOCK (VERBATIM-EVAL () \"abc\\n~~~\"))"}, {"~~~~go\nabc\n~~~~", "(BLOCK (VERBATIM-EVAL ((\"\" . \"go\")) \"abc\"))"}, }) } func TestVerbatimMath(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"$$$\n$$$", "()"}, {"$$$\nabc\n$$$", "(BLOCK (VERBATIM-MATH () \"abc\"))"}, {"$$$\nabc\n$$$$", "(BLOCK (VERBATIM-MATH () \"abc\"))"}, {"$$$$\nabc\n$$$$", "(BLOCK (VERBATIM-MATH () \"abc\"))"}, {"$$$$\nabc\n$$$\n$$$$", "(BLOCK (VERBATIM-MATH () \"abc\\n$$$\"))"}, {"$$$$go\nabc\n$$$$", "(BLOCK (VERBATIM-MATH ((\"\" . \"go\")) \"abc\"))"}, }) } func TestVerbatimComment(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"%%%\n%%%", "()"}, {"%%%\nabc\n%%%", "(BLOCK (VERBATIM-COMMENT () \"abc\"))"}, {"%%%%go\nabc\n%%%%", "(BLOCK (VERBATIM-COMMENT ((\"\" . \"go\")) \"abc\"))"}, }) } func TestPara(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"a\n\nb", "(BLOCK (PARA (TEXT \"a\")) (PARA (TEXT \"b\")))"}, {"a\n \nb", "(BLOCK (PARA (TEXT \"a\") (SOFT) (HARD) (TEXT \"b\")))"}, }) } func TestSpanRegion(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {":::\n:::", "()"}, {":::\nabc\n:::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"abc\")))))"}, {":::\nabc\n::::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"abc\")))))"}, {"::::\nabc\n::::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"abc\")))))"}, {"::::\nabc\n:::\ndef\n:::\n::::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"abc\")) (REGION-BLOCK () ((PARA (TEXT \"def\")))))))"}, {":::{go}\n:::a", "(BLOCK (REGION-BLOCK ((\"go\" . \"\")) () (TEXT \"a\")))"}, {":::\nabc\n::: def ", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"abc\"))) (TEXT \"def\")))"}, }) } func TestQuoteRegion(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"<<<\n<<<", "()"}, {"<<<\nabc\n<<<", "(BLOCK (REGION-QUOTE () ((PARA (TEXT \"abc\")))))"}, {"<<<\nabc\n<<<<", "(BLOCK (REGION-QUOTE () ((PARA (TEXT \"abc\")))))"}, {"<<<<\nabc\n<<<<", "(BLOCK (REGION-QUOTE () ((PARA (TEXT \"abc\")))))"}, {"<<<<\nabc\n<<<\ndef\n<<<\n<<<<", "(BLOCK (REGION-QUOTE () ((PARA (TEXT \"abc\")) (REGION-QUOTE () ((PARA (TEXT \"def\")))))))"}, {"<<<go\n<<< a", "(BLOCK (REGION-QUOTE ((\"\" . \"go\")) () (TEXT \"a\")))"}, {"<<<\nabc\n<<< def ", "(BLOCK (REGION-QUOTE () ((PARA (TEXT \"abc\"))) (TEXT \"def\")))"}, }) } func TestVerseRegion(t *testing.T) { t.Parallel() checkTcs(t, true, replace("\"", nil, TestCases{ {"$$$\n$$$", "()"}, {"$$$\nabc\n$$$", "(BLOCK (REGION-VERSE () ((PARA (TEXT \"abc\")))))"}, {"$$$\nabc\n$$$$", "(BLOCK (REGION-VERSE () ((PARA (TEXT \"abc\")))))"}, {"$$$$\nabc\n$$$$", "(BLOCK (REGION-VERSE () ((PARA (TEXT \"abc\")))))"}, {"$$$\nabc\ndef\n$$$", "(BLOCK (REGION-VERSE () ((PARA (TEXT \"abc\") (HARD) (TEXT \"def\")))))"}, {"$$$$\nabc\n$$$\ndef\n$$$\n$$$$", "(BLOCK (REGION-VERSE () ((PARA (TEXT \"abc\")) (REGION-VERSE () ((PARA (TEXT \"def\")))))))"}, {"$$$go\n$$$x", "(BLOCK (REGION-VERSE ((\"\" . \"go\")) () (TEXT \"x\")))"}, {"$$$\nabc\n$$$ def ", "(BLOCK (REGION-VERSE () ((PARA (TEXT \"abc\"))) (TEXT \"def\")))"}, {"$$$\n space \n$$$", "(BLOCK (REGION-VERSE () ((PARA (SPACE \"\u00a0\") (TEXT \"space\")))))"}, {"$$$\n spaces \n$$$", "(BLOCK (REGION-VERSE () ((PARA (SPACE \"\u00a0\u00a0\") (TEXT \"spaces\")))))"}, {"$$$\n spaces \n space \n$$$", "(BLOCK (REGION-VERSE () ((PARA (SPACE \"\u00a0\u00a0\") (TEXT \"spaces\") (SPACE \"\u00a0\u00a0\") (HARD) (SPACE \"\u00a0\") (TEXT \"space\")))))"}, })) } func TestHeading(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"=h", "(BLOCK (PARA (TEXT \"=h\")))"}, {"= h", "(BLOCK (PARA (TEXT \"=\") (SPACE) (TEXT \"h\")))"}, {"==h", "(BLOCK (PARA (TEXT \"==h\")))"}, {"== h", "(BLOCK (PARA (TEXT \"==\") (SPACE) (TEXT \"h\")))"}, {"===h", "(BLOCK (PARA (TEXT \"===h\")))"}, {"===", "(BLOCK (PARA (TEXT \"===\")))"}, {"=== h", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h\")))"}, {"=== h", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h\")))"}, {"==== h", "(BLOCK (HEADING 2 () \"\" \"\" (TEXT \"h\")))"}, {"===== h", "(BLOCK (HEADING 3 () \"\" \"\" (TEXT \"h\")))"}, {"====== h", "(BLOCK (HEADING 4 () \"\" \"\" (TEXT \"h\")))"}, {"======= h", "(BLOCK (HEADING 5 () \"\" \"\" (TEXT \"h\")))"}, {"======== h", "(BLOCK (HEADING 5 () \"\" \"\" (TEXT \"h\")))"}, {"=", "(BLOCK (PARA (TEXT \"=\")))"}, {"=== h=__=a__", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h=\") (FORMAT-EMPH () (TEXT \"=a\"))))"}, {"=\n", "(BLOCK (PARA (TEXT \"=\")))"}, {"a=", "(BLOCK (PARA (TEXT \"a=\")))"}, {" =", "(BLOCK (PARA (TEXT \"=\")))"}, {"=== h\na", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h\")) (PARA (TEXT \"a\")))"}, {"=== h i {-}", "(BLOCK (HEADING 1 ((\"-\" . \"\")) \"\" \"\" (TEXT \"h\") (SPACE) (TEXT \"i\")))"}, {"=== h {{a}}", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h\") (SPACE) (EMBED () \"a\")))"}, {"=== h{{a}}", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h\") (EMBED () \"a\")))"}, {"=== {{a}}", "(BLOCK (HEADING 1 () \"\" \"\" (EMBED () \"a\")))"}, {"=== h {{a}}{-}", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h\") (SPACE) (EMBED ((\"-\" . \"\")) \"a\")))"}, {"=== h {{a}} {-}", "(BLOCK (HEADING 1 ((\"-\" . \"\")) \"\" \"\" (TEXT \"h\") (SPACE) (EMBED () \"a\")))"}, {"=== h {-}{{a}}", "(BLOCK (HEADING 1 ((\"-\" . \"\")) \"\" \"\" (TEXT \"h\")))"}, {"=== h{id=abc}", "(BLOCK (HEADING 1 ((\"id\" . \"abc\")) \"\" \"\" (TEXT \"h\")))"}, {"=== h\n=== h", "(BLOCK (HEADING 1 () \"\" \"\" (TEXT \"h\")) (HEADING 1 () \"\" \"\" (TEXT \"h\")))"}, }) } func TestHRule(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"-", "(BLOCK (PARA (TEXT \"-\")))"}, {"---", "(BLOCK (THEMATIC ()))"}, {"----", "(BLOCK (THEMATIC ()))"}, {"---A", "(BLOCK (THEMATIC ((\"\" . \"A\"))))"}, {"---A-", "(BLOCK (THEMATIC ((\"\" . \"A-\"))))"}, {"-1", "(BLOCK (PARA (TEXT \"-1\")))"}, {"2-1", "(BLOCK (PARA (TEXT \"2-1\")))"}, {"--- { go } ", "(BLOCK (THEMATIC ((\"go\" . \"\"))))"}, {"--- { .go } ", "(BLOCK (THEMATIC ((\"class\" . \"go\"))))"}, }) } func TestList(t *testing.T) { t.Parallel() // No ">" in the following, because quotation lists may have empty items. for _, ch := range []string{"*", "#"} { checkTcs(t, true, replace(ch, nil, TestCases{ {"$", "(BLOCK (PARA (TEXT \"$\")))"}, {"$$", "(BLOCK (PARA (TEXT \"$$\")))"}, {"$$$", "(BLOCK (PARA (TEXT \"$$$\")))"}, {"$ ", "(BLOCK (PARA (TEXT \"$\")))"}, {"$$ ", "(BLOCK (PARA (TEXT \"$$\")))"}, {"$$$ ", "(BLOCK (PARA (TEXT \"$$$\")))"}, })) } checkTcs(t, true, TestCases{ {"* abc", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))))"}, {"** abc", "(BLOCK (UNORDERED (BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))))))"}, {"*** abc", "(BLOCK (UNORDERED (BLOCK (UNORDERED (BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))))))))"}, {"**** abc", "(BLOCK (UNORDERED (BLOCK (UNORDERED (BLOCK (UNORDERED (BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))))))))))"}, {"** abc\n**** def", "(BLOCK (UNORDERED (BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")) (UNORDERED (BLOCK (UNORDERED (BLOCK (PARA (TEXT \"def\")))))))))))"}, {"* abc\ndef", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))) (PARA (TEXT \"def\")))"}, {"* abc\n def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))) (PARA (TEXT \"def\")))"}, {"* abc\n* def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\"))) (BLOCK (PARA (TEXT \"def\")))))"}, {"* abc\n def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\") (SOFT) (TEXT \"def\")))))"}, {"* abc\n def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\") (SOFT) (TEXT \"def\")))))"}, {"* abc\n\ndef", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))) (PARA (TEXT \"def\")))"}, {"* abc\n\n def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))) (PARA (TEXT \"def\")))"}, {"* abc\n\n def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")) (PARA (TEXT \"def\")))))"}, {"* abc\n\n def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")) (PARA (TEXT \"def\")))))"}, {"* abc\n** def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")) (UNORDERED (BLOCK (PARA (TEXT \"def\")))))))"}, {"* abc\n** def\n* ghi", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")) (UNORDERED (BLOCK (PARA (TEXT \"def\"))))) (BLOCK (PARA (TEXT \"ghi\")))))"}, {"* abc\n\n def\n* ghi", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")) (PARA (TEXT \"def\"))) (BLOCK (PARA (TEXT \"ghi\")))))"}, {"* abc\n** def\n ghi\n jkl", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")) (UNORDERED (BLOCK (PARA (TEXT \"def\") (SOFT) (TEXT \"ghi\")))) (PARA (TEXT \"jkl\")))))"}, // A list does not last beyond a region {":::\n# abc\n:::\n# def", "(BLOCK (REGION-BLOCK () ((ORDERED (BLOCK (PARA (TEXT \"abc\")))))) (ORDERED (BLOCK (PARA (TEXT \"def\")))))"}, // A HRule creates a new list {"* abc\n---\n* def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))) (THEMATIC ()) (UNORDERED (BLOCK (PARA (TEXT \"def\")))))"}, // Changing list type adds a new list {"* abc\n# def", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))) (ORDERED (BLOCK (PARA (TEXT \"def\")))))"}, // Quotation lists may have empty items {">", "(BLOCK (QUOTATION (BLOCK)))"}, // Empty continuation {"* abc\n ", "(BLOCK (UNORDERED (BLOCK (PARA (TEXT \"abc\")))))"}, }) } func TestQuoteList(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"> w1 w2", "(BLOCK (QUOTATION (BLOCK (PARA (TEXT \"w1\") (SPACE) (TEXT \"w2\")))))"}, {"> w1\n> w2", "(BLOCK (QUOTATION (BLOCK (PARA (TEXT \"w1\") (SOFT) (TEXT \"w2\")))))"}, {"> w1\n>w2", "(BLOCK (QUOTATION (BLOCK (PARA (TEXT \"w1\")))) (PARA (TEXT \">w2\")))"}, {"> w1\n>\n>w2", "(BLOCK (QUOTATION (BLOCK (PARA (TEXT \"w1\"))) (BLOCK)) (PARA (TEXT \">w2\")))"}, {"> w1\n> \n> w2", "(BLOCK (QUOTATION (BLOCK (PARA (TEXT \"w1\"))) (BLOCK) (BLOCK (PARA (TEXT \"w2\")))))"}, }) } func TestEnumAfterPara(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"abc\n* def", "(BLOCK (PARA (TEXT \"abc\")) (UNORDERED (BLOCK (PARA (TEXT \"def\")))))"}, {"abc\n*def", "(BLOCK (PARA (TEXT \"abc\") (SOFT) (TEXT \"*def\")))"}, }) } func TestDefinition(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {";", "(BLOCK (PARA (TEXT \";\")))"}, {"; ", "(BLOCK (PARA (TEXT \";\")))"}, {"; abc", "(BLOCK (DESCRIPTION ((TEXT \"abc\"))))"}, {"; abc\ndef", "(BLOCK (DESCRIPTION ((TEXT \"abc\"))) (PARA (TEXT \"def\")))"}, {"; abc\n def", "(BLOCK (DESCRIPTION ((TEXT \"abc\"))) (PARA (TEXT \"def\")))"}, {"; abc\n def", "(BLOCK (DESCRIPTION ((TEXT \"abc\") (SOFT) (TEXT \"def\"))))"}, {"; abc\n def\n ghi", "(BLOCK (DESCRIPTION ((TEXT \"abc\") (SOFT) (TEXT \"def\") (SOFT) (TEXT \"ghi\"))))"}, {":", "(BLOCK (PARA (TEXT \":\")))"}, {": ", "(BLOCK (PARA (TEXT \":\")))"}, {": abc", "(BLOCK (PARA (TEXT \":\") (SPACE) (TEXT \"abc\")))"}, {"; abc\n: def", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\"))))))"}, {"; abc\n: def\nghi", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\"))))) (PARA (TEXT \"ghi\")))"}, {"; abc\n: def\n ghi", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\"))))) (PARA (TEXT \"ghi\")))"}, {"; abc\n: def\n ghi", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\") (SOFT) (TEXT \"ghi\"))))))"}, {"; abc\n: def\n\n ghi", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\"))) (PARA (TEXT \"ghi\")))))"}, {"; abc\n:", "(BLOCK (DESCRIPTION ((TEXT \"abc\"))) (PARA (TEXT \":\")))"}, {"; abc\n: def\n: ghi", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\"))) (BLOCK (PARA (TEXT \"ghi\"))))))"}, {"; abc\n: def\n; ghi\n: jkl", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\")))) ((TEXT \"ghi\")) (BLOCK (BLOCK (PARA (TEXT \"jkl\"))))))"}, // Empty description {"; abc\n: ", "(BLOCK (DESCRIPTION ((TEXT \"abc\"))) (PARA (TEXT \":\")))"}, // Empty continuation of definition {"; abc\n: def\n ", "(BLOCK (DESCRIPTION ((TEXT \"abc\")) (BLOCK (BLOCK (PARA (TEXT \"def\"))))))"}, }) } func TestTable(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"|", "()"}, {"||", "(BLOCK (TABLE () ((CELL))))"}, {"| |", "(BLOCK (TABLE () ((CELL))))"}, {"|a", "(BLOCK (TABLE () ((CELL (TEXT \"a\")))))"}, {"|a|", "(BLOCK (TABLE () ((CELL (TEXT \"a\")))))"}, {"|a| ", "(BLOCK (TABLE () ((CELL (TEXT \"a\")) (CELL))))"}, {"|a|b", "(BLOCK (TABLE () ((CELL (TEXT \"a\")) (CELL (TEXT \"b\")))))"}, {"|a\n|b", "(BLOCK (TABLE () ((CELL (TEXT \"a\"))) ((CELL (TEXT \"b\")))))"}, {"|a|b\n|c|d", "(BLOCK (TABLE () ((CELL (TEXT \"a\")) (CELL (TEXT \"b\"))) ((CELL (TEXT \"c\")) (CELL (TEXT \"d\")))))"}, {"|%", "()"}, {"|=a", "(BLOCK (TABLE ((CELL (TEXT \"a\")))))"}, {"|=a\n|b", "(BLOCK (TABLE ((CELL (TEXT \"a\"))) ((CELL (TEXT \"b\")))))"}, {"|a|b\n|%---\n|c|d", "(BLOCK (TABLE () ((CELL (TEXT \"a\")) (CELL (TEXT \"b\"))) ((CELL (TEXT \"c\")) (CELL (TEXT \"d\")))))"}, {"|a|b\n|c", "(BLOCK (TABLE () ((CELL (TEXT \"a\")) (CELL (TEXT \"b\"))) ((CELL (TEXT \"c\")) (CELL))))"}, {"|=<a>\n|b|c", "(BLOCK (TABLE ((CELL-LEFT (TEXT \"a\")) (CELL)) ((CELL-RIGHT (TEXT \"b\")) (CELL (TEXT \"c\")))))"}, {"|=<a|=b>\n||", "(BLOCK (TABLE ((CELL-LEFT (TEXT \"a\")) (CELL-RIGHT (TEXT \"b\"))) ((CELL) (CELL-RIGHT))))"}, }) } func TestTransclude(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"{{{a}}}", "(BLOCK (TRANSCLUDE () (EXTERNAL \"a\")))"}, {"{{{a}}}b", "(BLOCK (TRANSCLUDE ((\"\" . \"b\")) (EXTERNAL \"a\")))"}, {"{{{a}}}}", "(BLOCK (TRANSCLUDE () (EXTERNAL \"a\")))"}, {"{{{a\\}}}}", "(BLOCK (TRANSCLUDE () (EXTERNAL \"a\\\\}\")))"}, {"{{{a\\}}}}b", "(BLOCK (TRANSCLUDE ((\"\" . \"b\")) (EXTERNAL \"a\\\\}\")))"}, {"{{{a}}", "(BLOCK (PARA (TEXT \"{\") (EMBED () \"a\")))"}, {"{{{a}}}{go=b}", "(BLOCK (TRANSCLUDE ((\"go\" . \"b\")) (EXTERNAL \"a\")))"}, }) } func TestBlockAttr(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {":::go\na\n:::", "(BLOCK (REGION-BLOCK ((\"\" . \"go\")) ((PARA (TEXT \"a\")))))"}, {":::go=\na\n:::", "(BLOCK (REGION-BLOCK ((\"\" . \"go\")) ((PARA (TEXT \"a\")))))"}, {":::{}\na\n:::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"a\")))))"}, {":::{ }\na\n:::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"a\")))))"}, {":::{.go}\na\n:::", "(BLOCK (REGION-BLOCK ((\"class\" . \"go\")) ((PARA (TEXT \"a\")))))"}, {":::{=go}\na\n:::", "(BLOCK (REGION-BLOCK ((\"\" . \"go\")) ((PARA (TEXT \"a\")))))"}, {":::{go}\na\n:::", "(BLOCK (REGION-BLOCK ((\"go\" . \"\")) ((PARA (TEXT \"a\")))))"}, {":::{go=py}\na\n:::", "(BLOCK (REGION-BLOCK ((\"go\" . \"py\")) ((PARA (TEXT \"a\")))))"}, {":::{.go=py}\na\n:::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"a\")))))"}, {":::{go=}\na\n:::", "(BLOCK (REGION-BLOCK ((\"go\" . \"\")) ((PARA (TEXT \"a\")))))"}, {":::{.go=}\na\n:::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"a\")))))"}, {":::{go py}\na\n:::", "(BLOCK (REGION-BLOCK ((\"go\" . \"\") (\"py\" . \"\")) ((PARA (TEXT \"a\")))))"}, {":::{go\npy}\na\n:::", "(BLOCK (REGION-BLOCK ((\"go\" . \"\") (\"py\" . \"\")) ((PARA (TEXT \"a\")))))"}, {":::{.go py}\na\n:::", "(BLOCK (REGION-BLOCK ((\"class\" . \"go\") (\"py\" . \"\")) ((PARA (TEXT \"a\")))))"}, {":::{go .py}\na\n:::", "(BLOCK (REGION-BLOCK ((\"class\" . \"py\") (\"go\" . \"\")) ((PARA (TEXT \"a\")))))"}, {":::{.go py=3}\na\n:::", "(BLOCK (REGION-BLOCK ((\"class\" . \"go\") (\"py\" . \"3\")) ((PARA (TEXT \"a\")))))"}, {"::: { go } \na\n:::", "(BLOCK (REGION-BLOCK ((\"go\" . \"\")) ((PARA (TEXT \"a\")))))"}, {"::: { .go } \na\n:::", "(BLOCK (REGION-BLOCK ((\"class\" . \"go\")) ((PARA (TEXT \"a\")))))"}, }) checkTcs(t, true, replace("\"", nil, TestCases{ {":::{py=3}\na\n:::", "(BLOCK (REGION-BLOCK ((\"py\" . \"3\")) ((PARA (TEXT \"a\")))))"}, {":::{py=$2 3$}\na\n:::", "(BLOCK (REGION-BLOCK ((\"py\" . \"2 3\")) ((PARA (TEXT \"a\")))))"}, {":::{py=$2\\$3$}\na\n:::", "(BLOCK (REGION-BLOCK ((\"py\" . \"2\\\"3\")) ((PARA (TEXT \"a\")))))"}, {":::{py=2$3}\na\n:::", "(BLOCK (REGION-BLOCK ((\"py\" . \"2\\\"3\")) ((PARA (TEXT \"a\")))))"}, {":::{py=$2\n3$}\na\n:::", "(BLOCK (REGION-BLOCK ((\"py\" . \"2\\n3\")) ((PARA (TEXT \"a\")))))"}, {":::{py=$2 3}\na\n:::", "(BLOCK (REGION-BLOCK () ((PARA (TEXT \"a\")))))"}, {":::{py=2 py=3}\na\n:::", "(BLOCK (REGION-BLOCK ((\"py\" . \"2 3\")) ((PARA (TEXT \"a\")))))"}, {":::{.go .py}\na\n:::", "(BLOCK (REGION-BLOCK ((\"class\" . \"go py\")) ((PARA (TEXT \"a\")))))"}, {":::{go go}\na\n:::", "(BLOCK (REGION-BLOCK ((\"go\" . \"\")) ((PARA (TEXT \"a\")))))"}, {":::{=py =go}\na\n:::", "(BLOCK (REGION-BLOCK ((\"\" . \"go\")) ((PARA (TEXT \"a\")))))"}, })) } func TestInlineAttr(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"::a::{}", "(BLOCK (PARA (FORMAT-SPAN () (TEXT \"a\"))))"}, {"::a::{ }", "(BLOCK (PARA (FORMAT-SPAN () (TEXT \"a\"))))"}, {"::a::{.go}", "(BLOCK (PARA (FORMAT-SPAN ((\"class\" . \"go\")) (TEXT \"a\"))))"}, {"::a::{=go}", "(BLOCK (PARA (FORMAT-SPAN ((\"\" . \"go\")) (TEXT \"a\"))))"}, {"::a::{go}", "(BLOCK (PARA (FORMAT-SPAN ((\"go\" . \"\")) (TEXT \"a\"))))"}, {"::a::{go=py}", "(BLOCK (PARA (FORMAT-SPAN ((\"go\" . \"py\")) (TEXT \"a\"))))"}, {"::a::{.go=py}", "(BLOCK (PARA (FORMAT-SPAN () (TEXT \"a\")) (TEXT \"{.go=py}\")))"}, {"::a::{go=}", "(BLOCK (PARA (FORMAT-SPAN ((\"go\" . \"\")) (TEXT \"a\"))))"}, {"::a::{.go=}", "(BLOCK (PARA (FORMAT-SPAN () (TEXT \"a\")) (TEXT \"{.go=}\")))"}, {"::a::{go py}", "(BLOCK (PARA (FORMAT-SPAN ((\"go\" . \"\") (\"py\" . \"\")) (TEXT \"a\"))))"}, {"::a::{go\npy}", "(BLOCK (PARA (FORMAT-SPAN ((\"go\" . \"\") (\"py\" . \"\")) (TEXT \"a\"))))"}, {"::a::{.go py}", "(BLOCK (PARA (FORMAT-SPAN ((\"class\" . \"go\") (\"py\" . \"\")) (TEXT \"a\"))))"}, {"::a::{go .py}", "(BLOCK (PARA (FORMAT-SPAN ((\"class\" . \"py\") (\"go\" . \"\")) (TEXT \"a\"))))"}, {"::a::{ \n go \n .py\n \n}", "(BLOCK (PARA (FORMAT-SPAN ((\"class\" . \"py\") (\"go\" . \"\")) (TEXT \"a\"))))"}, {"::a::{ \n go \n .py\n\n}", "(BLOCK (PARA (FORMAT-SPAN ((\"class\" . \"py\") (\"go\" . \"\")) (TEXT \"a\"))))"}, {"::a::{\ngo\n}", "(BLOCK (PARA (FORMAT-SPAN ((\"go\" . \"\")) (TEXT \"a\"))))"}, }) checkTcs(t, true, TestCases{ {"::a::{py=3}", "(BLOCK (PARA (FORMAT-SPAN ((\"py\" . \"3\")) (TEXT \"a\"))))"}, {"::a::{py=\"2 3\"}", "(BLOCK (PARA (FORMAT-SPAN ((\"py\" . \"2 3\")) (TEXT \"a\"))))"}, {"::a::{py=\"2\\\"3\"}", "(BLOCK (PARA (FORMAT-SPAN ((\"py\" . \"2\\\"3\")) (TEXT \"a\"))))"}, {"::a::{py=2\"3}", "(BLOCK (PARA (FORMAT-SPAN ((\"py\" . \"2\\\"3\")) (TEXT \"a\"))))"}, {"::a::{py=\"2\n3\"}", "(BLOCK (PARA (FORMAT-SPAN ((\"py\" . \"2\\n3\")) (TEXT \"a\"))))"}, {"::a::{py=\"2 3}", "(BLOCK (PARA (FORMAT-SPAN () (TEXT \"a\")) (TEXT \"{py=\\\"2\") (SPACE) (TEXT \"3}\")))"}, }) checkTcs(t, true, TestCases{ {"::a::{py=2 py=3}", "(BLOCK (PARA (FORMAT-SPAN ((\"py\" . \"2 3\")) (TEXT \"a\"))))"}, {"::a::{.go .py}", "(BLOCK (PARA (FORMAT-SPAN ((\"class\" . \"go py\")) (TEXT \"a\"))))"}, }) } func TestTemp(t *testing.T) { t.Parallel() checkTcs(t, true, TestCases{ {"", "()"}, }) } |