]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Fix coverity false positive
[features.git] / src / insets / InsetCitation.cpp
1 /**
2  * \file InsetCitation.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 Herbert Voß
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetCitation.h"
15
16 #include "BiblioInfo.h"
17 #include "Buffer.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "DispatchResult.h"
22 #include "FuncCode.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "LaTeXFeatures.h"
26 #include "output_xhtml.h"
27 #include "ParIterator.h"
28 #include "texstream.h"
29 #include "TocBackend.h"
30
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/FileNameList.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36
37 #include <algorithm>
38 #include <climits>
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44
45 ParamInfo InsetCitation::param_info_;
46
47
48 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
49         : InsetCommand(buf, p)
50 {
51         buffer().removeBiblioTempFiles();
52 }
53
54
55 InsetCitation::~InsetCitation()
56 {
57         if (isBufferLoaded())
58                 buffer().removeBiblioTempFiles();
59 }
60
61
62 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
63 {
64         // standard cite does only take one argument, but biblatex, jurabib
65         // and natbib extend this to two arguments, so
66         // we have to allow both here. InsetCitation takes care that
67         // LaTeX output is nevertheless correct.
68         if (param_info_.empty()) {
69                 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
70                                 ParamInfo::HANDLING_LATEXIFY);
71                 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
72                                 ParamInfo::HANDLING_LATEXIFY);
73                 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
74                 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
75                                 ParamInfo::HANDLING_LATEXIFY);
76                 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
77                                 ParamInfo::HANDLING_LATEXIFY);
78                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
79         }
80         return param_info_;
81 }
82
83
84 // We allow any command here, since we fall back to cite
85 // anyway if a command is not allowed by a style
86 bool InsetCitation::isCompatibleCommand(string const &)
87 {
88         return true;
89 }
90
91
92 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
93                                   vector<CitationStyle> const & valid_styles) const
94 {
95         CitationStyle cs = valid_styles[0];
96         cs.forceUpperCase = false;
97         cs.hasStarredVersion = false;
98
99         string normalized_input = input;
100         string::size_type const n = input.size() - 1;
101         if (isUpperCase(input[0]))
102                 normalized_input[0] = lowercase(input[0]);
103         if (input[n] == '*')
104                 normalized_input = normalized_input.substr(0, n);
105
106         string const alias = bp.getCiteAlias(normalized_input);
107         if (!alias.empty())
108                 normalized_input = alias;
109
110         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
111         vector<CitationStyle>::const_iterator end = valid_styles.end();
112         for (; it != end; ++it) {
113                 CitationStyle this_cs = *it;
114                 if (this_cs.name == normalized_input) {
115                         cs = *it;
116                         break;
117                 }
118         }
119
120         return cs;
121 }
122
123
124 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
125 {
126         switch (cmd.action()) {
127         case LFUN_INSET_MODIFY: {
128                 buffer().removeBiblioTempFiles();
129                 cache.recalculate = true;
130                 if (cmd.getArg(0) == "toggleparam") {
131                         string cmdname = getCmdName();
132                         string const alias =
133                                 buffer().masterParams().getCiteAlias(cmdname);
134                         if (!alias.empty())
135                                 cmdname = alias;
136                         string const par = cmd.getArg(1);
137                         string newcmdname = cmdname;
138                         if (par == "star") {
139                                 if (suffixIs(cmdname, "*"))
140                                         newcmdname = rtrim(cmdname, "*");
141                                 else
142                                         newcmdname = cmdname + "*";
143                         } else if (par == "casing") {
144                                 if (isUpperCase(cmdname[0]))
145                                         newcmdname[0] = lowercase(cmdname[0]);
146                                 else
147                                         newcmdname[0] = uppercase(newcmdname[0]);
148                         }
149                         cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
150                 }
151         }
152                 // fall through
153         default:
154                 InsetCommand::doDispatch(cur, cmd);
155         }
156 }
157
158
159 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
160         FuncStatus & status) const
161 {
162         switch (cmd.action()) {
163         // Handle the alias case
164         case LFUN_INSET_MODIFY:
165                 if (cmd.getArg(0) == "changetype") {
166                         string cmdname = getCmdName();
167                         string const alias =
168                                 buffer().masterParams().getCiteAlias(cmdname);
169                         if (!alias.empty())
170                                 cmdname = alias;
171                         if (suffixIs(cmdname, "*"))
172                                 cmdname = rtrim(cmdname, "*");
173                         string const newtype = cmd.getArg(1);
174                         status.setEnabled(isCompatibleCommand(newtype));
175                         status.setOnOff(newtype == cmdname);
176                 }
177                 if (cmd.getArg(0) == "toggleparam") {
178                         string cmdname = getCmdName();
179                         string const alias =
180                                 buffer().masterParams().getCiteAlias(cmdname);
181                         if (!alias.empty())
182                                 cmdname = alias;
183                         vector<CitationStyle> citation_styles =
184                                 buffer().masterParams().citeStyles();
185                         CitationStyle cs = getCitationStyle(buffer().masterParams(),
186                                                             cmdname, citation_styles);
187                         if (cmd.getArg(1) == "star") {
188                                 status.setEnabled(cs.hasStarredVersion);
189                                 status.setOnOff(suffixIs(cmdname, "*"));
190                         }
191                         else if (cmd.getArg(1) == "casing") {
192                                 status.setEnabled(cs.forceUpperCase);
193                                 status.setOnOff(isUpperCase(cmdname[0]));
194                         }
195                 }
196                 return true;
197         default:
198                 return InsetCommand::getStatus(cur, cmd, status);
199         }
200 }
201
202
203 bool InsetCitation::addKey(string const & key)
204 {
205         docstring const ukey = from_utf8(key);
206         docstring const & curkeys = getParam("key");
207         if (curkeys.empty()) {
208                 setParam("key", ukey);
209                 cache.recalculate = true;
210                 return true;
211         }
212
213         vector<docstring> keys = getVectorFromString(curkeys);
214         vector<docstring>::const_iterator it = keys.begin();
215         vector<docstring>::const_iterator en = keys.end();
216         for (; it != en; ++it) {
217                 if (*it == ukey) {
218                         LYXERR0("Key " << key << " already present.");
219                         return false;
220                 }
221         }
222         keys.push_back(ukey);
223         setParam("key", getStringFromVector(keys));
224         cache.recalculate = true;
225         return true;
226 }
227
228
229 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
230 {
231         Buffer const & buf = bv.buffer();
232         // Only after the buffer is loaded from file...
233         if (!buf.isFullyLoaded())
234                 return docstring();
235
236         BiblioInfo const & bi = buf.masterBibInfo();
237         if (bi.empty())
238                 return _("No bibliography defined!");
239
240         docstring const & key = getParam("key");
241         if (key.empty())
242                 return _("No citations selected!");
243
244         CiteItem ci;
245         ci.richtext = true;
246         vector<docstring> keys = getVectorFromString(key);
247         if (keys.size() == 1)
248                 return bi.getInfo(keys[0], buffer(), ci);
249
250         docstring tip;
251         tip += "<ol>";
252         int count = 0;
253         for (docstring const & key : keys) {
254                 docstring const key_info = bi.getInfo(key, buffer(), ci);
255                 // limit to reasonable size.
256                 if (count > 9 && keys.size() > 11) {
257                         tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
258                         tip += "<p>"
259                                 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
260                                 + "</p>";
261                         break;
262                 }
263                 if (key_info.empty())
264                         continue;
265                 tip += "<li>" + key_info + "</li>";
266                 ++count;
267         }
268         tip += "</ol>";
269         return tip;
270 }
271
272
273 namespace {
274
275 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
276                                   vector<CitationStyle> const & valid_styles)
277 {
278         CitationStyle cs = valid_styles[0];
279         cs.forceUpperCase = false;
280         cs.hasStarredVersion = false;
281
282         string normalized_input = input;
283         string::size_type const n = input.size() - 1;
284         if (isUpperCase(input[0]))
285                 normalized_input[0] = lowercase(input[0]);
286         if (input[n] == '*')
287                 normalized_input = normalized_input.substr(0, n);
288
289         string const alias = bp.getCiteAlias(normalized_input);
290         if (!alias.empty())
291                 normalized_input = alias;
292
293         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
294         vector<CitationStyle>::const_iterator end = valid_styles.end();
295         for (; it != end; ++it) {
296                 CitationStyle this_cs = *it;
297                 if (this_cs.name == normalized_input) {
298                         cs = *it;
299                         break;
300                 }
301         }
302
303         cs.forceUpperCase &= input[0] == uppercase(input[0]);
304         cs.hasStarredVersion &= input[n] == '*';
305
306         return cs;
307 }
308
309
310 inline docstring wrapCitation(docstring const & key,
311                 docstring const & content, bool for_xhtml)
312 {
313         if (!for_xhtml)
314                 return content;
315         // we have to do the escaping here, because we will ultimately
316         // write this as a raw string, so as not to escape the tags.
317         return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
318                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
319 }
320
321 } // anonymous namespace
322
323
324 map<docstring, docstring> InsetCitation::getQualifiedLists(docstring const p) const
325 {
326         vector<docstring> ps =
327                 getVectorFromString(p, from_ascii("\t"));
328         std::map<docstring, docstring> res;
329         for (docstring const & s: ps) {
330                 docstring key;
331                 docstring val = split(s, key, ' ');
332                 res[key] = val;
333         }
334         return res;
335 }
336
337 docstring InsetCitation::generateLabel(bool for_xhtml) const
338 {
339         docstring label;
340         label = complexLabel(for_xhtml);
341
342         // Fallback to fail-safe
343         if (label.empty())
344                 label = basicLabel(for_xhtml);
345
346         return label;
347 }
348
349
350 docstring InsetCitation::complexLabel(bool for_xhtml) const
351 {
352         Buffer const & buf = buffer();
353         // Only start the process off after the buffer is loaded from file.
354         if (!buf.isFullyLoaded())
355                 return docstring();
356
357         BiblioInfo const & biblist = buf.masterBibInfo();
358         if (biblist.empty())
359                 return docstring();
360
361         docstring const & key = getParam("key");
362         if (key.empty())
363                 return _("No citations selected!");
364
365         string cite_type = getCmdName();
366         bool const uppercase = isUpperCase(cite_type[0]);
367         if (uppercase)
368                 cite_type[0] = lowercase(cite_type[0]);
369         bool const starred = (cite_type[cite_type.size() - 1] == '*');
370         if (starred)
371                 cite_type = cite_type.substr(0, cite_type.size() - 1);
372
373         // handle alias
374         string const alias = buf.masterParams().getCiteAlias(cite_type);
375         if (!alias.empty())
376                 cite_type = alias;
377
378         // FIXME: allow to add cite macros
379         /*
380         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
381         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
382         */
383         docstring label;
384         vector<docstring> keys = getVectorFromString(key);
385         CitationStyle cs = getCitationStyle(buffer().masterParams(),
386                                             cite_type, buffer().masterParams().citeStyles());
387         bool const qualified = cs.hasQualifiedList
388                 && (keys.size() > 1
389                     || !getParam("pretextlist").empty()
390                     || !getParam("posttextlist").empty());
391         map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
392         map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
393
394         CiteItem ci;
395         ci.textBefore = getParam("before");
396         ci.textAfter = getParam("after");
397         ci.forceUpperCase = uppercase;
398         ci.Starred = starred;
399         ci.max_size = UINT_MAX;
400         ci.isQualified = qualified;
401         ci.pretexts = pres;
402         ci.posttexts = posts;
403         if (for_xhtml) {
404                 ci.max_key_size = UINT_MAX;
405                 ci.context = CiteItem::Export;
406         }
407         ci.richtext = for_xhtml;
408         label = biblist.getLabel(keys, buffer(), cite_type, ci);
409         return label;
410 }
411
412
413 docstring InsetCitation::basicLabel(bool for_xhtml) const
414 {
415         docstring keys = getParam("key");
416         docstring label;
417
418         docstring key;
419         do {
420                 // if there is no comma, then everything goes into key
421                 // and keys will be empty.
422                 keys = trim(split(keys, key, ','));
423                 key = trim(key);
424                 if (!label.empty())
425                         label += ", ";
426                 label += wrapCitation(key, key, for_xhtml);
427         } while (!keys.empty());
428
429         docstring const & after = getParam("after");
430         if (!after.empty())
431                 label += ", " + after;
432
433         return '[' + label + ']';
434 }
435
436 docstring InsetCitation::screenLabel() const
437 {
438         return cache.screen_label;
439 }
440
441
442 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
443 {
444         if (!cache.recalculate && buffer().citeLabelsValid())
445                 return;
446         // The label may have changed, so we have to re-create it.
447         docstring const glabel = generateLabel();
448         cache.recalculate = false;
449         cache.generated_label = glabel;
450         unsigned int const maxLabelChars = 45;
451         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
452         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
453 }
454
455
456 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
457                                                          UpdateType, TocBackend & backend) const
458 {
459         // NOTE
460         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations 
461         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
462         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
463         // then we will also need to change that routine.
464         docstring const tocitem = getParam("key");
465         TocBuilder & b = backend.builder("citation");
466         b.pushItem(cpit, tocitem, output_active);
467         b.pop();
468 }
469
470
471 int InsetCitation::plaintext(odocstringstream & os,
472        OutputParams const &, size_t) const
473 {
474         string const & cmd = getCmdName();
475         if (cmd == "nocite")
476                 return 0;
477
478         docstring const label = generateLabel(false);
479         os << label;
480         return label.size();
481 }
482
483
484 static docstring const cleanupWhitespace(docstring const & citelist)
485 {
486         docstring::const_iterator it  = citelist.begin();
487         docstring::const_iterator end = citelist.end();
488         // Paranoia check: make sure that there is no whitespace in here
489         // -- at least not behind commas or at the beginning
490         docstring result;
491         char_type last = ',';
492         for (; it != end; ++it) {
493                 if (*it != ' ')
494                         last = *it;
495                 if (*it != ' ' || last != ',')
496                         result += *it;
497         }
498         return result;
499 }
500
501
502 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
503 {
504         os << from_ascii("<citation>")
505            << cleanupWhitespace(getParam("key"))
506            << from_ascii("</citation>");
507         return 0;
508 }
509
510
511 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
512 {
513         string const & cmd = getCmdName();
514         if (cmd == "nocite")
515                 return docstring();
516
517         // have to output this raw, because generateLabel() will include tags
518         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
519
520         return docstring();
521 }
522
523
524 void InsetCitation::toString(odocstream & os) const
525 {
526         odocstringstream ods;
527         plaintext(ods, OutputParams(0));
528         os << ods.str();
529 }
530
531
532 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
533 {
534         os += screenLabel();
535 }
536
537
538 // Have to overwrite the default InsetCommand method in order to check that
539 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
540 // citations and then changes his mind, turning natbib support off. The output
541 // should revert to the default citation command as provided by the citation
542 // engine, e.g. \cite[]{} for the basic engine.
543 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
544 {
545         BiblioInfo const & bi = buffer().masterBibInfo();
546         docstring const key = getParam("key");
547         // "keyonly" command: output the plain key and stop.
548         if (getCmdName() == "keyonly") {
549                 // Special command to only return the key
550                 if (!bi.isBibtex(getParam("key")))
551                         // escape chars with bibitems
552                         os << escape(cleanupWhitespace(key));
553                 else
554                         os << cleanupWhitespace(key);
555                 return;
556         }
557         vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
558         CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
559                                                getCmdName(), citation_styles);
560         // FIXME UNICODE
561         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
562
563         // check if we have to do a qualified list
564         vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
565         bool const qualified = cs.hasQualifiedList
566                 && (!getParam("pretextlist").empty()
567                     || !getParam("posttextlist").empty());
568
569         if (runparams.inulemcmd > 0)
570                 os << "\\mbox{";
571
572         os << "\\" << cite_str;
573
574         if (qualified)
575                 os << "s";
576
577         docstring before = params().prepareCommand(runparams, getParam("before"),
578                                                    param_info_["before"].handling());
579         docstring after = params().prepareCommand(runparams, getParam("after"),
580                                                    param_info_["after"].handling());
581         if (!before.empty() && cs.textBefore) {
582                 if (qualified)
583                         os << '(' << protectArgument(before, '(', ')')
584                            << ")(" << protectArgument(after, '(', ')') << ')';
585                 else
586                         os << '[' << protectArgument(before) << "]["
587                            << protectArgument(after) << ']';
588         } else if (!after.empty() && cs.textAfter) {
589                 if (qualified)
590                         os << '(' << protectArgument(after, '(', ')') << ')';
591                 else
592                         os << '[' << protectArgument(after) << ']';
593         }
594
595         if (!bi.isBibtex(key))
596                 // escape chars with bibitems
597                 os << '{' << escape(cleanupWhitespace(key)) << '}';
598         else {
599                 if (qualified) {
600                         map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
601                         map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
602                         for (docstring const & k: keys) {
603                                 docstring bef = params().prepareCommand(runparams, pres[k],
604                                                                         param_info_["pretextlist"].handling());
605                                 docstring aft  = params().prepareCommand(runparams, posts[k],
606                                                                          param_info_["posttextlist"].handling());
607                                 if (!bef.empty())
608                                         os << '[' << protectArgument(bef)
609                                            << "][" << protectArgument(aft) << ']';
610                                 else if (!aft.empty())
611                                         os << '[' << protectArgument(aft) << ']';
612                                 os << '{' << k << '}';
613                         }
614                 } else
615                         os << '{' << cleanupWhitespace(key) << '}';
616         }
617
618         if (runparams.inulemcmd)
619                 os << "}";
620 }
621
622
623 string InsetCitation::contextMenuName() const
624 {
625         return "context-citation";
626 }
627
628
629 } // namespace lyx