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)
48 buffer().removeBiblioTempFiles();
52 InsetCitation::~InsetCitation()
55 buffer().removeBiblioTempFiles();
59 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
61 // standard cite does only take one argument if jurabib is
62 // not used, but jurabib extends this to two arguments, so
63 // we have to allow both here. InsetCitation takes care that
64 // LaTeX output is nevertheless correct.
65 if (param_info_.empty()) {
66 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
67 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
68 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
76 vector<string> const init_possible_cite_commands()
78 char const * const possible[] = {
79 "cite", "nocite", "citet", "citep", "citealt", "citealp",
80 "citeauthor", "citeyear", "citeyearpar",
81 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
82 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
83 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
85 "footcite", "footcitet", "footcitep", "footcitealt",
86 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
87 "citefield", "citetitle", "cite*"
89 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
91 return vector<string>(possible, possible + size_possible);
95 vector<string> const & possibleCiteCommands()
97 static vector<string> const possible = init_possible_cite_commands();
105 // FIXME: use the citeCommands provided by the TextClass
106 // instead of possibleCiteCommands defined in this file.
107 bool InsetCitation::isCompatibleCommand(string const & cmd)
109 vector<string> const & possibles = possibleCiteCommands();
110 vector<string>::const_iterator const end = possibles.end();
111 return find(possibles.begin(), end, cmd) != end;
115 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
117 if (cmd.action() == LFUN_INSET_MODIFY) {
118 buffer().removeBiblioTempFiles();
119 cache.recalculate = true;
121 InsetCommand::doDispatch(cur, cmd);
125 bool InsetCitation::addKey(string const & key)
127 docstring const ukey = from_utf8(key);
128 docstring const & curkeys = getParam("key");
129 if (curkeys.empty()) {
130 setParam("key", ukey);
131 cache.recalculate = true;
135 vector<docstring> keys = getVectorFromString(curkeys);
136 vector<docstring>::const_iterator it = keys.begin();
137 vector<docstring>::const_iterator en = keys.end();
138 for (; it != en; ++it) {
140 LYXERR0("Key " << key << " already present.");
144 keys.push_back(ukey);
145 setParam("key", getStringFromVector(keys));
146 cache.recalculate = true;
151 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
153 Buffer const & buf = bv.buffer();
154 // Only after the buffer is loaded from file...
155 if (!buf.isFullyLoaded())
158 BiblioInfo const & bi = buf.masterBibInfo();
160 return _("No bibliography defined!");
162 docstring const & key = getParam("key");
164 return _("No citations selected!");
166 vector<docstring> keys = getVectorFromString(key);
167 vector<docstring>::const_iterator it = keys.begin();
168 vector<docstring>::const_iterator en = keys.end();
170 for (; it != en; ++it) {
171 docstring const key_info = bi.getInfo(*it, buffer());
172 if (key_info.empty())
176 tip += wrap(key_info, -4);
185 CitationStyle asValidLatexCommand(string const & input, vector<CitationStyle> const valid_styles)
187 CitationStyle cs = valid_styles[0];
188 cs.forceUpperCase = false;
189 cs.fullAuthorList = false;
190 if (!InsetCitation::isCompatibleCommand(input))
193 string normalized_input = input;
194 string::size_type const n = input.size() - 1;
196 normalized_input[0] = 'c';
198 normalized_input = normalized_input.substr(0, n);
200 vector<CitationStyle>::const_iterator it = valid_styles.begin();
201 vector<CitationStyle>::const_iterator end = valid_styles.end();
202 for (; it != end; ++it) {
203 CitationStyle this_cs = *it;
204 if (this_cs.cmd == normalized_input) {
210 cs.forceUpperCase &= input[0] == 'C';
211 cs.fullAuthorList &= input[n] == '*';
217 inline docstring wrapCitation(docstring const & key,
218 docstring const & content, bool for_xhtml)
222 // we have to do the escaping here, because we will ultimately
223 // write this as a raw string, so as not to escape the tags.
224 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
225 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
228 } // anonymous namespace
230 docstring InsetCitation::generateLabel(bool for_xhtml) const
233 label = complexLabel(for_xhtml);
235 // Fallback to fail-safe
237 label = basicLabel(for_xhtml);
243 docstring InsetCitation::complexLabel(bool for_xhtml) const
245 Buffer const & buf = buffer();
246 // Only start the process off after the buffer is loaded from file.
247 if (!buf.isFullyLoaded())
250 BiblioInfo const & biblist = buf.masterBibInfo();
254 docstring const & key = getParam("key");
256 return _("No citations selected!");
258 // We don't currently use the full or forceUCase fields.
259 string cite_type = getCmdName();
260 if (cite_type[0] == 'C')
261 // If we were going to use them, this would mean ForceUCase
262 cite_type = string(1, 'c') + cite_type.substr(1);
263 if (cite_type[cite_type.size() - 1] == '*')
264 // and this would mean FULL
265 cite_type = cite_type.substr(0, cite_type.size() - 1);
267 docstring const & before = getParam("before");
268 docstring const & after = getParam("after");
270 // FIXME: allow to add cite macros
272 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
273 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
276 vector<docstring> const keys = getVectorFromString(key);
277 label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, before, after);
282 docstring InsetCitation::basicLabel(bool for_xhtml) const
284 docstring keys = getParam("key");
289 // if there is no comma, then everything goes into key
290 // and keys will be empty.
291 keys = trim(split(keys, key, ','));
295 label += wrapCitation(key, key, for_xhtml);
296 } while (!keys.empty());
298 docstring const & after = getParam("after");
300 label += ", " + after;
302 return '[' + label + ']';
305 docstring InsetCitation::screenLabel() const
307 return cache.screen_label;
311 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
313 if (!cache.recalculate && buffer().citeLabelsValid())
316 // The label may have changed, so we have to re-create it.
317 docstring const glabel = generateLabel();
319 unsigned int const maxLabelChars = 45;
321 docstring label = glabel;
322 if (label.size() > maxLabelChars) {
323 label.erase(maxLabelChars - 3);
327 cache.recalculate = false;
328 cache.generated_label = glabel;
329 cache.screen_label = label;
333 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active) const
336 // XHTML output uses the TOC to collect the citations
337 // from the document. So if this gets changed, then we
338 // will need to change how the citations are collected.
339 docstring const tocitem = getParam("key");
340 Toc & toc = buffer().tocBackend().toc("citation");
341 toc.push_back(TocItem(cpit, 0, tocitem, output_active));
345 int InsetCitation::plaintext(odocstringstream & os,
346 OutputParams const &, size_t) const
348 string const & cmd = getCmdName();
352 docstring const label = generateLabel(false);
358 static docstring const cleanupWhitespace(docstring const & citelist)
360 docstring::const_iterator it = citelist.begin();
361 docstring::const_iterator end = citelist.end();
362 // Paranoia check: make sure that there is no whitespace in here
363 // -- at least not behind commas or at the beginning
365 char_type last = ',';
366 for (; it != end; ++it) {
369 if (*it != ' ' || last != ',')
376 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
378 os << from_ascii("<citation>")
379 << cleanupWhitespace(getParam("key"))
380 << from_ascii("</citation>");
385 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
387 string const & cmd = getCmdName();
391 // have to output this raw, because generateLabel() will include tags
392 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
398 void InsetCitation::toString(odocstream & os) const
400 odocstringstream ods;
401 plaintext(ods, OutputParams(0));
406 void InsetCitation::forToc(docstring & os, size_t) const
412 // Have to overwrite the default InsetCommand method in order to check that
413 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
414 // citations and then changes his mind, turning natbib support off. The output
415 // should revert to the default citation command as provided by the citation
416 // engine, e.g. \cite[]{} for the basic engine.
417 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
419 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
420 CitationStyle cs = asValidLatexCommand(getCmdName(), citation_styles);
421 BiblioInfo const & bi = buffer().masterBibInfo();
423 docstring const cite_str = from_utf8(citationStyleToString(cs));
425 if (runparams.inulemcmd)
428 os << "\\" << cite_str;
430 docstring const & before = getParam("before");
431 docstring const & after = getParam("after");
432 if (!before.empty() && cs.textBefore)
433 os << '[' << before << "][" << after << ']';
434 else if (!after.empty() && cs.textAfter)
435 os << '[' << after << ']';
437 if (!bi.isBibtex(getParam("key")))
438 // escape chars with bibitems
439 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
441 os << '{' << cleanupWhitespace(getParam("key")) << '}';
443 if (runparams.inulemcmd)
448 string InsetCitation::contextMenuName() const
450 return "context-citation";