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.
315 std::string removeExtraNewlinesRst(const std::string &text)
317 // Start from 2, so that all newlines in the beginning get stripped off.
318 int newlineCount = 2;
320 result.reserve(text.length());
321 for (size_t i = 0; i < text.length(); ++i)
326 if (newlineCount > 2)
335 result.push_back(text[i]);
337 size_t last = result.find_last_not_of('\n');
338 if (last != std::string::npos)
340 result.resize(last + 1);
349 /********************************************************************
354 * Private implementation class for HelpLinks.
356 * \ingroup module_onlinehelp
358 class HelpLinks::Impl
363 LinkItem(const std::string &linkName,
364 const std::string &replacement)
365 : linkName(linkName), replacement(replacement)
368 std::string linkName;
369 std::string replacement;
372 //! Shorthand for a list of links.
373 typedef std::vector<LinkItem> LinkList;
375 //! Initializes empty links with the given format.
376 explicit Impl(HelpOutputFormat format) : format_(format)
382 //! Output format for which the links are formatted.
383 HelpOutputFormat format_;
386 /********************************************************************
390 HelpLinks::HelpLinks(HelpOutputFormat format) : impl_(new Impl(format))
394 HelpLinks::~HelpLinks()
398 void HelpLinks::addLink(const std::string &linkName,
399 const std::string &targetName,
400 const std::string &displayName)
402 std::string replacement;
403 switch (impl_->format_)
405 case eHelpOutputFormat_Console:
406 replacement = repall(displayName, sandrTty);
408 case eHelpOutputFormat_Rst:
409 replacement = targetName;
412 GMX_RELEASE_ASSERT(false, "Output format not implemented for links");
414 impl_->links_.push_back(Impl::LinkItem(linkName, replacement));
417 /********************************************************************
418 * HelpWriterContext::Impl
422 * Private implementation class for HelpWriterContext.
424 * \ingroup module_onlinehelp
426 class HelpWriterContext::Impl
430 * Shared, non-modifiable state for context objects.
432 * Contents of this structure are shared between all context objects
433 * that are created from a common parent.
434 * This state should not be modified after construction.
436 * \ingroup module_onlinehelp
440 //! Initializes the state with the given parameters.
441 SharedState(File *file, HelpOutputFormat format,
442 const HelpLinks *links)
443 : file_(*file), format_(format), links_(links)
447 //! Output file to which the help is written.
449 //! Output format for the help output.
450 HelpOutputFormat format_;
452 const HelpLinks *links_;
457 ReplaceItem(const std::string &search,
458 const std::string &replace)
459 : search(search), replace(replace)
466 //! Smart pointer type for managing the shared state.
467 typedef boost::shared_ptr<const SharedState> StatePointer;
468 //! Shorthand for a list of markup/other replacements.
469 typedef std::vector<ReplaceItem> ReplaceList;
471 //! Initializes the context with the given state and section depth.
472 Impl(const StatePointer &state, int sectionDepth)
473 : state_(state), sectionDepth_(sectionDepth)
475 initDefaultReplacements();
478 //! Initializes default replacements for the chosen output format.
479 void initDefaultReplacements();
480 //! Adds a new replacement.
481 void addReplacement(const std::string &search,
482 const std::string &replace)
484 replacements_.push_back(ReplaceItem(search, replace));
487 //! Replaces links in a given string.
488 std::string replaceLinks(const std::string &input) const;
491 * Process markup and wrap lines within a block of text.
493 * \param[in] text Text to process.
494 * \param wrapper Object used to wrap the text.
496 * The \p wrapper should take care of either writing the text to output
497 * or providing an interface for the caller to retrieve the output.
499 void processMarkup(const std::string &text,
500 WrapperInterface *wrapper) const;
502 //! Constant state shared by all child context objects.
504 //! List of markup/other replacements.
505 ReplaceList replacements_;
506 //! Number of subsections above this context.
510 GMX_DISALLOW_ASSIGN(Impl);
513 void HelpWriterContext::Impl::initDefaultReplacements()
515 const char *program = getProgramContext().programName();
516 addReplacement("[PROGRAM]", program);
519 std::string HelpWriterContext::Impl::replaceLinks(const std::string &input) const
521 std::string result(input);
522 if (state_->links_ != NULL)
524 HelpLinks::Impl::LinkList::const_iterator link;
525 for (link = state_->links_->impl_->links_.begin();
526 link != state_->links_->impl_->links_.end(); ++link)
528 result = replaceAllWords(result, link->linkName, link->replacement);
534 void HelpWriterContext::Impl::processMarkup(const std::string &text,
535 WrapperInterface *wrapper) const
537 std::string result(text);
538 for (ReplaceList::const_iterator i = replacements_.begin();
539 i != replacements_.end(); ++i)
541 result = replaceAll(result, i->search, i->replace);
543 switch (state_->format_)
545 case eHelpOutputFormat_Console:
547 const int baseFirstLineIndent = wrapper->settings().firstLineIndent();
548 const int baseIndent = wrapper->settings().indent();
549 result = repall(result, sandrTty);
550 result = replaceLinks(result);
551 std::string paragraph;
552 paragraph.reserve(result.length());
554 int nextBreakSize = 0;
555 bool bLiteral = false;
556 while (i < result.length())
558 while (i < result.length() && result[i] == '\n')
562 if (i == result.length())
566 const int breakSize = nextBreakSize;
568 bool bLineStart = true;
569 int currentIndent = 0;
575 if (result[i] == '\n' || i == result.length())
577 if (currentLine == 0)
579 firstIndent = currentIndent;
581 else if (currentLine == 1)
583 indent = currentIndent;
588 if (i + 1 >= result.length() || result[i + 1] == '\n')
595 if (!std::isspace(result[i - 1]))
597 paragraph.push_back(' ');
604 if (std::isspace(result[i]))
609 else if (i + 1 < result.length()
610 && result[i] == '*' && result[i + 1] == ' ')
614 while (i > 0 && result[i - 1] != '\n')
618 paragraph = stripString(paragraph);
622 indent = currentIndent + 2;
626 paragraph.push_back(result[i]);
628 if (endsWith(paragraph, "::"))
631 if (paragraph.length() == 2)
639 if (paragraph[paragraph.length() - 3] == ' ')
641 paragraph.resize(paragraph.length() - 3);
645 paragraph.resize(paragraph.length() - 1);
654 wrapper->wrap(std::string(breakSize, '\n'));
656 wrapper->settings().setFirstLineIndent(baseFirstLineIndent + firstIndent);
657 wrapper->settings().setIndent(baseIndent + indent);
658 wrapper->wrap(paragraph);
659 wrapper->settings().setFirstLineIndent(baseFirstLineIndent);
660 wrapper->settings().setIndent(baseIndent);
664 case eHelpOutputFormat_Rst:
666 result = repall(result, sandrRst);
667 result = replaceLinks(result);
668 result = replaceAll(result, "[REF]", "");
669 result = replaceAll(result, "[ref]", "");
670 result = removeExtraNewlinesRst(result);
671 wrapper->wrap(result);
675 GMX_THROW(InternalError("Invalid help output format"));
679 /********************************************************************
683 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format)
684 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, NULL)), 0))
688 HelpWriterContext::HelpWriterContext(File *file, HelpOutputFormat format,
689 const HelpLinks *links)
690 : impl_(new Impl(Impl::StatePointer(new Impl::SharedState(file, format, links)), 0))
694 GMX_RELEASE_ASSERT(links->impl_->format_ == format,
695 "Links must have the same output format as the context");
699 HelpWriterContext::HelpWriterContext(Impl *impl)
704 HelpWriterContext::HelpWriterContext(const HelpWriterContext &other)
705 : impl_(new Impl(*other.impl_))
709 HelpWriterContext::~HelpWriterContext()
713 void HelpWriterContext::setReplacement(const std::string &search,
714 const std::string &replace)
716 impl_->addReplacement(search, replace);
719 HelpOutputFormat HelpWriterContext::outputFormat() const
721 return impl_->state_->format_;
724 File &HelpWriterContext::outputFile() const
726 return impl_->state_->file_;
729 void HelpWriterContext::enterSubSection(const std::string &title)
731 GMX_RELEASE_ASSERT(impl_->sectionDepth_ - 1 < static_cast<int>(std::strlen(g_titleChars)),
732 "Too deeply nested subsections");
734 ++impl_->sectionDepth_;
738 HelpWriterContext::substituteMarkupAndWrapToString(
739 const TextLineWrapperSettings &settings, const std::string &text) const
741 WrapperToString wrapper(settings);
742 impl_->processMarkup(text, &wrapper);
743 return wrapper.result();
746 std::vector<std::string>
747 HelpWriterContext::substituteMarkupAndWrapToVector(
748 const TextLineWrapperSettings &settings, const std::string &text) const
750 WrapperToVector wrapper(settings);
751 impl_->processMarkup(text, &wrapper);
752 return wrapper.result();
755 void HelpWriterContext::writeTitle(const std::string &title) const
761 File &file = outputFile();
762 switch (outputFormat())
764 case eHelpOutputFormat_Console:
765 file.writeLine(toUpperCase(title));
768 case eHelpOutputFormat_Rst:
769 file.writeLine(title);
770 file.writeLine(std::string(title.length(),
771 g_titleChars[impl_->sectionDepth_]));
774 GMX_THROW(NotImplementedError(
775 "This output format is not implemented"));
779 void HelpWriterContext::writeTextBlock(const std::string &text) const
781 TextLineWrapperSettings settings;
782 if (outputFormat() == eHelpOutputFormat_Console)
784 settings.setLineLength(78);
786 outputFile().writeLine(substituteMarkupAndWrapToString(settings, text));
789 void HelpWriterContext::writeOptionListStart() const
793 void HelpWriterContext::writeOptionItem(const std::string &name,
794 const std::string &args,
795 const std::string &description) const
797 File &file = outputFile();
798 switch (outputFormat())
800 case eHelpOutputFormat_Console:
801 // TODO: Generalize this when there is need for it; the current,
802 // special implementation is in CommandLineHelpWriter.
803 GMX_THROW(NotImplementedError("Option item formatting for console output not implemented"));
805 case eHelpOutputFormat_Rst:
807 file.writeLine(formatString("``%s`` %s", name.c_str(), args.c_str()));
808 TextLineWrapperSettings settings;
809 settings.setIndent(4);
810 file.writeLine(substituteMarkupAndWrapToString(settings, description));
814 GMX_THROW(NotImplementedError(
815 "This output format is not implemented"));
819 void HelpWriterContext::writeOptionListEnd() const