├── CONTRIBUTING.adoc ├── LICENSE ├── README.adoc ├── asciidoc.png ├── converttoasciidoc.gapps └── gdoc2adoc.java /CONTRIBUTING.adoc: -------------------------------------------------------------------------------- 1 | = Contributing 2 | 3 | I would love contributions in form of bug reports or even better pull 4 | request fixing bugs or missing features! 5 | 6 | The best way to do bug reports are that you replicate the issue in a Google 7 | Document, make it publically readable (if I need to edit, I can copy 8 | it) and put a link to said document in your bug reports and/or pull 9 | requests. 10 | 11 | If you are adding or requesting a new feature please do not hesitate 12 | to simply copy the 13 | https://docs.google.com/document/d/19VD9FCTj6tHeWxdhkmctA1r9Ko3surX3Ee8wp_iwlo4/edit?usp=sharing[test 14 | document] and provide a link to your new document (remember to share 15 | it) with the new/missing feture illustrated in a new section. 16 | 17 | For fun I've also enabled comments on the test document so you can actually provide 18 | suggestions directly - if you do, please put a link back to the relevant issue 19 | or pull-request in this git repo. 20 | 21 | Thank you! -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = gdoc2adoc 2 | 3 | 4 | This project contains two ways to convert a Google Document to asciidoc(tor) format. 5 | 6 | The first one is most mature and uses Google Apps Script, the second one is more experimental and uses the https://developers.google.com/docs/api/[Google Doc API]. 7 | 8 | == Google Apps 9 | 10 | A simple Google Apps script to convert a properly formatted Google 11 | Drive Document to asciidoc (.adoc) format, or rather more precisly 12 | asciidoctor compatible format. 13 | 14 | image:asciidoc.png[Screenshot Google Docs with gdoc2adoc] 15 | 16 | === Try it 17 | 18 | You can explore this script on this https://docs.google.com/document/d/19VD9FCTj6tHeWxdhkmctA1r9Ko3surX3Ee8wp_iwlo4/edit?usp=sharing[Google Doc] document - you just need to copy this to your own Google Drive to be able to run the script via the Tools or AsciiDoc menu. 19 | 20 | === Usage 21 | 22 | * Adding this script to your doc (once per doc): 23 | ** Open your Google Drive document (http://drive.google.com) 24 | ** Tools -> Script Manager > New 25 | ** Select "Blank Project", then paste this code in and save. 26 | *** Clear the myFunction() default empty function and paste the contents of `converttoasciidoc.gapps` into the code editor 27 | *** File -> Save 28 | 29 | * Running the script (run as many times as you want): 30 | ** AsciiDoc > Export File (Creates a new folder `target` in the same directory as the document. AsciiDoc and image files are stored in it. A warning is generated if a `target` directory already exists) 31 | ** AsciiDoc > Export Email (Sends you an email with the AsciiDoc and image files) 32 | 33 | === Interpreted formats 34 | 35 | Things not yet handled proper asciidoc way is marked with a todo. 36 | 37 | * Text: 38 | ** paragraphs are separated by two newlines 39 | ** text styled as heading 1, 2, 3, etc is converted to AsciiDoc heading: =, ==, ===, etc 40 | ** TODO: text formatted with Courier New is backquoted: ``text`` 41 | ** links are converted to asciidoc format: `url[anchortext]` 42 | * Lists: 43 | ** Numbered lists are converted correctly, including nested lists 44 | ** bullet lists are converted to "`*`" AsciiDoc format appropriately, including nested lists 45 | ** Honors linebreak in paragraphs by using asciidoc line continuation ('+' on empty line) 46 | * Images: 47 | ** images are correctly extracted and sent as attachments 48 | * Drawings: 49 | ** not supported - there seems to be no API function to export a drawing as a rasterized or vector image. 50 | * TODO: Equations: 51 | ** Equaations are not supported. 52 | * Table of contents: 53 | ** Is handled by asciidoctor `toc` macros 54 | * Horizontal line: 55 | ** Inserts a `---` 56 | * Header/Footer: 57 | ** Extracts text with all formattings and inserts it at the top and bottom of the AsciiDoc document, seperated by `---`. 58 | * Tables: 59 | ** Converted to AsciiDoc tables. Formatting within cells gets transferred. 60 | * Source code: 61 | ** Fenced code blocks are started by three back-ticks and a string and ended by three back-ticks. If such a fenced code block is detected, single line break is used within it. 62 | 63 | === Reading materials 64 | 65 | Documentation about https://developers.google.com/apps-script/guides/docs[Google Documentation document structure] 66 | 67 | == Google Doc API 68 | 69 | This implementation is for now a proof-of-concept, lots of formatting not supported yet (contributions welcome)! 70 | 71 | To use this you need to: 72 | 73 | 1. https://console.developers.google.com/apis/library/docs.googleapis.com?q=google%20doc&id=9bc59c8c-49cd-4ac5-8665-d0891d366733&project=orggcal-270008[Enable Google Doc Api] and get auth credentials and save it in `credentials.json`. 74 | 2. Install https://github.com/maxandersen/jbang[jbang] 75 | 3. Run `./gdoc2adoc.java > mydoc.adoc` 76 | 77 | == CONTRIBUTORS 78 | 79 | * Heavily inspired by https://github.com/jacksonicson/gdocs2md 80 | 81 | == LICENSE 82 | 83 | Use this script at your will, on any document you want and for any purpose, commercial or not. 84 | The AsciiDoc files generated by this script are not considered derivative work and 85 | don't require any attribution to the owners of this script. 86 | 87 | If you want to modify and redistribute the script (not the converted documents - those are yours), 88 | just keep a reference to this repo or to the license info below: 89 | 90 | ``` 91 | Copyright 2013 Google Inc. All Rights Reserved. 92 | 93 | Licensed under the Apache License, Version 2.0 (the "License"); 94 | you may not use this file except in compliance with the License. 95 | You may obtain a copy of the License at 96 | 97 | http://www.apache.org/licenses/LICENSE-2.0 98 | 99 | Unless required by applicable law or agreed to in writing, software 100 | distributed under the License is distributed on an "AS IS" BASIS, 101 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 102 | See the License for the specific language governing permissions and 103 | limitations under the License. 104 | ``` 105 | -------------------------------------------------------------------------------- /asciidoc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxandersen/gdoc2adoc/d4676413b9c9376c68fc406ec180e43bcd6aa35c/asciidoc.png -------------------------------------------------------------------------------- /converttoasciidoc.gapps: -------------------------------------------------------------------------------- 1 | // vim: set softtabstop=2 shiftwidth=2 expandtab : 2 | var ADOC_MIMETYPE = "text/asciidoc"; 3 | 4 | // Open handler to add Menu 5 | function onOpen(e) { 6 | var ui = DocumentApp.getUi(); 7 | 8 | if (e && e.authMode == ScriptApp.AuthMode.NONE) { 9 | ui.createMenu('AsciiDoc') 10 | // .addItem('Latex Equation', 'ConvertEquation') 11 | .addToUi(); 12 | } else { 13 | ui.createMenu('AsciiDoc') 14 | .addItem('Export File', 'ConvertToAsciiDocFile') 15 | .addItem('Export Email', 'ConvertToAsciiDocEmail') 16 | // .addItem('Latex Equation', 'ConvertEquation') 17 | .addToUi(); 18 | } 19 | } 20 | 21 | function onInstall(e) { 22 | onOpen(e); 23 | } 24 | 25 | function ConvertEquation() { 26 | var element = DocumentApp.getActiveDocument().getCursor().getElement(); 27 | 28 | // Scan upwards for an equation 29 | while(element.getType() != DocumentApp.ElementType.EQUATION) { 30 | if(element.getParent() == null) 31 | break; 32 | 33 | element = element.getParent(); 34 | } 35 | 36 | if(element.getType() != DocumentApp.ElementType.EQUATION) { 37 | DocumentApp.getUi().alert("Put cursor into an equation element!"); 38 | return; 39 | } 40 | 41 | // Covert equation 42 | var latexEquation = handleEquationFunction(element); 43 | var latexEquationText = "$" + latexEquation.trim() + "$"; 44 | 45 | // Show results 46 | DocumentApp.getUi().alert(latexEquationText); 47 | } 48 | 49 | // Convert current document to asciidoc and email it 50 | function ConvertToAsciiDocEmail() { 51 | // Convert to asciidoc 52 | var convertedDoc = asciidoc(); 53 | 54 | // Add asciidoc document to attachments 55 | convertedDoc.attachments.push({"fileName":DocumentApp.getActiveDocument().getName()+".adoc", 56 | "mimeType": ADOC_MIMETYPE, "content": convertedDoc.text}); 57 | 58 | // In some cases user email is not accessible 59 | var mail = Session.getActiveUser().getEmail(); 60 | if(mail === '') { 61 | DocumentApp.getUi().alert("Could not read your email address"); 62 | return; 63 | } 64 | 65 | // Send email with asciidoc document 66 | MailApp.sendEmail(mail, 67 | "[gdoc2adoc] "+DocumentApp.getActiveDocument().getName(), 68 | "Your converted AsciiDoc document is attached (converted from "+DocumentApp.getActiveDocument().getUrl()+")", 69 | { "attachments": convertedDoc.attachments }); 70 | } 71 | 72 | function getFolder(parent_folder,folder_name){ 73 | var folders = parent_folder.getFolders(); 74 | while (folders.hasNext()) { 75 | var folder = folders.next(); 76 | if(folder_name == folder.getName()) { 77 | return folder; 78 | } 79 | } 80 | return false; 81 | } 82 | 83 | // Convert current document to file and save it to GDrive 84 | function ConvertToAsciiDocFile() { 85 | // Convert to asciidoc 86 | var convertedDoc = asciidoc(); 87 | 88 | // Create folder 89 | var id = DocumentApp.getActiveDocument().getId(); 90 | var file = DriveApp.getFileById(id); 91 | var parents = file.getParents(); 92 | var parent = null; 93 | 94 | if(parents.hasNext()) { 95 | parent = parents.next() 96 | if(parents.hasNext()) { 97 | //Logger.log("File has multiple parent directories. Script does not work in this case"); 98 | DocumentApp.getUi().alert("Document must not be in multiple directories"); 99 | return; 100 | } 101 | } else { 102 | DocumentApp.getUi().alert("Document has to be in a directory for the export"); 103 | return; 104 | } 105 | 106 | var targetDirName = DocumentApp.getActiveDocument().getName() + ".adoc" 107 | var found = getFolder(parent,targetDirName); 108 | if (found === false){ 109 | //Logger.log("Creating output folder..."); 110 | found = parent.createFolder(targetDirName); 111 | } else { 112 | //Logger.log("Reusing existing target"); 113 | var ui = DocumentApp.getUi(); 114 | var result = ui.alert('Existing target folder found!', 'You already have "' + targetDirName + '" in your Drive. Delete folder or Cancel ?', 115 | ui.ButtonSet.OK_CANCEL) 116 | 117 | if(result == ui.Button.OK) { 118 | //Logger.log("Trashing target folder..."); 119 | found.setTrashed(true); 120 | //Logger.log("Re-Creating output folder..."); 121 | found = parent.createFolder(targetDirName); 122 | 123 | } else { 124 | //Logger.log("Do not delete target folder, stopping!"); 125 | return; 126 | } 127 | } 128 | 129 | // Write all files to target folder 130 | for(var file in convertedDoc.files) { 131 | file = convertedDoc.files[file]; 132 | var blob = file.blob.copyBlob(); 133 | var name = file.name; 134 | blob.setName(name); 135 | 136 | 137 | found.createFile(blob); 138 | } 139 | 140 | // Write mardown file to target folder 141 | // using same nameas folder. 142 | found.createFile(targetDirName, convertedDoc.text, ADOC_MIMETYPE); 143 | 144 | } 145 | 146 | function processSection(section) { 147 | var state = { 148 | 'inSource' : false, // Document read pointer is within a fenced code block 149 | 'images' : [], // Image data found in document 150 | 'imageCounter' : 0, // Image counter 151 | 'prevDoc' : [], // Pointer to the previous element on aparsing tree level 152 | 'nextDoc' : [], // Pointer to the next element on a parsing tree level 153 | 'size' : [], // Number of elements on a parsing tree level 154 | 'listCounters' : [], // List counter 155 | 'needToc' : false, // saw a toc reference 156 | 'indent' : 0, // indent on current block 157 | 'headingPrefix' : '', // Should headings be prefixed by a `=` to make heading1 `==` (see detectHeadingRules) 158 | }; 159 | 160 | // Detect title, heading1 etc 161 | detectHeadingRules(section, state); 162 | 163 | // Process element tree outgoing from the root element 164 | var textElements = processElement(section, state, 0); 165 | 166 | return { 167 | 'textElements' : textElements, 168 | 'state' : state, 169 | }; 170 | } 171 | 172 | function detectHeadingRulesNested(element, state, headingState) { 173 | Logger.log("detectHeadingRulesNested: " + element.getType()); 174 | 175 | switch(element.getType()) { 176 | case DocumentApp.ElementType.DOCUMENT: 177 | case DocumentApp.ElementType.BODY_SECTION: 178 | // Iterates over all childs 179 | for(var i=0; i < element.getNumChildren(); i++) { 180 | var child = element.getChild(i); 181 | 182 | detectHeadingRulesNested(child, state, headingState); 183 | } 184 | break; 185 | 186 | case DocumentApp.ElementType.PARAGRAPH: 187 | switch (element.getHeading()) { 188 | case DocumentApp.ParagraphHeading.HEADING1: 189 | headingState.nbrOfH1 += 1; break; 190 | case DocumentApp.ParagraphHeading.TITLE: 191 | headingState.hasTitle = true; 192 | } 193 | 194 | // Iterates over all childs 195 | for(var i=0; i < element.getNumChildren(); i++) { 196 | var child = element.getChild(i); 197 | 198 | detectHeadingRulesNested(child, state, headingState); 199 | } 200 | } 201 | } 202 | 203 | function detectHeadingRules(element, state) { 204 | 205 | var headingState = { 206 | 'nbrOfH1': 0, 207 | 'hasTitle' : false, 208 | }; 209 | 210 | detectHeadingRulesNested(element, state, headingState); 211 | 212 | Logger.log("Heading detection, nbrOfH1: " + headingState.nbrOfH1 + " and title: " + headingState.hasTitle); 213 | 214 | if (headingState.hasTitle == true) { 215 | Logger.log("Heading prefix `=` because there is a title"); 216 | state.headingPrefix = '='; 217 | } 218 | else if (headingState.nbrOfH1 == 1) { 219 | // we have a single heading1 so we will pretend it's the title and h2 is for subsections 220 | Logger.log("Heading prefix `` because there is a single h1"); 221 | state.headingPrefix = ''; 222 | } 223 | else { 224 | // no title and multiple (or no h1) => treat h1 as a Asciidoc subsection (i.e. `==`) 225 | Logger.log("No title and multiple (or no h1) => treat h1 as a Asciidoc subsection (i.e. `==`)"); 226 | state.headingPrefix = '='; 227 | } 228 | } 229 | 230 | 231 | function asciidoc() { 232 | // Text elements 233 | var textElements = []; 234 | 235 | // Process header 236 | var head = DocumentApp.getActiveDocument().getHeader(); 237 | if(head != null) { 238 | // Do not include empty header sections 239 | var teHead = processSection(head); 240 | if(teHead.textElements.length > 0) { 241 | textElements = textElements.concat(teHead.textElements); 242 | textElements.push('\n\n'); 243 | textElements.push('---'); 244 | textElements.push('\n\n'); 245 | } 246 | } 247 | 248 | // Process body 249 | var doc = DocumentApp.getActiveDocument().getBody(); 250 | doc = processSection(doc); 251 | textElements = textElements.concat(doc.textElements); 252 | 253 | // Process footer 254 | var foot = DocumentApp.getActiveDocument().getFooter(); 255 | //Logger.log("foot: " + foot); 256 | if(foot != null) { 257 | var teFoot = processSection(foot); 258 | // Do not include empty footer sections 259 | if(teFoot.textElements.length > 0) { 260 | textElements.push('\n\n'); 261 | textElements.push('---'); 262 | textElements.push('\n\n'); 263 | textElements = textElements.concat(teFoot.textElements); 264 | } 265 | } 266 | 267 | // Build final output string 268 | var text = textElements.join(''); 269 | 270 | // Replace critical chars 271 | text = text.replace('\u201d', '"').replace('\u201c', '"'); 272 | 273 | // Debug logging 274 | //Logger.log("Result: " + text); 275 | Logger.log("Images: " + doc.state.imageCounter); 276 | 277 | // Build attachment and file lists 278 | var attachments = []; 279 | var files = []; 280 | for(var i in doc.state.images) { 281 | var image = doc.state.images[i]; 282 | attachments.push( { 283 | "fileName": image.name, 284 | "mimeType": image.type, 285 | "content": image.bytes 286 | } ); 287 | 288 | files.push( { 289 | "name" : image.name, 290 | "blob" : image.blob 291 | }); 292 | } 293 | 294 | // Results 295 | return { 296 | 'files' : files, 297 | 'attachments' : attachments, 298 | 'text' : text, 299 | }; 300 | } 301 | 302 | 303 | function escapeHTML(text) { 304 | return text.replace(//g, '>'); 305 | } 306 | 307 | // Add repeat function to strings 308 | String.prototype.repeat = function( num ) { 309 | return new Array( num + 1 ).join( this ); 310 | } 311 | 312 | function handleTable(element, state, depth) { 313 | var textElements = []; 314 | 315 | textElements.push("\n"); 316 | 317 | textElements.push("|===\n") 318 | 319 | function buildTable(size) { 320 | var stack = [] 321 | var maxSize = 0; 322 | 323 | for(var ir=0; ir text.length) { 345 | text += " ".repeat(size - text.length) 346 | } 347 | 348 | stack.push("| " + text); 349 | } 350 | 351 | stack.push(" \n"); 352 | } 353 | 354 | stack.push("|===\n") 355 | stack.push("\n"); 356 | return { 357 | maxSize : maxSize, 358 | stack : stack, 359 | }; 360 | } 361 | 362 | var table = buildTable(100); 363 | table = buildTable(Math.max(10, table.maxSize + 1)); 364 | textElements = textElements.concat(table.stack); 365 | 366 | textElements.push('\n'); 367 | return textElements; 368 | } 369 | 370 | function formatMd(text, indexLeft, formatLeft, indexRight, formatRight) { 371 | var leftPad = '' + formatLeft; 372 | if(indexLeft > 0) { 373 | if(text[indexLeft - 1] != ' ') 374 | leftPad = ' ' + formatLeft; 375 | } 376 | 377 | var rightPad = formatRight + ''; 378 | if(indexRight < text.length) { 379 | if(text[indexRight] != ' ') { 380 | rightPad = formatRight + ' '; 381 | } 382 | } 383 | 384 | //Note: we do a trim via .replace since asciidoc wont format i.e. * test* with bold. 385 | var formatted = text.substring(0, indexLeft) + leftPad + text.substring(indexLeft, indexRight).replace(/^\s+|\s+$/g,"") + rightPad + text.substring(indexRight); 386 | return formatted; 387 | } 388 | 389 | 390 | function handleText(doc, state) { 391 | var formatted = doc.getText(); 392 | var lastIndex = formatted.length; 393 | var attrs = doc.getTextAttributeIndices(); 394 | 395 | // Iterate backwards through all attributes 396 | for(var i=attrs.length-1; i >= 0; i--) { 397 | // Current position in text 398 | var index = attrs[i]; 399 | 400 | // Handle links 401 | if(doc.getLinkUrl(index)) { 402 | var url = doc.getLinkUrl(index); 403 | if (i > 0 && attrs[i-1] == index - 1 && doc.getLinkUrl(attrs[i-1]) === url) { 404 | i -= 1; 405 | index = attrs[i]; 406 | url = doc.getLinkUrl(index); 407 | } 408 | formatted = formatted.substring(0, index) + url + '[' + formatted.substring(index, lastIndex) + ']' + formatted.substring(lastIndex); 409 | 410 | // Do not handle additional formattings for links 411 | continue; 412 | } 413 | 414 | // Handle source code 415 | if(isTextCode(doc, index)) { 416 | if (!state.inSource) { 417 | // Scan left until text without source font is found 418 | while (i > 0 && doc.getFontFamily(attrs[i-1]) && doc.getFontFamily(attrs[i-1]) === sourceFont) { 419 | i -= 1; 420 | off = attrs[i]; 421 | } 422 | 423 | formatted = formatMd(formatted, index, '`', lastIndex, '`'); 424 | 425 | // Do not handle additional formattings for code 426 | continue; 427 | } 428 | } 429 | 430 | 431 | // TODO: does not handle nested formatting well. 432 | // Handle bold and bold italic 433 | if(doc.isBold(index)) { 434 | var dleft, right; 435 | dleft = dright = "*"; 436 | if (doc.isItalic(index)) 437 | { 438 | // edbacher: changed this to handle bold italic properly. 439 | dleft = "**__"; 440 | dright = "__**"; 441 | } 442 | 443 | formatted = formatMd(formatted, index, dleft, lastIndex, dright); 444 | } 445 | // Handle italic 446 | else if(doc.isItalic(index)) { 447 | formatted = formatMd(formatted, index, '_', lastIndex, '_'); 448 | } else if (doc.isUnderline(index)) { 449 | formatted = formatMd(formatted, index, '[.underline]#', lastIndex, '#'); 450 | } else if(doc.isStrikethrough(index)) { 451 | formatted = formatMd(formatted, index, '[.line-through]#', lastIndex, '#'); 452 | } else if(doc.getTextAlignment(index) == DocumentApp.TextAlignment.SUBSCRIPT) { 453 | formatted = formatMd(formatted, index, '~', lastIndex, '~'); 454 | } else if(doc.getTextAlignment(index) == DocumentApp.TextAlignment.SUPERSCRIPT) { 455 | formatted = formatMd(formatted, index, '^', lastIndex, '^'); 456 | } 457 | 458 | // replace newlines wit any indent requested from higher up formatting. 459 | var haslinebreak = /\r/.exec(formatted); 460 | formatted = formatted.replace(/(?:\r)/g, '\n+\n'); 461 | if (haslinebreak) // add extra newline to let list and others continue 462 | formatted += "\n"; 463 | // Keep track of last position in text 464 | lastIndex = index; 465 | } 466 | 467 | var textElements = [formatted]; 468 | return textElements; 469 | } 470 | 471 | 472 | 473 | function handleListItem(item, state, depth) { 474 | var textElements = []; 475 | 476 | // Prefix 477 | var prefix = ''; 478 | 479 | // Add nesting level 480 | for (var i=0; i= 0)?doc.getChild(i-1) : child; 613 | state.prevDoc[depth] = prevDoc; 614 | 615 | textElements = textElements.concat(processElement(child, state, depth+1)); 616 | 617 | } 618 | 619 | 620 | return textElements; 621 | } 622 | 623 | 624 | function processElement(element, state, depth) { 625 | // Result 626 | var textElements = []; 627 | 628 | switch(element.getType()) { 629 | case DocumentApp.ElementType.DOCUMENT: 630 | Logger.log("this is a document"); 631 | break; 632 | 633 | case DocumentApp.ElementType.BODY_SECTION: 634 | textElements = textElements.concat(processChilds(element, state, depth)); 635 | break; 636 | 637 | case DocumentApp.ElementType.PARAGRAPH: 638 | // Determine header prefix 639 | var prefix = ''; 640 | switch (element.getHeading()) { 641 | case DocumentApp.ParagraphHeading.HEADING6: prefix = state.headingPrefix + '======'; break; 642 | case DocumentApp.ParagraphHeading.HEADING5: prefix = state.headingPrefix + '====='; break; 643 | case DocumentApp.ParagraphHeading.HEADING4: prefix = state.headingPrefix + '===='; break; 644 | case DocumentApp.ParagraphHeading.HEADING3: prefix = state.headingPrefix + '==='; break; 645 | case DocumentApp.ParagraphHeading.HEADING2: prefix = state.headingPrefix + '=='; break; 646 | case DocumentApp.ParagraphHeading.HEADING1: prefix = state.headingPrefix + '='; break; 647 | case DocumentApp.ParagraphHeading.TITLE: 648 | prefix = '='; state.needToc = true; break; 649 | //default:prefix = element.getHeading(); break; 650 | } 651 | 652 | // Add space 653 | if(prefix.length > 0) 654 | prefix += ' '; 655 | 656 | 657 | // Process childs 658 | var child = processChilds(element, state, depth) 659 | 660 | // Only Push prefix if it has kids otherwise it will just be treated as lone =='s 661 | if (child.length > 0) { 662 | textElements.push(prefix); 663 | textElements = textElements.concat(child); 664 | if(state.needToc) { 665 | textElements.push("\n:toc: macro\n") 666 | state.needToc = false; 667 | } 668 | 669 | // look for positioned images 670 | var positionedImages = element.getPositionedImages() 671 | for(var image in positionedImages) { 672 | image = positionedImages[image]; 673 | textElements.push("\n" + handleImage(image, state) + "\n") 674 | } 675 | 676 | } 677 | 678 | // Add paragraph break only if its not the last element on this layer 679 | if(state.nextDoc[depth-1] == element) 680 | break; 681 | 682 | if(state.inSource) 683 | textElements.push('\n'); 684 | else 685 | textElements.push('\n\n'); 686 | 687 | break; 688 | 689 | case DocumentApp.ElementType.LIST_ITEM: 690 | textElements = textElements.concat(handleListItem(element, state, depth)); 691 | textElements.push('\n'); 692 | 693 | if(state.nextDoc[depth-1].getType() != element.getType()) { 694 | textElements.push('\n'); 695 | } 696 | 697 | break; 698 | 699 | case DocumentApp.ElementType.HEADER_SECTION: 700 | textElements = textElements.concat(processChilds(element, state, depth)); 701 | break; 702 | 703 | case DocumentApp.ElementType.FOOTER_SECTION: 704 | textElements = textElements.concat(processChilds(element, state, depth)); 705 | break; 706 | 707 | case DocumentApp.ElementType.FOOTNOTE: 708 | //adoced 709 | textElements.push('.footnote:['); 710 | textElements = textElements.concat(processChilds(element.getFootnoteContents(), state, depth)); 711 | textElements.push(']'); 712 | break; 713 | 714 | case DocumentApp.ElementType.HORIZONTAL_RULE: 715 | textElements.push('---\n'); 716 | break; 717 | 718 | case DocumentApp.ElementType.INLINE_DRAWING: 719 | // Cannot handle this type - there is no export function for rasterized or SVG images... 720 | break; 721 | 722 | case DocumentApp.ElementType.TABLE: 723 | textElements = textElements.concat(handleTable(element, state, depth)); 724 | break; 725 | 726 | case DocumentApp.ElementType.TABLE_OF_CONTENTS: 727 | textElements.push('toc::[]'); 728 | state.needToc = true 729 | break; 730 | 731 | case DocumentApp.ElementType.TEXT: 732 | var text = handleText(element, state); 733 | 734 | // Check for source code delimiter 735 | if(/^```.+$/.test(text.join(''))) { 736 | state.inSource = true; 737 | } 738 | 739 | if(text.join('') === '```') { 740 | state.inSource = false; 741 | } 742 | 743 | textElements = textElements.concat(text); 744 | break; 745 | 746 | case DocumentApp.ElementType.INLINE_IMAGE: 747 | textElements = textElements.concat(handleImage(element, state)); 748 | break; 749 | 750 | case DocumentApp.ElementType.PAGE_BREAK: 751 | // Ignore page breaks 752 | break; 753 | 754 | case DocumentApp.ElementType.EQUATION: 755 | var latexEquation = handleEquationFunction(element, state); 756 | 757 | // If equation is the only one in a paragraph - center it 758 | var wrap = '$' 759 | if(state.size[depth-1] == 1) { 760 | wrap = '$$' 761 | } 762 | 763 | latexEquation = wrap + latexEquation.trim() + wrap; 764 | textElements.push(latexEquation); 765 | break; 766 | default: 767 | throw("Unknown element type: " + element.getType()); 768 | } 769 | 770 | return textElements; 771 | } 772 | 773 | // from https://github.com/Mogztter/asciidoc-googledocs-addon/blob/master/app/Code.gs 774 | /** Guess if the text is code by looking at the font family. */ 775 | function isTextCode(doc, index) { 776 | // Things will be better if Google Fonts can tell us about a font 777 | var i, fontFamily = doc.getFontFamily(index), /* Now it returns a string! */ 778 | monospaceFonts = ['Consolas', 'Courier New', 'Source Code Pro']; 779 | if (fontFamily === null) { 780 | return false; // Handle null early.. It means multiple values. 781 | } 782 | // See ES7 Array.prototype.includes(elem, pos) 783 | for (i = 0; i < monospaceFonts.length; i++) { 784 | if (fontFamily === monospaceFonts[i]) { 785 | return true; 786 | } 787 | } 788 | // Last Try: Assume it's mono if it ends with ' Mono'. 789 | // This works for all Google Fonts as of 2016-10-21. 790 | // See ES6 String.prototype.endsWith(str, pos). 791 | return fontFamily.indexOf(' Mono') === fontFamily.length - 5; 792 | } -------------------------------------------------------------------------------- /gdoc2adoc.java: -------------------------------------------------------------------------------- 1 | //usr/bin/env jbang "$0" "$@" ; exit $? 2 | //DEPS info.picocli:picocli:4.2.0 3 | //DEPS com.google.api-client:google-api-client:1.30.1 4 | //DEPS com.google.oauth-client:google-oauth-client-jetty:1.30.1 5 | //DEPS com.google.apis:google-api-services-docs:v1-rev20190827-1.30.1 6 | //DEPS com.fasterxml.jackson.core:jackson-databind:2.9.8 7 | // com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.9.8 8 | 9 | 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | import com.google.api.client.auth.oauth2.Credential; 12 | import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; 13 | import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; 14 | import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; 15 | import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; 16 | import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 17 | import com.google.api.client.googleapis.json.GoogleJsonResponseException; 18 | import com.google.api.client.http.javanet.NetHttpTransport; 19 | import com.google.api.client.json.JsonFactory; 20 | import com.google.api.client.json.jackson2.JacksonFactory; 21 | import com.google.api.client.util.store.FileDataStoreFactory; 22 | import com.google.api.services.docs.v1.Docs; 23 | import com.google.api.services.docs.v1.DocsScopes; 24 | import com.google.api.services.docs.v1.model.Document; 25 | import com.google.api.services.docs.v1.model.Link; 26 | import com.google.api.services.docs.v1.model.Paragraph; 27 | import com.google.api.services.docs.v1.model.ParagraphElement; 28 | import com.google.api.services.docs.v1.model.ParagraphStyle; 29 | import com.google.api.services.docs.v1.model.StructuralElement; 30 | import com.google.api.services.docs.v1.model.Table; 31 | import com.google.api.services.docs.v1.model.TableOfContents; 32 | import com.google.api.services.docs.v1.model.TextRun; 33 | import com.google.api.services.docs.v1.model.TextStyle; 34 | import picocli.CommandLine; 35 | import picocli.CommandLine.Command; 36 | import picocli.CommandLine.Option; 37 | import picocli.CommandLine.Parameters; 38 | 39 | import java.io.File; 40 | import java.io.FileReader; 41 | import java.io.IOException; 42 | import java.util.Collections; 43 | import java.util.HashMap; 44 | import java.util.List; 45 | import java.util.Map; 46 | import java.util.concurrent.Callable; 47 | 48 | //import static java.lang.System.*; 49 | 50 | @Command(name = "gdoc2adoc", mixinStandardHelpOptions = true, version = "gdoc2adoc 0.1", 51 | description = "gdoc2adoc made with jbang") 52 | class gdoc2adoc implements Callable { 53 | 54 | @Parameters(index = "0", description = "Document id or url to convert", arity = "1") 55 | private String documentid; 56 | 57 | @Option(names = {"--credentials"}, defaultValue = "credentials.json") 58 | private File credentials; 59 | 60 | @Option(names = {"--dump"}, description = "If enabled print document structure to output") 61 | boolean dump; 62 | 63 | private static final String APPLICATION_NAME = "gdoc2adoc"; 64 | private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 65 | private static final String TOKENS_DIRECTORY_PATH = "tokens"; 66 | 67 | /** 68 | * Global instance of the scopes required by this sample. If modifying these scopes, delete 69 | * your previously saved tokens/ folder. 70 | */ 71 | private static final List SCOPES = 72 | Collections.singletonList(DocsScopes.DOCUMENTS_READONLY); 73 | 74 | /** 75 | * Creates an authorized Credential object. 76 | * 77 | * @param HTTP_TRANSPORT The network HTTP Transport. 78 | * @return An authorized Credential object. 79 | * @throws IOException If the credentials.json file cannot be found. 80 | */ 81 | private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) 82 | throws IOException { 83 | // Load client secrets. 84 | GoogleClientSecrets secrets = 85 | GoogleClientSecrets.load(JSON_FACTORY, new FileReader(credentials)); 86 | 87 | // Build flow and trigger user authorization request. 88 | GoogleAuthorizationCodeFlow flow = 89 | new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, secrets, SCOPES) 90 | .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) 91 | .setAccessType("offline") 92 | .build(); 93 | LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); 94 | return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); 95 | } 96 | 97 | public static void main(String... args) { 98 | int exitCode = new CommandLine(new gdoc2adoc()).execute(args); 99 | System.exit(exitCode); 100 | } 101 | 102 | @Override 103 | public Integer call() throws Exception { // your business logic goes here... 104 | // Build a new authorized API client service. 105 | final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); 106 | Docs docsService = 107 | new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) 108 | .setApplicationName(APPLICATION_NAME) 109 | .build(); 110 | 111 | 112 | documentid = documentid.replaceAll("^.*/document/d/([a-zA-Z0-9-_]+)/?.*$", 113 | "$1"); 114 | 115 | try { 116 | Document doc = docsService.documents().get(documentid).execute(); 117 | 118 | var v = new GDocVisitor(); 119 | 120 | if(dump) { 121 | 122 | ObjectMapper mapper = new ObjectMapper(new com.fasterxml.jackson.core.JsonFactory()); 123 | System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc)); 124 | 125 | } else { 126 | System.out.println(v.visit(doc)); 127 | } 128 | 129 | //Gson gson = new GsonBuilder().setPrettyPrinting().create(); 130 | 131 | 132 | //System.out.println(gson.toJson(response)); 133 | } catch(GoogleJsonResponseException e) { 134 | throw new IllegalStateException("Error fetching document id " + documentid, e); 135 | } 136 | return 0; 137 | } 138 | } 139 | 140 | class GDocVisitor { 141 | 142 | public GDocVisitor() { 143 | 144 | } 145 | 146 | public StringBuffer visit(Document doc) { 147 | List content = doc.getBody().getContent(); 148 | return visit(content); 149 | } 150 | 151 | public StringBuffer visit(List elements) { 152 | StringBuffer buf = new StringBuffer(); 153 | for (StructuralElement element : elements) { 154 | buf.append(visit(element)); 155 | } 156 | return buf; 157 | } 158 | 159 | public StringBuffer visit(StructuralElement element) { 160 | var buf = new StringBuffer(); 161 | if (element.getParagraph() != null) { 162 | buf.append(visit(element.getParagraph())); 163 | } else if (element.getTable() != null) { 164 | buf.append(visit(element.getTable())); 165 | } else if (element.getTableOfContents() != null) { 166 | buf.append(visit(element.getTableOfContents())); 167 | } 168 | return buf; 169 | } 170 | 171 | Map type2Prefix = new HashMap<>() { 172 | { 173 | put("TITLE", header(1)); 174 | put("SUBTITLE", header(2)); 175 | 176 | put("HEADING_1", header(2)); 177 | put("HEADING_2", header(3)); 178 | put("HEADING_3", header(4)); 179 | put("HEADING_4", header(5)); 180 | put("HEADING_5", header(6)); 181 | put("HEADING_6", header(7)); 182 | 183 | } 184 | }; 185 | 186 | private String header(int i) { 187 | var buf = new StringBuffer(); 188 | while(i>0) { 189 | buf.append("="); 190 | i--; 191 | } 192 | return buf.toString(); 193 | } 194 | 195 | public StringBuffer visit(Paragraph element) { 196 | StringBuffer buf = new StringBuffer(); 197 | 198 | StringBuffer contentbuf = new StringBuffer(); 199 | for (ParagraphElement paragraphElement : element.getElements()) { 200 | contentbuf.append(visit(paragraphElement)); 201 | } 202 | 203 | ParagraphStyle style = element.getParagraphStyle(); 204 | 205 | if(style.getHeadingId()!=null) { 206 | var type = style.getNamedStyleType(); 207 | String indent = type2Prefix.get(type); 208 | if(indent==null) { 209 | nyi("namedstyletype: " + type ); 210 | } 211 | buf.append(indent); 212 | buf.append(" "); 213 | } 214 | 215 | if(!contentbuf.toString().isBlank()) { 216 | buf.append(contentbuf); 217 | buf.append("\n"); 218 | return buf; 219 | } else { 220 | contentbuf.append("\n"); 221 | return contentbuf; // blank/empty area 222 | } 223 | 224 | } 225 | 226 | private StringBuffer visit(TableOfContents element ) { 227 | // simply let asciidoctor generate the toc and ignore 228 | // whatever google have done. 229 | return new StringBuffer("toc::[]"); 230 | } 231 | 232 | private StringBuffer nyi(String o) { 233 | System.err.println(o + " not implemented yet!"); 234 | return new StringBuffer(); 235 | } 236 | 237 | private StringBuffer nyi(Object o) { 238 | return nyi(o.getClass().getName()); 239 | } 240 | 241 | public StringBuffer visit(Table table) { 242 | return nyi(table); 243 | } 244 | 245 | public StringBuffer visit(ParagraphElement element) { 246 | StringBuffer buf = new StringBuffer(); 247 | 248 | var textrun = element.getTextRun(); 249 | if(textrun!=null) { 250 | buf.append(visit(textrun)); 251 | } 252 | return buf; 253 | } 254 | 255 | public StringBuffer visit(TextRun element) { 256 | StringBuffer buf = new StringBuffer(); 257 | 258 | TextStyle style = element.getTextStyle(); 259 | 260 | Link link = style.getLink(); 261 | if(link!=null) { 262 | if(element.getContent().trim().length()>0) { 263 | String url = link.getUrl(); 264 | buf.append(String.format("%s[%s]", url, element.getContent())); 265 | } else { 266 | buf.append(element.getContent()); // should be just empty space, not linking in as asciidoc will then use url as the content. 267 | } 268 | return buf; //no additional formatting for links 269 | } 270 | 271 | var left = new StringBuffer(); 272 | var right = new StringBuffer(); 273 | if(truth(style.getBold())) { 274 | if(truth(style.getItalic())) { 275 | // to handle bold italic properly 276 | left.append("**__"); 277 | right.append("__**"); 278 | } else { 279 | left.append("*"); 280 | right.append("*"); 281 | } 282 | } else if(truth(style.getItalic())) { 283 | left.append("_"); 284 | right.append("_"); 285 | } else if(truth(style.getUnderline())) { 286 | left.append("[.underline]#"); 287 | right.append("#"); 288 | } else if(truth(style.getStrikethrough())) { 289 | left.append("[.line-through]#"); 290 | right.append("#"); 291 | } 292 | 293 | String text = element.getContent().replace("\n", ""); // trims to remove newlines 294 | String postfix = ""; 295 | if(text.length()!=element.getContent().length()) { 296 | postfix = "\n"; 297 | } 298 | 299 | if(left.length()>0 || right.length()>0) { 300 | // trim spaces as asciidoc does not format *test * 301 | //text = text.replaceFirst("\\s+$", ""); 302 | //text = text.replaceFirst("^\\s+", ""); 303 | text = text.trim(); // TODO: is both ends necessary ? 304 | } 305 | 306 | 307 | buf.append(String.format("%s%s%s%s", left, text, right, postfix)); 308 | return buf; 309 | 310 | } 311 | 312 | private boolean truth(Boolean bool) { 313 | return bool == null ? false : bool; 314 | } 315 | 316 | } 317 | --------------------------------------------------------------------------------