]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCommandParams.cpp
074bd3adae14b19c38315d103390aa2dab540be7
[lyx.git] / src / insets / InsetCommandParams.cpp
1 /**
2  * \file InsetCommandParams.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Georg Baum
8  * \author Richard Heck
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14 #include <algorithm>
15
16 #include "InsetCommandParams.h"
17
18 #include "InsetBibitem.h"
19 #include "InsetBibtex.h"
20 #include "InsetCitation.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"
28 #include "InsetRef.h"
29 #include "InsetTOC.h"
30
31 #include "Buffer.h"
32 #include "Encoding.h"
33 #include "Lexer.h"
34 #include "OutputParams.h"
35
36 #include "frontends/alert.h"
37
38 #include "support/debug.h"
39 #include "support/docstream.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43
44 #include "support/lassert.h"
45
46 using namespace std;
47 using namespace lyx::support;
48
49
50 namespace lyx {
51
52 /// Get information for \p code and command \p cmdName.
53 /// Don't call this without first making sure the command name is
54 /// acceptable to the inset.
55 static ParamInfo const & findInfo(InsetCode code, string const & cmdName)
56 {
57         switch (code) {
58         case BIBITEM_CODE:
59                 return InsetBibitem::findInfo(cmdName);
60         case BIBTEX_CODE:
61                 return InsetBibtex::findInfo(cmdName);
62         case CITE_CODE:
63                 return InsetCitation::findInfo(cmdName);
64         case FLOAT_LIST_CODE:
65                 return InsetFloatList::findInfo(cmdName);
66         case HYPERLINK_CODE:
67                 return InsetHyperlink::findInfo(cmdName);
68         case INCLUDE_CODE:
69                 return InsetInclude::findInfo(cmdName);
70         case INDEX_PRINT_CODE:
71                 return InsetPrintIndex::findInfo(cmdName);
72         case LABEL_CODE:
73                 return InsetLabel::findInfo(cmdName);
74         case LINE_CODE:
75                 return InsetLine::findInfo(cmdName);
76         case NOMENCL_CODE:
77                 return InsetNomencl::findInfo(cmdName);
78         case NOMENCL_PRINT_CODE:
79                 return InsetPrintNomencl::findInfo(cmdName);
80         case REF_CODE:
81                 return InsetRef::findInfo(cmdName);
82         case TOC_CODE:
83                 return InsetTOC::findInfo(cmdName);
84         default:
85                 LATTEST(false);
86                 // fall through in release mode
87         }
88         static const ParamInfo pi;
89         return pi;
90 }
91
92
93 /////////////////////////////////////////////////////////////////////
94 //
95 // ParamInfo::ParamData
96 //
97 /////////////////////////////////////////////////////////////////////
98
99 ParamInfo::ParamData::ParamData(std::string const & s, ParamType t,
100                                 ParamHandling h)
101         : name_(s), type_(t), handling_(h)
102 {}
103
104
105 bool ParamInfo::ParamData::isOptional() const
106 {
107         return type_ == ParamInfo::LATEX_OPTIONAL;
108 }
109
110
111 bool ParamInfo::ParamData::operator==(ParamInfo::ParamData const & rhs) const
112 {
113         return name() == rhs.name() && type() == rhs.type()
114                 && handling() == rhs.handling();
115 }
116
117
118 bool ParamInfo::hasParam(std::string const & name) const
119 {
120         const_iterator it = begin();
121         const_iterator last = end();
122         for (; it != last; ++it) {
123                 if (it->name() == name)
124                         return true;
125         }
126         return false;
127 }
128
129
130 void ParamInfo::add(std::string const & name, ParamType type,
131                     ParamHandling handling)
132
133         info_.push_back(ParamData(name, type, handling)); 
134 }
135
136
137 bool ParamInfo::operator==(ParamInfo const & rhs) const
138 {
139         if (size() != rhs.size())
140                 return false;
141         return equal(begin(), end(), rhs.begin());
142 }
143
144
145 ParamInfo::ParamData const & 
146         ParamInfo::operator[](std::string const & name) const
147 {
148         const_iterator it = begin();
149         const_iterator last = end();
150         for (; it != last; ++it) {
151                 if (it->name() == name)
152                         return *it;
153         }
154         LATTEST(false);
155         // we will try to continue in release mode
156         static const ParamData pd("asdfghjkl", LYX_INTERNAL);
157         return pd;
158 }
159
160
161 /////////////////////////////////////////////////////////////////////
162 //
163 // InsetCommandParams
164 //
165 /////////////////////////////////////////////////////////////////////
166
167
168 InsetCommandParams::InsetCommandParams(InsetCode code)
169         : insetCode_(code), preview_(false)
170 {
171         cmdName_ = getDefaultCmd(code);
172         info_ = findInfo(code, cmdName_);
173 }
174
175
176 InsetCommandParams::InsetCommandParams(InsetCode code,
177         string const & cmdName)
178         : insetCode_(code), cmdName_(cmdName), preview_(false)
179 {
180         info_ = findInfo(code, cmdName);
181 }
182
183
184 std::string InsetCommandParams::insetType() const
185 {
186         return insetName(insetCode_);
187 }
188
189
190 string InsetCommandParams::getDefaultCmd(InsetCode code)
191 {
192         switch (code) {
193                 case BIBITEM_CODE: 
194                         return InsetBibitem::defaultCommand();
195                 case BIBTEX_CODE:
196                         return InsetBibtex::defaultCommand();
197                 case CITE_CODE:
198                         return InsetCitation::defaultCommand();
199                 case FLOAT_LIST_CODE:
200                         return InsetFloatList::defaultCommand();
201                 case HYPERLINK_CODE:
202                         return InsetHyperlink::defaultCommand();
203                 case INCLUDE_CODE:
204                         return InsetInclude::defaultCommand();
205                 case INDEX_PRINT_CODE:
206                         return InsetPrintIndex::defaultCommand();
207                 case LABEL_CODE:
208                         return InsetLabel::defaultCommand();
209                 case LINE_CODE:
210                         return InsetLine::defaultCommand();
211                 case NOMENCL_CODE:
212                         return InsetNomencl::defaultCommand();
213                 case NOMENCL_PRINT_CODE:
214                         return InsetPrintNomencl::defaultCommand();
215                 case REF_CODE:
216                         return InsetRef::defaultCommand();
217                 case TOC_CODE:
218                         return InsetTOC::defaultCommand();
219                 default:
220                         LATTEST(false);
221                         // fall through in release mode
222         }
223         return string();
224 }
225
226
227 bool InsetCommandParams::isCompatibleCommand(InsetCode code, string const & s)
228 {
229         switch (code) {
230                 case BIBITEM_CODE: 
231                         return InsetBibitem::isCompatibleCommand(s);
232                 case BIBTEX_CODE:
233                         return InsetBibtex::isCompatibleCommand(s);
234                 case CITE_CODE:
235                         return InsetCitation::isCompatibleCommand(s);
236                 case FLOAT_LIST_CODE:
237                         return InsetFloatList::isCompatibleCommand(s);
238                 case HYPERLINK_CODE:
239                         return InsetHyperlink::isCompatibleCommand(s);
240                 case INCLUDE_CODE:
241                         return InsetInclude::isCompatibleCommand(s);
242                 case INDEX_PRINT_CODE:
243                         return InsetPrintIndex::isCompatibleCommand(s);
244                 case LABEL_CODE:
245                         return InsetLabel::isCompatibleCommand(s);
246                 case LINE_CODE:
247                         return InsetLine::isCompatibleCommand(s);
248                 case NOMENCL_CODE:
249                         return InsetNomencl::isCompatibleCommand(s);
250                 case NOMENCL_PRINT_CODE:
251                         return InsetPrintNomencl::isCompatibleCommand(s);
252                 case REF_CODE:
253                         return InsetRef::isCompatibleCommand(s);
254                 case TOC_CODE:
255                         return InsetTOC::isCompatibleCommand(s);
256         default:
257                 LATTEST(false);
258                 // fall through in release mode
259         }
260         return false;
261 }
262
263
264 void InsetCommandParams::setCmdName(string const & name)
265 {
266         if (!isCompatibleCommand(insetCode_, name)) {
267                 LYXERR0("InsetCommand: Incompatible command name " << 
268                                 name << ".");
269                 throw ExceptionMessage(WarningException, _("InsetCommand Error: "),
270                                        _("Incompatible command name."));
271         }
272
273         cmdName_ = name;
274         info_ = findInfo(insetCode_, cmdName_);
275 }
276
277
278 void InsetCommandParams::read(Lexer & lex)
279 {
280         lex.setContext("InsetCommandParams::read");
281         lex >> insetName(insetCode_).c_str();
282         lex >> "LatexCommand";
283         lex >> cmdName_;
284         if (!isCompatibleCommand(insetCode_, cmdName_)) {
285                 lex.printError("Incompatible command name " + cmdName_ + ".");
286                 throw ExceptionMessage(WarningException, _("InsetCommandParams Error: "),
287                                        _("Incompatible command name."));
288         }
289
290         info_ = findInfo(insetCode_, cmdName_);
291         
292         string token;
293         while (lex.isOK()) {
294                 lex.next();
295                 token = lex.getString();
296                 if (token == "\\end_inset")
297                         break;
298                 if (token == "preview") {
299                         lex.next();
300                         preview_ = lex.getBool();
301                         continue;
302                 }
303                 if (info_.hasParam(token)) {
304                         lex.next(true);
305                         params_[token] = lex.getDocString();
306                 } else {
307                         lex.printError("Unknown parameter name `$$Token' for command " + cmdName_);
308                         throw ExceptionMessage(WarningException,
309                                 _("InsetCommandParams: ") + from_ascii(cmdName_),
310                                 _("Unknown parameter name: ") + from_utf8(token));
311                 }
312         }
313         if (token != "\\end_inset") {
314                 lex.printError("Missing \\end_inset at this point. "
315                                "Read: `$$Token'");
316                 throw ExceptionMessage(WarningException,
317                         _("InsetCommandParams Error: "),
318                         _("Missing \\end_inset at this point: ") + from_utf8(token));
319         }
320 }
321
322
323 void InsetCommandParams::write(ostream & os) const
324 {
325         Write(os, 0);
326 }
327
328
329 void InsetCommandParams::Write(ostream & os, Buffer const * buffer) const
330 {
331         os << "CommandInset " << insetType() << '\n';
332         os << "LatexCommand " << cmdName_ << '\n';
333         if (preview_)
334                 os << "preview true\n";
335         ParamInfo::const_iterator it  = info_.begin();
336         ParamInfo::const_iterator end = info_.end();
337         for (; it != end; ++it) {
338                 string const & name = it->name();
339                 string data = to_utf8((*this)[name]);
340                 if (!data.empty()) {
341                         // Adjust path of files if document was moved
342                         if (buffer && name == "filename") {
343                                 data = buffer->includedFilePath(data);
344                         } else if (buffer && name == "bibfiles") {
345                                 int i = 0;
346                                 string newdata;
347                                 string bib = token(data, ',', i);
348                                 while (!bib.empty()) {
349                                         bib = buffer->includedFilePath(bib, "bib");
350                                         if (!newdata.empty())
351                                                 newdata.append(1, ',');
352                                         newdata.append(bib);
353                                         bib = token(data, ',', ++i);
354                                 }
355                                 data = newdata;
356                         }
357                         os << name << ' '
358                            << Lexer::quoteString(data)
359                            << '\n';
360                 }
361         }
362 }
363
364
365 bool InsetCommandParams::writeEmptyOptional(ParamInfo::const_iterator ci) const
366 {
367         LASSERT(ci->isOptional(), return false);
368
369         ++ci; // we want to start with the next one
370         ParamInfo::const_iterator end = info_.end();
371         for (; ci != end; ++ci) {
372                 switch (ci->type()) {
373                 case ParamInfo::LYX_INTERNAL:
374                         break;
375
376                 case ParamInfo::LATEX_REQUIRED:
377                         return false;
378
379                 case ParamInfo::LATEX_OPTIONAL: {
380                         std::string const & name = ci->name();
381                         docstring const & data = (*this)[name];
382                         if (!data.empty())
383                                 return true;
384                         break;
385                 }
386
387                 } //end switch
388         }
389         return false;
390 }
391
392
393 docstring InsetCommandParams::prepareCommand(OutputParams const & runparams,
394                                              docstring const & command,
395                                              ParamInfo::ParamHandling handling) const
396 {
397         docstring result;
398         switch (handling) {
399         case ParamInfo::HANDLING_LATEXIFY: {
400                 pair<docstring, docstring> command_latexed =
401                         runparams.encoding->latexString(command, runparams.dryrun);
402                 result = command_latexed.first;
403                 if (!command_latexed.second.empty()) {
404                         // issue a warning about omitted characters
405                         // FIXME: should be passed to the error dialog
406                         frontend::Alert::warning(_("Uncodable characters"),
407                                 bformat(_("The following characters that are used in the inset %1$s are not\n"
408                                           "representable in the current encoding and therefore have been omitted:\n%2$s."),
409                                         from_utf8(insetType()), command_latexed.second));
410                 }
411                 break;
412         } 
413         case ParamInfo::HANDLING_ESCAPE:
414                 result = escape(command);
415                 break;
416         case ParamInfo::HANDLING_NONE:
417                 result = command;
418                 break;
419         } // switch
420
421         return result;
422 }
423
424
425 docstring InsetCommandParams::getCommand(OutputParams const & runparams) const
426 {
427         docstring s = '\\' + from_ascii(cmdName_);
428         bool noparam = true;
429         ParamInfo::const_iterator it  = info_.begin();
430         ParamInfo::const_iterator end = info_.end();
431         for (; it != end; ++it) {
432                 std::string const & name = it->name();
433                 switch (it->type()) {
434                 case ParamInfo::LYX_INTERNAL:
435                         break;
436
437                 case ParamInfo::LATEX_REQUIRED: {
438                         docstring const data =
439                                 prepareCommand(runparams, (*this)[name], it->handling());
440                         s += '{' + data + '}';
441                         noparam = false;
442                         break;
443                 }
444                 case ParamInfo::LATEX_OPTIONAL: {
445                         docstring const data =
446                                 prepareCommand(runparams, (*this)[name], it->handling());
447                         if (!data.empty()) {
448                                 s += '[' + data + ']';
449                                 noparam = false;
450                         } else if (writeEmptyOptional(it)) {
451                                         s += "[]";
452                                         noparam = false;
453                         }
454                         break;
455                 } 
456                 } //end switch
457         }
458         if (noparam)
459                 // Make sure that following stuff does not change the
460                 // command name.
461                 s += "{}";
462         return s;
463 }
464
465
466 docstring InsetCommandParams::getFirstNonOptParam() const
467 {
468         ParamInfo::const_iterator it = 
469                 find_if(info_.begin(), info_.end(), 
470                         not1(mem_fun_ref(&ParamInfo::ParamData::isOptional)));
471         LASSERT(it != info_.end(), return docstring());
472         return (*this)[it->name()];
473 }
474
475
476 docstring const & InsetCommandParams::operator[](string const & name) const
477 {
478         static const docstring dummy;
479         LASSERT(info_.hasParam(name), return dummy);
480         ParamMap::const_iterator data = params_.find(name);
481         if (data == params_.end() || data->second.empty())
482                 return dummy;
483         return data->second;
484 }
485
486
487 docstring & InsetCommandParams::operator[](string const & name)
488 {
489         LATTEST(info_.hasParam(name));
490         // this will add the name in release mode
491         return params_[name];
492 }
493
494
495 void InsetCommandParams::clear()
496 {
497         params_.clear();
498 }
499
500
501 bool operator==(InsetCommandParams const & o1, InsetCommandParams const & o2)
502 {
503         return o1.insetCode_ == o2.insetCode_
504                 && o1.cmdName_ == o2.cmdName_
505                 && o1.info_ == o2.info_
506                 && o1.params_ == o2.params_
507                 && o1.preview_ == o2.preview_;
508 }
509
510
511 bool operator!=(InsetCommandParams const & o1, InsetCommandParams const & o2)
512 {
513         return !(o1 == o2);
514 }
515
516
517 } // namespace lyx