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