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 "InsetFloatList.h"
24 #include "InsetHyperlink.h"
25 #include "InsetInclude.h"
26 #include "InsetIndex.h"
27 #include "InsetLabel.h"
28 #include "InsetLine.h"
29 #include "InsetNomencl.h"
36 #include "OutputParams.h"
38 #include "frontends/alert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/ExceptionMessage.h"
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
46 #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 InsetFloatList::findInfo(cmdName);
69 return InsetHyperlink::findInfo(cmdName);
71 return InsetInclude::findInfo(cmdName);
72 case INDEX_PRINT_CODE:
73 return InsetPrintIndex::findInfo(cmdName);
75 return InsetLabel::findInfo(cmdName);
77 return InsetLine::findInfo(cmdName);
79 return InsetNomencl::findInfo(cmdName);
80 case NOMENCL_PRINT_CODE:
81 return InsetPrintNomencl::findInfo(cmdName);
83 return InsetRef::findInfo(cmdName);
85 return InsetTOC::findInfo(cmdName);
88 // fall through in release mode
90 static const ParamInfo pi;
95 /////////////////////////////////////////////////////////////////////
97 // ParamInfo::ParamData
99 /////////////////////////////////////////////////////////////////////
101 ParamInfo::ParamData::ParamData(std::string const & s, ParamType t,
102 ParamHandling h, bool ignore,
103 docstring default_value)
104 : name_(s), type_(t), handling_(h), ignore_(ignore),
105 default_value_(default_value)
109 bool ParamInfo::ParamData::isOptional() const
111 return type_ == ParamInfo::LATEX_OPTIONAL;
115 bool ParamInfo::ParamData::operator==(ParamInfo::ParamData const & rhs) const
117 return name() == rhs.name() && type() == rhs.type()
118 && handling() == rhs.handling();
122 bool ParamInfo::hasParam(std::string const & name) const
124 const_iterator it = begin();
125 const_iterator last = end();
126 for (; it != last; ++it) {
127 if (it->name() == name)
134 void ParamInfo::add(std::string const & name, ParamType type,
135 ParamHandling handling, bool ignoreval,
136 docstring default_value)
138 info_.push_back(ParamData(name, type, handling, ignoreval, default_value));
142 bool ParamInfo::operator==(ParamInfo const & rhs) const
144 if (size() != rhs.size())
146 return equal(begin(), end(), rhs.begin());
150 ParamInfo::ParamData const &
151 ParamInfo::operator[](std::string const & name) const
153 const_iterator it = begin();
154 const_iterator last = end();
155 for (; it != last; ++it) {
156 if (it->name() == name)
160 // we will try to continue in release mode
161 static const ParamData pd("asdfghjkl", LYX_INTERNAL);
166 /////////////////////////////////////////////////////////////////////
168 // InsetCommandParams
170 /////////////////////////////////////////////////////////////////////
173 InsetCommandParams::InsetCommandParams(InsetCode code)
174 : insetCode_(code), preview_(false)
176 cmdName_ = getDefaultCmd(code);
177 info_ = findInfo(code, cmdName_);
181 InsetCommandParams::InsetCommandParams(InsetCode code,
182 string const & cmdName)
183 : insetCode_(code), cmdName_(cmdName), preview_(false)
185 info_ = findInfo(code, cmdName);
189 std::string InsetCommandParams::insetType() const
191 return insetName(insetCode_);
195 string InsetCommandParams::getDefaultCmd(InsetCode code)
199 return InsetBibitem::defaultCommand();
201 return InsetBibtex::defaultCommand();
203 return InsetCitation::defaultCommand();
204 case FLOAT_LIST_CODE:
205 return InsetFloatList::defaultCommand();
207 return InsetHyperlink::defaultCommand();
209 return InsetInclude::defaultCommand();
210 case INDEX_PRINT_CODE:
211 return InsetPrintIndex::defaultCommand();
213 return InsetLabel::defaultCommand();
215 return InsetLine::defaultCommand();
217 return InsetNomencl::defaultCommand();
218 case NOMENCL_PRINT_CODE:
219 return InsetPrintNomencl::defaultCommand();
221 return InsetRef::defaultCommand();
223 return InsetTOC::defaultCommand();
226 // fall through in release mode
232 bool InsetCommandParams::isCompatibleCommand(InsetCode code, string const & s)
236 return InsetBibitem::isCompatibleCommand(s);
238 return InsetBibtex::isCompatibleCommand(s);
240 return InsetCitation::isCompatibleCommand(s);
241 case FLOAT_LIST_CODE:
242 return InsetFloatList::isCompatibleCommand(s);
244 return InsetHyperlink::isCompatibleCommand(s);
246 return InsetInclude::isCompatibleCommand(s);
247 case INDEX_PRINT_CODE:
248 return InsetPrintIndex::isCompatibleCommand(s);
250 return InsetLabel::isCompatibleCommand(s);
252 return InsetLine::isCompatibleCommand(s);
254 return InsetNomencl::isCompatibleCommand(s);
255 case NOMENCL_PRINT_CODE:
256 return InsetPrintNomencl::isCompatibleCommand(s);
258 return InsetRef::isCompatibleCommand(s);
260 return InsetTOC::isCompatibleCommand(s);
263 // fall through in release mode
269 void InsetCommandParams::setCmdName(string const & name)
271 if (!isCompatibleCommand(insetCode_, name)) {
272 LYXERR0("InsetCommand: Incompatible command name " <<
274 throw ExceptionMessage(WarningException, _("InsetCommand Error: "),
275 _("Incompatible command name."));
279 info_ = findInfo(insetCode_, cmdName_);
283 void InsetCommandParams::read(Lexer & lex)
289 void InsetCommandParams::Read(Lexer & lex, Buffer const * buffer)
291 lex.setContext("InsetCommandParams::read");
292 lex >> insetName(insetCode_).c_str();
293 lex >> "LatexCommand";
295 if (!isCompatibleCommand(insetCode_, cmdName_)) {
296 lex.printError("Incompatible command name " + cmdName_ + ".");
297 throw ExceptionMessage(WarningException, _("InsetCommandParams Error: "),
298 _("Incompatible command name."));
301 info_ = findInfo(insetCode_, cmdName_);
303 for (ParamInfo::ParamData const & param : info_)
304 if (param.ignore()) {
305 params_[param.name()] = param.defaultValue();
311 token = lex.getString();
312 if (token == "\\end_inset")
314 if (token == "preview") {
316 preview_ = lex.getBool();
319 if (info_.hasParam(token)) {
321 docstring data = lex.getDocString();
322 if (buffer && token == "filename") {
323 data = from_utf8(buffer->includedFilePath(to_utf8(data)));
324 } else if (buffer && token == "bibfiles") {
327 docstring bib = support::token(data, ',', i);
328 while (!bib.empty()) {
329 bib = from_utf8(buffer->includedFilePath(to_utf8(bib), "bib"));
330 if (!newdata.empty())
331 newdata.append(1, ',');
333 bib = support::token(data, ',', ++i);
336 } else if (buffer && token == "options") {
337 data = from_utf8(buffer->includedFilePath(to_utf8(data), "bst"));
339 params_[token] = data;
341 lex.printError("Unknown parameter name `$$Token' for command " + cmdName_);
342 throw ExceptionMessage(WarningException,
343 _("InsetCommandParams: ") + from_ascii(cmdName_),
344 _("Unknown parameter name: ") + from_utf8(token));
347 if (token != "\\end_inset") {
348 lex.printError("Missing \\end_inset at this point. "
350 throw ExceptionMessage(WarningException,
351 _("InsetCommandParams Error: "),
352 _("Missing \\end_inset at this point: ") + from_utf8(token));
357 void InsetCommandParams::write(ostream & os) const
363 void InsetCommandParams::Write(ostream & os, Buffer const * buffer) const
365 os << "CommandInset " << insetType() << '\n';
366 os << "LatexCommand " << cmdName_ << '\n';
368 os << "preview true\n";
369 ParamInfo::const_iterator it = info_.begin();
370 ParamInfo::const_iterator end = info_.end();
371 for (; it != end; ++it) {
374 string const & name = it->name();
375 string data = to_utf8((*this)[name]);
377 // Adjust path of files if document was moved
378 if (buffer && name == "filename") {
379 data = buffer->includedFilePath(data);
380 } else if (buffer && name == "bibfiles") {
383 string bib = token(data, ',', i);
384 while (!bib.empty()) {
385 bib = buffer->includedFilePath(bib, "bib");
386 if (!newdata.empty())
387 newdata.append(1, ',');
389 bib = token(data, ',', ++i);
392 } else if (buffer && name == "options") {
393 data = buffer->includedFilePath(data, "bst");
396 << Lexer::quoteString(data)
403 bool InsetCommandParams::writeEmptyOptional(ParamInfo::const_iterator ci) const
405 LASSERT(ci->isOptional(), return false);
407 ++ci; // we want to start with the next one
408 ParamInfo::const_iterator end = info_.end();
409 for (; ci != end; ++ci) {
410 switch (ci->type()) {
411 case ParamInfo::LYX_INTERNAL:
414 case ParamInfo::LATEX_REQUIRED:
417 case ParamInfo::LATEX_OPTIONAL: {
418 std::string const & name = ci->name();
419 docstring const & data = (*this)[name];
431 docstring InsetCommandParams::prepareCommand(OutputParams const & runparams,
432 docstring const & command,
433 ParamInfo::ParamHandling handling) const
436 bool ltrimmed = false;
437 // Trimming can be done on top of any of the other handlings
438 // We check this here since handling might be changed below.
439 if (handling & ParamInfo::HANDLING_LTRIM) {
440 // this is used if no other handling is done
444 if (handling & ParamInfo::HANDLING_LATEXIFY
445 || handling & ParamInfo::HANDLING_INDEX_ESCAPE)
446 if ((*this)["literal"] == "true")
447 handling = ParamInfo::HANDLING_NONE;
449 // LATEXIFY, ESCAPE and NONE are mutually exclusive
450 if (handling & ParamInfo::HANDLING_LATEXIFY) {
451 // First handle backslash
452 result = subst(command, from_ascii("\\"), from_ascii("\\textbackslash{}"));
453 // Then get LaTeX macros
454 pair<docstring, docstring> command_latexed =
455 runparams.encoding->latexString(result, runparams.dryrun);
456 result = command_latexed.first;
457 if (!command_latexed.second.empty()) {
458 // Issue a warning about omitted characters
459 // FIXME: should be passed to the error dialog
460 frontend::Alert::warning(_("Uncodable characters"),
461 bformat(_("The following characters that are used in the inset %1$s are not\n"
462 "representable in the current encoding and therefore have been omitted:\n%2$s."),
463 from_utf8(insetType()), command_latexed.second));
465 // Now escape special commands
466 static docstring const backslash = from_ascii("\\");
467 int const nchars_escape = 8;
468 static char_type const chars_escape[nchars_escape] = {
469 '&', '_', '$', '%', '#', '^', '{', '}'};
471 if (!result.empty()) {
473 // The characters in chars_name[] need to be changed to a command when
474 // they are LaTeXified.
475 for (int k = 0; k < nchars_escape; k++)
476 for (size_t i = 0, pos;
477 (pos = result.find(chars_escape[k], i)) != string::npos;
479 //(Only) \\^ needs to be terminated
480 docstring const term = (k == 5) ? from_ascii("{}") : docstring();
485 // only if not already escaped
486 if (result[previous] != '\\')
487 result.replace(pos, 1, backslash + chars_escape[k] + term);
491 else if (handling & ParamInfo::HANDLING_ESCAPE)
492 result = escape(command);
493 else if (handling & ParamInfo::HANDLING_NONE) {
494 // we can only output characters covered by the current
497 for (size_type i = 0 ; i < command.size() ; ++i) {
498 char_type c = command[i];
500 if (runparams.encoding->encodable(c))
502 else if (runparams.dryrun) {
503 result += "<" + _("LyX Warning: ")
504 + _("uncodable character") + " '";
505 result += docstring(1, c);
509 } catch (EncodingException & /* e */) {
510 if (runparams.dryrun) {
511 result += "<" + _("LyX Warning: ")
512 + _("uncodable character") + " '";
513 result += docstring(1, c);
519 if (!uncodable.empty() && !runparams.silent) {
520 // issue a warning about omitted characters
521 // FIXME: should be passed to the error dialog
522 frontend::Alert::warning(_("Uncodable characters in inset"),
523 bformat(_("The following characters in one of the insets are\n"
524 "not representable in the current encoding and have been omitted:\n%1$s."),
528 // INDEX_ESCAPE is independent of the others
529 if (handling & ParamInfo::HANDLING_INDEX_ESCAPE) {
530 // Now escape special commands
531 static docstring const quote = from_ascii("\"");
532 int const nchars_escape = 4;
533 static char_type const chars_escape[nchars_escape] = { '"', '@', '|', '!' };
535 if (!result.empty()) {
536 // The characters in chars_name[] need to be changed to a command when
537 // they are LaTeXified.
538 for (int k = 0; k < nchars_escape; k++)
539 for (size_t i = 0, pos;
540 (pos = result.find(chars_escape[k], i)) != string::npos;
542 result.replace(pos, 1, quote + chars_escape[k]);
546 return ltrimmed ? ltrim(result) : result;
550 docstring InsetCommandParams::getCommand(OutputParams const & runparams) const
552 docstring s = '\\' + from_ascii(cmdName_);
554 ParamInfo::const_iterator it = info_.begin();
555 ParamInfo::const_iterator end = info_.end();
556 for (; it != end; ++it) {
557 std::string const & name = it->name();
558 switch (it->type()) {
559 case ParamInfo::LYX_INTERNAL:
562 case ParamInfo::LATEX_REQUIRED: {
563 docstring const data =
564 prepareCommand(runparams, (*this)[name], it->handling());
565 s += '{' + data + '}';
569 case ParamInfo::LATEX_OPTIONAL: {
571 prepareCommand(runparams, (*this)[name], it->handling());
573 s += '[' + protectArgument(data) + ']';
575 } else if (writeEmptyOptional(it)) {
584 // Make sure that following stuff does not change the
591 docstring InsetCommandParams::getFirstNonOptParam() const
593 ParamInfo::const_iterator it =
594 find_if(info_.begin(), info_.end(),
595 not1(mem_fun_ref(&ParamInfo::ParamData::isOptional)));
596 LASSERT(it != info_.end(), return docstring());
597 return (*this)[it->name()];
601 docstring const & InsetCommandParams::operator[](string const & name) const
603 static const docstring dummy;
604 LASSERT(info_.hasParam(name), return dummy);
605 ParamMap::const_iterator data = params_.find(name);
606 if (data == params_.end() || data->second.empty())
608 ParamInfo::ParamData const & param = info_[name];
610 return param.defaultValue();
615 docstring & InsetCommandParams::operator[](string const & name)
617 LATTEST(info_.hasParam(name));
618 // this will add the name in release mode
619 ParamInfo::ParamData const & param = info_[name];
621 params_[name] = param.defaultValue();
622 return params_[name];
626 void InsetCommandParams::clear()
632 bool operator==(InsetCommandParams const & o1, InsetCommandParams const & o2)
634 return o1.insetCode_ == o2.insetCode_
635 && o1.cmdName_ == o2.cmdName_
636 && o1.info_ == o2.info_
637 && o1.params_ == o2.params_
638 && o1.preview_ == o2.preview_;
642 bool operator!=(InsetCommandParams const & o1, InsetCommandParams const & o2)