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