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(" },
139 //! List of replacements for reStructuredText output.
140 const t_sandr sandrRst[] = {
149 { "[CHEVRON]", "<" },
150 { "[chevron]", ">" },
153 { "[INT]", "integral" },
154 { "[FROM]", " from " },
163 { "[SQRT]", "sqrt(" },
177 { "[COSH]", "cosh(" },
179 { "[SINH]", "sinh(" },
181 { "[TANH]", "tanh(" },
184 // [BR] is fundamentally incompatible with rst
191 * Replaces all entries from a list of replacements.
193 std::string repall(const std::string &s, int nsr, const t_sandr sa[])
195 std::string result(s);
196 for (int i = 0; i < nsr; ++i)
198 result = replaceAll(result, sa[i].search, sa[i].replace);
204 * Replaces all entries from a list of replacements.
206 template <size_t nsr>
207 std::string repall(const std::string &s, const t_sandr (&sa)[nsr])
209 return repall(s, nsr, sa);
213 * Custom output interface for HelpWriterContext::Impl::processMarkup().
215 * Provides an interface that is used to implement different types of output
216 * from HelpWriterContext::Impl::processMarkup().
218 class WrapperInterface
221 virtual ~WrapperInterface() {}
224 * Provides the wrapping settings.
226 * HelpWriterContext::Impl::processMarkup() may provide some default
227 * values for the settings if they are not set; this is the reason the
228 * return value is not const.
230 virtual TextLineWrapperSettings &settings() = 0;
231 //! Appends the given string to output.
232 virtual void wrap(const std::string &text) = 0;
236 * Wraps markup output into a single string.
238 class WrapperToString : public WrapperInterface
241 //! Creates a wrapper with the given settings.
242 explicit WrapperToString(const TextLineWrapperSettings &settings)
247 virtual TextLineWrapperSettings &settings()
249 return wrapper_.settings();
251 virtual void wrap(const std::string &text)
253 result_.append(wrapper_.wrapToString(text));
255 //! Returns the result string.
256 const std::string &result() const { return result_; }
259 TextLineWrapper wrapper_;
264 * Wraps markup output into a vector of string (one line per element).
266 class WrapperToVector : public WrapperInterface
269 //! Creates a wrapper with the given settings.
270 explicit WrapperToVector(const TextLineWrapperSettings &settings)
275 virtual TextLineWrapperSettings &settings()
277 return wrapper_.settings();
279 virtual void wrap(const std::string &text)
281 const std::vector<std::string> &lines = wrapper_.wrapToVector(text);
282 result_.insert(result_.end(), lines.begin(), lines.end());
284 //! Returns a vector with the output lines.
285 const std::vector<std::string> &result() const { return result_; }
288 TextLineWrapper wrapper_;
289 std::vector<std::string> result_;
293 * Makes the string uppercase.
295 * \param[in] text Input text.
296 * \returns \p text with all characters transformed to uppercase.
297 * \throws std::bad_alloc if out of memory.
299 std::string toUpperCase(const std::string &text)
301 std::string result(text);
302 std::transform(result.begin(), result.end(), result.begin(), toupper);
307 * Removes extra newlines from reStructuredText.
309 * \param[in] text Input text.
310 * \returns \p text with all sequences of more than two newlines replaced
311 * with just two newlines.
312 * \throws std::bad_alloc if out of memory.
314 std::string removeExtraNewlinesRst(const std::string &text)
316 // Start from 2, so that all newlines in the beginning get stripped off.
317 int newlineCount = 2;
319 result.reserve(text.length());
320 for (size_t i = 0; i < text.length(); ++i)
325 if (newlineCount > 2)
334 result.push_back(text[i]);
336 size_t last = result.find_last_not_of('\n');
337 if (last != std::string::npos)
339 result.resize(last + 1);
345 * Returns `true` if a list item starts in \p text at \p index.
349 bool startsListItem(const std::string &text, size_t index)
351 if (text.length() <= index + 1)
355 if (text[index] == '*' && std::isspace(text[index+1]))
359 if (std::isdigit(text[index]))
361 while (index < text.length() && std::isdigit(text[index]))
365 if (text.length() > index + 1 && text[index] == '.'
366 && std::isspace(text[index+1]))
375 * Returns `true` if a table starts in \p text at \p index.
377 * The function only inspects the first line for something that looks like a
378 * reStructuredText table, and accepts also some malformed tables.
379 * Any issues should be apparent when Sphinx parses the reStructuredText
380 * export, so full validation is not done here.
384 bool startsTable(const std::string &text, size_t index)
386 if (text[index] == '=')
388 while (index < text.length() && text[index] != '\n')
390 if (text[index] != '=' && !std::isspace(text[index]))
398 else if (text[index] == '+')
400 while (index < text.length() && text[index] != '\n')
402 if (text[index] != '-' && text[index] != '+')
417 /********************************************************************
422 * Private implementation class for HelpLinks.
424 * \ingroup module_onlinehelp
426 class HelpLinks::Impl
431 LinkItem(const std::string &linkName,
432 const std::string &replacement)
433 : linkName(linkName), replacement(replacement)
436 std::string linkName;
437 std::string replacement;
440 //! Shorthand for a list of links.
441 typedef std::vector<LinkItem> LinkList;
443 //! Initializes empty links with the given format.
444 explicit Impl(HelpOutputFormat format) : format_(format)
450 //! Output format for which the links are formatted.
451 HelpOutputFormat format_;
454 /********************************************************************
458 HelpLinks::HelpLinks(HelpOutputFormat format) : impl_(new Impl(format))
462 HelpLinks::~HelpLinks()
466 void HelpLinks::addLink(const std::string &linkName,
467 const std::string &targetName,
468 const std::string &displayName)
470 std::string replacement;
471 switch (impl_->format_)
473 case eHelpOutputFormat_Console:
474 replacement = repall(displayName, sandrTty);
476 case eHelpOutputFormat_Rst:
477 replacement = targetName;
480 GMX_RELEASE_ASSERT(false, "Output format not implemented for links");
482 impl_->links_.push_back(Impl::LinkItem(linkName, replacement));
485 /********************************************************************
486 * HelpWriterContext::Impl
490 * Private implementation class for HelpWriterContext.
492 * \ingroup module_onlinehelp
494 class HelpWriterContext::Impl
498 * Shared, non-modifiable state for context objects.
500 * Contents of this structure are shared between all context objects
501 * that are created from a common parent.
502 * This state should not be modified after construction.
504 * \ingroup module_onlinehelp
508 //! Initializes the state with the given parameters.
509 SharedState(File *file, HelpOutputFormat format,
510 const HelpLinks *links)
511 : file_(*file), format_(format), links_(links)
515 //! Output file to which the help is written.
517 //! Output format for the help output.
518 HelpOutputFormat format_;
520 const HelpLinks *links_;
525 ReplaceItem(const std::string &search,
526 const std::string &replace)
527 : search(search), replace(replace)
534 //! Smart pointer type for managing the shared state.
535 typedef boost::shared_ptr<const SharedState> StatePointer;
536 //! Shorthand for a list of markup/other replacements.
537 typedef std::vector<ReplaceItem> ReplaceList;
539 //! Initializes the context with the given state and section depth.
540 Impl(const StatePointer &state, int sectionDepth)
541 : state_(state), sectionDepth_(sectionDepth)
543 initDefaultReplacements();
546 //! Initializes default replacements for the chosen output format.
547 void initDefaultReplacements();
548 //! Adds a new replacement.
549 void addReplacement(const std::string &search,
550 const std::string &replace)
552 replacements_.push_back(ReplaceItem(search, replace));
555 //! Replaces links in a given string.
556 std::string replaceLinks(const std::string &input) const;
559 * Process markup and wrap lines within a block of text.
561 * \param[in] text Text to process.
562 * \param wrapper Object used to wrap the text.
564 * The \p wrapper should take care of either writing the text to output
565 * or providing an interface for the caller to retrieve the output.
567 void processMarkup(const std::string &text,
568 WrapperInterface *wrapper) const;
570 //! Constant state shared by all child context objects.
572 //! List of markup/other replacements.
573 ReplaceList replacements_;
574 //! Number of subsections above this context.
578 GMX_DISALLOW_ASSIGN(Impl);
581 void HelpWriterContext::Impl::initDefaultReplacements()
583 const char *program = getProgramContext().programName();
584 addReplacement("[PROGRAM]", program);
587 std::string HelpWriterContext::Impl::replaceLinks(const std::string &input) const
589 std::string result(input);
590 if (state_->links_ != NULL)
592 HelpLinks::Impl::LinkList::const_iterator link;
593 for (link = state_->links_->impl_->links_.begin();
594 link != state_->links_->impl_->links_.end(); ++link)
596 result = replaceAllWords(result, link->linkName, link->replacement);
602 void HelpWriterContext::Impl::processMarkup(const std::string &text,
603 WrapperInterface *wrapper) const
605 std::string result(text);
606 for (ReplaceList::const_iterator i = replacements_.begin();
607 i != replacements_.end(); ++i)
609 result = replaceAll(result, i->search, i->replace);
611 switch (state_->format_)
613 case eHelpOutputFormat_Console:
615 const int baseFirstLineIndent = wrapper->settings().firstLineIndent();
616 const int baseIndent = wrapper->settings().indent();
617 result = repall(result, sandrTty);
618 result = replaceLinks(result);
619 std::string paragraph;
620 paragraph.reserve(result.length());
622 int nextBreakSize = 0;
623 bool bLiteral = false;
624 while (i < result.length())
626 while (i < result.length() && result[i] == '\n')
630 if (i == result.length())
634 const int breakSize = nextBreakSize;
636 bool bLineStart = true;
637 int currentIndent = 0;
643 if (result[i] == '\n' || i == result.length())
645 if (currentLine == 0)
647 firstIndent = currentIndent;
649 else if (currentLine == 1)
651 indent = currentIndent;
656 if (i + 1 >= result.length() || result[i + 1] == '\n')
663 if (!std::isspace(result[i - 1]))
665 paragraph.push_back(' ');
672 if (std::isspace(result[i]))
677 else if (startsListItem(result, i))
681 while (i > 0 && result[i - 1] != '\n')
685 paragraph = stripString(paragraph);
689 int prefixLength = 0;
690 while (!std::isspace(result[i + prefixLength]))
694 while (i + prefixLength < result.length()
695 && std::isspace(result[i + prefixLength]))
699 indent = currentIndent + prefixLength;
701 else if (currentLine == 0 && startsTable(result, i))
707 paragraph.push_back(result[i]);
709 if (endsWith(paragraph, "::"))
712 if (paragraph.length() == 2)
720 if (paragraph[paragraph.length() - 3] == ' ')
722 paragraph.resize(paragraph.length() - 3);
726 paragraph.resize(paragraph.length() - 1);
735 wrapper->wrap(std::string(breakSize, '\n'));
737 wrapper->settings().setFirstLineIndent(baseFirstLineIndent + firstIndent);
738 wrapper->settings().setIndent(baseIndent + indent);
739 wrapper->wrap(paragraph);
740 wrapper->settings().setFirstLineIndent(baseFirstLineIndent);
741 wrapper->settings().setIndent(baseIndent);
745 case eHelpOutputFormat_Rst:
747 result = repall(result, sandrRst);
748 result = replaceLinks(result);
749 result = replaceAll(result, "[REF]", "");
750 result = replaceAll(result, "[ref]", "");
751 result = removeExtraNewlinesRst(result);
752 wrapper->wrap(result);
756 GMX_THROW(InternalError("Invalid help output format"));
760 /********************************************************************
764 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format)
765 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, NULL)), 0))
769 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format,
770 const HelpLinks *links)
771 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, links)), 0))
775 GMX_RELEASE_ASSERT(links->impl_->format_ == format,
776 "Links must have the same output format as the context");
780 HelpWriterContext::HelpWriterContext(Impl *impl)
785 HelpWriterContext::HelpWriterContext(const HelpWriterContext &other)
786 : impl_(new Impl(*other.impl_))
790 HelpWriterContext::~HelpWriterContext()
794 void HelpWriterContext::setReplacement(const std::string &search,
795 const std::string &replace)
797 impl_->addReplacement(search, replace);
800 HelpOutputFormat HelpWriterContext::outputFormat() const
802 return impl_->state_->format_;
805 File &HelpWriterContext::outputFile() const
807 return impl_->state_->file_;
810 void HelpWriterContext::enterSubSection(const std::string &title)
812 GMX_RELEASE_ASSERT(impl_->sectionDepth_ - 1 < static_cast<int>(std::strlen(g_titleChars)),
813 "Too deeply nested subsections");
815 ++impl_->sectionDepth_;
819 HelpWriterContext::substituteMarkupAndWrapToString(
820 const TextLineWrapperSettings &settings, const std::string &text) const
822 WrapperToString wrapper(settings);
823 impl_->processMarkup(text, &wrapper);
824 return wrapper.result();
827 std::vector<std::string>
828 HelpWriterContext::substituteMarkupAndWrapToVector(
829 const TextLineWrapperSettings &settings, const std::string &text) const
831 WrapperToVector wrapper(settings);
832 impl_->processMarkup(text, &wrapper);
833 return wrapper.result();
836 void HelpWriterContext::writeTitle(const std::string &title) const
842 File &file = outputFile();
843 switch (outputFormat())
845 case eHelpOutputFormat_Console:
846 file.writeLine(toUpperCase(title));
849 case eHelpOutputFormat_Rst:
850 file.writeLine(title);
851 file.writeLine(std::string(title.length(),
852 g_titleChars[impl_->sectionDepth_]));
855 GMX_THROW(NotImplementedError(
856 "This output format is not implemented"));
860 void HelpWriterContext::writeTextBlock(const std::string &text) const
862 TextLineWrapperSettings settings;
863 if (outputFormat() == eHelpOutputFormat_Console)
865 settings.setLineLength(78);
867 outputFile().writeLine(substituteMarkupAndWrapToString(settings, text));
870 void HelpWriterContext::writeOptionListStart() const
874 void HelpWriterContext::writeOptionItem(const std::string &name,
875 const std::string &args,
876 const std::string &description) const
878 File &file = outputFile();
879 switch (outputFormat())
881 case eHelpOutputFormat_Console:
882 // TODO: Generalize this when there is need for it; the current,
883 // special implementation is in CommandLineHelpWriter.
884 GMX_THROW(NotImplementedError("Option item formatting for console output not implemented"));
886 case eHelpOutputFormat_Rst:
888 file.writeLine(formatString("``%s`` %s", name.c_str(), args.c_str()));
889 TextLineWrapperSettings settings;
890 settings.setIndent(4);
891 file.writeLine(substituteMarkupAndWrapToString(settings, description));
895 GMX_THROW(NotImplementedError(
896 "This output format is not implemented"));
900 void HelpWriterContext::writeOptionListEnd() const