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