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 "texstream.h"
28 #include "TocBackend.h"
30 #include "support/debug.h"
31 #include "support/docstream.h"
32 #include "support/FileNameList.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
40 using namespace lyx::support;
44 ParamInfo InsetCitation::param_info_;
47 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
48 : InsetCommand(buf, p)
50 buffer().removeBiblioTempFiles();
54 InsetCitation::~InsetCitation()
57 buffer().removeBiblioTempFiles();
61 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
63 // standard cite does only take one argument if jurabib is
64 // not used, but jurabib extends this to two arguments, so
65 // we have to allow both here. InsetCitation takes care that
66 // LaTeX output is nevertheless correct.
67 if (param_info_.empty()) {
68 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
69 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
70 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
78 vector<string> const init_possible_cite_commands()
80 char const * const possible[] = {
81 "cite", "nocite", "citet", "citep", "citealt", "citealp",
82 "citeauthor", "citeyear", "citeyearpar",
83 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
84 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
85 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
87 "footcite", "footcitet", "footcitep", "footcitealt",
88 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
89 "citefield", "citetitle", "cite*"
91 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
93 return vector<string>(possible, possible + size_possible);
97 vector<string> const & possibleCiteCommands()
99 static vector<string> const possible = init_possible_cite_commands();
107 // FIXME: use the citeCommands provided by the TextClass
108 // instead of possibleCiteCommands defined in this file.
109 bool InsetCitation::isCompatibleCommand(string const & cmd)
111 vector<string> const & possibles = possibleCiteCommands();
112 vector<string>::const_iterator const end = possibles.end();
113 return find(possibles.begin(), end, cmd) != end;
117 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
119 if (cmd.action() == LFUN_INSET_MODIFY) {
120 buffer().removeBiblioTempFiles();
121 cache.recalculate = true;
123 InsetCommand::doDispatch(cur, cmd);
127 bool InsetCitation::addKey(string const & key)
129 docstring const ukey = from_utf8(key);
130 docstring const & curkeys = getParam("key");
131 if (curkeys.empty()) {
132 setParam("key", ukey);
133 cache.recalculate = true;
137 vector<docstring> keys = getVectorFromString(curkeys);
138 vector<docstring>::const_iterator it = keys.begin();
139 vector<docstring>::const_iterator en = keys.end();
140 for (; it != en; ++it) {
142 LYXERR0("Key " << key << " already present.");
146 keys.push_back(ukey);
147 setParam("key", getStringFromVector(keys));
148 cache.recalculate = true;
153 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
155 Buffer const & buf = bv.buffer();
156 // Only after the buffer is loaded from file...
157 if (!buf.isFullyLoaded())
160 BiblioInfo const & bi = buf.masterBibInfo();
162 return _("No bibliography defined!");
164 docstring const & key = getParam("key");
166 return _("No citations selected!");
168 vector<docstring> keys = getVectorFromString(key);
169 if (keys.size() == 1)
170 return bi.getInfo(keys[0], buffer(), true);
174 for (docstring const & key : keys) {
175 docstring const key_info = bi.getInfo(key, buffer(), true);
176 if (key_info.empty())
178 tip += "<li>" + key_info + "</li>";
188 CitationStyle asValidLatexCommand(string const & input, vector<CitationStyle> const & valid_styles)
190 CitationStyle cs = valid_styles[0];
191 cs.forceUpperCase = false;
192 cs.fullAuthorList = false;
193 if (!InsetCitation::isCompatibleCommand(input))
196 string normalized_input = input;
197 string::size_type const n = input.size() - 1;
199 normalized_input[0] = 'c';
201 normalized_input = normalized_input.substr(0, n);
203 vector<CitationStyle>::const_iterator it = valid_styles.begin();
204 vector<CitationStyle>::const_iterator end = valid_styles.end();
205 for (; it != end; ++it) {
206 CitationStyle this_cs = *it;
207 if (this_cs.cmd == normalized_input) {
213 cs.forceUpperCase &= input[0] == 'C';
214 cs.fullAuthorList &= input[n] == '*';
220 inline docstring wrapCitation(docstring const & key,
221 docstring const & content, bool for_xhtml)
225 // we have to do the escaping here, because we will ultimately
226 // write this as a raw string, so as not to escape the tags.
227 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
228 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
231 } // anonymous namespace
233 docstring InsetCitation::generateLabel(bool for_xhtml) const
236 label = complexLabel(for_xhtml);
238 // Fallback to fail-safe
240 label = basicLabel(for_xhtml);
246 docstring InsetCitation::complexLabel(bool for_xhtml) const
248 Buffer const & buf = buffer();
249 // Only start the process off after the buffer is loaded from file.
250 if (!buf.isFullyLoaded())
253 BiblioInfo const & biblist = buf.masterBibInfo();
257 docstring const & key = getParam("key");
259 return _("No citations selected!");
261 // We don't currently use the full or forceUCase fields.
262 string cite_type = getCmdName();
263 if (cite_type[0] == 'C')
264 // If we were going to use them, this would mean ForceUCase
265 cite_type = string(1, 'c') + cite_type.substr(1);
266 if (cite_type[cite_type.size() - 1] == '*')
267 // and this would mean FULL
268 cite_type = cite_type.substr(0, cite_type.size() - 1);
270 docstring const & before = getParam("before");
271 docstring const & after = getParam("after");
273 // FIXME: allow to add cite macros
275 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
276 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
279 vector<docstring> keys = getVectorFromString(key);
280 label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
285 docstring InsetCitation::basicLabel(bool for_xhtml) const
287 docstring keys = getParam("key");
292 // if there is no comma, then everything goes into key
293 // and keys will be empty.
294 keys = trim(split(keys, key, ','));
298 label += wrapCitation(key, key, for_xhtml);
299 } while (!keys.empty());
301 docstring const & after = getParam("after");
303 label += ", " + after;
305 return '[' + label + ']';
308 docstring InsetCitation::screenLabel() const
310 return cache.screen_label;
314 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
316 if (!cache.recalculate && buffer().citeLabelsValid())
318 // The label may have changed, so we have to re-create it.
319 docstring const glabel = generateLabel();
320 cache.recalculate = false;
321 cache.generated_label = glabel;
322 unsigned int const maxLabelChars = 45;
323 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
324 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
328 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
332 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
333 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
334 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
335 // then we will also need to change that routine.
336 docstring const tocitem = getParam("key");
337 shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
338 toc->push_back(TocItem(cpit, 0, tocitem, output_active));
342 int InsetCitation::plaintext(odocstringstream & os,
343 OutputParams const &, size_t) const
345 string const & cmd = getCmdName();
349 docstring const label = generateLabel(false);
355 static docstring const cleanupWhitespace(docstring const & citelist)
357 docstring::const_iterator it = citelist.begin();
358 docstring::const_iterator end = citelist.end();
359 // Paranoia check: make sure that there is no whitespace in here
360 // -- at least not behind commas or at the beginning
362 char_type last = ',';
363 for (; it != end; ++it) {
366 if (*it != ' ' || last != ',')
373 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
375 os << from_ascii("<citation>")
376 << cleanupWhitespace(getParam("key"))
377 << from_ascii("</citation>");
382 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
384 string const & cmd = getCmdName();
388 // have to output this raw, because generateLabel() will include tags
389 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
395 void InsetCitation::toString(odocstream & os) const
397 odocstringstream ods;
398 plaintext(ods, OutputParams(0));
403 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
409 // Have to overwrite the default InsetCommand method in order to check that
410 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
411 // citations and then changes his mind, turning natbib support off. The output
412 // should revert to the default citation command as provided by the citation
413 // engine, e.g. \cite[]{} for the basic engine.
414 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
416 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
417 CitationStyle cs = asValidLatexCommand(getCmdName(), citation_styles);
418 BiblioInfo const & bi = buffer().masterBibInfo();
420 docstring const cite_str = from_utf8(citationStyleToString(cs));
422 if (runparams.inulemcmd > 0)
425 os << "\\" << cite_str;
427 docstring const & before = getParam("before");
428 docstring const & after = getParam("after");
429 if (!before.empty() && cs.textBefore)
430 os << '[' << before << "][" << after << ']';
431 else if (!after.empty() && cs.textAfter)
432 os << '[' << after << ']';
434 if (!bi.isBibtex(getParam("key")))
435 // escape chars with bibitems
436 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
438 os << '{' << cleanupWhitespace(getParam("key")) << '}';
440 if (runparams.inulemcmd)
445 string InsetCitation::contextMenuName() const
447 return "context-citation";