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
10 * Full author contact details are available in file CREDITS.
18 #include "InsetCommandParams.h"
20 #include "InsetBibitem.h"
21 #include "InsetBibtex.h"
22 #include "InsetCitation.h"
23 #include "InsetCounter.h"
24 #include "InsetFloatList.h"
25 #include "InsetHyperlink.h"
26 #include "InsetInclude.h"
27 #include "InsetIndex.h"
28 #include "InsetLabel.h"
29 #include "InsetLine.h"
30 #include "InsetNomencl.h"
37 #include "OutputParams.h"
39 #include "frontends/alert.h"
41 #include "support/debug.h"
42 #include "support/docstream.h"
43 #include "support/ExceptionMessage.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
47 #include "support/lassert.h"
50 using namespace lyx::support;
55 /// Get information for \p code and command \p cmdName.
56 /// Don't call this without first making sure the command name is
57 /// acceptable to the inset.
58 static ParamInfo const & findInfo(InsetCode code, string const & cmdName)
62 return InsetBibitem::findInfo(cmdName);
64 return InsetBibtex::findInfo(cmdName);
66 return InsetCitation::findInfo(cmdName);
68 return InsetCounter::findInfo(cmdName);
70 return InsetFloatList::findInfo(cmdName);
72 return InsetHyperlink::findInfo(cmdName);
74 return InsetInclude::findInfo(cmdName);
75 case INDEX_PRINT_CODE:
76 return InsetPrintIndex::findInfo(cmdName);
78 return InsetLabel::findInfo(cmdName);
80 return InsetLine::findInfo(cmdName);
82 return InsetNomencl::findInfo(cmdName);
83 case NOMENCL_PRINT_CODE:
84 return InsetPrintNomencl::findInfo(cmdName);
86 return InsetRef::findInfo(cmdName);
88 return InsetTOC::findInfo(cmdName);
91 // fall through in release mode
93 static const ParamInfo pi;
98 /////////////////////////////////////////////////////////////////////
100 // ParamInfo::ParamData
102 /////////////////////////////////////////////////////////////////////
104 ParamInfo::ParamData::ParamData(std::string const & s, ParamType t,
105 ParamHandling h, bool ignore,
106 docstring default_value)
107 : name_(s), type_(t), handling_(h), ignore_(ignore),
108 default_value_(default_value)
112 bool ParamInfo::ParamData::isOptional() const
114 return type_ == ParamInfo::LATEX_OPTIONAL;
118 bool ParamInfo::ParamData::operator==(ParamInfo::ParamData const & rhs) const
120 return name() == rhs.name() && type() == rhs.type()
121 && handling() == rhs.handling();
125 bool ParamInfo::hasParam(std::string const & name) const
127 const_iterator it = begin();
128 const_iterator last = end();
129 for (; it != last; ++it) {
130 if (it->name() == name)
137 void ParamInfo::add(std::string const & name, ParamType type,
138 ParamHandling handling, bool ignoreval,
139 docstring default_value)
141 info_.push_back(ParamData(name, type, handling, ignoreval, default_value));
145 bool ParamInfo::operator==(ParamInfo const & rhs) const
147 if (size() != rhs.size())
149 return equal(begin(), end(), rhs.begin());
153 ParamInfo::ParamData const &
154 ParamInfo::operator[](std::string const & name) const
156 const_iterator it = begin();
157 const_iterator last = end();
158 for (; it != last; ++it) {
159 if (it->name() == name)
163 // we will try to continue in release mode
164 static const ParamData pd("asdfghjkl", LYX_INTERNAL);
169 /////////////////////////////////////////////////////////////////////
171 // InsetCommandParams
173 /////////////////////////////////////////////////////////////////////
176 InsetCommandParams::InsetCommandParams(InsetCode code)
177 : insetCode_(code), preview_(false)
179 cmdName_ = getDefaultCmd(code);
180 info_ = findInfo(code, cmdName_);
184 InsetCommandParams::InsetCommandParams(InsetCode code,
185 string const & cmdName)
186 : insetCode_(code), cmdName_(cmdName), preview_(false)
188 info_ = findInfo(code, cmdName);
192 std::string InsetCommandParams::insetType() const
194 return insetName(insetCode_);
198 string InsetCommandParams::getDefaultCmd(InsetCode code)
202 return InsetBibitem::defaultCommand();
204 return InsetBibtex::defaultCommand();
206 return InsetCitation::defaultCommand();
208 return InsetCounter::defaultCommand();
209 case FLOAT_LIST_CODE:
210 return InsetFloatList::defaultCommand();
212 return InsetHyperlink::defaultCommand();
214 return InsetInclude::defaultCommand();
215 case INDEX_PRINT_CODE:
216 return InsetPrintIndex::defaultCommand();
218 return InsetLabel::defaultCommand();
220 return InsetLine::defaultCommand();
222 return InsetNomencl::defaultCommand();
223 case NOMENCL_PRINT_CODE:
224 return InsetPrintNomencl::defaultCommand();
226 return InsetRef::defaultCommand();
228 return InsetTOC::defaultCommand();
231 // fall through in release mode
237 bool InsetCommandParams::isCompatibleCommand(InsetCode code, string const & s)
241 return InsetBibitem::isCompatibleCommand(s);
243 return InsetBibtex::isCompatibleCommand(s);
245 return InsetCitation::isCompatibleCommand(s);
247 return InsetCounter::isCompatibleCommand(s);
248 case FLOAT_LIST_CODE:
249 return InsetFloatList::isCompatibleCommand(s);
251 return InsetHyperlink::isCompatibleCommand(s);
253 return InsetInclude::isCompatibleCommand(s);
254 case INDEX_PRINT_CODE:
255 return InsetPrintIndex::isCompatibleCommand(s);
257 return InsetLabel::isCompatibleCommand(s);
259 return InsetLine::isCompatibleCommand(s);
261 return InsetNomencl::isCompatibleCommand(s);
262 case NOMENCL_PRINT_CODE:
263 return InsetPrintNomencl::isCompatibleCommand(s);
265 return InsetRef::isCompatibleCommand(s);
267 return InsetTOC::isCompatibleCommand(s);
270 // fall through in release mode
276 void InsetCommandParams::setCmdName(string const & name)
278 if (!isCompatibleCommand(insetCode_, name)) {
279 LYXERR0("InsetCommand: Incompatible command name " <<
281 throw ExceptionMessage(WarningException, _("InsetCommand Error: "),
282 _("Incompatible command name."));
286 info_ = findInfo(insetCode_, cmdName_);
290 void InsetCommandParams::read(Lexer & lex)
296 void InsetCommandParams::Read(Lexer & lex, Buffer const * buffer)
298 lex.setContext("InsetCommandParams::read");
299 lex >> insetName(insetCode_).c_str();
300 lex >> "LatexCommand";
302 if (!isCompatibleCommand(insetCode_, cmdName_)) {
303 lex.printError("Incompatible command name " + cmdName_ + ".");
304 throw ExceptionMessage(WarningException, _("InsetCommandParams Error: "),
305 _("Incompatible command name."));
308 info_ = findInfo(insetCode_, cmdName_);
310 for (ParamInfo::ParamData const & param : info_)
311 if (param.ignore()) {
312 params_[param.name()] = param.defaultValue();
318 token = lex.getString();
319 if (token == "\\end_inset")
321 if (token == "preview") {
323 preview_ = lex.getBool();
326 if (info_.hasParam(token)) {
328 docstring data = lex.getDocString();
329 if (buffer && token == "filename") {
330 data = from_utf8(buffer->includedFilePath(to_utf8(data)));
331 } else if (buffer && token == "bibfiles") {
334 docstring bib = support::token(data, ',', i);
335 while (!bib.empty()) {
336 bib = from_utf8(buffer->includedFilePath(to_utf8(bib), "bib"));
337 if (!newdata.empty())
338 newdata.append(1, ',');
340 bib = support::token(data, ',', ++i);
343 } else if (buffer && token == "options") {
344 data = from_utf8(buffer->includedFilePath(to_utf8(data), "bst"));
346 params_[token] = data;
348 lex.printError("Unknown parameter name `$$Token' for command " + cmdName_);
349 throw ExceptionMessage(WarningException,
350 _("InsetCommandParams: ") + from_ascii(cmdName_),
351 _("Unknown parameter name: ") + from_utf8(token));
354 if (token != "\\end_inset") {
355 lex.printError("Missing \\end_inset at this point. "
357 throw ExceptionMessage(WarningException,
358 _("InsetCommandParams Error: "),
359 _("Missing \\end_inset at this point: ") + from_utf8(token));
364 void InsetCommandParams::write(ostream & os) const
370 void InsetCommandParams::Write(ostream & os, Buffer const * buffer) const
372 os << "CommandInset " << insetType() << '\n';
373 os << "LatexCommand " << cmdName_ << '\n';
375 os << "preview true\n";
376 ParamInfo::const_iterator it = info_.begin();
377 ParamInfo::const_iterator end = info_.end();
378 for (; it != end; ++it) {
381 string const & name = it->name();
382 string data = to_utf8((*this)[name]);
384 // Adjust path of files if document was moved
385 if (buffer && name == "filename") {
386 data = buffer->includedFilePath(data);
387 } else if (buffer && name == "bibfiles") {
390 string bib = token(data, ',', i);
391 while (!bib.empty()) {
392 bib = buffer->includedFilePath(bib, "bib");
393 if (!newdata.empty())
394 newdata.append(1, ',');
396 bib = token(data, ',', ++i);
399 } else if (buffer && name == "options") {
400 data = buffer->includedFilePath(data, "bst");
403 << Lexer::quoteString(data)
410 bool InsetCommandParams::writeEmptyOptional(ParamInfo::const_iterator ci) const
412 LASSERT(ci->isOptional(), return false);
414 ++ci; // we want to start with the next one
415 ParamInfo::const_iterator end = info_.end();
416 for (; ci != end; ++ci) {
417 switch (ci->type()) {
418 case ParamInfo::LYX_INTERNAL:
421 case ParamInfo::LATEX_REQUIRED:
424 case ParamInfo::LATEX_OPTIONAL: {
425 std::string const & name = ci->name();
426 docstring const & data = (*this)[name];
438 docstring InsetCommandParams::prepareCommand(OutputParams const & runparams,
439 docstring const & command,
440 ParamInfo::ParamHandling handling) const
443 bool ltrimmed = false;
444 // Trimming can be done on top of any of the other handlings
445 // We check this here since handling might be changed below.
446 if (handling & ParamInfo::HANDLING_LTRIM) {
447 // this is used if no other handling is done
451 if (handling & ParamInfo::HANDLING_LATEXIFY
452 || handling & ParamInfo::HANDLING_INDEX_ESCAPE)
453 if ((*this)["literal"] == "true")
454 handling = ParamInfo::HANDLING_NONE;
456 // LATEXIFY, ESCAPE and NONE are mutually exclusive
457 if (handling & ParamInfo::HANDLING_LATEXIFY) {
458 // First handle backslash
459 result = subst(command, from_ascii("\\"), from_ascii("\\textbackslash{}"));
460 // Then get LaTeX macros
461 pair<docstring, docstring> command_latexed =
462 runparams.encoding->latexString(result, runparams.dryrun);
463 result = command_latexed.first;
464 if (!command_latexed.second.empty()) {
465 // Issue a warning about omitted characters
466 // FIXME: should be passed to the error dialog
467 frontend::Alert::warning(_("Uncodable characters"),
468 bformat(_("The following characters that are used in the inset %1$s are not\n"
469 "representable in the current encoding and therefore have been omitted:\n%2$s."),
470 from_utf8(insetType()), command_latexed.second));
472 // Now escape special commands
473 static docstring const backslash = from_ascii("\\");
474 int const nchars_escape = 8;
475 static char_type const chars_escape[nchars_escape] = {
476 '&', '_', '$', '%', '#', '^', '{', '}'};
478 if (!result.empty()) {
480 // The characters in chars_name[] need to be changed to a command when
481 // they are LaTeXified.
482 for (int k = 0; k < nchars_escape; k++)
483 for (size_t i = 0, pos;
484 (pos = result.find(chars_escape[k], i)) != string::npos;
486 //(Only) \\^ needs to be terminated
487 docstring const term = (k == 5) ? from_ascii("{}") : docstring();
492 // only if not already escaped
493 if (result[previous] != '\\')
494 result.replace(pos, 1, backslash + chars_escape[k] + term);
498 else if (handling & ParamInfo::HANDLING_ESCAPE)
499 result = escape(command);
500 else if (handling & ParamInfo::HANDLING_NONE) {
501 // we can only output characters covered by the current
504 for (size_type i = 0 ; i < command.size() ; ++i) {
505 char_type c = command[i];
507 if (runparams.encoding->encodable(c))
509 else if (runparams.dryrun) {
510 result += "<" + _("LyX Warning: ")
511 + _("uncodable character") + " '";
512 result += docstring(1, c);
516 } catch (EncodingException & /* e */) {
517 if (runparams.dryrun) {
518 result += "<" + _("LyX Warning: ")
519 + _("uncodable character") + " '";
520 result += docstring(1, c);
526 if (!uncodable.empty() && !runparams.silent) {
527 // issue a warning about omitted characters
528 // FIXME: should be passed to the error dialog
529 frontend::Alert::warning(_("Uncodable characters in inset"),
530 bformat(_("The following characters in one of the insets are\n"
531 "not representable in the current encoding and have been omitted: %1$s.\n"
532 "Unchecking 'Literal' in the respective inset dialog might help."),
536 // INDEX_ESCAPE is independent of the others
537 if (handling & ParamInfo::HANDLING_INDEX_ESCAPE) {
538 // Now escape special commands
539 static docstring const quote = from_ascii("\"");
540 int const nchars_escape = 4;
541 static char_type const chars_escape[nchars_escape] = { '"', '@', '|', '!' };
543 if (!result.empty()) {
544 // The characters in chars_name[] need to be changed to a command when
545 // they are LaTeXified.
546 for (int k = 0; k < nchars_escape; k++)
547 for (size_t i = 0, pos;
548 (pos = result.find(chars_escape[k], i)) != string::npos;
550 result.replace(pos, 1, quote + chars_escape[k]);
554 return ltrimmed ? ltrim(result) : result;
558 docstring InsetCommandParams::getCommand(OutputParams const & runparams) const
560 docstring s = '\\' + from_ascii(cmdName_);
562 ParamInfo::const_iterator it = info_.begin();
563 ParamInfo::const_iterator end = info_.end();
564 for (; it != end; ++it) {
565 std::string const & name = it->name();
566 switch (it->type()) {
567 case ParamInfo::LYX_INTERNAL:
570 case ParamInfo::LATEX_REQUIRED: {
571 docstring const data =
572 prepareCommand(runparams, (*this)[name], it->handling());
573 s += '{' + data + '}';
577 case ParamInfo::LATEX_OPTIONAL: {
579 prepareCommand(runparams, (*this)[name], it->handling());
581 s += '[' + protectArgument(data) + ']';
583 } else if (writeEmptyOptional(it)) {
592 // Make sure that following stuff does not change the
599 docstring InsetCommandParams::getFirstNonOptParam() const
601 ParamInfo::const_iterator it =
602 find_if(info_.begin(), info_.end(),
603 [](ParamInfo::ParamData const & d) { return !d.isOptional(); });
604 LASSERT(it != info_.end(), return docstring());
605 return (*this)[it->name()];
609 docstring const & InsetCommandParams::operator[](string const & name) const
611 static const docstring dummy;
612 LASSERT(info_.hasParam(name), return dummy);
613 ParamMap::const_iterator data = params_.find(name);
614 if (data == params_.end() || data->second.empty())
616 ParamInfo::ParamData const & param = info_[name];
618 return param.defaultValue();
623 docstring & InsetCommandParams::operator[](string const & name)
625 LATTEST(info_.hasParam(name));
626 // this will add the name in release mode
627 ParamInfo::ParamData const & param = info_[name];
629 params_[name] = param.defaultValue();
630 return params_[name];
634 void InsetCommandParams::clear()
641 bool operator==(InsetCommandParams const & o1, InsetCommandParams const & o2)
643 return o1.insetCode_ == o2.insetCode_
644 && o1.cmdName_ == o2.cmdName_
645 && o1.info_ == o2.info_
646 && o1.params_ == o2.params_
647 && o1.preview_ == o2.preview_;
651 bool operator!=(InsetCommandParams const & o1, InsetCommandParams const & o2)