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]))
378 /********************************************************************
383 * Private implementation class for HelpLinks.
385 * \ingroup module_onlinehelp
387 class HelpLinks::Impl
392 LinkItem(const std::string &linkName,
393 const std::string &replacement)
394 : linkName(linkName), replacement(replacement)
397 std::string linkName;
398 std::string replacement;
401 //! Shorthand for a list of links.
402 typedef std::vector<LinkItem> LinkList;
404 //! Initializes empty links with the given format.
405 explicit Impl(HelpOutputFormat format) : format_(format)
411 //! Output format for which the links are formatted.
412 HelpOutputFormat format_;
415 /********************************************************************
419 HelpLinks::HelpLinks(HelpOutputFormat format) : impl_(new Impl(format))
423 HelpLinks::~HelpLinks()
427 void HelpLinks::addLink(const std::string &linkName,
428 const std::string &targetName,
429 const std::string &displayName)
431 std::string replacement;
432 switch (impl_->format_)
434 case eHelpOutputFormat_Console:
435 replacement = repall(displayName, sandrTty);
437 case eHelpOutputFormat_Rst:
438 replacement = targetName;
441 GMX_RELEASE_ASSERT(false, "Output format not implemented for links");
443 impl_->links_.push_back(Impl::LinkItem(linkName, replacement));
446 /********************************************************************
447 * HelpWriterContext::Impl
451 * Private implementation class for HelpWriterContext.
453 * \ingroup module_onlinehelp
455 class HelpWriterContext::Impl
459 * Shared, non-modifiable state for context objects.
461 * Contents of this structure are shared between all context objects
462 * that are created from a common parent.
463 * This state should not be modified after construction.
465 * \ingroup module_onlinehelp
469 //! Initializes the state with the given parameters.
470 SharedState(File *file, HelpOutputFormat format,
471 const HelpLinks *links)
472 : file_(*file), format_(format), links_(links)
476 //! Output file to which the help is written.
478 //! Output format for the help output.
479 HelpOutputFormat format_;
481 const HelpLinks *links_;
486 ReplaceItem(const std::string &search,
487 const std::string &replace)
488 : search(search), replace(replace)
495 //! Smart pointer type for managing the shared state.
496 typedef boost::shared_ptr<const SharedState> StatePointer;
497 //! Shorthand for a list of markup/other replacements.
498 typedef std::vector<ReplaceItem> ReplaceList;
500 //! Initializes the context with the given state and section depth.
501 Impl(const StatePointer &state, int sectionDepth)
502 : state_(state), sectionDepth_(sectionDepth)
504 initDefaultReplacements();
507 //! Initializes default replacements for the chosen output format.
508 void initDefaultReplacements();
509 //! Adds a new replacement.
510 void addReplacement(const std::string &search,
511 const std::string &replace)
513 replacements_.push_back(ReplaceItem(search, replace));
516 //! Replaces links in a given string.
517 std::string replaceLinks(const std::string &input) const;
520 * Process markup and wrap lines within a block of text.
522 * \param[in] text Text to process.
523 * \param wrapper Object used to wrap the text.
525 * The \p wrapper should take care of either writing the text to output
526 * or providing an interface for the caller to retrieve the output.
528 void processMarkup(const std::string &text,
529 WrapperInterface *wrapper) const;
531 //! Constant state shared by all child context objects.
533 //! List of markup/other replacements.
534 ReplaceList replacements_;
535 //! Number of subsections above this context.
539 GMX_DISALLOW_ASSIGN(Impl);
542 void HelpWriterContext::Impl::initDefaultReplacements()
544 const char *program = getProgramContext().programName();
545 addReplacement("[PROGRAM]", program);
548 std::string HelpWriterContext::Impl::replaceLinks(const std::string &input) const
550 std::string result(input);
551 if (state_->links_ != NULL)
553 HelpLinks::Impl::LinkList::const_iterator link;
554 for (link = state_->links_->impl_->links_.begin();
555 link != state_->links_->impl_->links_.end(); ++link)
557 result = replaceAllWords(result, link->linkName, link->replacement);
563 void HelpWriterContext::Impl::processMarkup(const std::string &text,
564 WrapperInterface *wrapper) const
566 std::string result(text);
567 for (ReplaceList::const_iterator i = replacements_.begin();
568 i != replacements_.end(); ++i)
570 result = replaceAll(result, i->search, i->replace);
572 switch (state_->format_)
574 case eHelpOutputFormat_Console:
576 const int baseFirstLineIndent = wrapper->settings().firstLineIndent();
577 const int baseIndent = wrapper->settings().indent();
578 result = repall(result, sandrTty);
579 result = replaceLinks(result);
580 std::string paragraph;
581 paragraph.reserve(result.length());
583 int nextBreakSize = 0;
584 bool bLiteral = false;
585 while (i < result.length())
587 while (i < result.length() && result[i] == '\n')
591 if (i == result.length())
595 const int breakSize = nextBreakSize;
597 bool bLineStart = true;
598 int currentIndent = 0;
604 if (result[i] == '\n' || i == result.length())
606 if (currentLine == 0)
608 firstIndent = currentIndent;
610 else if (currentLine == 1)
612 indent = currentIndent;
617 if (i + 1 >= result.length() || result[i + 1] == '\n')
624 if (!std::isspace(result[i - 1]))
626 paragraph.push_back(' ');
633 if (std::isspace(result[i]))
638 else if (startsListItem(result, i))
642 while (i > 0 && result[i - 1] != '\n')
646 paragraph = stripString(paragraph);
650 int prefixLength = 0;
651 while (!std::isspace(result[i + prefixLength]))
655 while (i + prefixLength < result.length()
656 && std::isspace(result[i + prefixLength]))
660 indent = currentIndent + prefixLength;
664 paragraph.push_back(result[i]);
666 if (endsWith(paragraph, "::"))
669 if (paragraph.length() == 2)
677 if (paragraph[paragraph.length() - 3] == ' ')
679 paragraph.resize(paragraph.length() - 3);
683 paragraph.resize(paragraph.length() - 1);
692 wrapper->wrap(std::string(breakSize, '\n'));
694 wrapper->settings().setFirstLineIndent(baseFirstLineIndent + firstIndent);
695 wrapper->settings().setIndent(baseIndent + indent);
696 wrapper->wrap(paragraph);
697 wrapper->settings().setFirstLineIndent(baseFirstLineIndent);
698 wrapper->settings().setIndent(baseIndent);
702 case eHelpOutputFormat_Rst:
704 result = repall(result, sandrRst);
705 result = replaceLinks(result);
706 result = replaceAll(result, "[REF]", "");
707 result = replaceAll(result, "[ref]", "");
708 result = removeExtraNewlinesRst(result);
709 wrapper->wrap(result);
713 GMX_THROW(InternalError("Invalid help output format"));
717 /********************************************************************
721 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format)
722 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, NULL)), 0))
726 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format,
727 const HelpLinks *links)
728 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, links)), 0))
732 GMX_RELEASE_ASSERT(links->impl_->format_ == format,
733 "Links must have the same output format as the context");
737 HelpWriterContext::HelpWriterContext(Impl *impl)
742 HelpWriterContext::HelpWriterContext(const HelpWriterContext &other)
743 : impl_(new Impl(*other.impl_))
747 HelpWriterContext::~HelpWriterContext()
751 void HelpWriterContext::setReplacement(const std::string &search,
752 const std::string &replace)
754 impl_->addReplacement(search, replace);
757 HelpOutputFormat HelpWriterContext::outputFormat() const
759 return impl_->state_->format_;
762 File &HelpWriterContext::outputFile() const
764 return impl_->state_->file_;
767 void HelpWriterContext::enterSubSection(const std::string &title)
769 GMX_RELEASE_ASSERT(impl_->sectionDepth_ - 1 < static_cast<int>(std::strlen(g_titleChars)),
770 "Too deeply nested subsections");
772 ++impl_->sectionDepth_;
776 HelpWriterContext::substituteMarkupAndWrapToString(
777 const TextLineWrapperSettings &settings, const std::string &text) const
779 WrapperToString wrapper(settings);
780 impl_->processMarkup(text, &wrapper);
781 return wrapper.result();
784 std::vector<std::string>
785 HelpWriterContext::substituteMarkupAndWrapToVector(
786 const TextLineWrapperSettings &settings, const std::string &text) const
788 WrapperToVector wrapper(settings);
789 impl_->processMarkup(text, &wrapper);
790 return wrapper.result();
793 void HelpWriterContext::writeTitle(const std::string &title) const
799 File &file = outputFile();
800 switch (outputFormat())
802 case eHelpOutputFormat_Console:
803 file.writeLine(toUpperCase(title));
806 case eHelpOutputFormat_Rst:
807 file.writeLine(title);
808 file.writeLine(std::string(title.length(),
809 g_titleChars[impl_->sectionDepth_]));
812 GMX_THROW(NotImplementedError(
813 "This output format is not implemented"));
817 void HelpWriterContext::writeTextBlock(const std::string &text) const
819 TextLineWrapperSettings settings;
820 if (outputFormat() == eHelpOutputFormat_Console)
822 settings.setLineLength(78);
824 outputFile().writeLine(substituteMarkupAndWrapToString(settings, text));
827 void HelpWriterContext::writeOptionListStart() const
831 void HelpWriterContext::writeOptionItem(const std::string &name,
832 const std::string &args,
833 const std::string &description) const
835 File &file = outputFile();
836 switch (outputFormat())
838 case eHelpOutputFormat_Console:
839 // TODO: Generalize this when there is need for it; the current,
840 // special implementation is in CommandLineHelpWriter.
841 GMX_THROW(NotImplementedError("Option item formatting for console output not implemented"));
843 case eHelpOutputFormat_Rst:
845 file.writeLine(formatString("``%s`` %s", name.c_str(), args.c_str()));
846 TextLineWrapperSettings settings;
847 settings.setIndent(4);
848 file.writeLine(substituteMarkupAndWrapToString(settings, description));
852 GMX_THROW(NotImplementedError(
853 "This output format is not implemented"));
857 void HelpWriterContext::writeOptionListEnd() const