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"
66 //! \internal \addtogroup module_onlinehelp
69 //! Characters used for reStructuredText title underlining.
70 const char g_titleChars[] = "=-^*~+#'_.";
78 /* The order of these arrays is significant. Text search and replace
79 * for each element occurs in order, so earlier changes can induce
80 * subsequent changes even though the original text might not appear
81 * to invoke the latter changes.
82 * TODO: Get rid of this behavior. It makes it very difficult to manage
83 * replacements coming from multiple sources (e.g., hyperlinks).*/
85 //! List of replacements for console output.
86 const t_sandr sandrTty[] = {
100 { "[chevron]", ">" },
103 { "[INT]", "integral" },
104 { "[FROM]", " from " },
113 { "[SQRT]", "sqrt(" },
127 { "[COSH]", "cosh(" },
129 { "[SINH]", "sinh(" },
131 { "[TANH]", "tanh(" },
138 //! List of replacements for reStructuredText output.
139 const t_sandr sandrRst[] = {
148 { "[CHEVRON]", "<" },
149 { "[chevron]", ">" },
152 { "[INT]", "integral" },
153 { "[FROM]", " from " },
162 { "[SQRT]", "sqrt(" },
176 { "[COSH]", "cosh(" },
178 { "[SINH]", "sinh(" },
180 { "[TANH]", "tanh(" },
188 * Replaces all entries from a list of replacements.
190 std::string repall(const std::string &s, int nsr, const t_sandr sa[])
192 std::string result(s);
193 for (int i = 0; i < nsr; ++i)
195 result = replaceAll(result, sa[i].search, sa[i].replace);
201 * Replaces all entries from a list of replacements.
203 template <size_t nsr>
204 std::string repall(const std::string &s, const t_sandr (&sa)[nsr])
206 return repall(s, nsr, sa);
210 * Custom output interface for HelpWriterContext::Impl::processMarkup().
212 * Provides an interface that is used to implement different types of output
213 * from HelpWriterContext::Impl::processMarkup().
215 class WrapperInterface
218 virtual ~WrapperInterface() {}
221 * Provides the wrapping settings.
223 * HelpWriterContext::Impl::processMarkup() may provide some default
224 * values for the settings if they are not set; this is the reason the
225 * return value is not const.
227 virtual TextLineWrapperSettings &settings() = 0;
228 //! Appends the given string to output.
229 virtual void wrap(const std::string &text) = 0;
233 * Wraps markup output into a single string.
235 class WrapperToString : public WrapperInterface
238 //! Creates a wrapper with the given settings.
239 explicit WrapperToString(const TextLineWrapperSettings &settings)
244 virtual TextLineWrapperSettings &settings()
246 return wrapper_.settings();
248 virtual void wrap(const std::string &text)
250 result_.append(wrapper_.wrapToString(text));
252 //! Returns the result string.
253 const std::string &result() const { return result_; }
256 TextLineWrapper wrapper_;
261 * Wraps markup output into a vector of string (one line per element).
263 class WrapperToVector : public WrapperInterface
266 //! Creates a wrapper with the given settings.
267 explicit WrapperToVector(const TextLineWrapperSettings &settings)
272 virtual TextLineWrapperSettings &settings()
274 return wrapper_.settings();
276 virtual void wrap(const std::string &text)
278 const std::vector<std::string> &lines = wrapper_.wrapToVector(text);
279 result_.insert(result_.end(), lines.begin(), lines.end());
281 //! Returns a vector with the output lines.
282 const std::vector<std::string> &result() const { return result_; }
285 TextLineWrapper wrapper_;
286 std::vector<std::string> result_;
290 * Makes the string uppercase.
292 * \param[in] text Input text.
293 * \returns \p text with all characters transformed to uppercase.
294 * \throws std::bad_alloc if out of memory.
296 std::string toUpperCase(const std::string &text)
298 std::string result(text);
299 std::transform(result.begin(), result.end(), result.begin(), toupper);
304 * Removes extra newlines from reStructuredText.
306 * \param[in] text Input text.
307 * \returns \p text with all sequences of more than two newlines replaced
308 * with just two newlines.
309 * \throws std::bad_alloc if out of memory.
311 std::string removeExtraNewlinesRst(const std::string &text)
313 // Start from 2, so that all newlines in the beginning get stripped off.
314 int newlineCount = 2;
316 result.reserve(text.length());
317 for (size_t i = 0; i < text.length(); ++i)
322 if (newlineCount > 2)
331 result.push_back(text[i]);
333 size_t last = result.find_last_not_of('\n');
334 if (last != std::string::npos)
336 result.resize(last + 1);
342 * Returns `true` if a list item starts in \p text at \p index.
346 bool startsListItem(const std::string &text, size_t index)
348 if (text.length() <= index + 1)
352 if (text[index] == '*' && std::isspace(text[index+1]))
356 if (std::isdigit(text[index]))
358 while (index < text.length() && std::isdigit(text[index]))
362 if (text.length() > index + 1 && text[index] == '.'
363 && std::isspace(text[index+1]))
372 * Returns `true` if a table starts in \p text at \p index.
374 * The function only inspects the first line for something that looks like a
375 * reStructuredText table, and accepts also some malformed tables.
376 * Any issues should be apparent when Sphinx parses the reStructuredText
377 * export, so full validation is not done here.
381 bool startsTable(const std::string &text, size_t index)
383 if (text[index] == '=')
385 while (index < text.length() && text[index] != '\n')
387 if (text[index] != '=' && !std::isspace(text[index]))
395 else if (text[index] == '+')
397 while (index < text.length() && text[index] != '\n')
399 if (text[index] != '-' && text[index] != '+')
411 * Returns `true` if a line in \p text starting at \p index is a title underline.
415 bool isTitleUnderline(const std::string &text, size_t index)
417 const char firstChar = text[index];
418 if (std::ispunct(firstChar))
420 while (index < text.length() && text[index] != '\n')
422 if (text[index] != firstChar)
437 /********************************************************************
442 * Private implementation class for HelpLinks.
444 * \ingroup module_onlinehelp
446 class HelpLinks::Impl
451 LinkItem(const std::string &linkName,
452 const std::string &replacement)
453 : linkName(linkName), replacement(replacement)
456 std::string linkName;
457 std::string replacement;
460 //! Shorthand for a list of links.
461 typedef std::vector<LinkItem> LinkList;
463 //! Initializes empty links with the given format.
464 explicit Impl(HelpOutputFormat format) : format_(format)
470 //! Output format for which the links are formatted.
471 HelpOutputFormat format_;
474 /********************************************************************
478 HelpLinks::HelpLinks(HelpOutputFormat format) : impl_(new Impl(format))
482 HelpLinks::~HelpLinks()
486 void HelpLinks::addLink(const std::string &linkName,
487 const std::string &targetName,
488 const std::string &displayName)
490 std::string replacement;
491 switch (impl_->format_)
493 case eHelpOutputFormat_Console:
494 replacement = repall(displayName, sandrTty);
496 case eHelpOutputFormat_Rst:
497 replacement = targetName;
500 GMX_RELEASE_ASSERT(false, "Output format not implemented for links");
502 impl_->links_.push_back(Impl::LinkItem(linkName, replacement));
505 /********************************************************************
506 * HelpWriterContext::Impl
510 * Private implementation class for HelpWriterContext.
512 * \ingroup module_onlinehelp
514 class HelpWriterContext::Impl
518 * Shared, non-modifiable state for context objects.
520 * Contents of this structure are shared between all context objects
521 * that are created from a common parent.
522 * This state should not be modified after construction.
524 * \ingroup module_onlinehelp
528 //! Initializes the state with the given parameters.
529 SharedState(File *file, HelpOutputFormat format,
530 const HelpLinks *links)
531 : file_(*file), format_(format), links_(links)
535 //! Output file to which the help is written.
537 //! Output format for the help output.
538 HelpOutputFormat format_;
540 const HelpLinks *links_;
545 ReplaceItem(const std::string &search,
546 const std::string &replace)
547 : search(search), replace(replace)
554 //! Smart pointer type for managing the shared state.
555 typedef boost::shared_ptr<const SharedState> StatePointer;
556 //! Shorthand for a list of markup/other replacements.
557 typedef std::vector<ReplaceItem> ReplaceList;
559 //! Initializes the context with the given state and section depth.
560 Impl(const StatePointer &state, int sectionDepth)
561 : state_(state), sectionDepth_(sectionDepth)
563 initDefaultReplacements();
566 //! Initializes default replacements for the chosen output format.
567 void initDefaultReplacements();
568 //! Adds a new replacement.
569 void addReplacement(const std::string &search,
570 const std::string &replace)
572 replacements_.push_back(ReplaceItem(search, replace));
575 //! Replaces links in a given string.
576 std::string replaceLinks(const std::string &input) const;
579 * Process markup and wrap lines within a block of text.
581 * \param[in] text Text to process.
582 * \param wrapper Object used to wrap the text.
584 * The \p wrapper should take care of either writing the text to output
585 * or providing an interface for the caller to retrieve the output.
587 void processMarkup(const std::string &text,
588 WrapperInterface *wrapper) const;
590 //! Constant state shared by all child context objects.
592 //! List of markup/other replacements.
593 ReplaceList replacements_;
594 //! Number of subsections above this context.
598 GMX_DISALLOW_ASSIGN(Impl);
601 void HelpWriterContext::Impl::initDefaultReplacements()
603 const char *program = getProgramContext().programName();
604 addReplacement("[PROGRAM]", program);
607 std::string HelpWriterContext::Impl::replaceLinks(const std::string &input) const
609 std::string result(input);
610 if (state_->links_ != NULL)
612 HelpLinks::Impl::LinkList::const_iterator link;
613 for (link = state_->links_->impl_->links_.begin();
614 link != state_->links_->impl_->links_.end(); ++link)
616 result = replaceAllWords(result, link->linkName, link->replacement);
622 void HelpWriterContext::Impl::processMarkup(const std::string &text,
623 WrapperInterface *wrapper) const
625 std::string result(text);
626 for (ReplaceList::const_iterator i = replacements_.begin();
627 i != replacements_.end(); ++i)
629 result = replaceAll(result, i->search, i->replace);
631 switch (state_->format_)
633 case eHelpOutputFormat_Console:
635 const int baseFirstLineIndent = wrapper->settings().firstLineIndent();
636 const int baseIndent = wrapper->settings().indent();
637 result = repall(result, sandrTty);
638 result = replaceLinks(result);
639 std::string paragraph;
640 paragraph.reserve(result.length());
642 int nextBreakSize = 0;
643 bool bLiteral = false;
644 while (i < result.length())
646 while (i < result.length() && result[i] == '\n')
650 if (i == result.length())
654 const int breakSize = nextBreakSize;
656 bool bLineStart = true;
657 int currentIndent = 0;
663 if (result[i] == '\n' || i == result.length())
665 if (currentLine == 0)
667 firstIndent = currentIndent;
669 else if (currentLine == 1)
671 indent = currentIndent;
676 if (i + 1 >= result.length() || result[i + 1] == '\n')
683 if (!std::isspace(result[i - 1]))
685 paragraph.push_back(' ');
692 if (std::isspace(result[i]))
697 else if (startsListItem(result, i))
701 while (i > 0 && result[i - 1] != '\n')
705 paragraph = stripString(paragraph);
709 int prefixLength = 0;
710 while (!std::isspace(result[i + prefixLength]))
714 while (i + prefixLength < result.length()
715 && std::isspace(result[i + prefixLength]))
719 indent = currentIndent + prefixLength;
721 else if (currentLine == 0 && startsTable(result, i))
725 else if (currentLine == 1 && isTitleUnderline(result, i))
727 // TODO: Nicer formatting that shares
728 // implementation with writeTitle() and honors the
729 // nesting depths etc.
732 paragraph[paragraph.length() - 1] = '\n';
737 paragraph.push_back(result[i]);
739 if (endsWith(paragraph, "::"))
742 if (paragraph.length() == 2)
750 if (paragraph[paragraph.length() - 3] == ' ')
752 paragraph.resize(paragraph.length() - 3);
756 paragraph.resize(paragraph.length() - 1);
765 wrapper->wrap(std::string(breakSize, '\n'));
767 wrapper->settings().setFirstLineIndent(baseFirstLineIndent + firstIndent);
768 wrapper->settings().setIndent(baseIndent + indent);
769 wrapper->wrap(paragraph);
770 wrapper->settings().setFirstLineIndent(baseFirstLineIndent);
771 wrapper->settings().setIndent(baseIndent);
775 case eHelpOutputFormat_Rst:
777 result = repall(result, sandrRst);
778 result = replaceLinks(result);
779 result = replaceAll(result, "[REF]", "");
780 result = replaceAll(result, "[ref]", "");
781 result = removeExtraNewlinesRst(result);
782 wrapper->wrap(result);
786 GMX_THROW(InternalError("Invalid help output format"));
790 /********************************************************************
794 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format)
795 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, NULL)), 0))
799 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format,
800 const HelpLinks *links)
801 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, links)), 0))
805 GMX_RELEASE_ASSERT(links->impl_->format_ == format,
806 "Links must have the same output format as the context");
810 HelpWriterContext::HelpWriterContext(Impl *impl)
815 HelpWriterContext::HelpWriterContext(const HelpWriterContext &other)
816 : impl_(new Impl(*other.impl_))
820 HelpWriterContext::~HelpWriterContext()
824 void HelpWriterContext::setReplacement(const std::string &search,
825 const std::string &replace)
827 impl_->addReplacement(search, replace);
830 HelpOutputFormat HelpWriterContext::outputFormat() const
832 return impl_->state_->format_;
835 File &HelpWriterContext::outputFile() const
837 return impl_->state_->file_;
840 void HelpWriterContext::enterSubSection(const std::string &title)
842 GMX_RELEASE_ASSERT(impl_->sectionDepth_ - 1 < static_cast<int>(std::strlen(g_titleChars)),
843 "Too deeply nested subsections");
845 ++impl_->sectionDepth_;
849 HelpWriterContext::substituteMarkupAndWrapToString(
850 const TextLineWrapperSettings &settings, const std::string &text) const
852 WrapperToString wrapper(settings);
853 impl_->processMarkup(text, &wrapper);
854 return wrapper.result();
857 std::vector<std::string>
858 HelpWriterContext::substituteMarkupAndWrapToVector(
859 const TextLineWrapperSettings &settings, const std::string &text) const
861 WrapperToVector wrapper(settings);
862 impl_->processMarkup(text, &wrapper);
863 return wrapper.result();
866 void HelpWriterContext::writeTitle(const std::string &title) const
872 File &file = outputFile();
873 switch (outputFormat())
875 case eHelpOutputFormat_Console:
876 file.writeLine(toUpperCase(title));
879 case eHelpOutputFormat_Rst:
880 file.writeLine(title);
881 file.writeLine(std::string(title.length(),
882 g_titleChars[impl_->sectionDepth_]));
885 GMX_THROW(NotImplementedError(
886 "This output format is not implemented"));
890 void HelpWriterContext::writeTextBlock(const std::string &text) const
892 TextLineWrapperSettings settings;
893 if (outputFormat() == eHelpOutputFormat_Console)
895 settings.setLineLength(78);
897 outputFile().writeLine(substituteMarkupAndWrapToString(settings, text));
900 void HelpWriterContext::writeOptionListStart() const
904 void HelpWriterContext::writeOptionItem(const std::string &name,
905 const std::string &args,
906 const std::string &description) const
908 File &file = outputFile();
909 switch (outputFormat())
911 case eHelpOutputFormat_Console:
912 // TODO: Generalize this when there is need for it; the current,
913 // special implementation is in CommandLineHelpWriter.
914 GMX_THROW(NotImplementedError("Option item formatting for console output not implemented"));
916 case eHelpOutputFormat_Rst:
918 file.writeLine(formatString("``%s`` %s", name.c_str(), args.c_str()));
919 TextLineWrapperSettings settings;
920 settings.setIndent(4);
921 file.writeLine(substituteMarkupAndWrapToString(settings, description));
925 GMX_THROW(NotImplementedError(
926 "This output format is not implemented"));
930 void HelpWriterContext::writeOptionListEnd() const