]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
Buffer param \cite_engine_type (authoryear|numerical).
[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 "LaTeXFeatures.h"
25 #include "output_xhtml.h"
26 #include "ParIterator.h"
27 #include "TocBackend.h"
28
29 #include "support/debug.h"
30 #include "support/docstream.h"
31 #include "support/FileNameList.h"
32 #include "support/gettext.h"
33 #include "support/lstrings.h"
34
35 #include <algorithm>
36
37 using namespace std;
38 using namespace lyx::support;
39
40 namespace lyx {
41
42 ParamInfo InsetCitation::param_info_;
43
44
45 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
46         : InsetCommand(buf, p)
47 {}
48
49
50 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
51 {
52         // standard cite does only take one argument if jurabib is
53         // not used, but jurabib extends this to two arguments, so
54         // we have to allow both here. InsetCitation takes care that
55         // LaTeX output is nevertheless correct.
56         if (param_info_.empty()) {
57                 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
58                 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
59                 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
60         }
61         return param_info_;
62 }
63
64
65 namespace {
66
67 vector<string> const init_possible_cite_commands()
68 {
69         char const * const possible[] = {
70                 "cite", "nocite", "citet", "citep", "citealt", "citealp",
71                 "citeauthor", "citeyear", "citeyearpar",
72                 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
73                 "Citet",  "Citep",  "Citealt",  "Citealp",  "Citeauthor",
74                 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
75                 "fullcite",
76                 "footcite", "footcitet", "footcitep", "footcitealt",
77                 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
78                 "citefield", "citetitle", "cite*"
79         };
80         size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
81
82         return vector<string>(possible, possible + size_possible);
83 }
84
85
86 vector<string> const & possibleCiteCommands()
87 {
88         static vector<string> const possible = init_possible_cite_commands();
89         return possible;
90 }
91
92
93 } // anon namespace
94
95
96 bool InsetCitation::isCompatibleCommand(string const & cmd)
97 {
98         vector<string> const & possibles = possibleCiteCommands();
99         vector<string>::const_iterator const end = possibles.end();
100         return find(possibles.begin(), end, cmd) != end;
101 }
102
103
104 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
105 {
106         if (cmd.action() == LFUN_INSET_MODIFY)
107                 cache.recalculate = true;
108         InsetCommand::doDispatch(cur, cmd);
109 }
110
111
112 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
113 {
114         Buffer const & buf = bv.buffer();
115         // Only after the buffer is loaded from file...
116         if (!buf.isFullyLoaded())
117                 return docstring();
118
119         BiblioInfo const & bi = buf.masterBibInfo();
120         if (bi.empty())
121                 return _("No bibliography defined!");
122
123         docstring const & key = getParam("key");
124         if (key.empty())
125                 return _("No citations selected!");
126
127         vector<docstring> keys = getVectorFromString(key);
128         vector<docstring>::const_iterator it = keys.begin();
129         vector<docstring>::const_iterator en = keys.end();
130         docstring tip;
131         for (; it != en; ++it) {
132                 docstring const key_info = bi.getInfo(*it, buffer());
133                 if (key_info.empty())
134                         continue;
135                 if (!tip.empty())
136                         tip += "\n";
137                 tip += wrap(key_info, -4);
138         }
139         return tip;
140 }
141
142
143 namespace {
144
145 // FIXME See the header for the issue.
146 string defaultCiteCommand(CiteEngine engine, CiteEngineType engine_type)
147 {
148         string str;
149         switch (engine) {
150                 case ENGINE_BASIC:
151                         str = "cite";
152                         break;
153                 case ENGINE_NATBIB:
154                         if (engine_type == ENGINE_TYPE_AUTHORYEAR)
155                                 str = "citet";
156                         else
157                                 str = "citep";
158                         break;
159                 case ENGINE_JURABIB:
160                         str = "cite";
161                         break;
162         }
163         return str;
164 }
165
166
167 string asValidLatexCommand(string const & input, CiteEngine const engine,
168         CiteEngineType const engine_type)
169 {
170         string const default_str = defaultCiteCommand(engine, engine_type);
171         if (!InsetCitation::isCompatibleCommand(input))
172                 return default_str;
173
174         string output;
175         switch (engine) {
176                 case ENGINE_BASIC:
177                         if (input == "nocite")
178                                 output = input;
179                         else
180                                 output = default_str;
181                         break;
182
183                 case ENGINE_NATBIB:
184                         if (input == "cite" || input == "citefield"
185                             || input == "citetitle" || input == "cite*")
186                                 output = default_str;
187                         else if (prefixIs(input, "foot"))
188                                 output = input.substr(4);
189                         else
190                                 output = input;
191                         break;
192
193                 case ENGINE_JURABIB: {
194                         // Jurabib does not support the 'uppercase' natbib style.
195                         if (input[0] == 'C')
196                                 output = string(1, 'c') + input.substr(1);
197                         else
198                                 output = input;
199
200                         // Jurabib does not support the 'full' natbib style.
201                         string::size_type const n = output.size() - 1;
202                         if (output != "cite*" && output[n] == '*')
203                                 output = output.substr(0, n);
204
205                         break;
206                 }
207         }
208
209         return output;
210 }
211
212
213 inline docstring wrapCitation(docstring const & key,
214                 docstring const & content, bool for_xhtml)
215 {
216         if (!for_xhtml)
217                 return content;
218         // we have to do the escaping here, because we will ultimately
219         // write this as a raw string, so as not to escape the tags.
220         return "<a href='#" + key + "'>" +
221                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
222 }
223
224 } // anonymous namespace
225
226 docstring InsetCitation::generateLabel(bool for_xhtml) const
227 {
228         docstring label;
229         label = complexLabel(for_xhtml);
230
231         // Fallback to fail-safe
232         if (label.empty())
233                 label = basicLabel(for_xhtml);
234
235         return label;
236 }
237
238
239 docstring InsetCitation::complexLabel(bool for_xhtml) const
240 {
241         Buffer const & buf = buffer();
242         // Only start the process off after the buffer is loaded from file.
243         if (!buf.isFullyLoaded())
244                 return docstring();
245
246         BiblioInfo const & biblist = buf.masterBibInfo();
247         if (biblist.empty())
248                 return docstring();
249
250         // the natbib citation-styles
251         // CITET:       author (year)
252         // CITEP:       (author,year)
253         // CITEALT:     author year
254         // CITEALP:     author, year
255         // CITEAUTHOR:  author
256         // CITEYEAR:    year
257         // CITEYEARPAR: (year)
258         // jurabib supports these plus
259         // CITE:        author/<before field>
260
261         CiteEngine const engine = buffer().params().citeEngine();
262         CiteEngineType const engine_type = buffer().params().citeEngineType();
263         // We don't currently use the full or forceUCase fields.
264         string cite_type = asValidLatexCommand(getCmdName(), engine, engine_type);
265         if (cite_type[0] == 'C')
266                 // If we were going to use them, this would mean ForceUCase
267                 cite_type = string(1, 'c') + cite_type.substr(1);
268         if (cite_type[cite_type.size() - 1] == '*')
269                 // and this would mean FULL
270                 cite_type = cite_type.substr(0, cite_type.size() - 1);
271
272         docstring const & before = getParam("before");
273         docstring before_str;
274         if (!before.empty()) {
275                 // In CITET and CITEALT mode, the "before" string is
276                 // attached to the label associated with each and every key.
277                 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
278                 // to the front of the whole only.
279                 // In other modes, it is not used at all.
280                 if (cite_type == "citet" ||
281                     cite_type == "citealt" ||
282                     cite_type == "citep" ||
283                     cite_type == "citealp" ||
284                     cite_type == "citeyearpar")
285                         before_str = before + ' ';
286                 // In CITE (jurabib), the "before" string is used to attach
287                 // the annotator (of legal texts) to the author(s) of the
288                 // first reference.
289                 else if (cite_type == "cite")
290                         before_str = '/' + before;
291         }
292
293         docstring const & after = getParam("after");
294         docstring after_str;
295         // The "after" key is appended only to the end of the whole.
296         if (cite_type == "nocite")
297                 after_str =  " (" + _("not cited") + ')';
298         else if (!after.empty()) {
299                 after_str = ", " + after;
300         }
301
302         // One day, these might be tunable (as they are in BibTeX).
303         char op, cp;    // opening and closing parenthesis.
304         const char * sep;       // punctuation mark separating citation entries.
305         if (engine == ENGINE_BASIC) {
306                 op  = '[';
307                 cp  = ']';
308                 sep = ",";
309         } else {
310                 op  = '(';
311                 cp  = ')';
312                 sep = ";";
313         }
314
315         docstring const op_str = ' ' + docstring(1, op);
316         docstring const cp_str = docstring(1, cp) + ' ';
317         docstring const sep_str = from_ascii(sep) + ' ';
318
319         docstring label;
320         vector<docstring> keys = getVectorFromString(getParam("key"));
321         vector<docstring>::const_iterator it  = keys.begin();
322         vector<docstring>::const_iterator end = keys.end();
323         for (; it != end; ++it) {
324                 // get the bibdata corresponding to the key
325                 docstring const author = biblist.getAbbreviatedAuthor(*it);
326                 docstring const year = biblist.getYear(*it, for_xhtml);
327                 docstring const citenum = for_xhtml ? biblist.getCiteNumber(*it) : *it;
328
329                 if (author.empty() || year.empty())
330                         // We can't construct a "complex" label without that info.
331                         // So fail safely.
332                         return docstring();
333
334                 // authors1/<before>;  ... ;
335                 //  authors_last, <after>
336                 if (cite_type == "cite") {
337                         if (engine == ENGINE_BASIC) {
338                                 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
339                         } else if (engine == ENGINE_JURABIB) {
340                                 if (it == keys.begin())
341                                         label += wrapCitation(*it, author, for_xhtml) + before_str + sep_str;
342                                 else
343                                         label += wrapCitation(*it, author, for_xhtml) + sep_str;
344                         }
345                 }
346                 // nocite
347                 else if (cite_type == "nocite") {
348                         label += *it + sep_str;
349                 }
350                 // (authors1 (<before> year);  ... ;
351                 //  authors_last (<before> year, <after>)
352                 else if (cite_type == "citet") {
353                         switch (engine) {
354                         case ENGINE_NATBIB:
355                                 if (engine_type == ENGINE_TYPE_AUTHORYEAR)
356                                         label += author + op_str + before_str +
357                                                 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
358                                 else
359                                         label += author + op_str + before_str +
360                                                 wrapCitation(*it, citenum, for_xhtml) + cp + sep_str;
361                                 break;
362                         case ENGINE_JURABIB:
363                                 label += before_str + author + op_str +
364                                         wrapCitation(*it, year, for_xhtml) + cp + sep_str;
365                                 break;
366                         case ENGINE_BASIC:
367                                 break;
368                         }
369                 }
370                 // author, year; author, year; ...
371                 else if (cite_type == "citep" ||
372                            cite_type == "citealp") {
373                         if (engine_type == ENGINE_TYPE_NUMERICAL) {
374                                 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
375                         } else {
376                                 label += wrapCitation(*it, author + ", " + year, for_xhtml) + sep_str;
377                         }
378
379                 }
380                 // (authors1 <before> year;
381                 //  authors_last <before> year, <after>)
382                 else if (cite_type == "citealt") {
383                         switch (engine) {
384                         case ENGINE_NATBIB:
385                                 if (engine_type == ENGINE_TYPE_AUTHORYEAR)
386                                         label += author + ' ' + before_str +
387                                                 wrapCitation(*it, year, for_xhtml) + sep_str;
388                                 else
389                                         label += author + ' ' + before_str + '#' +
390                                                 wrapCitation(*it, citenum, for_xhtml) + sep_str;
391                                 break;
392                         case ENGINE_JURABIB:
393                                 label += before_str +
394                                         wrapCitation(*it, author + ' ' + year, for_xhtml) + sep_str;
395                                 break;
396                         case ENGINE_BASIC:
397                                 break;
398                         }
399
400
401                 }
402                 // author; author; ...
403                 else if (cite_type == "citeauthor") {
404                         label += wrapCitation(*it, author, for_xhtml) + sep_str;
405                 }
406                 // year; year; ...
407                 else if (cite_type == "citeyear" ||
408                            cite_type == "citeyearpar") {
409                         label += wrapCitation(*it, year, for_xhtml) + sep_str;
410                 }
411         }
412         label = rtrim(rtrim(label), sep);
413
414         if (!after_str.empty()) {
415                 if (cite_type == "citet") {
416                         // insert "after" before last ')'
417                         label.insert(label.size() - 1, after_str);
418                 } else {
419                         bool const add =
420                                 !(engine == ENGINE_NATBIB &&
421                                   engine_type == ENGINE_TYPE_NUMERICAL &&
422                                   (cite_type == "citeauthor" ||
423                                    cite_type == "citeyear"));
424                         if (add)
425                                 label += after_str;
426                 }
427         }
428
429         if (!before_str.empty() && (cite_type == "citep" ||
430                                     cite_type == "citealp" ||
431                                     cite_type == "citeyearpar")) {
432                 label = before_str + label;
433         }
434
435         if (cite_type == "citep" || cite_type == "citeyearpar" ||
436             (cite_type == "cite" && engine == ENGINE_BASIC) )
437                 label = op + label + cp;
438
439         return label;
440 }
441
442
443 docstring InsetCitation::basicLabel(bool for_xhtml) const
444 {
445         docstring keys = getParam("key");
446         docstring label;
447
448         docstring key;
449         do {
450                 // if there is no comma, then everything goes into key
451                 // and keys will be empty.
452                 keys = trim(split(keys, key, ','));
453                 key = trim(key);
454                 if (!label.empty())
455                         label += ", ";
456                 label += wrapCitation(key, key, for_xhtml);
457         } while (!keys.empty());
458
459         docstring const & after = getParam("after");
460         if (!after.empty())
461                 label += ", " + after;
462
463         return '[' + label + ']';
464 }
465
466 docstring InsetCitation::screenLabel() const
467 {
468         return cache.screen_label;
469 }
470
471
472 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
473 {
474         if (!cache.recalculate && buffer().citeLabelsValid())
475                 return;
476
477         // The label may have changed, so we have to re-create it.
478         docstring const glabel = generateLabel();
479
480         unsigned int const maxLabelChars = 45;
481
482         docstring label = glabel;
483         if (label.size() > maxLabelChars) {
484                 label.erase(maxLabelChars - 3);
485                 label += "...";
486         }
487
488         cache.recalculate = false;
489         cache.generated_label = glabel;
490         cache.screen_label = label;
491 }
492
493
494 void InsetCitation::addToToc(DocIterator const & cpit) const
495 {
496         // NOTE
497         // XHTML output uses the TOC to collect the citations
498         // from the document. So if this gets changed, then we
499         // will need to change how the citations are collected.
500         docstring const tocitem = getParam("key");
501         Toc & toc = buffer().tocBackend().toc("citation");
502         toc.push_back(TocItem(cpit, 0, tocitem));
503 }
504
505
506 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
507 {
508         os << cache.generated_label;
509         return cache.generated_label.size();
510 }
511
512
513 static docstring const cleanupWhitespace(docstring const & citelist)
514 {
515         docstring::const_iterator it  = citelist.begin();
516         docstring::const_iterator end = citelist.end();
517         // Paranoia check: make sure that there is no whitespace in here
518         // -- at least not behind commas or at the beginning
519         docstring result;
520         char_type last = ',';
521         for (; it != end; ++it) {
522                 if (*it != ' ')
523                         last = *it;
524                 if (*it != ' ' || last != ',')
525                         result += *it;
526         }
527         return result;
528 }
529
530
531 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
532 {
533         os << from_ascii("<citation>")
534            << cleanupWhitespace(getParam("key"))
535            << from_ascii("</citation>");
536         return 0;
537 }
538
539
540 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
541 {
542         string const & cmd = getCmdName();
543         if (cmd == "nocite")
544                 return docstring();
545
546         // have to output this raw, because generateLabel() will include tags
547         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
548
549         return docstring();
550 }
551
552
553 void InsetCitation::toString(odocstream & os) const
554 {
555         plaintext(os, OutputParams(0));
556 }
557
558
559 void InsetCitation::forToc(docstring & os, size_t) const
560 {
561         os += screenLabel();
562 }
563
564
565 // Have to overwrite the default InsetCommand method in order to check that
566 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
567 // citations and then changes his mind, turning natbib support off. The output
568 // should revert to \cite[]{}
569 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
570 {
571         CiteEngine cite_engine = buffer().params().citeEngine();
572         CiteEngineType cite_engine_type = buffer().params().citeEngineType();
573         BiblioInfo const & bi = buffer().masterBibInfo();
574         // FIXME UNICODE
575         docstring const cite_str = from_utf8(
576                 asValidLatexCommand(getCmdName(), cite_engine, cite_engine_type));
577
578         if (runparams.inulemcmd)
579                 os << "\\mbox{";
580
581         os << "\\" << cite_str;
582
583         docstring const & before = getParam("before");
584         docstring const & after  = getParam("after");
585         if (!before.empty() && cite_engine != ENGINE_BASIC)
586                 os << '[' << before << "][" << after << ']';
587         else if (!after.empty())
588                 os << '[' << after << ']';
589
590         if (!bi.isBibtex(getParam("key")))
591                 // escape chars with bibitems
592                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
593         else
594                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
595
596         if (runparams.inulemcmd)
597                 os << "}";
598 }
599
600
601 void InsetCitation::validate(LaTeXFeatures & features) const
602 {
603         switch (features.bufferParams().citeEngine()) {
604         case ENGINE_BASIC:
605                 break;
606         case ENGINE_NATBIB:
607                 features.require("natbib");
608                 break;
609         case ENGINE_JURABIB:
610                 features.require("jurabib");
611                 break;
612         }
613 }
614
615
616 string InsetCitation::contextMenuName() const
617 {
618         return "context-citation";
619 }
620
621
622 } // namespace lyx