001 package org.asciidoctor;
002
003 import com.sun.javadoc.*;
004 import com.sun.tools.doclets.standard.Standard;
005
006 import java.io.File;
007 import java.util.HashSet;
008 import java.util.Map;
009 import java.util.Set;
010 import java.util.regex.Matcher;
011 import java.util.regex.Pattern;
012
013 /**
014 * = Asciidoclet
015 *
016 * https://github.com/asciidoctor/asciidoclet[Asciidoclet] is a Javadoc Doclet
017 * that uses http://asciidoctor.org[Asciidoctor] (via the
018 * https://github.com/asciidoctor/asciidoctor-java-integration[Asciidoctor Java integration])
019 * to render http://asciidoc.org[AsciiDoc] markup within Javadoc comments.
020 *
021 * == Usage
022 *
023 * Asciidoclet may be used via a custom doclet in the maven-javadoc-plugin:
024 *
025 * [source,xml]
026 * ----
027 * include::pom.xml[tags=pom_include]
028 * ----
029 *
030 * <1> The -includes-basedir option must be set, typically this is the project root. It allows
031 * source inclusions within javadocs, relative to the specified directory.
032 *
033 * == Examples
034 *
035 * Code block (with syntax highlighting added by CodeRay)::
036 * +
037 * [source,java]
038 * --
039 * /**
040 * * = Asciidoclet
041 * *
042 * * A Javadoc Doclet that uses http://asciidoctor.org[Asciidoctor]
043 * * to render http://asciidoc.org[AsciiDoc] markup in Javadoc comments.
044 * *
045 * * @author https://github.com/johncarl81[John Ericksen]
046 * *\/
047 * public class Asciidoclet extends Doclet {
048 * private final Asciidoctor asciidoctor = Asciidoctor.Factory.create(); // <1>
049 *
050 * @SuppressWarnings("UnusedDeclaration")
051 * public static boolean start(RootDoc rootDoc) {
052 * new Asciidoclet().render(rootDoc); // <2>
053 * return Standard.start(rootDoc);
054 * }
055 * }
056 * --
057 * <1> Creates an instance of the Asciidoctor Java integration
058 * <2> Runs Javadoc comment strings through Asciidoctor
059 *
060 * Inline code:: `code()` or +code()+
061 *
062 * Headings::
063 * +
064 * --
065 * [float]
066 * = Heading 1
067 * [float]
068 * == Heading 2
069 * [float]
070 * === Heading 3
071 * [float]
072 * ==== Heading 4
073 * [float]
074 * ===== Heading 5
075 * --
076 *
077 * Links::
078 * Doc Writer <doc@example.com> +
079 * http://asciidoc.org[AsciiDoc] is a lightweight markup language. +
080 * Learn more about it at http://asciidoctor.org. +
081 *
082 * Bullets::
083 * +
084 * --
085 * .Unnumbered
086 * * bullet
087 * * bullet
088 * - bullet
089 * - bullet
090 * * bullet
091 * ** bullet
092 * ** bullet
093 * *** bullet
094 * *** bullet
095 * **** bullet
096 * **** bullet
097 * ***** bullet
098 * ***** bullet
099 * **** bullet
100 * *** bullet
101 * ** bullet
102 * * bullet
103 * --
104 * +
105 * --
106 * .Numbered
107 * . bullet
108 * . bullet
109 * .. bullet
110 * .. bullet
111 * . bullet
112 * .. bullet
113 * ... bullet
114 * ... bullet
115 * .... bullet
116 * .... bullet
117 * ... bullet
118 * ... bullet
119 * .. bullet
120 * .. bullet
121 * . bullet
122 * --
123 *
124 * Tables::
125 * +
126 * .An example table
127 * [cols="3", options="header"]
128 * |===
129 * |Column 1
130 * |Column 2
131 * |Column 3
132 *
133 * |1
134 * |Item 1
135 * |a
136 *
137 * |2
138 * |Item 2
139 * |b
140 *
141 * |3
142 * |Item 3
143 * |c
144 * |===
145 *
146 * Sidebar block::
147 * +
148 * .Optional Title
149 * ****
150 * *Sidebar* Block
151 *
152 * Usage: Notes in a sidebar, naturally.
153 * ****
154 *
155 * Admonitions::
156 * +
157 * IMPORTANT: Check this out!
158 *
159 * @author https://github.com/johncarl81[John Ericksen]
160 * @version 0.1.0
161 * @see org.asciidoctor.Asciidoclet
162 * @since 0.1.0
163 * @serial (or @serialField or @serialData)
164 */
165 public class Asciidoclet extends Doclet {
166
167 private final Asciidoctor asciidoctor = Asciidoctor.Factory.create();
168
169 private final AttributesBuilder attributesBuilder = AttributesBuilder.attributes()
170 .attribute("at", "@")
171 .attribute("slash", "/")
172 .attribute("icons", null)
173 .attribute("idprefix", "")
174 .attribute("notitle", null)
175 .attribute("source-highlighter", "coderay")
176 .attribute("coderay-css", "style");
177
178 private String baseDir;
179
180 /**
181 * .Example usage
182 * [source,java]
183 * exampleDeprecated("do not use");
184 *
185 * @deprecated for example purposes
186 * @exception Exception example
187 * @throws RuntimeException example
188 * @serialData something else
189 * @link Asciidoclet
190 */
191 public static void exampleDeprecated(String field) throws Exception{
192 //noop
193 }
194
195 /**
196 * Sets the language version to Java 5.
197 *
198 * _Javadoc spec requirement._
199 *
200 * @return language version number
201 */
202 @SuppressWarnings("UnusedDeclaration")
203 public static LanguageVersion languageVersion() {
204 return LanguageVersion.JAVA_1_5;
205 }
206
207 /**
208 * Sets the option length to the standard Javadoc option length.
209 *
210 * _Javadoc spec requirement._
211 *
212 * @param option input option
213 * @return length of required parameters
214 */
215 @SuppressWarnings("UnusedDeclaration")
216 public static int optionLength(String option) {
217 if ("-include-basedir".equals(option)) {
218 return 2;
219 }
220 return Standard.optionLength(option);
221 }
222
223 /**
224 * The starting point of Javadoc render.
225 *
226 * _Javadoc spec requirement._
227 *
228 * @param rootDoc input class documents
229 * @return success
230 */
231 @SuppressWarnings("UnusedDeclaration")
232 public static boolean start(RootDoc rootDoc) {
233 final Asciidoclet doclet = new Asciidoclet();
234 doclet.baseDir = getBaseDir(rootDoc.options());
235 doclet.render(rootDoc);
236 return Standard.start(rootDoc);
237 }
238
239 /**
240 * Processes the input options by delegating to the standard handler.
241 *
242 * _Javadoc spec requirement._
243 *
244 * @param options input option array
245 * @param errorReporter error handling
246 * @return success
247 */
248 @SuppressWarnings("UnusedDeclaration")
249 public static boolean validOptions(String[][] options, DocErrorReporter errorReporter) {
250 boolean hasBaseDir = false;
251 for (final String option[] : options) {
252 if ("-include-basedir".equals(option[0])) {
253 hasBaseDir = true;
254 }
255 }
256 if (!hasBaseDir) {
257 errorReporter.printWarning("-include-basedir must be present for includes or file reference features.");
258 }
259
260 return Standard.validOptions(options, errorReporter);
261 }
262
263 private static String getBaseDir(String[][] options) {
264 for (final String option[] : options) {
265 if ("-include-basedir".equals(option[0])) {
266 return option[1];
267 }
268 }
269 return null;
270 }
271
272 /**
273 * Renders the input document.
274 *
275 * @param rootDoc input
276 */
277 private void render(RootDoc rootDoc) {
278 Set<PackageDoc> packages = new HashSet<PackageDoc>();
279 for ( ClassDoc doc : rootDoc.classes() ) {
280 packages.add(doc.containingPackage());
281 renderClass(doc);
282 }
283 for ( PackageDoc doc : packages ) {
284 renderDoc(doc);
285 }
286 }
287
288 /**
289 * Renders an individual class.
290 *
291 * @param doc input
292 */
293 private void renderClass(ClassDoc doc) {
294 //handle the various parts of the Class doc
295 renderDoc(doc);
296 for ( MemberDoc member : doc.fields() ) {
297 renderDoc(member);
298 }
299 for ( MemberDoc member : doc.constructors() ) {
300 renderDoc(member);
301 }
302 for ( MemberDoc member : doc.methods() ) {
303 renderDoc(member);
304 }
305 if ( doc instanceof AnnotationTypeDoc ) {
306 for ( MemberDoc member : ((AnnotationTypeDoc)doc).elements() ) {
307 renderDoc(member);
308 }
309 }
310 }
311
312 /**
313 * Renders a generic document (class, field, method, etc)
314 *
315 * @param doc input
316 */
317 private void renderDoc(Doc doc) {
318 // hide text that looks like tags (such as annotations in source code) from Javadoc
319 doc.setRawCommentText(doc.getRawCommentText().replaceAll("@([A-Z])", "{@literal @}$1"));
320
321 StringBuilder buffer = new StringBuilder();
322 buffer.append(render(doc.commentText(), false));
323 buffer.append('\n');
324 for ( Tag tag : doc.tags() ) {
325 renderTag(tag, buffer);
326 buffer.append('\n');
327 }
328 doc.setRawCommentText(buffer.toString());
329 }
330
331 /**
332 * Renders a document tag in the standard way.
333 *
334 * @param tag input
335 * @param buffer output buffer
336 */
337 private void renderTag(Tag tag, StringBuilder buffer) {
338 //print out directly
339 buffer.append(tag.name());
340 buffer.append(" ");
341 buffer.append(render(tag.text(), true));
342 }
343
344 /**
345 * Renders the input using Asciidoctor.
346 *
347 * The source is first cleaned by stripping any trailing space after an
348 * end line (e.g., `"\n "`), which gets left behind by the Javadoc
349 * processor.
350 *
351 * @param input AsciiDoc source
352 * @return content rendered by Asciidoctor
353 */
354 private String render(String input, boolean inline) {
355 // Replace "\n " to remove default Javadoc space.
356 String cleanedInput = input.trim()
357 .replaceAll("\n ", "\n") // Newline space to accommodate javadoc newlines.
358 .replaceAll("\\{at}", "@") // {at} is translated into @.
359 .replaceAll("\\{slash}", "/") // {slash} is translated into /.
360 .replaceAll("(?m)^( *)\\*\\\\/$", "$1*/") // Multi-line comment end tag is translated into */.
361 .replaceAll("\\{@literal (.*?)}", "$1"); // {@literal _} is translated into _ (standard javadoc).
362
363 OptionsBuilder optionsBuilder = OptionsBuilder.options()
364 .safe(SafeMode.SAFE).backend("html5").eruby("erubis");
365
366 optionsBuilder.attributes(attributesBuilder.asMap());
367
368 if(this.baseDir != null){
369 optionsBuilder.baseDir(new File(this.baseDir));
370 }
371 if(inline){
372 optionsBuilder.docType("inline");
373 }
374
375 Map<String, Object> options = optionsBuilder.asMap();
376 return asciidoctor.render(cleanedInput, options);
377 }
378 }