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