2 * \file InsetCitation.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "InsetCitation.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 "ParIterator.h"
24 #include "TocBackend.h"
26 #include "support/debug.h"
27 #include "support/docstream.h"
28 #include "support/FileNameList.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
35 using namespace lyx::support;
41 vector<string> const init_possible_cite_commands()
43 char const * const possible[] = {
44 "cite", "nocite", "citet", "citep", "citealt", "citealp",
45 "citeauthor", "citeyear", "citeyearpar",
46 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
47 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
48 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
50 "footcite", "footcitet", "footcitep", "footcitealt",
51 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
52 "citefield", "citetitle", "cite*"
54 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
56 return vector<string>(possible, possible + size_possible);
60 vector<string> const & possibleCiteCommands()
62 static vector<string> const possible = init_possible_cite_commands();
67 // FIXME See the header for the issue.
68 string defaultCiteCommand(CiteEngine engine)
75 case ENGINE_NATBIB_AUTHORYEAR:
78 case ENGINE_NATBIB_NUMERICAL:
89 string asValidLatexCommand(string const & input, CiteEngine const engine)
91 string const default_str = defaultCiteCommand(engine);
92 if (!InsetCitation::isCompatibleCommand(input))
98 if (input == "nocite")
101 output = default_str;
104 case ENGINE_NATBIB_AUTHORYEAR:
105 case ENGINE_NATBIB_NUMERICAL:
106 if (input == "cite" || input == "citefield"
107 || input == "citetitle" || input == "cite*")
108 output = default_str;
109 else if (prefixIs(input, "foot"))
110 output = input.substr(4);
115 case ENGINE_JURABIB: {
116 // Jurabib does not support the 'uppercase' natbib style.
118 output = string(1, 'c') + input.substr(1);
122 // Jurabib does not support the 'full' natbib style.
123 string::size_type const n = output.size() - 1;
124 if (output != "cite*" && output[n] == '*')
125 output = output.substr(0, n);
135 docstring complexLabel(Buffer const & buffer,
136 string const & citeType, docstring const & keyList,
137 docstring const & before, docstring const & after,
140 // Only start the process off after the buffer is loaded from file.
141 if (!buffer.isFullyLoaded())
144 BiblioInfo const & biblist = buffer.masterBibInfo();
148 // the natbib citation-styles
149 // CITET: author (year)
150 // CITEP: (author,year)
151 // CITEALT: author year
152 // CITEALP: author, year
153 // CITEAUTHOR: author
155 // CITEYEARPAR: (year)
156 // jurabib supports these plus
157 // CITE: author/<before field>
159 // We don't currently use the full or forceUCase fields.
160 string cite_type = asValidLatexCommand(citeType, engine);
161 if (cite_type[0] == 'C')
162 //If we were going to use them, this would mean ForceUCase
163 cite_type = string(1, 'c') + cite_type.substr(1);
164 if (cite_type[cite_type.size() - 1] == '*')
165 //and this would mean FULL
166 cite_type = cite_type.substr(0, cite_type.size() - 1);
168 docstring before_str;
169 if (!before.empty()) {
170 // In CITET and CITEALT mode, the "before" string is
171 // attached to the label associated with each and every key.
172 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
173 // to the front of the whole only.
174 // In other modes, it is not used at all.
175 if (cite_type == "citet" ||
176 cite_type == "citealt" ||
177 cite_type == "citep" ||
178 cite_type == "citealp" ||
179 cite_type == "citeyearpar")
180 before_str = before + ' ';
181 // In CITE (jurabib), the "before" string is used to attach
182 // the annotator (of legal texts) to the author(s) of the
184 else if (cite_type == "cite")
185 before_str = '/' + before;
189 // The "after" key is appended only to the end of the whole.
190 if (cite_type == "nocite")
191 after_str = " (" + _("not cited") + ')';
192 else if (!after.empty()) {
193 after_str = ", " + after;
196 // One day, these might be tunable (as they are in BibTeX).
197 char op, cp; // opening and closing parenthesis.
198 const char * sep; // punctuation mark separating citation entries.
199 if (engine == ENGINE_BASIC) {
209 docstring const op_str = ' ' + docstring(1, op);
210 docstring const cp_str = docstring(1, cp) + ' ';
211 docstring const sep_str = from_ascii(sep) + ' ';
214 vector<docstring> keys = getVectorFromString(keyList);
215 vector<docstring>::const_iterator it = keys.begin();
216 vector<docstring>::const_iterator end = keys.end();
217 for (; it != end; ++it) {
218 // get the bibdata corresponding to the key
219 docstring const author(biblist.getAbbreviatedAuthor(*it));
220 docstring const year(biblist.getYear(*it));
222 // Something isn't right. Fail safely.
223 if (author.empty() || year.empty())
226 // authors1/<before>; ... ;
227 // authors_last, <after>
228 if (cite_type == "cite") {
229 if (engine == ENGINE_BASIC) {
230 label += *it + sep_str;
231 } else if (engine == ENGINE_JURABIB) {
232 if (it == keys.begin())
233 label += author + before_str + sep_str;
235 label += author + sep_str;
239 } else if (cite_type == "nocite") {
240 label += *it + sep_str;
242 // (authors1 (<before> year); ... ;
243 // authors_last (<before> year, <after>)
244 } else if (cite_type == "citet") {
246 case ENGINE_NATBIB_AUTHORYEAR:
247 label += author + op_str + before_str +
250 case ENGINE_NATBIB_NUMERICAL:
251 label += author + op_str + before_str + '#' + *it + cp + sep_str;
254 label += before_str + author + op_str +
261 // author, year; author, year; ...
262 } else if (cite_type == "citep" ||
263 cite_type == "citealp") {
264 if (engine == ENGINE_NATBIB_NUMERICAL) {
265 label += *it + sep_str;
267 label += author + ", " + year + sep_str;
270 // (authors1 <before> year;
271 // authors_last <before> year, <after>)
272 } else if (cite_type == "citealt") {
274 case ENGINE_NATBIB_AUTHORYEAR:
275 label += author + ' ' + before_str +
278 case ENGINE_NATBIB_NUMERICAL:
279 label += author + ' ' + before_str + '#' + *it + sep_str;
282 label += before_str + author + ' ' +
289 // author; author; ...
290 } else if (cite_type == "citeauthor") {
291 label += author + sep_str;
294 } else if (cite_type == "citeyear" ||
295 cite_type == "citeyearpar") {
296 label += year + sep_str;
299 label = rtrim(rtrim(label), sep);
301 if (!after_str.empty()) {
302 if (cite_type == "citet") {
303 // insert "after" before last ')'
304 label.insert(label.size() - 1, after_str);
307 !(engine == ENGINE_NATBIB_NUMERICAL &&
308 (cite_type == "citeauthor" ||
309 cite_type == "citeyear"));
315 if (!before_str.empty() && (cite_type == "citep" ||
316 cite_type == "citealp" ||
317 cite_type == "citeyearpar")) {
318 label = before_str + label;
321 if (cite_type == "citep" || cite_type == "citeyearpar" ||
322 (cite_type == "cite" && engine == ENGINE_BASIC) )
323 label = op + label + cp;
329 docstring basicLabel(docstring const & keyList, docstring const & after)
331 docstring keys = keyList;
334 if (contains(keys, ',')) {
335 // Final comma allows while loop to cover all keys
336 keys = ltrim(split(keys, label, ',')) + ',';
337 while (contains(keys, ',')) {
339 keys = ltrim(split(keys, key, ','));
347 label += ", " + after;
349 return '[' + label + ']';
355 ParamInfo InsetCitation::param_info_;
358 InsetCitation::InsetCitation(InsetCommandParams const & p)
359 : InsetCommand(p, "citation")
363 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
365 // standard cite does only take one argument if jurabib is
366 // not used, but jurabib extends this to two arguments, so
367 // we have to allow both here. InsetCitation takes care that
368 // LaTeX output is nevertheless correct.
369 if (param_info_.empty()) {
370 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
371 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
372 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
378 bool InsetCitation::isCompatibleCommand(string const & cmd)
380 vector<string> const & possibles = possibleCiteCommands();
381 vector<string>::const_iterator const end = possibles.end();
382 return find(possibles.begin(), end, cmd) != end;
386 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
388 Buffer const & buf = bv.buffer();
389 // Only after the buffer is loaded from file...
390 if (!buf.isFullyLoaded())
393 BiblioInfo const & bi = buf.masterBibInfo();
395 return _("No bibliography defined!");
397 docstring const & key = getParam("key");
399 return _("No citations selected!");
401 vector<docstring> keys = getVectorFromString(key);
402 vector<docstring>::const_iterator it = keys.begin();
403 vector<docstring>::const_iterator en = keys.end();
405 for (; it != en; ++it) {
406 docstring const key_info = bi.getInfo(*it);
407 if (key_info.empty())
411 tip += wrap(key_info, -4);
418 docstring InsetCitation::generateLabel() const
420 docstring const & before = getParam("before");
421 docstring const & after = getParam("after");
424 CiteEngine const engine = buffer().params().citeEngine();
425 label = complexLabel(buffer(), getCmdName(), getParam("key"),
426 before, after, engine);
428 // Fallback to fail-safe
430 label = basicLabel(getParam("key"), after);
436 docstring InsetCitation::screenLabel() const
438 return cache.screen_label;
442 void InsetCitation::updateLabels(ParIterator const &)
444 CiteEngine const engine = buffer().params().citeEngine();
445 if (cache.params == params() && cache.engine == engine)
448 // The label has changed, so we have to re-create it.
449 docstring const glabel = generateLabel();
451 unsigned int const maxLabelChars = 45;
453 docstring label = glabel;
454 if (label.size() > maxLabelChars) {
455 label.erase(maxLabelChars-3);
459 cache.engine = engine;
460 cache.params = params();
461 cache.generated_label = glabel;
462 cache.screen_label = label;
466 void InsetCitation::addToToc(DocIterator const & cpit)
468 Toc & toc = buffer().tocBackend().toc("citation");
469 toc.push_back(TocItem(cpit, 0, getParam("key")));
473 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
475 os << cache.generated_label;
476 return cache.generated_label.size();
480 static docstring const cleanupWhitespace(docstring const & citelist)
482 docstring::const_iterator it = citelist.begin();
483 docstring::const_iterator end = citelist.end();
484 // Paranoia check: make sure that there is no whitespace in here
485 // -- at least not behind commas or at the beginning
487 char_type last = ',';
488 for (; it != end; ++it) {
491 if (*it != ' ' || last != ',')
498 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
500 os << from_ascii("<citation>")
501 << cleanupWhitespace(getParam("key"))
502 << from_ascii("</citation>");
507 docstring InsetCitation::xhtml(odocstream & os, OutputParams const &) const
509 BiblioInfo const & bi = buffer().masterBibInfo();
510 docstring const & keyList = getParam("key");
514 // FIXME We shuld do a better job outputing different things for the
515 // different citation styles. For now, we use square brackets for every
518 docstring const & before = getParam("before");
522 vector<docstring> keys = getVectorFromString(keyList);
523 vector<docstring>::const_iterator it = keys.begin();
524 vector<docstring>::const_iterator en = keys.end();
526 for (; it != en; ++it) {
527 BiblioInfo::const_iterator const bt = bi.find(*it);
530 BibTeXInfo const & bibinfo = bt->second;
535 docstring const & label = bibinfo.label();
536 docstring const & target = label.empty() ? *it : label;
537 os << "<a href='#" << *it << "'>" << target << "</a>";
540 docstring const & after = getParam("after");
548 void InsetCitation::tocString(odocstream & os) const
550 plaintext(os, OutputParams(0));
554 // Have to overwrite the default InsetCommand method in order to check that
555 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
556 // citations and then changes his mind, turning natbib support off. The output
557 // should revert to \cite[]{}
558 int InsetCitation::latex(odocstream & os, OutputParams const & runparams) const
560 CiteEngine cite_engine = buffer().params().citeEngine();
562 docstring const cite_str = from_utf8(
563 asValidLatexCommand(getCmdName(), cite_engine));
565 if (runparams.inulemcmd)
568 os << "\\" << cite_str;
570 docstring const & before = getParam("before");
571 docstring const & after = getParam("after");
572 if (!before.empty() && cite_engine != ENGINE_BASIC)
573 os << '[' << before << "][" << after << ']';
574 else if (!after.empty())
575 os << '[' << after << ']';
577 os << '{' << cleanupWhitespace(getParam("key")) << '}';
579 if (runparams.inulemcmd)
586 void InsetCitation::validate(LaTeXFeatures & features) const
588 switch (features.bufferParams().citeEngine()) {
591 case ENGINE_NATBIB_AUTHORYEAR:
592 case ENGINE_NATBIB_NUMERICAL:
593 features.require("natbib");
596 features.require("jurabib");
602 docstring InsetCitation::contextMenu(BufferView const &, int, int) const
604 return from_ascii("context-citation");