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"
39 using namespace lyx::support;
43 ParamInfo InsetCitation::param_info_;
46 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
47 : InsetCommand(buf, p)
49 buffer().removeBiblioTempFiles();
53 InsetCitation::~InsetCitation()
56 buffer().removeBiblioTempFiles();
60 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
62 // standard cite does only take one argument if jurabib is
63 // not used, but jurabib extends this to two arguments, so
64 // we have to allow both here. InsetCitation takes care that
65 // LaTeX output is nevertheless correct.
66 if (param_info_.empty()) {
67 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
68 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
69 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
77 vector<string> const init_possible_cite_commands()
79 char const * const possible[] = {
80 "cite", "nocite", "citet", "citep", "citealt", "citealp",
81 "citeauthor", "citeyear", "citeyearpar",
82 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
83 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
84 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
86 "footcite", "footcitet", "footcitep", "footcitealt",
87 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
88 "citefield", "citetitle", "cite*"
90 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
92 return vector<string>(possible, possible + size_possible);
96 vector<string> const & possibleCiteCommands()
98 static vector<string> const possible = init_possible_cite_commands();
106 // FIXME: use the citeCommands provided by the TextClass
107 // instead of possibleCiteCommands defined in this file.
108 bool InsetCitation::isCompatibleCommand(string const & cmd)
110 vector<string> const & possibles = possibleCiteCommands();
111 vector<string>::const_iterator const end = possibles.end();
112 return find(possibles.begin(), end, cmd) != end;
116 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
118 if (cmd.action() == LFUN_INSET_MODIFY) {
119 buffer().removeBiblioTempFiles();
120 cache.recalculate = true;
122 InsetCommand::doDispatch(cur, cmd);
126 bool InsetCitation::addKey(string const & key)
128 docstring const ukey = from_utf8(key);
129 docstring const & curkeys = getParam("key");
130 if (curkeys.empty()) {
131 setParam("key", ukey);
132 cache.recalculate = true;
136 vector<docstring> keys = getVectorFromString(curkeys);
137 vector<docstring>::const_iterator it = keys.begin();
138 vector<docstring>::const_iterator en = keys.end();
139 for (; it != en; ++it) {
141 LYXERR0("Key " << key << " already present.");
145 keys.push_back(ukey);
146 setParam("key", getStringFromVector(keys));
147 cache.recalculate = true;
152 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
154 Buffer const & buf = bv.buffer();
155 // Only after the buffer is loaded from file...
156 if (!buf.isFullyLoaded())
159 BiblioInfo const & bi = buf.masterBibInfo();
161 return _("No bibliography defined!");
163 docstring const & key = getParam("key");
165 return _("No citations selected!");
167 vector<docstring> keys = getVectorFromString(key);
168 if (keys.size() == 1)
169 return bi.getInfo(keys[0], buffer(), true);
173 for (docstring const & key : keys) {
174 docstring const key_info = bi.getInfo(key, buffer(), true);
175 if (key_info.empty())
177 tip += "<li>" + key_info + "</li>";
187 CitationStyle asValidLatexCommand(string const & input, vector<CitationStyle> const & valid_styles)
189 CitationStyle cs = valid_styles[0];
190 cs.forceUpperCase = false;
191 cs.fullAuthorList = false;
192 if (!InsetCitation::isCompatibleCommand(input))
195 string normalized_input = input;
196 string::size_type const n = input.size() - 1;
198 normalized_input[0] = 'c';
200 normalized_input = normalized_input.substr(0, n);
202 vector<CitationStyle>::const_iterator it = valid_styles.begin();
203 vector<CitationStyle>::const_iterator end = valid_styles.end();
204 for (; it != end; ++it) {
205 CitationStyle this_cs = *it;
206 if (this_cs.cmd == normalized_input) {
212 cs.forceUpperCase &= input[0] == 'C';
213 cs.fullAuthorList &= input[n] == '*';
219 inline docstring wrapCitation(docstring const & key,
220 docstring const & content, bool for_xhtml)
224 // we have to do the escaping here, because we will ultimately
225 // write this as a raw string, so as not to escape the tags.
226 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
227 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
230 } // anonymous namespace
232 docstring InsetCitation::generateLabel(bool for_xhtml) const
235 label = complexLabel(for_xhtml);
237 // Fallback to fail-safe
239 label = basicLabel(for_xhtml);
245 docstring InsetCitation::complexLabel(bool for_xhtml) const
247 Buffer const & buf = buffer();
248 // Only start the process off after the buffer is loaded from file.
249 if (!buf.isFullyLoaded())
252 BiblioInfo const & biblist = buf.masterBibInfo();
256 docstring const & key = getParam("key");
258 return _("No citations selected!");
260 // We don't currently use the full or forceUCase fields.
261 string cite_type = getCmdName();
262 if (cite_type[0] == 'C')
263 // If we were going to use them, this would mean ForceUCase
264 cite_type = string(1, 'c') + cite_type.substr(1);
265 if (cite_type[cite_type.size() - 1] == '*')
266 // and this would mean FULL
267 cite_type = cite_type.substr(0, cite_type.size() - 1);
269 docstring const & before = getParam("before");
270 docstring const & after = getParam("after");
272 // FIXME: allow to add cite macros
274 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
275 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
278 vector<docstring> keys = getVectorFromString(key);
279 label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
284 docstring InsetCitation::basicLabel(bool for_xhtml) const
286 docstring keys = getParam("key");
291 // if there is no comma, then everything goes into key
292 // and keys will be empty.
293 keys = trim(split(keys, key, ','));
297 label += wrapCitation(key, key, for_xhtml);
298 } while (!keys.empty());
300 docstring const & after = getParam("after");
302 label += ", " + after;
304 return '[' + label + ']';
307 docstring InsetCitation::screenLabel() const
309 return cache.screen_label;
313 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
315 if (!cache.recalculate && buffer().citeLabelsValid())
317 // The label may have changed, so we have to re-create it.
318 docstring const glabel = generateLabel();
319 cache.recalculate = false;
320 cache.generated_label = glabel;
321 unsigned int const maxLabelChars = 45;
322 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
323 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
327 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
331 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
332 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
333 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
334 // then we will also need to change that routine.
335 docstring const tocitem = getParam("key");
336 shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
337 toc->push_back(TocItem(cpit, 0, tocitem, output_active));
341 int InsetCitation::plaintext(odocstringstream & os,
342 OutputParams const &, size_t) const
344 string const & cmd = getCmdName();
348 docstring const label = generateLabel(false);
354 static docstring const cleanupWhitespace(docstring const & citelist)
356 docstring::const_iterator it = citelist.begin();
357 docstring::const_iterator end = citelist.end();
358 // Paranoia check: make sure that there is no whitespace in here
359 // -- at least not behind commas or at the beginning
361 char_type last = ',';
362 for (; it != end; ++it) {
365 if (*it != ' ' || last != ',')
372 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
374 os << from_ascii("<citation>")
375 << cleanupWhitespace(getParam("key"))
376 << from_ascii("</citation>");
381 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
383 string const & cmd = getCmdName();
387 // have to output this raw, because generateLabel() will include tags
388 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
394 void InsetCitation::toString(odocstream & os) const
396 odocstringstream ods;
397 plaintext(ods, OutputParams(0));
402 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
408 // Have to overwrite the default InsetCommand method in order to check that
409 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
410 // citations and then changes his mind, turning natbib support off. The output
411 // should revert to the default citation command as provided by the citation
412 // engine, e.g. \cite[]{} for the basic engine.
413 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
415 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
416 CitationStyle cs = asValidLatexCommand(getCmdName(), citation_styles);
417 BiblioInfo const & bi = buffer().masterBibInfo();
419 docstring const cite_str = from_utf8(citationStyleToString(cs));
421 if (runparams.inulemcmd > 0)
424 os << "\\" << cite_str;
426 docstring const & before = getParam("before");
427 docstring const & after = getParam("after");
428 if (!before.empty() && cs.textBefore)
429 os << '[' << before << "][" << after << ']';
430 else if (!after.empty() && cs.textAfter)
431 os << '[' << after << ']';
433 if (!bi.isBibtex(getParam("key")))
434 // escape chars with bibitems
435 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
437 os << '{' << cleanupWhitespace(getParam("key")) << '}';
439 if (runparams.inulemcmd)
444 string InsetCitation::contextMenuName() const
446 return "context-citation";