]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
Internal buffers are valid
[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 "Font.h"
23 #include "FuncCode.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "output_xhtml.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 & key : keys) {
263                 docstring const key_info = bi.getInfo(key, 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-" + html::cleanAttr(key) + "'>" +
327                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
328 }
329
330 } // anonymous namespace
331
332
333 map<docstring, docstring> InsetCitation::getQualifiedLists(docstring const p) const
334 {
335         vector<docstring> ps =
336                 getVectorFromString(p, from_ascii("\t"));
337         std::map<docstring, docstring> res;
338         for (docstring const & s: ps) {
339                 docstring key;
340                 docstring val = split(s, key, ' ');
341                 res[key] = val;
342         }
343         return res;
344 }
345
346 docstring InsetCitation::generateLabel(bool for_xhtml) const
347 {
348         docstring label;
349         label = complexLabel(for_xhtml);
350
351         // Fallback to fail-safe
352         if (label.empty())
353                 label = basicLabel(for_xhtml);
354
355         return label;
356 }
357
358
359 docstring InsetCitation::complexLabel(bool for_xhtml) const
360 {
361         Buffer const & buf = buffer();
362         // Only start the process off after the buffer is loaded from file.
363         if (!buf.isFullyLoaded())
364                 return docstring();
365
366         BiblioInfo const & biblist = buf.masterBibInfo();
367         if (biblist.empty())
368                 return docstring();
369
370         docstring const & key = getParam("key");
371         if (key.empty())
372                 return _("No citations selected!");
373
374         string cite_type = getCmdName();
375         bool const uppercase = isUpperCase(cite_type[0]);
376         if (uppercase)
377                 cite_type[0] = lowercase(cite_type[0]);
378         bool const starred = (cite_type[cite_type.size() - 1] == '*');
379         if (starred)
380                 cite_type = cite_type.substr(0, cite_type.size() - 1);
381
382         // handle alias
383         string const alias = buf.masterParams().getCiteAlias(cite_type);
384         if (!alias.empty())
385                 cite_type = alias;
386
387         // FIXME: allow to add cite macros
388         /*
389         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
390         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
391         */
392         docstring label;
393         // we only really want the last 'false', to suppress trimming, but
394         // we need to give the other defaults, too, to set it.
395         vector<docstring> keys =
396                 getVectorFromString(key, from_ascii(","), false, false);
397         CitationStyle cs = getCitationStyle(buffer().masterParams(),
398                         cite_type, buffer().masterParams().citeStyles());
399         bool const qualified = cs.hasQualifiedList
400                 && (keys.size() > 1
401                     || !getParam("pretextlist").empty()
402                     || !getParam("posttextlist").empty());
403         map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
404         map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
405
406         CiteItem ci;
407         ci.textBefore = getParam("before");
408         ci.textAfter = getParam("after");
409         ci.forceUpperCase = uppercase;
410         ci.Starred = starred;
411         ci.max_size = UINT_MAX;
412         ci.isQualified = qualified;
413         ci.pretexts = pres;
414         ci.posttexts = posts;
415         if (for_xhtml) {
416                 ci.max_key_size = UINT_MAX;
417                 ci.context = CiteItem::Export;
418         }
419         ci.richtext = for_xhtml;
420         label = biblist.getLabel(keys, buffer(), cite_type, ci);
421         return label;
422 }
423
424
425 docstring InsetCitation::basicLabel(bool for_xhtml) const
426 {
427         docstring keys = getParam("key");
428         docstring label;
429
430         docstring key;
431         do {
432                 // if there is no comma, then everything goes into key
433                 // and keys will be empty.
434                 keys = split(keys, key, ',');
435                 if (!label.empty())
436                         label += ", ";
437                 label += wrapCitation(key, key, for_xhtml);
438         } while (!keys.empty());
439
440         docstring const & after = getParam("after");
441         if (!after.empty())
442                 label += ", " + after;
443
444         return '[' + label + ']';
445 }
446
447
448 bool InsetCitation::forceLTR(OutputParams const & rp) const
449 {
450         // We have to force LTR for numeric references
451         // [= plain BibTeX, numeric natbib and biblatex].
452         // Except for XeTeX/bidi . See #3005.
453         if (rp.local_font->isRightToLeft()
454             && rp.use_polyglossia
455             && rp.flavor == OutputParams::XETEX)
456                 return false;
457         return (buffer().masterParams().citeEngine().list().front() == "basic"
458                 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
459 }
460
461 docstring InsetCitation::screenLabel() const
462 {
463         return cache.screen_label;
464 }
465
466
467 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
468 {
469         if (!cache.recalculate && buffer().citeLabelsValid())
470                 return;
471         // The label may have changed, so we have to re-create it.
472         docstring const glabel = generateLabel();
473         cache.recalculate = false;
474         cache.generated_label = glabel;
475         unsigned int const maxLabelChars = 45;
476         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
477         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
478 }
479
480
481 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
482                                                          UpdateType, TocBackend & backend) const
483 {
484         // NOTE
485         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
486         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
487         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
488         // then we will also need to change that routine.
489         docstring const tocitem = getParam("key");
490         TocBuilder & b = backend.builder("citation");
491         b.pushItem(cpit, tocitem, output_active);
492         b.pop();
493 }
494
495
496 int InsetCitation::plaintext(odocstringstream & os,
497        OutputParams const &, size_t) const
498 {
499         string const & cmd = getCmdName();
500         if (cmd == "nocite")
501                 return 0;
502
503         docstring const label = generateLabel(false);
504         os << label;
505         return label.size();
506 }
507
508
509 static docstring const cleanupWhitespace(docstring const & citelist)
510 {
511         docstring::const_iterator it  = citelist.begin();
512         docstring::const_iterator end = citelist.end();
513         // Paranoia check: make sure that there is no whitespace in here
514         // -- at least not behind commas or at the beginning
515         docstring result;
516         char_type last = ',';
517         for (; it != end; ++it) {
518                 if (*it != ' ')
519                         last = *it;
520                 if (*it != ' ' || last != ',')
521                         result += *it;
522         }
523         return result;
524 }
525
526
527 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
528 {
529         os << from_ascii("<citation>")
530            << cleanupWhitespace(getParam("key"))
531            << from_ascii("</citation>");
532         return 0;
533 }
534
535
536 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
537 {
538         string const & cmd = getCmdName();
539         if (cmd == "nocite")
540                 return docstring();
541
542         // have to output this raw, because generateLabel() will include tags
543         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
544
545         return docstring();
546 }
547
548
549 void InsetCitation::toString(odocstream & os) const
550 {
551         odocstringstream ods;
552         plaintext(ods, OutputParams(0));
553         os << ods.str();
554 }
555
556
557 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
558 {
559         os += screenLabel();
560 }
561
562
563 // Have to overwrite the default InsetCommand method in order to check that
564 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
565 // citations and then changes his mind, turning natbib support off. The output
566 // should revert to the default citation command as provided by the citation
567 // engine, e.g. \cite[]{} for the basic engine.
568 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
569 {
570         // When this is a child compiled on its own, we use the childs
571         // own bibinfo, else the master's
572         BiblioInfo const & bi = runparams.is_child
573                         ? buffer().masterBibInfo() : buffer().bibInfo();
574         docstring const key = getParam("key");
575         // "keyonly" command: output the plain key and stop.
576         if (getCmdName() == "keyonly") {
577                 // Special command to only return the key
578                 if (!bi.isBibtex(getParam("key")))
579                         // escape chars with bibitems
580                         os << escape(cleanupWhitespace(key));
581                 else
582                         os << cleanupWhitespace(key);
583                 return;
584         }
585         vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
586         CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
587                                                getCmdName(), citation_styles);
588         // FIXME UNICODE
589         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
590
591         // check if we have to do a qualified list
592         vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
593         bool const qualified = cs.hasQualifiedList
594                 && (!getParam("pretextlist").empty()
595                     || !getParam("posttextlist").empty());
596
597         if (runparams.inulemcmd > 0)
598                 os << "\\mbox{";
599
600         os << "\\" << cite_str;
601
602         if (qualified)
603                 os << "s";
604
605         ParamInfo const & pinfo = findInfo(string());
606         docstring before = params().prepareCommand(runparams, getParam("before"),
607                                                    pinfo["before"].handling());
608         docstring after = params().prepareCommand(runparams, getParam("after"),
609                                                    pinfo["after"].handling());
610         if (!before.empty() && cs.textBefore) {
611                 if (qualified)
612                         os << '(' << protectArgument(before, '(', ')')
613                            << ")(" << protectArgument(after, '(', ')') << ')';
614                 else
615                         os << '[' << protectArgument(before) << "]["
616                            << protectArgument(after) << ']';
617         } else if (!after.empty() && cs.textAfter) {
618                 if (qualified)
619                         os << '(' << protectArgument(after, '(', ')') << ')';
620                 else
621                         os << '[' << protectArgument(after) << ']';
622         }
623
624         if (!bi.isBibtex(key))
625                 // escape chars with bibitems
626                 os << '{' << escape(cleanupWhitespace(key)) << '}';
627         else {
628                 if (qualified) {
629                         map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
630                         map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
631                         for (docstring const & k: keys) {
632                                 docstring bef = params().prepareCommand(runparams, pres[k],
633                                                    pinfo["pretextlist"].handling());
634                                 docstring aft = params().prepareCommand(runparams, posts[k],
635                                                    pinfo["posttextlist"].handling());
636                                 if (!bef.empty())
637                                         os << '[' << protectArgument(bef)
638                                            << "][" << protectArgument(aft) << ']';
639                                 else if (!aft.empty())
640                                         os << '[' << protectArgument(aft) << ']';
641                                 os << '{' << k << '}';
642                         }
643                 } else
644                         os << '{' << cleanupWhitespace(key) << '}';
645         }
646
647         if (runparams.inulemcmd)
648                 os << "}";
649 }
650
651
652 string InsetCitation::contextMenuName() const
653 {
654         return "context-citation";
655 }
656
657
658 } // namespace lyx