2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements gmx::HelpWriterContext.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_onlinehelp
44 #include "helpwritercontext.h"
52 #include <boost/shared_ptr.hpp>
54 #include "gromacs/utility/exceptions.h"
55 #include "gromacs/utility/file.h"
56 #include "gromacs/utility/gmxassert.h"
57 #include "gromacs/utility/programcontext.h"
58 #include "gromacs/utility/stringutil.h"
60 #include "rstparser.h"
68 //! \internal \addtogroup module_onlinehelp
71 //! Characters used for reStructuredText title underlining.
72 const char g_titleChars[] = "=-^*~+#'_.";
80 /* The order of these arrays is significant. Text search and replace
81 * for each element occurs in order, so earlier changes can induce
82 * subsequent changes even though the original text might not appear
83 * to invoke the latter changes.
84 * TODO: Get rid of this behavior. It makes it very difficult to manage
85 * replacements coming from multiple sources (e.g., hyperlinks).*/
87 //! List of replacements for console output.
88 const t_sandr sandrTty[] = {
101 { "[CHEVRON]", "<" },
102 { "[chevron]", ">" },
105 { "[INT]", "integral" },
106 { "[FROM]", " from " },
115 { "[SQRT]", "sqrt(" },
129 { "[COSH]", "cosh(" },
131 { "[SINH]", "sinh(" },
133 { "[TANH]", "tanh(" },
140 //! List of replacements for reStructuredText output.
141 const t_sandr sandrRst[] = {
150 { "[CHEVRON]", "<" },
151 { "[chevron]", ">" },
154 { "[INT]", "integral" },
155 { "[FROM]", " from " },
164 { "[SQRT]", "sqrt(" },
178 { "[COSH]", "cosh(" },
180 { "[SINH]", "sinh(" },
182 { "[TANH]", "tanh(" },
190 * Replaces all entries from a list of replacements.
192 std::string repall(const std::string &s, int nsr, const t_sandr sa[])
194 std::string result(s);
195 for (int i = 0; i < nsr; ++i)
197 result = replaceAll(result, sa[i].search, sa[i].replace);
203 * Replaces all entries from a list of replacements.
205 template <size_t nsr>
206 std::string repall(const std::string &s, const t_sandr (&sa)[nsr])
208 return repall(s, nsr, sa);
212 * Custom output interface for HelpWriterContext::Impl::processMarkup().
214 * Provides an interface that is used to implement different types of output
215 * from HelpWriterContext::Impl::processMarkup().
217 class WrapperInterface
220 virtual ~WrapperInterface() {}
223 * Provides the wrapping settings.
225 * HelpWriterContext::Impl::processMarkup() may provide some default
226 * values for the settings if they are not set; this is the reason the
227 * return value is not const.
229 virtual TextLineWrapperSettings &settings() = 0;
230 //! Appends the given string to output.
231 virtual void wrap(const std::string &text) = 0;
235 * Wraps markup output into a single string.
237 class WrapperToString : public WrapperInterface
240 //! Creates a wrapper with the given settings.
241 explicit WrapperToString(const TextLineWrapperSettings &settings)
246 virtual TextLineWrapperSettings &settings()
248 return wrapper_.settings();
250 virtual void wrap(const std::string &text)
252 result_.append(wrapper_.wrapToString(text));
254 //! Returns the result string.
255 const std::string &result() const { return result_; }
258 TextLineWrapper wrapper_;
263 * Wraps markup output into a vector of string (one line per element).
265 class WrapperToVector : public WrapperInterface
268 //! Creates a wrapper with the given settings.
269 explicit WrapperToVector(const TextLineWrapperSettings &settings)
274 virtual TextLineWrapperSettings &settings()
276 return wrapper_.settings();
278 virtual void wrap(const std::string &text)
280 const std::vector<std::string> &lines = wrapper_.wrapToVector(text);
281 result_.insert(result_.end(), lines.begin(), lines.end());
283 //! Returns a vector with the output lines.
284 const std::vector<std::string> &result() const { return result_; }
287 TextLineWrapper wrapper_;
288 std::vector<std::string> result_;
292 * Makes the string uppercase.
294 * \param[in] text Input text.
295 * \returns \p text with all characters transformed to uppercase.
296 * \throws std::bad_alloc if out of memory.
298 std::string toUpperCase(const std::string &text)
300 std::string result(text);
301 std::transform(result.begin(), result.end(), result.begin(), toupper);
306 * Removes extra newlines from reStructuredText.
308 * \param[in] text Input text.
309 * \returns \p text with all sequences of more than two newlines replaced
310 * with just two newlines.
311 * \throws std::bad_alloc if out of memory.
313 std::string removeExtraNewlinesRst(const std::string &text)
315 // Start from 2, so that all newlines in the beginning get stripped off.
316 int newlineCount = 2;
318 result.reserve(text.length());
319 for (size_t i = 0; i < text.length(); ++i)
324 if (newlineCount > 2)
333 result.push_back(text[i]);
335 size_t last = result.find_last_not_of('\n');
336 if (last != std::string::npos)
338 result.resize(last + 1);
347 /********************************************************************
352 * Private implementation class for HelpLinks.
354 * \ingroup module_onlinehelp
356 class HelpLinks::Impl
361 LinkItem(const std::string &linkName,
362 const std::string &replacement)
363 : linkName(linkName), replacement(replacement)
366 std::string linkName;
367 std::string replacement;
370 //! Shorthand for a list of links.
371 typedef std::vector<LinkItem> LinkList;
373 //! Initializes empty links with the given format.
374 explicit Impl(HelpOutputFormat format) : format_(format)
380 //! Output format for which the links are formatted.
381 HelpOutputFormat format_;
384 /********************************************************************
388 HelpLinks::HelpLinks(HelpOutputFormat format) : impl_(new Impl(format))
392 HelpLinks::~HelpLinks()
396 void HelpLinks::addLink(const std::string &linkName,
397 const std::string &targetName,
398 const std::string &displayName)
400 std::string replacement;
401 switch (impl_->format_)
403 case eHelpOutputFormat_Console:
404 replacement = repall(displayName, sandrTty);
406 case eHelpOutputFormat_Rst:
407 replacement = targetName;
410 GMX_RELEASE_ASSERT(false, "Output format not implemented for links");
412 impl_->links_.push_back(Impl::LinkItem(linkName, replacement));
415 /********************************************************************
416 * HelpWriterContext::Impl
420 * Private implementation class for HelpWriterContext.
422 * \ingroup module_onlinehelp
424 class HelpWriterContext::Impl
428 * Shared, non-modifiable state for context objects.
430 * Contents of this structure are shared between all context objects
431 * that are created from a common parent.
432 * This state should not be modified after construction.
434 * \ingroup module_onlinehelp
438 //! Initializes the state with the given parameters.
439 SharedState(File *file, HelpOutputFormat format,
440 const HelpLinks *links)
441 : file_(*file), format_(format), links_(links)
445 //! Output file to which the help is written.
447 //! Output format for the help output.
448 HelpOutputFormat format_;
450 const HelpLinks *links_;
455 ReplaceItem(const std::string &search,
456 const std::string &replace)
457 : search(search), replace(replace)
464 //! Smart pointer type for managing the shared state.
465 typedef boost::shared_ptr<const SharedState> StatePointer;
466 //! Shorthand for a list of markup/other replacements.
467 typedef std::vector<ReplaceItem> ReplaceList;
469 //! Initializes the context with the given state and section depth.
470 Impl(const StatePointer &state, int sectionDepth)
471 : state_(state), sectionDepth_(sectionDepth)
473 initDefaultReplacements();
476 //! Initializes default replacements for the chosen output format.
477 void initDefaultReplacements();
478 //! Adds a new replacement.
479 void addReplacement(const std::string &search,
480 const std::string &replace)
482 replacements_.push_back(ReplaceItem(search, replace));
485 //! Replaces links in a given string.
486 std::string replaceLinks(const std::string &input) const;
489 * Process markup and wrap lines within a block of text.
491 * \param[in] text Text to process.
492 * \param wrapper Object used to wrap the text.
494 * The \p wrapper should take care of either writing the text to output
495 * or providing an interface for the caller to retrieve the output.
497 void processMarkup(const std::string &text,
498 WrapperInterface *wrapper) const;
500 //! Constant state shared by all child context objects.
502 //! List of markup/other replacements.
503 ReplaceList replacements_;
504 //! Number of subsections above this context.
508 GMX_DISALLOW_ASSIGN(Impl);
511 void HelpWriterContext::Impl::initDefaultReplacements()
513 const char *program = getProgramContext().programName();
514 addReplacement("[PROGRAM]", program);
517 std::string HelpWriterContext::Impl::replaceLinks(const std::string &input) const
519 std::string result(input);
520 if (state_->links_ != NULL)
522 HelpLinks::Impl::LinkList::const_iterator link;
523 for (link = state_->links_->impl_->links_.begin();
524 link != state_->links_->impl_->links_.end(); ++link)
526 result = replaceAllWords(result, link->linkName, link->replacement);
532 void HelpWriterContext::Impl::processMarkup(const std::string &text,
533 WrapperInterface *wrapper) const
535 std::string result(text);
536 for (ReplaceList::const_iterator i = replacements_.begin();
537 i != replacements_.end(); ++i)
539 result = replaceAll(result, i->search, i->replace);
541 switch (state_->format_)
543 case eHelpOutputFormat_Console:
545 const int baseFirstLineIndent = wrapper->settings().firstLineIndent();
546 const int baseIndent = wrapper->settings().indent();
547 result = repall(result, sandrTty);
548 result = replaceLinks(result);
549 std::string paragraph;
550 paragraph.reserve(result.length());
551 RstParagraphIterator iter(result);
552 while (iter.nextParagraph())
554 iter.getParagraphText(¶graph);
555 wrapper->settings().setFirstLineIndent(baseFirstLineIndent + iter.firstLineIndent());
556 wrapper->settings().setIndent(baseIndent + iter.indent());
557 wrapper->wrap(paragraph);
559 wrapper->settings().setFirstLineIndent(baseFirstLineIndent);
560 wrapper->settings().setIndent(baseIndent);
563 case eHelpOutputFormat_Rst:
565 result = repall(result, sandrRst);
566 result = replaceLinks(result);
567 result = replaceAll(result, "[REF]", "");
568 result = replaceAll(result, "[ref]", "");
569 result = removeExtraNewlinesRst(result);
570 wrapper->wrap(result);
574 GMX_THROW(InternalError("Invalid help output format"));
578 /********************************************************************
582 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format)
583 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, NULL)), 0))
587 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format,
588 const HelpLinks *links)
589 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, links)), 0))
593 GMX_RELEASE_ASSERT(links->impl_->format_ == format,
594 "Links must have the same output format as the context");
598 HelpWriterContext::HelpWriterContext(Impl *impl)
603 HelpWriterContext::HelpWriterContext(const HelpWriterContext &other)
604 : impl_(new Impl(*other.impl_))
608 HelpWriterContext::~HelpWriterContext()
612 void HelpWriterContext::setReplacement(const std::string &search,
613 const std::string &replace)
615 impl_->addReplacement(search, replace);
618 HelpOutputFormat HelpWriterContext::outputFormat() const
620 return impl_->state_->format_;
623 File &HelpWriterContext::outputFile() const
625 return impl_->state_->file_;
628 void HelpWriterContext::enterSubSection(const std::string &title)
630 GMX_RELEASE_ASSERT(impl_->sectionDepth_ - 1 < static_cast<int>(std::strlen(g_titleChars)),
631 "Too deeply nested subsections");
633 ++impl_->sectionDepth_;
637 HelpWriterContext::substituteMarkupAndWrapToString(
638 const TextLineWrapperSettings &settings, const std::string &text) const
640 WrapperToString wrapper(settings);
641 impl_->processMarkup(text, &wrapper);
642 return wrapper.result();
645 std::vector<std::string>
646 HelpWriterContext::substituteMarkupAndWrapToVector(
647 const TextLineWrapperSettings &settings, const std::string &text) const
649 WrapperToVector wrapper(settings);
650 impl_->processMarkup(text, &wrapper);
651 return wrapper.result();
654 void HelpWriterContext::writeTitle(const std::string &title) const
660 File &file = outputFile();
661 switch (outputFormat())
663 case eHelpOutputFormat_Console:
664 file.writeLine(toUpperCase(title));
667 case eHelpOutputFormat_Rst:
668 file.writeLine(title);
669 file.writeLine(std::string(title.length(),
670 g_titleChars[impl_->sectionDepth_]));
673 GMX_THROW(NotImplementedError(
674 "This output format is not implemented"));
678 void HelpWriterContext::writeTextBlock(const std::string &text) const
680 TextLineWrapperSettings settings;
681 if (outputFormat() == eHelpOutputFormat_Console)
683 settings.setLineLength(78);
685 outputFile().writeLine(substituteMarkupAndWrapToString(settings, text));
688 void HelpWriterContext::writeOptionListStart() const
692 void HelpWriterContext::writeOptionItem(const std::string &name,
693 const std::string &args,
694 const std::string &description) const
696 File &file = outputFile();
697 switch (outputFormat())
699 case eHelpOutputFormat_Console:
700 // TODO: Generalize this when there is need for it; the current,
701 // special implementation is in CommandLineHelpWriter.
702 GMX_THROW(NotImplementedError("Option item formatting for console output not implemented"));
704 case eHelpOutputFormat_Rst:
706 file.writeLine(formatString("``%s`` %s", name.c_str(), args.c_str()));
707 TextLineWrapperSettings settings;
708 settings.setIndent(4);
709 file.writeLine(substituteMarkupAndWrapToString(settings, description));
713 GMX_THROW(NotImplementedError(
714 "This output format is not implemented"));
718 void HelpWriterContext::writeOptionListEnd() const