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"
16 #include "BiblioInfo.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "LaTeXFeatures.h"
25 #include "output_xhtml.h"
26 #include "ParIterator.h"
27 #include "TocBackend.h"
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"
38 using namespace lyx::support;
42 ParamInfo InsetCitation::param_info_;
45 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
46 : InsetCommand(buf, p)
50 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
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);
67 vector<string> const init_possible_cite_commands()
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*",
76 "footcite", "footcitet", "footcitep", "footcitealt",
77 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
78 "citefield", "citetitle", "cite*"
80 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
82 return vector<string>(possible, possible + size_possible);
86 vector<string> const & possibleCiteCommands()
88 static vector<string> const possible = init_possible_cite_commands();
96 bool InsetCitation::isCompatibleCommand(string const & cmd)
98 vector<string> const & possibles = possibleCiteCommands();
99 vector<string>::const_iterator const end = possibles.end();
100 return find(possibles.begin(), end, cmd) != end;
104 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
106 if (cmd.action() == LFUN_INSET_MODIFY)
107 cache.recalculate = true;
108 InsetCommand::doDispatch(cur, cmd);
112 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
114 Buffer const & buf = bv.buffer();
115 // Only after the buffer is loaded from file...
116 if (!buf.isFullyLoaded())
119 BiblioInfo const & bi = buf.masterBibInfo();
121 return _("No bibliography defined!");
123 docstring const & key = getParam("key");
125 return _("No citations selected!");
127 vector<docstring> keys = getVectorFromString(key);
128 vector<docstring>::const_iterator it = keys.begin();
129 vector<docstring>::const_iterator en = keys.end();
131 for (; it != en; ++it) {
132 docstring const key_info = bi.getInfo(*it, buffer());
133 if (key_info.empty())
137 tip += wrap(key_info, -4);
145 // FIXME See the header for the issue.
146 string defaultCiteCommand(CiteEngine engine, CiteEngineType engine_type)
154 if (engine_type == ENGINE_TYPE_AUTHORYEAR)
167 string asValidLatexCommand(string const & input, CiteEngine const engine,
168 CiteEngineType const engine_type)
170 string const default_str = defaultCiteCommand(engine, engine_type);
171 if (!InsetCitation::isCompatibleCommand(input))
177 if (input == "nocite")
180 output = default_str;
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);
193 case ENGINE_JURABIB: {
194 // Jurabib does not support the 'uppercase' natbib style.
196 output = string(1, 'c') + input.substr(1);
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);
213 inline docstring wrapCitation(docstring const & key,
214 docstring const & content, bool for_xhtml)
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>";
224 } // anonymous namespace
226 docstring InsetCitation::generateLabel(bool for_xhtml) const
229 label = complexLabel(for_xhtml);
231 // Fallback to fail-safe
233 label = basicLabel(for_xhtml);
239 docstring InsetCitation::complexLabel(bool for_xhtml) const
241 Buffer const & buf = buffer();
242 // Only start the process off after the buffer is loaded from file.
243 if (!buf.isFullyLoaded())
246 BiblioInfo const & biblist = buf.masterBibInfo();
250 // the natbib citation-styles
251 // CITET: author (year)
252 // CITEP: (author,year)
253 // CITEALT: author year
254 // CITEALP: author, year
255 // CITEAUTHOR: author
257 // CITEYEARPAR: (year)
258 // jurabib supports these plus
259 // CITE: author/<before field>
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);
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
289 else if (cite_type == "cite")
290 before_str = '/' + before;
293 docstring const & after = getParam("after");
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;
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) {
315 docstring const op_str = ' ' + docstring(1, op);
316 docstring const cp_str = docstring(1, cp) + ' ';
317 docstring const sep_str = from_ascii(sep) + ' ';
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;
329 if (author.empty() || year.empty())
330 // We can't construct a "complex" label without that info.
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;
343 label += wrapCitation(*it, author, for_xhtml) + sep_str;
347 else if (cite_type == "nocite") {
348 label += *it + sep_str;
350 // (authors1 (<before> year); ... ;
351 // authors_last (<before> year, <after>)
352 else if (cite_type == "citet") {
355 if (engine_type == ENGINE_TYPE_AUTHORYEAR)
356 label += author + op_str + before_str +
357 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
359 label += author + op_str + before_str +
360 wrapCitation(*it, citenum, for_xhtml) + cp + sep_str;
363 label += before_str + author + op_str +
364 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
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;
376 label += wrapCitation(*it, author + ", " + year, for_xhtml) + sep_str;
380 // (authors1 <before> year;
381 // authors_last <before> year, <after>)
382 else if (cite_type == "citealt") {
385 if (engine_type == ENGINE_TYPE_AUTHORYEAR)
386 label += author + ' ' + before_str +
387 wrapCitation(*it, year, for_xhtml) + sep_str;
389 label += author + ' ' + before_str + '#' +
390 wrapCitation(*it, citenum, for_xhtml) + sep_str;
393 label += before_str +
394 wrapCitation(*it, author + ' ' + year, for_xhtml) + sep_str;
402 // author; author; ...
403 else if (cite_type == "citeauthor") {
404 label += wrapCitation(*it, author, for_xhtml) + sep_str;
407 else if (cite_type == "citeyear" ||
408 cite_type == "citeyearpar") {
409 label += wrapCitation(*it, year, for_xhtml) + sep_str;
412 label = rtrim(rtrim(label), sep);
414 if (!after_str.empty()) {
415 if (cite_type == "citet") {
416 // insert "after" before last ')'
417 label.insert(label.size() - 1, after_str);
420 !(engine == ENGINE_NATBIB &&
421 engine_type == ENGINE_TYPE_NUMERICAL &&
422 (cite_type == "citeauthor" ||
423 cite_type == "citeyear"));
429 if (!before_str.empty() && (cite_type == "citep" ||
430 cite_type == "citealp" ||
431 cite_type == "citeyearpar")) {
432 label = before_str + label;
435 if (cite_type == "citep" || cite_type == "citeyearpar" ||
436 (cite_type == "cite" && engine == ENGINE_BASIC) )
437 label = op + label + cp;
443 docstring InsetCitation::basicLabel(bool for_xhtml) const
445 docstring keys = getParam("key");
450 // if there is no comma, then everything goes into key
451 // and keys will be empty.
452 keys = trim(split(keys, key, ','));
456 label += wrapCitation(key, key, for_xhtml);
457 } while (!keys.empty());
459 docstring const & after = getParam("after");
461 label += ", " + after;
463 return '[' + label + ']';
466 docstring InsetCitation::screenLabel() const
468 return cache.screen_label;
472 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
474 if (!cache.recalculate && buffer().citeLabelsValid())
477 // The label may have changed, so we have to re-create it.
478 docstring const glabel = generateLabel();
480 unsigned int const maxLabelChars = 45;
482 docstring label = glabel;
483 if (label.size() > maxLabelChars) {
484 label.erase(maxLabelChars - 3);
488 cache.recalculate = false;
489 cache.generated_label = glabel;
490 cache.screen_label = label;
494 void InsetCitation::addToToc(DocIterator const & cpit) const
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));
506 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
508 os << cache.generated_label;
509 return cache.generated_label.size();
513 static docstring const cleanupWhitespace(docstring const & citelist)
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
520 char_type last = ',';
521 for (; it != end; ++it) {
524 if (*it != ' ' || last != ',')
531 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
533 os << from_ascii("<citation>")
534 << cleanupWhitespace(getParam("key"))
535 << from_ascii("</citation>");
540 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
542 string const & cmd = getCmdName();
546 // have to output this raw, because generateLabel() will include tags
547 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
553 void InsetCitation::toString(odocstream & os) const
555 plaintext(os, OutputParams(0));
559 void InsetCitation::forToc(docstring & os, size_t) const
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
571 CiteEngine cite_engine = buffer().params().citeEngine();
572 CiteEngineType cite_engine_type = buffer().params().citeEngineType();
573 BiblioInfo const & bi = buffer().masterBibInfo();
575 docstring const cite_str = from_utf8(
576 asValidLatexCommand(getCmdName(), cite_engine, cite_engine_type));
578 if (runparams.inulemcmd)
581 os << "\\" << cite_str;
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 << ']';
590 if (!bi.isBibtex(getParam("key")))
591 // escape chars with bibitems
592 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
594 os << '{' << cleanupWhitespace(getParam("key")) << '}';
596 if (runparams.inulemcmd)
601 void InsetCitation::validate(LaTeXFeatures & features) const
603 switch (features.bufferParams().citeEngine()) {
607 features.require("natbib");
610 features.require("jurabib");
616 string InsetCitation::contextMenuName() const
618 return "context-citation";