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