├── gradle.properties ├── settings.gradle ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── signing.gradle └── publish.gradle ├── src ├── main │ ├── resources │ │ └── META-INF │ │ │ └── services │ │ │ └── org.asciidoctor.jruby.extension.spi.ExtensionRegistry │ └── groovy │ │ └── org │ │ └── asciidoctor │ │ └── groovydsl │ │ ├── AsciidoctorExtensionException.java │ │ ├── extensions │ │ ├── DelegatingDocinfoProcessor.groovy │ │ ├── DelegatingPostprocessor.groovy │ │ ├── DelegatingPreprocessor.groovy │ │ ├── DelegatingBlockMacroProcessor.groovy │ │ ├── DelegatingInlineMacroProcessor.groovy │ │ ├── DelegatingBlockProcessor.groovy │ │ ├── DelegatingTreeprocessor.groovy │ │ └── DelegatingIncludeProcessor.groovy │ │ ├── GroovyExtensionRegistry.groovy │ │ ├── AsciidoctorExtensionHandler.groovy │ │ └── AsciidoctorExtensions.groovy └── test │ ├── resources │ ├── testpreprocessorextension.groovy │ ├── testdocinfoprocessorextension.groovy │ ├── testinlinemacroprocessorextension.groovy │ ├── testincludeprocessorextension.groovy │ ├── testblockmacroextension.groovy │ ├── error.groovy │ ├── testpostprocessorextension.groovy │ ├── testblockextensions.groovy │ └── testtreeprocessorextension.groovy │ └── groovy │ └── org │ └── asciidoctor │ └── groovydsl │ └── AsciidoctorGroovyDSLSpec.groovy ├── config ├── HEADER └── codenarc │ └── codenarc.groovy ├── .gitignore ├── .github ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── release.yaml │ └── continuous-integration.yaml ├── CHANGELOG.adoc ├── gradlew.bat ├── gradlew ├── LICENSE.txt └── README.adoc /gradle.properties: -------------------------------------------------------------------------------- 1 | version=3.0.0-beta.1 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'asciidoctorj-groovy-dsl' 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asciidoctor/asciidoctorj-groovy-dsl/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry: -------------------------------------------------------------------------------- 1 | org.asciidoctor.groovydsl.GroovyExtensionRegistry 2 | -------------------------------------------------------------------------------- /src/test/resources/testpreprocessorextension.groovy: -------------------------------------------------------------------------------- 1 | preprocessor { 2 | document, reader -> 3 | reader.advance() 4 | reader 5 | } 6 | -------------------------------------------------------------------------------- /src/test/resources/testdocinfoprocessorextension.groovy: -------------------------------------------------------------------------------- 1 | String metatag = '' 2 | 3 | docinfo_processor { 4 | document -> metatag 5 | } 6 | -------------------------------------------------------------------------------- /src/test/resources/testinlinemacroprocessorextension.groovy: -------------------------------------------------------------------------------- 1 | inline_macro (name: "man") { 2 | parent, target, attributes -> 3 | options = [type: ":link", target: target + ".html"] 4 | createPhraseNode(parent, "anchor", target, attributes, options) 5 | } 6 | -------------------------------------------------------------------------------- /src/test/resources/testincludeprocessorextension.groovy: -------------------------------------------------------------------------------- 1 | String content = "The content of the URL" 2 | 3 | include_processor (filter: {it.startsWith("http")}) { 4 | document, reader, target, attributes -> 5 | reader.pushInclude(content, target, target, 1, attributes); 6 | } 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/test/resources/testblockmacroextension.groovy: -------------------------------------------------------------------------------- 1 | block_macro (name: "gist") { 2 | parent, target, attributes -> 3 | String content = """
4 | 5 |
""" 6 | createBlock(parent, "pass", [content], attributes); 7 | } 8 | 9 | -------------------------------------------------------------------------------- /src/test/resources/error.groovy: -------------------------------------------------------------------------------- 1 | throw new Exception('This error is on purpose') 2 | 3 | block (name: "BIG", contexts: [":paragraph"]) { 4 | parent, reader, attributes -> 5 | def upperLines = reader.readLines() 6 | .collect {it.toUpperCase()} 7 | .inject("") {a, b -> a + '\\n' + b} 8 | 9 | createBlock(parent, "paragraph", [upperLines], attributes, [:]) 10 | } 11 | -------------------------------------------------------------------------------- /src/test/resources/testpostprocessorextension.groovy: -------------------------------------------------------------------------------- 1 | import org.jsoup.* 2 | 3 | String copyright = "Copyright Acme, Inc." 4 | 5 | postprocessor { 6 | document, output -> 7 | if(document.isBasebackend("html")) { 8 | org.jsoup.nodes.Document doc = Jsoup.parse(output, "UTF-8") 9 | 10 | def contentElement = doc.getElementsByTag("body") 11 | contentElement.append(copyright) 12 | doc.html() 13 | } else { 14 | throw new IllegalArgumentException("Expected html!") 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/resources/testblockextensions.groovy: -------------------------------------------------------------------------------- 1 | block (name: "BIG", contexts: [":paragraph"]) { 2 | parent, reader, attributes -> 3 | def upperLines = reader.readLines() 4 | .collect {it.toUpperCase()} 5 | .inject("") {a, b -> a + '\\n' + b} 6 | 7 | createBlock(parent, "paragraph", [upperLines], attributes, [:]) 8 | } 9 | block("small") { 10 | parent, reader, attributes -> 11 | def lowerLines = reader.readLines() 12 | .collect {it.toLowerCase()} 13 | .inject("") {a, b -> a + '\\n' + b} 14 | 15 | createBlock(parent, "paragraph", [lowerLines], attributes, [:]) 16 | } 17 | -------------------------------------------------------------------------------- /config/HEADER: -------------------------------------------------------------------------------- 1 | Copyright ${year} the original author or authors. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /src/test/resources/testtreeprocessorextension.groovy: -------------------------------------------------------------------------------- 1 | treeprocessor { 2 | document -> 3 | def blocks = document.blocks 4 | (0.. 0 && lines[0].startsWith('$')) { 8 | Map attributes = block.attributes 9 | attributes["role"] = "terminal" 10 | def resultLines = lines.collect { 11 | it.startsWith('$') ? "${it.substring(2)}".toString() : it 12 | } 13 | blocks[it] = createBlock(document, "listing", resultLines, attributes,[:]) 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/AsciidoctorExtensionException.java: -------------------------------------------------------------------------------- 1 | package org.asciidoctor.groovydsl; 2 | 3 | 4 | /** 5 | * Generic exception to manage Asciidoctor Extension DSL processing errors 6 | */ 7 | public class AsciidoctorExtensionException extends Exception { 8 | 9 | public AsciidoctorExtensionException() { 10 | } 11 | 12 | public AsciidoctorExtensionException(String message) { 13 | super(message); 14 | } 15 | 16 | public AsciidoctorExtensionException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | 20 | public AsciidoctorExtensionException(Throwable cause) { 21 | super(cause); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | .gradle 3 | /build 4 | /out 5 | /intTestHomeDir 6 | /subprojects/*/out 7 | /intellij 8 | /buildSrc/lib 9 | /buildSrc/build 10 | /subprojects/*/build 11 | /subprojects/docs/src/samples/*/*/build 12 | /website/build 13 | /website/website.iml 14 | /website/website.ipr 15 | /website/website.iws 16 | /performanceTest/build 17 | /subprojects/*/ide 18 | /*.iml 19 | /*.ipr 20 | /*.iws 21 | /subprojects/*/*.iml 22 | /buildSrc/*.ipr 23 | /buildSrc/*.iws 24 | /buildSrc/*.iml 25 | /buildSrc/out 26 | *.classpath 27 | *.project 28 | *.settings 29 | /bin 30 | /subprojects/*/bin 31 | .DS_Store 32 | /performanceTest/lib 33 | .textmate 34 | /incoming-distributions 35 | .idea 36 | *.sublime-* 37 | .nb-gradle 38 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for opening a pull request and contributing to AsciidoctorJ Groovy DSL! 2 | 3 | Please take a bit of time giving some details about your pull request: 4 | 5 | ## Kind of change 6 | 7 | - [ ] Bug fix 8 | - [ ] New non-breaking feature 9 | - [ ] New breaking feature 10 | - [ ] Documentation update 11 | - [ ] Build improvement 12 | 13 | ## Description 14 | 15 | What is the goal of this pull request? 16 | 17 | How does it achieve that? 18 | 19 | Are there any alternative ways to implement this? 20 | 21 | Are there any implications of this pull request? Anything a user must know? 22 | 23 | ## Issue 24 | 25 | If this PR fixes an open issue, please add a line of the form: 26 | 27 | Fixes #Issue 28 | 29 | 30 | ## Release notes 31 | 32 | Please add a corresponding entry to the file CHANGELOG.adoc -------------------------------------------------------------------------------- /gradle/signing.gradle: -------------------------------------------------------------------------------- 1 | def hasSigningKey = project.hasProperty("signing.keyId") || project.findProperty("signingKey") 2 | if(hasSigningKey && !project.hasProperty('skip.signing')) { 3 | apply plugin: 'signing' 4 | sign(project) 5 | } 6 | void sign(Project project) { 7 | project.signing { 8 | required { project.gradle.taskGraph.hasTask("required") } 9 | def signingKeyId = project.findProperty("signingKeyId") 10 | def signingKey = project.findProperty("signingKey") 11 | def signingPassword = project.findProperty("signingPassword") 12 | if (signingKeyId) { 13 | useInMemoryPgpKeys(signingKeyId, signingKey, signingPassword) 14 | } else if (signingKey) { 15 | useInMemoryPgpKeys(signingKey, signingPassword) 16 | } 17 | sign publishing.publications[project.ext.publicationName] 18 | } 19 | } -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: workflow_dispatch 4 | 5 | env: 6 | ORG_GRADLE_PROJECT_signingKeyId: ${{ secrets.GPG_KEY_ID }} 7 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.GPG_PRIVATE_KEY }} 8 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.GPG_PASSPHRASE }} 9 | ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.OSS_SONATYPE_USERNAME }} 10 | ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.OSS_SONATYPE_PASSWORD }} 11 | 12 | jobs: 13 | release: 14 | environment: release 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v3 18 | - uses: actions/setup-java@v3 19 | with: 20 | distribution: 'temurin' 21 | java-version: '11' 22 | - name: Build 23 | run: | 24 | unset GEM_PATH GEM_HOME JRUBY_OPTS 25 | ./gradlew --no-daemon clean build 26 | ./gradlew --no-daemon publishToSonatype closeSonatypeStagingRepository 27 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingDocinfoProcessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | import org.asciidoctor.ast.Document 19 | import org.asciidoctor.extension.DocinfoProcessor 20 | 21 | class DelegatingDocinfoProcessor extends DocinfoProcessor { 22 | 23 | final Closure cl 24 | 25 | DelegatingDocinfoProcessor(Map options, @DelegatesTo(DocinfoProcessor) Closure cl) { 26 | super(options) 27 | this.cl = cl 28 | cl.delegate = this 29 | } 30 | 31 | String process(Document document) { 32 | cl.call(document) 33 | } 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingPostprocessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | import org.asciidoctor.ast.Document 19 | import org.asciidoctor.extension.Postprocessor 20 | 21 | class DelegatingPostprocessor extends Postprocessor { 22 | 23 | final Closure cl 24 | 25 | DelegatingPostprocessor(Map options, @DelegatesTo(Postprocessor) Closure cl) { 26 | super(options) 27 | this.cl = cl 28 | cl.delegate = this 29 | } 30 | 31 | String process(Document document, String output) { 32 | cl.call(document, output) 33 | } 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/GroovyExtensionRegistry.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl 17 | 18 | import org.asciidoctor.Asciidoctor 19 | import org.asciidoctor.jruby.extension.spi.ExtensionRegistry 20 | 21 | /** 22 | * The service implementation for org.asciidoctor.jruby.extension.spi.ExtensionRegistry. 23 | * It simply delegates the register() call to {@link AsciidoctorExtensions} 24 | * that owns all configured extensions and registers it on the Asciidoctor instance. 25 | */ 26 | class GroovyExtensionRegistry implements ExtensionRegistry { 27 | 28 | void register(Asciidoctor asciidoctor) { 29 | AsciidoctorExtensions.registerTo(asciidoctor) 30 | } 31 | 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingPreprocessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | import org.asciidoctor.ast.Document 19 | import org.asciidoctor.extension.Preprocessor 20 | import org.asciidoctor.extension.PreprocessorReader 21 | import org.asciidoctor.extension.Reader 22 | 23 | class DelegatingPreprocessor extends Preprocessor { 24 | 25 | private final Closure cl 26 | 27 | DelegatingPreprocessor(Map options, @DelegatesTo(Preprocessor) Closure cl) { 28 | super(options) 29 | this.cl = cl 30 | cl.delegate = this 31 | } 32 | 33 | Reader process(Document document, PreprocessorReader reader) { 34 | cl.call(document, reader) 35 | } 36 | 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingBlockMacroProcessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | import org.asciidoctor.ast.StructuralNode 19 | import org.asciidoctor.extension.BlockMacroProcessor 20 | 21 | class DelegatingBlockMacroProcessor extends BlockMacroProcessor { 22 | 23 | private final Closure cl 24 | 25 | DelegatingBlockMacroProcessor(String name, Map options, @DelegatesTo(BlockMacroProcessor) Closure cl) { 26 | super(name, options) 27 | this.cl = cl 28 | cl.delegate = this 29 | } 30 | 31 | StructuralNode process(StructuralNode parent, String target, Map attributes) { 32 | cl.call(parent, target, attributes) 33 | } 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingInlineMacroProcessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | 19 | import org.asciidoctor.ast.PhraseNode 20 | import org.asciidoctor.ast.StructuralNode 21 | import org.asciidoctor.extension.InlineMacroProcessor 22 | 23 | class DelegatingInlineMacroProcessor extends InlineMacroProcessor { 24 | 25 | private final Closure cl 26 | 27 | DelegatingInlineMacroProcessor(String name, Map options, @DelegatesTo(InlineMacroProcessor) Closure cl) { 28 | super(name, options) 29 | this.cl = cl 30 | cl.delegate = this 31 | } 32 | 33 | PhraseNode process(StructuralNode parent, String target, Map attributes) { 34 | cl.call(parent, target, attributes) 35 | } 36 | 37 | } 38 | 39 | -------------------------------------------------------------------------------- /.github/workflows/continuous-integration.yaml: -------------------------------------------------------------------------------- 1 | name: Build Master 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | branches: 8 | - main 9 | schedule: 10 | - cron: '0 0 * * *' 11 | 12 | jobs: 13 | build: 14 | name: Build 15 | strategy: 16 | fail-fast: false 17 | max-parallel: 2 18 | matrix: 19 | java: 20 | - '11' 21 | - '17' 22 | - '21' 23 | os: 24 | - ubuntu-latest 25 | - macos-latest 26 | runs-on: ${{ matrix.os }} 27 | steps: 28 | - uses: actions/checkout@v3 29 | with: 30 | fetch-depth: 1 31 | - uses: actions/setup-java@v3 32 | with: 33 | distribution: temurin 34 | java-version: ${{ matrix.java }} 35 | - name: Build 36 | run: | 37 | ./gradlew -S -Pskip.signing assemble 38 | unset GEM_PATH GEM_HOME JRUBY_OPTS 39 | ./gradlew -S -Pskip.signing clean build 40 | build-windows: 41 | name: Build on Windows 42 | runs-on: windows-latest 43 | steps: 44 | - uses: actions/checkout@v3 45 | with: 46 | fetch-depth: 1 47 | - uses: actions/setup-java@v3 48 | with: 49 | distribution: temurin 50 | java-version: 17 51 | - name: Assemble 52 | shell: cmd 53 | run: | 54 | gradlew.bat -i assemble 55 | - name: Check 56 | shell: cmd 57 | run: | 58 | gradlew.bat -i -S clean build 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingBlockProcessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | import org.asciidoctor.ast.StructuralNode 19 | import org.asciidoctor.extension.BlockProcessor 20 | import org.asciidoctor.extension.Reader 21 | import org.asciidoctor.groovydsl.AsciidoctorExtensionHandler 22 | 23 | class DelegatingBlockProcessor extends BlockProcessor { 24 | 25 | Closure cl 26 | 27 | DelegatingBlockProcessor(Map attributes, @DelegatesTo(BlockProcessor) Closure cl) { 28 | super(attributes[AsciidoctorExtensionHandler.OPTION_NAME], attributes) 29 | this.cl = cl 30 | cl.delegate = this 31 | } 32 | 33 | Object process(StructuralNode parent, Reader reader, Map attributes) { 34 | cl.call(parent, reader, attributes) 35 | } 36 | 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingTreeprocessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | import org.asciidoctor.ast.Document 19 | import org.asciidoctor.extension.Treeprocessor 20 | 21 | class DelegatingTreeprocessor extends Treeprocessor { 22 | 23 | private final Closure cl 24 | 25 | DelegatingTreeprocessor(Map options, @DelegatesTo(Treeprocessor) Closure cl) { 26 | super(options) 27 | this.cl = cl 28 | cl.delegate = this 29 | } 30 | 31 | Document process(Document document) { 32 | def ret = cl.call(document) 33 | if (!(ret in Document)) { 34 | // Assume that the closure does something as last 35 | // statement that was not intended to be the return value 36 | // -> Return null 37 | null 38 | } else { 39 | ret 40 | } 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/extensions/DelegatingIncludeProcessor.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl.extensions 17 | 18 | import org.asciidoctor.ast.Document 19 | import org.asciidoctor.extension.IncludeProcessor 20 | import org.asciidoctor.extension.PreprocessorReader 21 | 22 | class DelegatingIncludeProcessor extends IncludeProcessor { 23 | 24 | private final Closure filter 25 | private final Closure cl 26 | 27 | DelegatingIncludeProcessor(Map options, Closure filter, @DelegatesTo(IncludeProcessor) Closure cl) { 28 | super(options) 29 | this.filter = filter 30 | this.cl = cl 31 | filter.delegate = this 32 | cl.delegate = this 33 | 34 | } 35 | 36 | boolean handles(String target) { 37 | filter.call(target) 38 | } 39 | 40 | void process(Document document, PreprocessorReader reader, String target, Map attributes) { 41 | cl.call(document, reader, target, attributes) 42 | } 43 | 44 | } 45 | 46 | -------------------------------------------------------------------------------- /config/codenarc/codenarc.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | ruleset { 18 | ruleset('rulesets/basic.xml') { 19 | exclude 'EmptyCatchBlock' 20 | exclude 'EmptyMethod' 21 | } 22 | ruleset('rulesets/imports.xml') { 23 | exclude 'MisorderedStaticImports' 24 | } 25 | ruleset('rulesets/naming.xml') { 26 | exclude 'PropertyName' 27 | 'ClassName' { 28 | regex = '^[A-Z][a-zA-Z0-9]*$' 29 | } 30 | 'FieldName' { 31 | finalRegex = '^_?[a-z][a-zA-Z0-9]*$' 32 | staticFinalRegex = '^[A-Z][A-Z_0-9]*$' 33 | } 34 | 'MethodName' { 35 | regex = '^[a-z][a-zA-Z0-9_]*$' 36 | } 37 | 'VariableName' { 38 | finalRegex = '^_?[a-z][a-zA-Z0-9]*$' 39 | } 40 | } 41 | ruleset('rulesets/unused.xml') 42 | ruleset('rulesets/exceptions.xml') 43 | ruleset('rulesets/logging.xml') 44 | ruleset('rulesets/braces.xml') { 45 | exclude 'IfStatementBraces' 46 | } 47 | ruleset('rulesets/size.xml') 48 | ruleset('rulesets/junit.xml') 49 | ruleset('rulesets/unnecessary.xml') 50 | ruleset('rulesets/dry.xml') 51 | ruleset('rulesets/design.xml') 52 | } 53 | -------------------------------------------------------------------------------- /CHANGELOG.adoc: -------------------------------------------------------------------------------- 1 | = AsciidoctorJ Groovy DSL Changelog 2 | :uri-asciidoctor: http://asciidoctor.org 3 | :uri-asciidoc: {uri-asciidoctor}/docs/what-is-asciidoc 4 | :uri-repo: https://github.com/asciidoctor/asciidoctorj-groovy-dsl 5 | :icons: font 6 | :star: icon:star[role=red] 7 | ifndef::icons[] 8 | :star: ★ 9 | endif::[] 10 | 11 | This document provides a high-level view of the changes introduced in AsciidoctorJ Groovy DSL by release. 12 | For a detailed view of what has changed, refer to the {uri-repo}/commits/master[commit history] on GitHub. 13 | 14 | == Unreleased 15 | 16 | Improvements:: 17 | 18 | * Upgrade to AsciidoctorJ 3.0.0 (Breaking) https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/37[#37] 19 | 20 | Build improvements:: 21 | 22 | * Upgrade to Gradle 8.5 https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/37[#37] 23 | * Release from Github actions https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/36[#36] 24 | 25 | == 2.0.2 26 | 27 | Release Date: 9.5.2021 28 | 29 | Bugfix: 30 | 31 | * Set java version in Gradle module to Java 8 https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/32[#32] 32 | 33 | == 2.0.1 34 | 35 | Release Date: 2.3.2021 36 | 37 | Improvements:: 38 | 39 | * Publish to Maven central 40 | 41 | == 2.0.0 42 | 43 | Release Date: 13.1.2020 44 | 45 | 46 | This version is the graduation of the previous 1.6.0-alpha.1 branch making it compatible with the latest improvements from Asciidoctorj v2.2.0. 47 | Note that extensions using version 1.0.0.preview2 may not be compatible. 48 | 49 | Improvements:: 50 | 51 | * Allow AsciidoctorExtensions to be instantiated (https://github.com/ysb33r[@ysb33r]) (https://github.com/asciidoctor/asciidoctorj-groovy-dsl/issues/18[#18]) 52 | * Upgrade to Asciidoctorj v2.2.0 (https://github.com/abelsromero[@abelsromero]) (https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/24[#24]). 53 | Continuation of the previous work of https://github.com/robertpanzer[@robertpanzer] in https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/21[#21] and https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/22[#22] 54 | * Removed deprecated methods `blockmacro`, `includeprocessor`, `inlinemacro`. Use the following instead: `block_macro`, `include_processor`, `inline_macro` (https://github.com/abelsromero[@abelsromero]) (https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/27[#27]) 55 | 56 | Bug Fixes:: 57 | 58 | Documentation:: 59 | 60 | * Fix artifact version in README examples (https://github.com/gtoast[@gtoast]) (https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/16[#16]) 61 | 62 | Build:: 63 | 64 | * Upgrade Gradle to v5.6.4 to support building with Java versions superior to 8 (https://github.com/abelsromero[@abelsromero]) (https://github.com/asciidoctor/asciidoctorj-groovy-dsl/pull/25[#25]) 65 | -------------------------------------------------------------------------------- /gradle/publish.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven-publish' 2 | 3 | publishing { 4 | publications.create(project.ext.publicationName, MavenPublication) { 5 | 6 | from components.java 7 | 8 | pom { 9 | name = project.name 10 | description = project.description 11 | url = 'https://github.com/asciidoctor/asciidoctorj-groovy-dsl' 12 | inceptionYear = '2014' 13 | licenses { 14 | license { 15 | name = 'The Apache Software License, Version 2.0' 16 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 17 | distribution = 'repo' 18 | } 19 | } 20 | issueManagement { 21 | system = 'github' 22 | url = 'https://github.com/asciidoctor/asciidoctorj-groovy-dsl/issues' 23 | } 24 | scm { 25 | url = 'https://github.com/asciidoctor/asciidoctorj-groovy-dsl' 26 | } 27 | developers { 28 | developer { 29 | id = 'mojavelinux' 30 | name = 'Dan Allen' 31 | email = 'dan.j.allen@gmail.com' 32 | timezone = '-7' 33 | roles = ['Contributor'] 34 | } 35 | developer { 36 | id = 'robertpanzer' 37 | name = 'Robert Panzer' 38 | email = 'robert.panzer.pb@gmail.com' 39 | timezone = '1' 40 | roles = ['Contributor'] 41 | } 42 | } 43 | } 44 | } 45 | } 46 | 47 | // QUESTION should we move manifest creation to general Java plugin config? 48 | jar { 49 | manifest { 50 | attributes \ 51 | 'Built-By': System.properties['user.name'], 52 | 'Created-By': "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})".toString(), 53 | 'Build-Date': buildDateOnly, 54 | //'Build-Time': buildTimeOnly, 55 | //'Specification-Title': project.name, 56 | //'Specification-Version': project.version, 57 | //'Specification-Vendor': 'asciidoctor.org', 58 | 'Implementation-Title': project.name, 59 | 'Implementation-Version': project.version, 60 | 'Implementation-Vendor': 'asciidoctor.org' 61 | } 62 | } 63 | 64 | publishing { 65 | repositories { 66 | maven { 67 | name = "local" 68 | // change URLs to point to your repos, e.g. http://my.org/repo 69 | def releasesRepoUrl = "${rootProject.buildDir}/repos/releases" 70 | def snapshotsRepoUrl = "${rootProject.buildDir}/repos/snapshots" 71 | url = version.endsWith("SNAPSHOT") ? snapshotsRepoUrl : releasesRepoUrl 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/AsciidoctorExtensionHandler.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl 17 | 18 | import org.asciidoctor.extension.BlockMacroProcessor 19 | import org.asciidoctor.extension.BlockProcessor 20 | import org.asciidoctor.extension.DocinfoProcessor 21 | import org.asciidoctor.extension.IncludeProcessor 22 | import org.asciidoctor.extension.InlineMacroProcessor 23 | import org.asciidoctor.extension.Postprocessor 24 | import org.asciidoctor.extension.Preprocessor 25 | import org.asciidoctor.extension.Treeprocessor 26 | import org.asciidoctor.groovydsl.extensions.DelegatingBlockMacroProcessor 27 | import org.asciidoctor.groovydsl.extensions.DelegatingBlockProcessor 28 | import org.asciidoctor.groovydsl.extensions.DelegatingDocinfoProcessor 29 | import org.asciidoctor.groovydsl.extensions.DelegatingIncludeProcessor 30 | import org.asciidoctor.groovydsl.extensions.DelegatingPostprocessor 31 | import org.asciidoctor.groovydsl.extensions.DelegatingPreprocessor 32 | import org.asciidoctor.groovydsl.extensions.DelegatingInlineMacroProcessor 33 | import org.asciidoctor.groovydsl.extensions.DelegatingTreeprocessor 34 | import org.asciidoctor.Asciidoctor 35 | 36 | class AsciidoctorExtensionHandler { 37 | 38 | private static final String OPTION_NAME = 'name' 39 | 40 | private static final String OPTION_FILTER = 'filter' 41 | 42 | private static final String OPTION_CONTEXTS = 'contexts' 43 | 44 | private final Asciidoctor asciidoctor 45 | 46 | AsciidoctorExtensionHandler(Asciidoctor asciidoctor) { 47 | this.asciidoctor = asciidoctor 48 | } 49 | 50 | void block(String blockName, @DelegatesTo(BlockProcessor) Closure cl) { 51 | block([(OPTION_NAME): blockName], cl) 52 | } 53 | 54 | void block(Map options=[:], @DelegatesTo(BlockProcessor) Closure cl) { 55 | if (!options.containsKey(OPTION_NAME)) { 56 | throw new IllegalArgumentException('Block must define a name!') 57 | } 58 | if (!options.containsKey(OPTION_CONTEXTS)) { 59 | //TODO: What are sensible defaults? 60 | options[OPTION_CONTEXTS] = [':open', ':paragraph'] 61 | } 62 | asciidoctor.javaExtensionRegistry().block(new DelegatingBlockProcessor(options, cl)) 63 | } 64 | 65 | void block_macro(Map options, @DelegatesTo(BlockMacroProcessor) Closure cl) { 66 | asciidoctor.javaExtensionRegistry().blockMacro(new DelegatingBlockMacroProcessor(options[OPTION_NAME], options, cl)) 67 | } 68 | 69 | void block_macro(String name, @DelegatesTo(BlockMacroProcessor) Closure cl) { 70 | block_macro([(OPTION_NAME): name], cl) 71 | } 72 | 73 | void postprocessor(Map options=[:], @DelegatesTo(Postprocessor) Closure cl) { 74 | asciidoctor.javaExtensionRegistry().postprocessor(new DelegatingPostprocessor(options, cl)) 75 | } 76 | 77 | void preprocessor(Map options=[:], @DelegatesTo(Preprocessor) Closure cl) { 78 | asciidoctor.javaExtensionRegistry().preprocessor(new DelegatingPreprocessor(options, cl)) 79 | } 80 | 81 | void include_processor(Map options=[:], @DelegatesTo(IncludeProcessor) Closure cl) { 82 | Closure filter = options[OPTION_FILTER] 83 | Map optionsWithoutFilter = options - options.subMap([OPTION_FILTER]) 84 | asciidoctor.javaExtensionRegistry().includeProcessor(new DelegatingIncludeProcessor(optionsWithoutFilter, filter, cl)) 85 | } 86 | 87 | void inline_macro(Map options, @DelegatesTo(InlineMacroProcessor) Closure cl) { 88 | asciidoctor.javaExtensionRegistry().inlineMacro(new DelegatingInlineMacroProcessor(options[OPTION_NAME], options, cl)) 89 | } 90 | 91 | void inline_macro(String macroName, @DelegatesTo(InlineMacroProcessor) Closure cl) { 92 | inline_macro([(OPTION_NAME): macroName], cl) 93 | } 94 | 95 | void treeprocessor(Map options=[:], @DelegatesTo(Treeprocessor) Closure cl) { 96 | asciidoctor.javaExtensionRegistry().treeprocessor(new DelegatingTreeprocessor(options, cl)) 97 | } 98 | 99 | void docinfo_processor(Map options=[:], @DelegatesTo(DocinfoProcessor) Closure cl) { 100 | asciidoctor.javaExtensionRegistry().docinfoProcessor(new DelegatingDocinfoProcessor(options, cl)) 101 | } 102 | 103 | } 104 | 105 | -------------------------------------------------------------------------------- /src/main/groovy/org/asciidoctor/groovydsl/AsciidoctorExtensions.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl 17 | 18 | import groovy.transform.CompileStatic 19 | import org.asciidoctor.Asciidoctor 20 | import org.codehaus.groovy.control.CompilerConfiguration 21 | import org.codehaus.groovy.control.customizers.ImportCustomizer 22 | 23 | import java.nio.file.Files 24 | import java.nio.file.Path 25 | 26 | /** 27 | * An instance of this class holds all extension closure and scripts. 28 | * It evaluates the blocks and scripts and forwards the extracted extensions 29 | * to the GroovyExtensionRegistry which is service implementation 30 | * of org.asciidoctor.extension.spi.wExtensionRegistry 31 | */ 32 | @CompileStatic 33 | class AsciidoctorExtensions { 34 | 35 | /** Add an extension from a closure 36 | * 37 | * @param cl Closure containing an extension 38 | */ 39 | void addExtension(@DelegatesTo(AsciidoctorExtensionHandler) Closure cl) { 40 | registeredExtensions.add(cl) 41 | } 42 | 43 | /** Add an extension via a string. 44 | * 45 | * @param groovyScript String containing extension. 46 | */ 47 | void addExtension(final String groovyScript) { 48 | registeredExtensions.add(groovyScript) 49 | } 50 | 51 | /** Add an extension via a file. 52 | * 53 | * @param groovyScript File containing extension 54 | */ 55 | void addExtension(final File groovyScript) { 56 | registeredExtensions.add(groovyScript) 57 | } 58 | 59 | /** Add an extension via a path instance 60 | * 61 | * @param groovyScript Path pointing to an extension 62 | */ 63 | void addExtension(final Path groovyScript) { 64 | registeredExtensions.add(groovyScript) 65 | } 66 | 67 | /** Remove all extensions. 68 | * 69 | */ 70 | void clearExtensions() { 71 | registeredExtensions.clear() 72 | } 73 | 74 | /** Register all extension with an instance of Asciidoctor. 75 | * 76 | * @param asciidoctor Asciidoctor instance awaiting extensions. 77 | * @throw AsciidoctorExtensionException 78 | */ 79 | @SuppressWarnings('UnnecessarySetter') 80 | void registerExtensionsWith(Asciidoctor asciidoctor) { 81 | AsciidoctorExtensionHandler extensionHandler = new AsciidoctorExtensionHandler(asciidoctor) 82 | for (def it : registeredExtensions) { 83 | switch (it) { 84 | case Closure: 85 | try { 86 | ((Closure) it).delegate = extensionHandler 87 | ((Closure) it).call() 88 | } catch (e) { 89 | throw new AsciidoctorExtensionException("Error registering extension from class in ${it.class.name}", e) 90 | } 91 | break 92 | case String: 93 | GroovyShell shell = makeGroovyShell() 94 | DelegatingScript script = (DelegatingScript) shell.parse((String) it) 95 | script.setDelegate(extensionHandler) 96 | try { 97 | script.run() 98 | } catch (e) { 99 | registeredExtensions.clear() 100 | throw new AsciidoctorExtensionException('Error registering extension from string', e) 101 | } 102 | break 103 | case File: 104 | File file = (File) it 105 | GroovyShell shell = makeGroovyShell() 106 | file.withReader { reader -> 107 | DelegatingScript script = (DelegatingScript) shell.parse(reader, file.name) 108 | script.setDelegate(extensionHandler) 109 | try { 110 | script.run() 111 | } catch (e) { 112 | throw new AsciidoctorExtensionException("Error registering extension from file ${file.name}", e) 113 | } 114 | } 115 | break 116 | case Path: 117 | Path path = (Path) it 118 | GroovyShell shell = makeGroovyShell() 119 | Files.newBufferedReader(path).withReader { reader -> 120 | DelegatingScript script = (DelegatingScript) shell.parse(reader, path.toString()) 121 | script.setDelegate(extensionHandler) 122 | try { 123 | script.run() 124 | } catch (e) { 125 | throw new AsciidoctorExtensionException("Error registering extension from file ${path}", e) 126 | } 127 | } 128 | break 129 | } 130 | } 131 | } 132 | 133 | /** Adds an extension to the AsciidoctorExtension singleton instance. 134 | * 135 | * @param cl Closure containing an instance 136 | */ 137 | static void extensions(@DelegatesTo(AsciidoctorExtensionHandler) Closure cl) { 138 | INSTANCE.addExtension(cl) 139 | } 140 | 141 | /** Adds an extension to the AsciidoctorExtension singleton instance. 142 | * 143 | * @param s String containing an instance 144 | */ 145 | static void extensions(String s) { 146 | INSTANCE.addExtension(s) 147 | } 148 | 149 | /** Adds an extension to the AsciidoctorExtension singleton instance. 150 | * 151 | * @param f File containing an instance 152 | */ 153 | static void extensions(File f) { 154 | INSTANCE.addExtension(f) 155 | } 156 | 157 | /** Attempt to register all exteniosn with ASciidoctor instance. 158 | * 159 | * This method has the side-effect of removing all extensions as well. 160 | * 161 | * @param asciidoctor 162 | */ 163 | static void registerTo(Asciidoctor asciidoctor) { 164 | try { 165 | INSTANCE.registerExtensionsWith(asciidoctor) 166 | } finally { 167 | INSTANCE.clearExtensions() 168 | } 169 | } 170 | 171 | private static GroovyShell makeGroovyShell() { 172 | def config = new CompilerConfiguration() 173 | 174 | config.scriptBaseClass = DelegatingScript.name 175 | 176 | ImportCustomizer importCustomizer = new ImportCustomizer() 177 | importCustomizer.addStarImports( 178 | 'org.asciidoctor', 179 | 'org.asciidoctor.ast', 180 | 'org.asciidoctor.extension') 181 | 182 | config.addCompilationCustomizers( 183 | importCustomizer 184 | ) 185 | 186 | new GroovyShell(new Binding(), config) 187 | } 188 | 189 | private final List registeredExtensions = [] 190 | private static final AsciidoctorExtensions INSTANCE = new AsciidoctorExtensions() 191 | } 192 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Asciidoctor Groovy DSL 2 | Robert Panzer 3 | :released-version: 1.6.0 4 | :asciidoctorj-version: 2.2.0 5 | :asciidoc-url: http://asciidoc.org 6 | :asciidoctor-url: https://asciidoctor.org 7 | :groovy-url: https://www.groovy-lang.org/ 8 | :gradle-url: https://gradle.org/ 9 | :asciidoctorj: https://github.com/asciidoctor/asciidoctorj 10 | :lordofthejars: https://github.com/lordofthejars 11 | :asciidoctor-docs: https://asciidoctor.org/docs/ 12 | :project-name: asciidoctor-groovy-dsl 13 | 14 | The {doctitle} allows to define Asciidoctor extensions in {groovy-url}[Groovy]. 15 | 16 | ifdef::env-github[] 17 | image:https://travis-ci.org/asciidoctor/asciidoctorj-groovy-dsl.svg?branch=master["Build Status", link="https://travis-ci.org/asciidoctor/asciidoctorj-groovy-dsl"] 18 | endif::[] 19 | 20 | == Quickstart 21 | 22 | To see the DSL in action at once simply fire up `groovyConsole`. 23 | Then execute this code: 24 | 25 | [source,groovy,subs="attributes+"] 26 | ---- 27 | @GrabConfig(systemClassLoader=true) 28 | @Grab(group='org.asciidoctor', module='asciidoctorj-groovy-dsl', version='{released-version}') // <1> 29 | import org.asciidoctor.groovydsl.AsciidoctorExtensions 30 | import org.asciidoctor.Asciidoctor 31 | 32 | AsciidoctorExtensions.extensions { //<2> 33 | block(name: 'BIG', contexts: [':paragraph']) { 34 | parent, reader, attributes -> 35 | def uppercaseLines = reader.readLines() 36 | .collect {it.toUpperCase()} 37 | .inject('') {a, b -> a + '\n' + b} 38 | 39 | createBlock(parent, 'paragraph', [uppercaseLines], attributes, [:]) 40 | } 41 | } 42 | 43 | println Asciidoctor.Factory.create().convert(''' 44 | [BIG] 45 | Hello World 46 | ''', [:]) // <3> 47 | ---- 48 | <1> Grab the module from jCenter. 49 | This fetches AsciidoctorJ transitively as well. 50 | <2> Register as block extension. 51 | Here, it is defined inline but extensions can also be passed as files or string values. 52 | <3> Invoke AsciidoctorJ to convert the passed string to HTML in the console. 53 | 54 | This results in: 55 | 56 | [source,html] 57 | ---- 58 |
59 |

60 | HELLO WORLD

61 |
62 | ---- 63 | 64 | == Usage 65 | 66 | To use the DSL you have to add a dependency on `org.asciidoctor:asciidoctorj-groovy-dsl:{released-version}` from jCenter. 67 | 68 | The integration into a {gradle-url}[Gradle] project is straightforward. 69 | To use AsciidoctorJ you also add the JCenter repository and add the respective dependency. 70 | 71 | [source,groovy,subs="attributes+"] 72 | ---- 73 | repositories { 74 | jcenter() 75 | } 76 | 77 | dependencies { 78 | compile 'org.asciidoctor:asciidoctorj:{asciidoctorj-version}' 79 | compile 'org.asciidoctor:asciidoctorj-groovy-dsl:{released-version}' 80 | } 81 | ---- 82 | 83 | Extensions can be defined inline in a groovy closure, and also in a separate file or string value. 84 | All extensions must be configured at the class `org.asciidoctor.groovydsl.AsciidoctorExtensions`, and always be registered *before* creating the `Asciidoctor` instance. 85 | 86 | There are two ways to register extensions using AsciidoctorExtensions: 87 | 88 | . Creating an instance. + 89 | This is the recommended method since is thread-safe. 90 | Once an instance is created, extensions can be registered using the `addExtension` method passing a closure, file or string value. 91 | + 92 | [source,groovy] 93 | ---- 94 | def extensions = new AsciidoctorExtensions() 95 | extensions.addExtension { 96 | block(name: 'BIG', contexts: [':paragraph']) { 97 | parent, reader, attributes -> 98 | def uppercaseLines = reader.readLines() 99 | .collect {it.toUpperCase()} 100 | .inject('') {a, b -> a + '\n' + b} 101 | 102 | createBlock(parent, 'paragraph', [uppercaseLines], attributes, [:]) 103 | } 104 | } 105 | ---- 106 | 107 | . Static registration. 108 | This method is offered for convenience and ease of use. 109 | The example below shows how to define an extension inline in a groovy script and convert a file: 110 | + 111 | [source,groovy] 112 | ---- 113 | AsciidoctorExtensions.extensions { 114 | block(name: 'BIG', contexts: [':paragraph']) { 115 | parent, reader, attributes -> 116 | def uppercaseLines = reader.readLines() 117 | .collect {it.toUpperCase()} 118 | .inject('') {a, b -> a + '\n' + b} 119 | 120 | createBlock(parent, 'paragraph', [uppercaseLines], attributes, [:]) 121 | } 122 | } 123 | 124 | Asciidoctor.Factory.create().convertFile('mydocument.ad', [:]) 125 | ---- 126 | 127 | As mentioned, extensions can be also defined from other sources. 128 | This is an example of how to define an extension in a separate file `bigblockextension.groovy`. 129 | 130 | [source,groovy] 131 | .bigblockextension.groovy 132 | ---- 133 | block(name: 'BIG', contexts: [':paragraph']) { 134 | parent, reader, attributes -> 135 | def uppercaseLines = reader.readLines() 136 | .collect {it.toUpperCase()} 137 | .inject('') {a, b -> a + '\n' + b} 138 | 139 | createBlock(parent, 'paragraph', [uppercaseLines], attributes, [:]) 140 | } 141 | ---- 142 | 143 | [source,groovy] 144 | ---- 145 | new AsciidoctorExtensions().addExtension(new File('bigblockextension.groovy')) 146 | Asciidoctor.Factory.create().convertFile('mydocument.ad', [:]) 147 | ---- 148 | 149 | All examples seen in this section will convert the following document as shown below: 150 | 151 | [source,asciidoc] 152 | ---- 153 | [BIG] 154 | Hello, World! 155 | ---- 156 | 157 | This will result in all text in the `[BIG]` block to be converted to upper case: 158 | 159 | ==== 160 | HELLO, WORLD! 161 | ==== 162 | 163 | == Description of the DSL 164 | 165 | For every Processor class in {asciidoctorj}[AsciidoctorJ] there is a function offered by the DSL to simply define such an extension. 166 | The following sections show examples for each kind of extension. 167 | Basically every extension is defined by calling the correct function for the extension type, passing options and a closure that holds the extension logic. 168 | 169 | Under the hood, every closure has an instance of the respective Processor class as its delegate. 170 | That means that all methods provided by `org.asciidoctor.extensions.Processor` and its subclasses are directly available. 171 | 172 | === BlockProcessor 173 | 174 | Block processors are registered using the function `block` and it must define at least the block name and context. 175 | The result of the closure will replace the original block. 176 | 177 | The following example registers an extension for paragraphs having the block name `BIG`: 178 | 179 | [source,groovy] 180 | ---- 181 | block(name: 'BIG', contexts: [':paragraph']) { 182 | parent, reader, attributes -> 183 | def uppercaseLines = reader.readLines() 184 | .collect {it.toUpperCase()} 185 | .inject('') {a, b -> a + '\n' + b} 186 | 187 | createBlock(parent, 'paragraph', [uppercaseLines], attributes, [:]) 188 | } 189 | ---- 190 | 191 | There is also a short form that only takes a block name and the closure. 192 | It automatically registers for 'open' and 'paragraph' block's context: 193 | 194 | [source,groovy] 195 | ---- 196 | block('small') { 197 | parent, reader, attributes -> 198 | def lowercaseLines = reader.readLines() 199 | .collect {it.toLowerCase()} 200 | .inject('') {a, b -> a + '\n' + b} 201 | 202 | createBlock(parent, 'paragraph', [lowercaseLines], attributes, [:]) 203 | } 204 | ---- 205 | 206 | === BlockMacroProcessor 207 | 208 | Block macros processors are registered using the function `block_macro`. 209 | It requires the option `name` that defines the macro name. 210 | There is also the long form taking an option map and the short form that only takes the name. 211 | 212 | [source,groovy] 213 | .Long form: defining name with an options map 214 | ---- 215 | block_macro (name: 'gist') { 216 | parent, target, attributes -> 217 | String content = """
218 | 219 |
""" 220 | createBlock(parent, "pass", [content], attributes, config) 221 | } 222 | ---- 223 | 224 | [source,groovy] 225 | .Short form: defining name directly 226 | ---- 227 | block_macro ('gist') { 228 | parent, target, attributes -> 229 | String content = """
230 | 231 |
""" 232 | createBlock(parent, "pass", [content], attributes, config) 233 | } 234 | ---- 235 | 236 | The extension will be called for a block like this: 237 | 238 | [source,asciidoc] 239 | ---- 240 | gist::123456[] 241 | ---- 242 | 243 | The extension will create a passthrough block that finally gets converted to this: 244 | 245 | ==== 246 |
247 | 248 |
249 | ==== 250 | 251 | === InlineMacroProcessor 252 | 253 | Inline macro processors are registered using the function `inline_macro`. 254 | It also requires the `name` option or the name given as the only additional parameter to the closure. 255 | 256 | [source,groovy] 257 | .Long form: defining name with an options map 258 | ---- 259 | inline_macro (name: 'man') { 260 | parent, target, attributes -> 261 | options = [type: ":link", target: target + ".html"] 262 | createPhraseNode(parent, "anchor", target, attributes, options) 263 | } 264 | ---- 265 | 266 | [source,groovy] 267 | .Short form: defining name directly 268 | ---- 269 | inline_macro ('man') { 270 | parent, target, attributes -> 271 | options = ["type": ":link", target: target + ".html"] 272 | createPhraseNode(parent, "anchor", target, attributes, options) 273 | } 274 | ---- 275 | 276 | The extension will be called for text like this: 277 | 278 | [source,asciidoc] 279 | ---- 280 | See man:gittutorial[7] to get started. 281 | ---- 282 | 283 | The extension will create a link to the gittutorial.html. 284 | 285 | === Preprocessor 286 | 287 | Preprocessor extensions are registered using the function `preprocessor`. 288 | It does not require any additional options besides the extension action. 289 | 290 | The following example will simply remove the first line of the document. 291 | 292 | [source,groovy] 293 | ---- 294 | preprocessor { 295 | document, reader -> 296 | reader.advance() 297 | reader 298 | } 299 | ---- 300 | 301 | === Postprocessor 302 | 303 | Postprocessor extensions are registered using the function `postprocessor`. 304 | It does not require any additional options besides the extension action. 305 | The task action must return the resulting string. 306 | 307 | Note that postprocessors are dependant on the specific backend being used (html, pdf, etc.). 308 | The following example assumes we are converting to HTML and adds a copyright notice at the end of the document: 309 | 310 | [source,groovy] 311 | ---- 312 | import org.jsoup.* 313 | 314 | String copyright = "Copyright Acme, Inc." 315 | 316 | postprocessor { 317 | document, output -> 318 | if (document.basebackend("html")) { 319 | org.jsoup.nodes.Document doc = Jsoup.parse(output, "UTF-8") 320 | def contentElement = doc.getElementsByTag("body") 321 | contentElement.append(copyright) 322 | doc.html() 323 | } else { 324 | throw new IllegalArgumentException("Expected html!") 325 | } 326 | } 327 | ---- 328 | 329 | === IncludeProcessor 330 | 331 | IncludeProcessor extensions are registered using the function `include_processor`. 332 | The options must contain an entry for the key `filter` that points to a closure that decides whether to call this extension for the current include macro. 333 | This closure receives the value of the include 334 | 335 | The following extension registers for all include macros whose resource starts with `https` like the one in the example below. 336 | 337 | [source,groovy] 338 | ---- 339 | String content = "The content of the URL" 340 | 341 | include_processor (filter: {it.startsWith("https")}) { 342 | document, reader, target, attributes -> 343 | reader.push_include(content, target, target, 1, attributes) 344 | } 345 | ---- 346 | 347 | [source,asciidoc] 348 | ---- 349 | This is a remote secures resource to incude: 350 | 351 | include::https://github.com/asciidoctor/asciidoctorj-groovy-dsl/blob/master/README.adoc[] 352 | ---- 353 | 354 | === Treeprocessor 355 | 356 | Treeprocessor extensions are registered using the function `treeprocessor`. 357 | 358 | The following example converts blocks that start with a `$` sign as a listing with the role "command". 359 | 360 | [source,groovy] 361 | ---- 362 | treeprocessor { 363 | document -> 364 | List blocks = document.blocks() 365 | (0.. 0 && lines[0].startsWith('$')) { 369 | Map attributes = block.attributes() 370 | attributes["role"] = "terminal" 371 | def resultLines = lines.collect { 372 | it.startsWith('$') ? "${it.substring(2)}" : it 373 | } 374 | blocks[it] = createBlock(document, "listing", resultLines, attributes,[:]) 375 | } 376 | } 377 | } 378 | ---- 379 | 380 | Here is an example of the source document. 381 | 382 | [source,asciidoc] 383 | ---- 384 | $ echo "Hello, World!" 385 | 386 | $ gem install asciidoctor 387 | ---- 388 | 389 | === DocinfoProcessor 390 | 391 | DocinfoProcessor extensions are registered using the function `docinfo_processor`. 392 | 393 | The following example adds a meta tag to the HTML head element to allow robots to follow links. 394 | 395 | [source, groovy] 396 | ---- 397 | docinfo_processor { 398 | document -> '' 399 | } 400 | ---- 401 | 402 | Additionally, to add content in the footer of the document pass the location option like this: 403 | 404 | [source,groovy] 405 | ---- 406 | docinfo_processor (location : ':footer') { 407 | document -> '
FOOBAR
' 408 | } 409 | ---- 410 | -------------------------------------------------------------------------------- /src/test/groovy/org/asciidoctor/groovydsl/AsciidoctorGroovyDSLSpec.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013-2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the 'License'); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an 'AS IS' BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.asciidoctor.groovydsl 17 | 18 | import org.asciidoctor.Asciidoctor 19 | import org.asciidoctor.Options 20 | import org.asciidoctor.SafeMode 21 | import org.jsoup.Jsoup 22 | import spock.lang.Specification 23 | 24 | /** 25 | * Asciidoctor task inline extensions specification 26 | * 27 | */ 28 | class AsciidoctorGroovyDSLSpec extends Specification { 29 | 30 | private static final String TEST_DOC_BLOCK = '''Ignore this. 31 | 32 | [BIG] 33 | But this should be uppercase 34 | 35 | [small] 36 | And THIS should be lowercase\n\ 37 | 38 | capitalize::tHIS_sets_the_fIRST_letter_in_cApItAlS_and_REMOVES_underscores[] 39 | 40 | .Gemfile 41 | [source,ruby] 42 | ---- 43 | include::https://raw.github.com/asciidoctor/asciidoctor/master/Gemfile[] 44 | ---- 45 | 46 | .My Gist 47 | gist::123456[] 48 | 49 | See man:gittutorial[7] to get started. 50 | 51 | blacklisted is a blacklisted word. 52 | 53 | ''' 54 | 55 | File testRootDir 56 | 57 | def setup() { 58 | testRootDir = new File('.') 59 | } 60 | 61 | 62 | def 'Should clear registry on exception when registering from a Closure'() { 63 | given: 64 | AsciidoctorExtensions.extensions { 65 | throw new Exception('This error is on purpose') 66 | } 67 | 68 | when: 69 | Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 70 | 71 | then: 72 | def e = thrown(ServiceConfigurationError) 73 | e.message.contains('Provider org.asciidoctor.jruby.internal.JRubyAsciidoctor could not be instantiated') 74 | e.cause.message.contains('Error registering extension from class') 75 | e.cause.cause.message.contains('This error is on purpose') 76 | } 77 | 78 | def 'Should clear registry on exception when registering from a String'() { 79 | 80 | given: 81 | AsciidoctorExtensions.extensions 'throw new Exception(\'This error is on purpose\')' 82 | 83 | when: 84 | Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 85 | 86 | then: 87 | def e = thrown(ServiceConfigurationError) 88 | e.message.contains('Provider org.asciidoctor.jruby.internal.JRubyAsciidoctor could not be instantiated') 89 | e.cause.message.contains('Error registering extension from string') 90 | e.cause.cause.message.contains('This error is on purpose') 91 | } 92 | 93 | def 'Should clear registry on exception when registering from a File'() { 94 | given: 95 | AsciidoctorExtensions.extensions(new File('src/test/resources/error.groovy')) 96 | 97 | when: 98 | Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 99 | 100 | then: 101 | def e = thrown(ServiceConfigurationError) 102 | e.message.contains('Provider org.asciidoctor.jruby.internal.JRubyAsciidoctor could not be instantiated') 103 | e.cause.message.contains('Error registering extension from file') 104 | e.cause.cause.message.contains('This error is on purpose') 105 | } 106 | 107 | def 'Should apply BlockProcessor from Script as String'() { 108 | given: 109 | 110 | AsciidoctorExtensions.extensions ''' 111 | block(name: 'BIG', contexts: [':paragraph']) { 112 | parent, reader, attributes -> 113 | def upperLines = reader.readLines() 114 | .collect {it.toUpperCase()} 115 | .inject('') {a, b -> a + '\\n' + b} 116 | 117 | createBlock(parent, 'paragraph', [upperLines], attributes, [:]) 118 | } 119 | block('small') { 120 | parent, reader, attributes -> 121 | def lowerLines = reader.readLines() 122 | .collect {it.toLowerCase()} 123 | .inject('') {a, b -> a + '\\n' + b} 124 | 125 | createBlock(parent, 'paragraph', [lowerLines], attributes, [:]) 126 | } 127 | 128 | ''' 129 | when: 130 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 131 | 132 | then: 133 | rendered.contains('BUT THIS SHOULD BE UPPERCASE') 134 | rendered.contains('and this should be lowercase') 135 | rendered.contains('Ignore this.') 136 | } 137 | 138 | 139 | def 'Should apply BlockProcessor from Closure'() { 140 | given: 141 | 142 | AsciidoctorExtensions.extensions { 143 | block(name: 'BIG', contexts: [':paragraph']) { 144 | parent, reader, attributes -> 145 | def upperLines = reader.readLines() 146 | .collect { it.toUpperCase() } 147 | .inject('') { a, b -> a + '\n' + b } 148 | 149 | createBlock(parent, 'paragraph', [upperLines], attributes, [:]) 150 | } 151 | block('small') { 152 | parent, reader, attributes -> 153 | def lowerLines = reader.readLines() 154 | .collect { it.toLowerCase() } 155 | .inject('') { a, b -> a + '\n' + b } 156 | 157 | createBlock(parent, 'paragraph', [lowerLines], attributes, [:]) 158 | } 159 | 160 | } 161 | 162 | when: 163 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 164 | 165 | then: 166 | rendered.contains('BUT THIS SHOULD BE UPPERCASE') 167 | rendered.contains('and this should be lowercase') 168 | rendered.contains('Ignore this.') 169 | } 170 | 171 | def 'Should apply BlockProcessor from Extension file'() { 172 | given: 173 | AsciidoctorExtensions.extensions(new File('src/test/resources/testblockextensions.groovy')) 174 | 175 | when: 176 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 177 | 178 | then: 179 | rendered.contains('BUT THIS SHOULD BE UPPERCASE') 180 | rendered.contains('and this should be lowercase') 181 | rendered.contains('Ignore this.') 182 | } 183 | 184 | def 'Should apply Postprocessor from String'() { 185 | given: 186 | String extension = new File('src/test/resources/testpostprocessorextension.groovy').text 187 | AsciidoctorExtensions.extensions(extension) 188 | 189 | when: 190 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 191 | 192 | then: 193 | rendered.contains('Copyright Acme, Inc.') 194 | } 195 | 196 | def 'Should apply Postprocessor from Closure'() { 197 | given: 198 | String copyright = "Copyright Acme, Inc." 199 | AsciidoctorExtensions.extensions { 200 | postprocessor { 201 | document, output -> 202 | if (document.isBasebackend("html")) { 203 | org.jsoup.nodes.Document doc = Jsoup.parse(output, "UTF-8") 204 | 205 | def contentElement = doc.getElementsByTag("body") 206 | contentElement.append(copyright) 207 | doc.html() 208 | } else { 209 | throw new IllegalArgumentException("Expected html!") 210 | } 211 | } 212 | } 213 | 214 | when: 215 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 216 | 217 | then: 218 | rendered.contains('Copyright Acme, Inc.') 219 | } 220 | 221 | def 'Should apply Postprocessor from Extension file'() { 222 | given: 223 | AsciidoctorExtensions.extensions(new File('src/test/resources/testpostprocessorextension.groovy')) 224 | 225 | when: 226 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 227 | 228 | then: 229 | rendered.contains('Copyright Acme, Inc.') 230 | } 231 | 232 | def 'Should apply Preprocessor from String'() { 233 | given: 234 | String extension = new File('src/test/resources/testpreprocessorextension.groovy').text 235 | AsciidoctorExtensions.extensions(extension) 236 | 237 | when: 238 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 239 | 240 | then: 241 | !rendered.contains('Ignore this.') 242 | } 243 | 244 | def 'Should apply Preprocessor from Closure'() { 245 | given: 246 | AsciidoctorExtensions.extensions { 247 | preprocessor { 248 | document, reader -> 249 | newReader(reader.lines.tail()) 250 | } 251 | } 252 | 253 | when: 254 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 255 | 256 | then: 257 | !rendered.contains('Ignore this.') 258 | } 259 | 260 | def 'Should apply Preprocessor from Extension file'() { 261 | given: 262 | AsciidoctorExtensions.extensions(new File('src/test/resources/testpreprocessorextension.groovy')) 263 | 264 | when: 265 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 266 | 267 | then: 268 | !rendered.contains('Ignore this.') 269 | } 270 | 271 | def 'Should apply Includeprocessor from String'() { 272 | given: 273 | String extension = new File('src/test/resources/testincludeprocessorextension.groovy').text 274 | AsciidoctorExtensions.extensions(extension) 275 | 276 | when: 277 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 278 | 279 | then: 280 | rendered.contains('The content of the URL') 281 | } 282 | 283 | def 'Should apply Includeprocessor from Closure'() { 284 | given: 285 | AsciidoctorExtensions.extensions { 286 | include_processor(filter: { it.startsWith("http") }) { 287 | document, reader, target, attributes -> 288 | reader.pushInclude("The content of the URL", target, target, 1, attributes) 289 | } 290 | } 291 | 292 | when: 293 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 294 | 295 | then: 296 | rendered.contains('The content of the URL') 297 | } 298 | 299 | def 'Should apply IncludeProcessor from Extension file'() { 300 | given: 301 | AsciidoctorExtensions.extensions(new File('src/test/resources/testincludeprocessorextension.groovy')) 302 | 303 | when: 304 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 305 | 306 | then: 307 | rendered.contains('The content of the URL') 308 | } 309 | 310 | def 'Should apply BlockMacroProcessor from String'() { 311 | given: 312 | String extension = new File('src/test/resources/testblockmacroextension.groovy').text 313 | AsciidoctorExtensions.extensions(extension) 314 | 315 | when: 316 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 317 | 318 | then: 319 | rendered.contains("https://gist.github.com/123456.js") 320 | } 321 | 322 | def 'Should apply BlockMacroProcessor from Closure'() { 323 | given: 324 | AsciidoctorExtensions.extensions { 325 | block_macro("gist") { 326 | parent, target, attributes -> 327 | String content = """
328 | 329 |
""" 330 | createBlock(parent, "pass", [content], attributes) 331 | } 332 | } 333 | 334 | when: 335 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 336 | 337 | then: 338 | rendered.contains("https://gist.github.com/123456.js") 339 | } 340 | 341 | def 'Should apply BlockMacroProcessor from Extension file'() { 342 | given: 343 | AsciidoctorExtensions.extensions(new File('src/test/resources/testblockmacroextension.groovy')) 344 | 345 | when: 346 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 347 | 348 | then: 349 | rendered.contains("https://gist.github.com/123456.js") 350 | } 351 | 352 | def 'Should apply InlineMacroProcessor from String'() { 353 | given: 354 | String extension = new File('src/test/resources/testinlinemacroprocessorextension.groovy').text 355 | AsciidoctorExtensions.extensions(extension) 356 | 357 | when: 358 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 359 | 360 | then: 361 | rendered.contains('gittutorial') 362 | } 363 | 364 | def 'Should apply InlineMacroProcessor from Closure'() { 365 | given: 366 | 367 | AsciidoctorExtensions.extensions { 368 | inline_macro('man') { 369 | parent, target, attributes -> 370 | def options = ["type": ":link", "target": target + ".html"] 371 | createPhraseNode(parent, "anchor", target, attributes, options) 372 | } 373 | } 374 | 375 | when: 376 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 377 | 378 | then: 379 | rendered.contains('gittutorial') 380 | } 381 | 382 | def 'Should apply InlineMacroProcessor from Extension file'() { 383 | given: 384 | AsciidoctorExtensions.extensions(new File('src/test/resources/testinlinemacroprocessorextension.groovy')) 385 | 386 | when: 387 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 388 | 389 | then: 390 | rendered.contains('gittutorial') 391 | } 392 | 393 | def 'Should apply Treeprocessor from String'() { 394 | given: 395 | String extension = new File('src/test/resources/testtreeprocessorextension.groovy').text 396 | AsciidoctorExtensions.extensions(extension) 397 | 398 | when: 399 | String rendered = Asciidoctor.Factory.create().convert(''' 400 | $ echo "Hello, World!" 401 | 402 | $ gem install asciidoctor 403 | ''', Options.builder().build()) 404 | 405 | then: 406 | rendered.contains('
') 407 | rendered.contains('gem install asciidoctor') 408 | } 409 | 410 | def 'Should apply Treeprocessor from Closure'() { 411 | given: 412 | AsciidoctorExtensions.extensions { 413 | treeprocessor { 414 | document -> 415 | def blocks = document.blocks 416 | blocks.eachWithIndex { block, i -> 417 | def lines = block.lines 418 | if (lines.size() > 0 && lines[0].startsWith('$')) { 419 | Map attributes = block.attributes 420 | attributes["role"] = "terminal" 421 | def resultLines = lines.collect { 422 | it.startsWith('$') ? "${it.substring(2)}".toString() : it 423 | } 424 | blocks[i] = createBlock(document, "listing", resultLines, attributes, [:]) 425 | } 426 | } 427 | } 428 | } 429 | 430 | when: 431 | String rendered = Asciidoctor.Factory.create().convert(''' 432 | $ echo "Hello, World!" 433 | 434 | $ gem install asciidoctor 435 | ''', Options.builder().build()) 436 | 437 | then: 438 | rendered.contains('
') 439 | rendered.contains('gem install asciidoctor') 440 | } 441 | 442 | def 'Should apply Treeprocessor from Extension file'() { 443 | given: 444 | AsciidoctorExtensions.extensions(new File('src/test/resources/testtreeprocessorextension.groovy')) 445 | 446 | when: 447 | String rendered = Asciidoctor.Factory.create().convert(''' 448 | $ echo "Hello, World!" 449 | 450 | $ gem install asciidoctor 451 | ''', Options.builder().build()) 452 | 453 | then: 454 | rendered.contains('
') 455 | rendered.contains('gem install asciidoctor') 456 | } 457 | 458 | def 'Should apply DocinfoProcessor from String'() { 459 | given: 460 | String extension = new File('src/test/resources/testdocinfoprocessorextension.groovy').text 461 | AsciidoctorExtensions.extensions(extension) 462 | 463 | when: 464 | String rendered = Asciidoctor.Factory.create().convert( 465 | ''' 466 | = Hello 467 | 468 | World''', 469 | Options.builder().standalone(true).safe(SafeMode.SERVER).toFile(false).build()) 470 | 471 | then: 472 | // (?ms) Multiline regexp with dotall (= '.' matches newline as well) 473 | rendered ==~ /(?ms).*.*.*<\/head>.*/ 474 | } 475 | 476 | def 'Should apply DocinfoProcessor from Closure'() { 477 | given: 478 | String metatag = '' 479 | AsciidoctorExtensions.extensions { 480 | docinfo_processor { 481 | document -> metatag 482 | } 483 | } 484 | 485 | when: 486 | String rendered = Asciidoctor.Factory.create().convert( 487 | ''' 488 | = Hello 489 | 490 | World''', 491 | Options.builder().standalone(true).safe(SafeMode.SERVER).toFile(false).build()) 492 | 493 | then: 494 | // (?ms) Multiline regexp with dotall (= '.' matches newline as well) 495 | rendered ==~ /(?ms).*.*.*<\/head>.*/ 496 | } 497 | 498 | def 'Should apply DocinfoProcessor from Extension file'() { 499 | given: 500 | AsciidoctorExtensions.extensions(new File('src/test/resources/testdocinfoprocessorextension.groovy')) 501 | 502 | when: 503 | String rendered = Asciidoctor.Factory.create().convert( 504 | ''' 505 | = Hello 506 | 507 | World''', 508 | Options.builder().standalone(true).safe(SafeMode.SERVER).toFile(false).build()) 509 | 510 | then: 511 | // (?ms) Multiline regexp with dotall (= '.' matches newline as well) 512 | rendered ==~ /(?ms).*.*.*<\/head>.*/ 513 | } 514 | 515 | def 'Should apply BlockMacroProcessor from Closure with string parameter'() { 516 | given: 517 | 518 | AsciidoctorExtensions.extensions { 519 | block_macro('capitalize') { 520 | parent, target, attributes -> 521 | def capitalLines = target.toLowerCase() 522 | .tokenize('_') 523 | .collect { it.capitalize() } 524 | .join(' ') 525 | createBlock(parent, 'pass', [capitalLines], attributes) 526 | } 527 | } 528 | 529 | when: 530 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 531 | 532 | then: 533 | rendered.contains('This Sets The First Letter In Capitals And Removes Underscores') 534 | rendered.contains('Ignore this.') 535 | } 536 | 537 | def 'Should apply BlockMacroProcessor from Closure with named parameter'() { 538 | given: 539 | 540 | AsciidoctorExtensions.extensions { 541 | block_macro(name: 'capitalize') { 542 | parent, target, attributes -> 543 | def capitalLines = target.toLowerCase() 544 | .tokenize('_') 545 | .collect { it.capitalize() } 546 | .join(' ') 547 | createBlock(parent, 'pass', [capitalLines], attributes) 548 | } 549 | } 550 | 551 | when: 552 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 553 | 554 | then: 555 | rendered.contains('This Sets The First Letter In Capitals And Removes Underscores') 556 | rendered.contains('Ignore this.') 557 | } 558 | 559 | def 'Should apply InlineMacroProcessor from Closure with named parameter'() { 560 | given: 561 | 562 | AsciidoctorExtensions.extensions { 563 | inline_macro(name: 'man') { 564 | parent, target, attributes -> 565 | def options = ["type": ":link", "target": target + ".html"] 566 | createPhraseNode(parent, "anchor", target, attributes, options) 567 | } 568 | } 569 | 570 | when: 571 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 572 | 573 | then: 574 | rendered.contains('gittutorial') 575 | } 576 | 577 | def 'Should apply InlineMacroProcessor from Closure with string parameter'() { 578 | given: 579 | 580 | AsciidoctorExtensions.extensions { 581 | inline_macro('man') { 582 | parent, target, attributes -> 583 | def options = ["type": ":link", "target": target + ".html"] 584 | createPhraseNode(parent, "anchor", target, attributes, options) 585 | } 586 | } 587 | 588 | when: 589 | String rendered = Asciidoctor.Factory.create().convert(TEST_DOC_BLOCK, Options.builder().build()) 590 | 591 | then: 592 | rendered.contains('gittutorial') 593 | } 594 | 595 | } 596 | --------------------------------------------------------------------------------