2 * \file InsetCommandParams.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * \author Richard Kimberly Heck
10 * Full author contact details are available in file CREDITS.
15 #include "InsetCommandParams.h"
17 #include "InsetBibitem.h"
18 #include "InsetBibtex.h"
19 #include "InsetCitation.h"
20 #include "InsetCounter.h"
21 #include "InsetFloatList.h"
22 #include "InsetHyperlink.h"
23 #include "InsetInclude.h"
24 #include "InsetIndex.h"
25 #include "InsetLabel.h"
26 #include "InsetLine.h"
27 #include "InsetNomencl.h"
35 #include "frontends/alert.h"
37 #include "support/debug.h"
38 #include "support/docstream.h"
39 #include "support/ExceptionMessage.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
43 #include "support/lassert.h"
49 using namespace lyx::support;
54 /// Get information for \p code and command \p cmdName.
55 /// Don't call this without first making sure the command name is
56 /// acceptable to the inset.
57 static ParamInfo const & findInfo(InsetCode code, string const & cmdName)
61 return InsetBibitem::findInfo(cmdName);
63 return InsetBibtex::findInfo(cmdName);
65 return InsetCitation::findInfo(cmdName);
67 return InsetCounter::findInfo(cmdName);
69 return InsetFloatList::findInfo(cmdName);
71 return InsetHyperlink::findInfo(cmdName);
73 return InsetInclude::findInfo(cmdName);
74 case INDEX_PRINT_CODE:
75 return InsetPrintIndex::findInfo(cmdName);
77 return InsetLabel::findInfo(cmdName);
79 return InsetLine::findInfo(cmdName);
81 return InsetNomencl::findInfo(cmdName);
82 case NOMENCL_PRINT_CODE:
83 return InsetPrintNomencl::findInfo(cmdName);
85 return InsetRef::findInfo(cmdName);
87 return InsetTOC::findInfo(cmdName);
90 // fall through in release mode
92 static const ParamInfo pi;
97 /////////////////////////////////////////////////////////////////////
99 // ParamInfo::ParamData
101 /////////////////////////////////////////////////////////////////////
103 ParamInfo::ParamData::ParamData(std::string const & s, ParamType t,
104 ParamHandling h, bool ignore,
105 docstring default_value)
106 : name_(s), type_(t), handling_(h), ignore_(ignore),
107 default_value_(default_value)
111 bool ParamInfo::ParamData::isOptional() const
113 return type_ == ParamInfo::LATEX_OPTIONAL;
117 bool ParamInfo::ParamData::operator==(ParamInfo::ParamData const & rhs) const
119 return name() == rhs.name() && type() == rhs.type()
120 && handling() == rhs.handling();
124 bool ParamInfo::hasParam(std::string const & name) const
126 const_iterator it = begin();
127 const_iterator last = end();
128 for (; it != last; ++it) {
129 if (it->name() == name)
136 void ParamInfo::add(std::string const & name, ParamType type,
137 ParamHandling handling, bool ignoreval,
138 docstring default_value)
140 info_.push_back(ParamData(name, type, handling, ignoreval, default_value));
144 bool ParamInfo::operator==(ParamInfo const & rhs) const
146 if (size() != rhs.size())
148 return equal(begin(), end(), rhs.begin());
152 ParamInfo::ParamData const &
153 ParamInfo::operator[](std::string const & name) const
155 const_iterator it = begin();
156 const_iterator last = end();
157 for (; it != last; ++it) {
158 if (it->name() == name)
162 // we will try to continue in release mode
163 static const ParamData pd("asdfghjkl", LYX_INTERNAL);
168 /////////////////////////////////////////////////////////////////////
170 // InsetCommandParams
172 /////////////////////////////////////////////////////////////////////
175 InsetCommandParams::InsetCommandParams(InsetCode code)
176 : insetCode_(code), preview_(false)
178 cmdName_ = getDefaultCmd(code);
179 info_ = findInfo(code, cmdName_);
183 InsetCommandParams::InsetCommandParams(InsetCode code,
184 string const & cmdName)
185 : insetCode_(code), cmdName_(cmdName), preview_(false)
187 info_ = findInfo(code, cmdName);
191 std::string InsetCommandParams::insetType() const
193 return insetName(insetCode_);
197 string InsetCommandParams::getDefaultCmd(InsetCode code)
201 return InsetBibitem::defaultCommand();
203 return InsetBibtex::defaultCommand();
205 return InsetCitation::defaultCommand();
207 return InsetCounter::defaultCommand();
208 case FLOAT_LIST_CODE:
209 return InsetFloatList::defaultCommand();
211 return InsetHyperlink::defaultCommand();
213 return InsetInclude::defaultCommand();
214 case INDEX_PRINT_CODE:
215 return InsetPrintIndex::defaultCommand();
217 return InsetLabel::defaultCommand();
219 return InsetLine::defaultCommand();
221 return InsetNomencl::defaultCommand();
222 case NOMENCL_PRINT_CODE:
223 return InsetPrintNomencl::defaultCommand();
225 return InsetRef::defaultCommand();
227 return InsetTOC::defaultCommand();
230 // fall through in release mode
236 bool InsetCommandParams::isCompatibleCommand(InsetCode code, string const & s)
240 return InsetBibitem::isCompatibleCommand(s);
242 return InsetBibtex::isCompatibleCommand(s);
244 return InsetCitation::isCompatibleCommand(s);
246 return InsetCounter::isCompatibleCommand(s);
247 case FLOAT_LIST_CODE:
248 return InsetFloatList::isCompatibleCommand(s);
250 return InsetHyperlink::isCompatibleCommand(s);
252 return InsetInclude::isCompatibleCommand(s);
253 case INDEX_PRINT_CODE:
254 return InsetPrintIndex::isCompatibleCommand(s);
256 return InsetLabel::isCompatibleCommand(s);
258 return InsetLine::isCompatibleCommand(s);
260 return InsetNomencl::isCompatibleCommand(s);
261 case NOMENCL_PRINT_CODE:
262 return InsetPrintNomencl::isCompatibleCommand(s);
264 return InsetRef::isCompatibleCommand(s);
266 return InsetTOC::isCompatibleCommand(s);
269 // fall through in release mode
275 void InsetCommandParams::setCmdName(string const & name)
277 if (!isCompatibleCommand(insetCode_, name)) {
278 LYXERR0("InsetCommand: Incompatible command name " <<
280 throw ExceptionMessage(WarningException, _("InsetCommand Error: "),
281 _("Incompatible command name."));
285 info_ = findInfo(insetCode_, cmdName_);
289 void InsetCommandParams::read(Lexer & lex)
295 void InsetCommandParams::Read(Lexer & lex, Buffer const * buffer)
297 lex.setContext("InsetCommandParams::read");
298 lex >> insetName(insetCode_).c_str();
299 lex >> "LatexCommand";
301 if (!isCompatibleCommand(insetCode_, cmdName_)) {
302 lex.printError("Incompatible command name " + cmdName_ + ".");
303 throw ExceptionMessage(WarningException, _("InsetCommandParams Error: "),
304 _("Incompatible command name."));
307 info_ = findInfo(insetCode_, cmdName_);
309 for (ParamInfo::ParamData const & param : info_)
310 if (param.ignore()) {
311 params_[param.name()] = param.defaultValue();
317 token = lex.getString();
318 if (token == "\\end_inset")
320 if (token == "preview") {
322 preview_ = lex.getBool();
325 if (hasParam(token)) {
327 docstring data = lex.getDocString();
328 if (buffer && token == "filename") {
329 data = from_utf8(buffer->includedFilePath(to_utf8(data)));
330 } else if (buffer && token == "bibfiles") {
333 docstring bib = support::token(data, ',', i);
334 while (!bib.empty()) {
335 bib = from_utf8(buffer->includedFilePath(to_utf8(bib), "bib"));
336 if (!newdata.empty())
337 newdata.append(1, ',');
339 bib = support::token(data, ',', ++i);
342 } else if (buffer && token == "options") {
343 data = from_utf8(buffer->includedFilePath(to_utf8(data), "bst"));
345 params_[token] = data;
347 lex.printError("Unknown parameter name `$$Token' for command " + cmdName_);
348 throw ExceptionMessage(WarningException,
349 _("InsetCommandParams: ") + from_ascii(cmdName_),
350 _("Unknown parameter name: ") + from_utf8(token));
353 if (token != "\\end_inset") {
354 lex.printError("Missing \\end_inset at this point. "
356 throw ExceptionMessage(WarningException,
357 _("InsetCommandParams Error: "),
358 _("Missing \\end_inset at this point: ") + from_utf8(token));
363 void InsetCommandParams::write(ostream & os) const
369 void InsetCommandParams::Write(ostream & os, Buffer const * buffer) const
371 os << "CommandInset " << insetType() << '\n';
372 os << "LatexCommand " << cmdName_ << '\n';
374 os << "preview true\n";
375 ParamInfo::const_iterator it = info_.begin();
376 ParamInfo::const_iterator end = info_.end();
377 for (; it != end; ++it) {
380 string const & name = it->name();
381 string data = to_utf8((*this)[name]);
383 // Adjust path of files if document was moved
384 if (buffer && name == "filename") {
385 data = buffer->includedFilePath(data);
386 } else if (buffer && name == "bibfiles") {
389 string bib = token(data, ',', i);
390 while (!bib.empty()) {
391 bib = buffer->includedFilePath(bib, "bib");
392 if (!newdata.empty())
393 newdata.append(1, ',');
395 bib = token(data, ',', ++i);
398 } else if (buffer && name == "options") {
399 data = buffer->includedFilePath(data, "bst");
402 << Lexer::quoteString(data)
409 bool InsetCommandParams::writeEmptyOptional(ParamInfo::const_iterator ci) const
411 LASSERT(ci->isOptional(), return false);
413 ++ci; // we want to start with the next one
414 ParamInfo::const_iterator end = info_.end();
415 for (; ci != end; ++ci) {
416 switch (ci->type()) {
417 case ParamInfo::LYX_INTERNAL:
420 case ParamInfo::LATEX_REQUIRED:
423 case ParamInfo::LATEX_OPTIONAL: {
424 std::string const & name = ci->name();
425 docstring const & data = (*this)[name];
437 docstring InsetCommandParams::prepareCommand(OutputParams const & runparams,
438 docstring const & command,
439 ParamInfo::ParamHandling handling) const
442 bool ltrimmed = false;
443 // Trimming can be done on top of any of the other handlings
444 // We check this here since handling might be changed below.
445 if (handling & ParamInfo::HANDLING_LTRIM) {
446 // this is used if no other handling is done
450 if (handling & ParamInfo::HANDLING_LATEXIFY
451 || handling & ParamInfo::HANDLING_INDEX_ESCAPE)
452 if ((*this)["literal"] == "true")
453 handling = ParamInfo::HANDLING_NONE;
455 // LATEXIFY, ESCAPE and NONE are mutually exclusive
456 if (handling & ParamInfo::HANDLING_LATEXIFY) {
457 // First handle backslash
458 result = subst(command, from_ascii("\\"), from_ascii("\\textbackslash{}"));
459 // Then get LaTeX macros
460 pair<docstring, docstring> command_latexed =
461 runparams.encoding->latexString(result, runparams.dryrun);
462 result = command_latexed.first;
463 if (!command_latexed.second.empty()) {
464 // Issue a warning about omitted characters
465 // FIXME: should be passed to the error dialog
466 frontend::Alert::warning(_("Uncodable characters"),
467 bformat(_("The following characters that are used in the inset %1$s are not\n"
468 "representable in the current encoding and therefore have been omitted:\n%2$s."),
469 from_utf8(insetType()), command_latexed.second));
471 // Now escape special commands
472 static docstring const backslash = from_ascii("\\");
473 int const nchars_escape = 8;
474 static char_type const chars_escape[nchars_escape] = {
475 '&', '_', '$', '%', '#', '^', '{', '}'};
477 if (!result.empty()) {
479 // The characters in chars_name[] need to be changed to a command when
480 // they are LaTeXified.
481 for (int k = 0; k < nchars_escape; k++)
482 for (size_t i = 0, pos;
483 (pos = result.find(chars_escape[k], i)) != string::npos;
485 //(Only) \\^ needs to be terminated
486 docstring const term = (k == 5) ? from_ascii("{}") : docstring();
491 // only if not already escaped
492 if (result[previous] != '\\')
493 result.replace(pos, 1, backslash + chars_escape[k] + term);
497 else if (handling & ParamInfo::HANDLING_ESCAPE)
498 result = escape(command);
499 else if (handling & ParamInfo::HANDLING_NONE) {
500 // we can only output characters covered by the current
503 for (char_type c : command) {
505 if (runparams.encoding->encodable(c))
507 else if (runparams.dryrun) {
508 result += "<" + _("LyX Warning: ")
509 + _("uncodable character") + " '";
510 result += docstring(1, c);
514 } catch (EncodingException & /* e */) {
515 if (runparams.dryrun) {
516 result += "<" + _("LyX Warning: ")
517 + _("uncodable character") + " '";
518 result += docstring(1, c);
524 if (!uncodable.empty() && !runparams.silent) {
525 // issue a warning about omitted characters
526 // FIXME: should be passed to the error dialog
527 frontend::Alert::warning(_("Uncodable characters in inset"),
528 bformat(_("The following characters in one of the insets are\n"
529 "not representable in the current encoding and have been omitted: %1$s.\n"
530 "Unchecking 'Literal' in the respective inset dialog might help."),
534 // INDEX_ESCAPE is independent of the others
535 if (handling & ParamInfo::HANDLING_INDEX_ESCAPE) {
536 // Now escape special commands
537 static docstring const quote = from_ascii("\"");
538 int const nchars_escape = 4;
539 static char_type const chars_escape[nchars_escape] = { '"', '@', '|', '!' };
541 if (!result.empty()) {
542 // The characters in chars_name[] need to be changed to a command when
543 // they are LaTeXified.
544 for (int k = 0; k < nchars_escape; k++)
545 for (size_t i = 0, pos;
546 (pos = result.find(chars_escape[k], i)) != string::npos;
548 result.replace(pos, 1, quote + chars_escape[k]);
552 return ltrimmed ? ltrim(result) : result;
556 docstring InsetCommandParams::getCommand(OutputParams const & runparams) const
558 docstring s = '\\' + from_ascii(cmdName_);
560 ParamInfo::const_iterator it = info_.begin();
561 ParamInfo::const_iterator end = info_.end();
562 for (; it != end; ++it) {
563 std::string const & name = it->name();
564 switch (it->type()) {
565 case ParamInfo::LYX_INTERNAL:
568 case ParamInfo::LATEX_REQUIRED: {
569 docstring const data =
570 prepareCommand(runparams, (*this)[name], it->handling());
571 s += '{' + data + '}';
575 case ParamInfo::LATEX_OPTIONAL: {
577 prepareCommand(runparams, (*this)[name], it->handling());
579 s += '[' + protectArgument(data) + ']';
581 } else if (writeEmptyOptional(it)) {
590 // Make sure that following stuff does not change the
597 docstring InsetCommandParams::getFirstNonOptParam() const
599 ParamInfo::const_iterator it =
600 find_if(info_.begin(), info_.end(),
601 [](ParamInfo::ParamData const & d) { return !d.isOptional(); });
602 LASSERT(it != info_.end(), return docstring());
603 return (*this)[it->name()];
607 bool InsetCommandParams::hasParam(std::string const & name) const
609 return info_.hasParam(name);
613 docstring const & InsetCommandParams::getParamOr(std::string const & name, docstring const & defaultValue) const
616 return (*this)[name];
621 docstring const & InsetCommandParams::operator[](string const & name) const
623 static const docstring dummy;
624 LASSERT(hasParam(name), return dummy);
625 ParamMap::const_iterator data = params_.find(name);
626 if (data == params_.end() || data->second.empty())
628 ParamInfo::ParamData const & param = info_[name];
630 return param.defaultValue();
635 docstring & InsetCommandParams::operator[](string const & name)
637 LATTEST(hasParam(name));
638 // this will add the name in release mode
639 ParamInfo::ParamData const & param = info_[name];
641 params_[name] = param.defaultValue();
642 return params_[name];
646 void InsetCommandParams::clear()
653 bool operator==(InsetCommandParams const & o1, InsetCommandParams const & o2)
655 return o1.insetCode_ == o2.insetCode_
656 && o1.cmdName_ == o2.cmdName_
657 && o1.info_ == o2.info_
658 && o1.params_ == o2.params_
659 && o1.preview_ == o2.preview_;
663 bool operator!=(InsetCommandParams const & o1, InsetCommandParams const & o2)