]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
ca96d1d56b45cc5a3a354238329d2e7bc942f0cb
[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 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                 /* We do not use buffer() because Coverity believes that this
59                  * may throw an exception. Actually this code path is not
60                  * taken when buffer_ == 0 */
61                 buffer_->removeBiblioTempFiles();
62 }
63
64
65 // May well be over-ridden when session settings are loaded
66 // in GuiCitation. Unfortunately, that will not happen until
67 // such a dialog is created.
68 bool InsetCitation::last_literal = true;
69
70
71 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
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         vector<docstring> keys = getVectorFromString(key);
394         CitationStyle cs = getCitationStyle(buffer().masterParams(),
395                                             cite_type, buffer().masterParams().citeStyles());
396         bool const qualified = cs.hasQualifiedList
397                 && (keys.size() > 1
398                     || !getParam("pretextlist").empty()
399                     || !getParam("posttextlist").empty());
400         map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
401         map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
402
403         CiteItem ci;
404         ci.textBefore = getParam("before");
405         ci.textAfter = getParam("after");
406         ci.forceUpperCase = uppercase;
407         ci.Starred = starred;
408         ci.max_size = UINT_MAX;
409         ci.isQualified = qualified;
410         ci.pretexts = pres;
411         ci.posttexts = posts;
412         if (for_xhtml) {
413                 ci.max_key_size = UINT_MAX;
414                 ci.context = CiteItem::Export;
415         }
416         ci.richtext = for_xhtml;
417         label = biblist.getLabel(keys, buffer(), cite_type, ci);
418         return label;
419 }
420
421
422 docstring InsetCitation::basicLabel(bool for_xhtml) const
423 {
424         docstring keys = getParam("key");
425         docstring label;
426
427         docstring key;
428         do {
429                 // if there is no comma, then everything goes into key
430                 // and keys will be empty.
431                 keys = trim(split(keys, key, ','));
432                 key = trim(key);
433                 if (!label.empty())
434                         label += ", ";
435                 label += wrapCitation(key, key, for_xhtml);
436         } while (!keys.empty());
437
438         docstring const & after = getParam("after");
439         if (!after.empty())
440                 label += ", " + after;
441
442         return '[' + label + ']';
443 }
444
445 docstring InsetCitation::screenLabel() const
446 {
447         return cache.screen_label;
448 }
449
450
451 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
452 {
453         if (!cache.recalculate && buffer().citeLabelsValid())
454                 return;
455         // The label may have changed, so we have to re-create it.
456         docstring const glabel = generateLabel();
457         cache.recalculate = false;
458         cache.generated_label = glabel;
459         unsigned int const maxLabelChars = 45;
460         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
461         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
462 }
463
464
465 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
466                                                          UpdateType, TocBackend & backend) const
467 {
468         // NOTE
469         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
470         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
471         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
472         // then we will also need to change that routine.
473         docstring const tocitem = getParam("key");
474         TocBuilder & b = backend.builder("citation");
475         b.pushItem(cpit, tocitem, output_active);
476         b.pop();
477 }
478
479
480 int InsetCitation::plaintext(odocstringstream & os,
481        OutputParams const &, size_t) const
482 {
483         string const & cmd = getCmdName();
484         if (cmd == "nocite")
485                 return 0;
486
487         docstring const label = generateLabel(false);
488         os << label;
489         return label.size();
490 }
491
492
493 static docstring const cleanupWhitespace(docstring const & citelist)
494 {
495         docstring::const_iterator it  = citelist.begin();
496         docstring::const_iterator end = citelist.end();
497         // Paranoia check: make sure that there is no whitespace in here
498         // -- at least not behind commas or at the beginning
499         docstring result;
500         char_type last = ',';
501         for (; it != end; ++it) {
502                 if (*it != ' ')
503                         last = *it;
504                 if (*it != ' ' || last != ',')
505                         result += *it;
506         }
507         return result;
508 }
509
510
511 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
512 {
513         os << from_ascii("<citation>")
514            << cleanupWhitespace(getParam("key"))
515            << from_ascii("</citation>");
516         return 0;
517 }
518
519
520 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
521 {
522         string const & cmd = getCmdName();
523         if (cmd == "nocite")
524                 return docstring();
525
526         // have to output this raw, because generateLabel() will include tags
527         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
528
529         return docstring();
530 }
531
532
533 void InsetCitation::toString(odocstream & os) const
534 {
535         odocstringstream ods;
536         plaintext(ods, OutputParams(0));
537         os << ods.str();
538 }
539
540
541 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
542 {
543         os += screenLabel();
544 }
545
546
547 // Have to overwrite the default InsetCommand method in order to check that
548 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
549 // citations and then changes his mind, turning natbib support off. The output
550 // should revert to the default citation command as provided by the citation
551 // engine, e.g. \cite[]{} for the basic engine.
552 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
553 {
554         BiblioInfo const & bi = buffer().masterBibInfo();
555         docstring const key = getParam("key");
556         // "keyonly" command: output the plain key and stop.
557         if (getCmdName() == "keyonly") {
558                 // Special command to only return the key
559                 if (!bi.isBibtex(getParam("key")))
560                         // escape chars with bibitems
561                         os << escape(cleanupWhitespace(key));
562                 else
563                         os << cleanupWhitespace(key);
564                 return;
565         }
566         vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
567         CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
568                                                getCmdName(), citation_styles);
569         // FIXME UNICODE
570         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
571
572         // check if we have to do a qualified list
573         vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
574         bool const qualified = cs.hasQualifiedList
575                 && (!getParam("pretextlist").empty()
576                     || !getParam("posttextlist").empty());
577
578         if (runparams.inulemcmd > 0)
579                 os << "\\mbox{";
580
581         os << "\\" << cite_str;
582
583         if (qualified)
584                 os << "s";
585
586         docstring before = params().prepareCommand(runparams, getParam("before"),
587                                                    param_info_["before"].handling());
588         docstring after = params().prepareCommand(runparams, getParam("after"),
589                                                    param_info_["after"].handling());
590         if (!before.empty() && cs.textBefore) {
591                 if (qualified)
592                         os << '(' << protectArgument(before, '(', ')')
593                            << ")(" << protectArgument(after, '(', ')') << ')';
594                 else
595                         os << '[' << protectArgument(before) << "]["
596                            << protectArgument(after) << ']';
597         } else if (!after.empty() && cs.textAfter) {
598                 if (qualified)
599                         os << '(' << protectArgument(after, '(', ')') << ')';
600                 else
601                         os << '[' << protectArgument(after) << ']';
602         }
603
604         if (!bi.isBibtex(key))
605                 // escape chars with bibitems
606                 os << '{' << escape(cleanupWhitespace(key)) << '}';
607         else {
608                 if (qualified) {
609                         map<docstring, docstring> pres = getQualifiedLists(getParam("pretextlist"));
610                         map<docstring, docstring> posts = getQualifiedLists(getParam("posttextlist"));
611                         for (docstring const & k: keys) {
612                                 docstring bef = params().prepareCommand(runparams, pres[k],
613                                                                         param_info_["pretextlist"].handling());
614                                 docstring aft  = params().prepareCommand(runparams, posts[k],
615                                                                          param_info_["posttextlist"].handling());
616                                 if (!bef.empty())
617                                         os << '[' << protectArgument(bef)
618                                            << "][" << protectArgument(aft) << ']';
619                                 else if (!aft.empty())
620                                         os << '[' << protectArgument(aft) << ']';
621                                 os << '{' << k << '}';
622                         }
623                 } else
624                         os << '{' << cleanupWhitespace(key) << '}';
625         }
626
627         if (runparams.inulemcmd)
628                 os << "}";
629 }
630
631
632 string InsetCitation::contextMenuName() const
633 {
634         return "context-citation";
635 }
636
637
638 } // namespace lyx