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