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 vector<docstring>::const_iterator it = keys.begin();
169 vector<docstring>::const_iterator en = keys.end();
171 for (; it != en; ++it) {
172 docstring const key_info = bi.getInfo(*it, buffer());
173 if (key_info.empty())
177 tip += wrap(key_info, -4);
186 CitationStyle asValidLatexCommand(string const & input, vector<CitationStyle> const & valid_styles)
188 CitationStyle cs = valid_styles[0];
189 cs.forceUpperCase = false;
190 cs.fullAuthorList = false;
191 if (!InsetCitation::isCompatibleCommand(input))
194 string normalized_input = input;
195 string::size_type const n = input.size() - 1;
197 normalized_input[0] = 'c';
199 normalized_input = normalized_input.substr(0, n);
201 vector<CitationStyle>::const_iterator it = valid_styles.begin();
202 vector<CitationStyle>::const_iterator end = valid_styles.end();
203 for (; it != end; ++it) {
204 CitationStyle this_cs = *it;
205 if (this_cs.cmd == normalized_input) {
211 cs.forceUpperCase &= input[0] == 'C';
212 cs.fullAuthorList &= input[n] == '*';
218 inline docstring wrapCitation(docstring const & key,
219 docstring const & content, bool for_xhtml)
223 // we have to do the escaping here, because we will ultimately
224 // write this as a raw string, so as not to escape the tags.
225 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
226 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
229 } // anonymous namespace
231 docstring InsetCitation::generateLabel(bool for_xhtml) const
234 label = complexLabel(for_xhtml);
236 // Fallback to fail-safe
238 label = basicLabel(for_xhtml);
244 docstring InsetCitation::complexLabel(bool for_xhtml) const
246 Buffer const & buf = buffer();
247 // Only start the process off after the buffer is loaded from file.
248 if (!buf.isFullyLoaded())
251 BiblioInfo const & biblist = buf.masterBibInfo();
255 docstring const & key = getParam("key");
257 return _("No citations selected!");
259 // We don't currently use the full or forceUCase fields.
260 string cite_type = getCmdName();
261 if (cite_type[0] == 'C')
262 // If we were going to use them, this would mean ForceUCase
263 cite_type = string(1, 'c') + cite_type.substr(1);
264 if (cite_type[cite_type.size() - 1] == '*')
265 // and this would mean FULL
266 cite_type = cite_type.substr(0, cite_type.size() - 1);
268 docstring const & before = getParam("before");
269 docstring const & after = getParam("after");
271 // FIXME: allow to add cite macros
273 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
274 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
277 vector<docstring> keys = getVectorFromString(key);
278 label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
283 docstring InsetCitation::basicLabel(bool for_xhtml) const
285 docstring keys = getParam("key");
290 // if there is no comma, then everything goes into key
291 // and keys will be empty.
292 keys = trim(split(keys, key, ','));
296 label += wrapCitation(key, key, for_xhtml);
297 } while (!keys.empty());
299 docstring const & after = getParam("after");
301 label += ", " + after;
303 return '[' + label + ']';
306 docstring InsetCitation::screenLabel() const
308 return cache.screen_label;
312 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
314 if (!cache.recalculate && buffer().citeLabelsValid())
316 // The label may have changed, so we have to re-create it.
317 docstring const glabel = generateLabel();
318 cache.recalculate = false;
319 cache.generated_label = glabel;
320 unsigned int const maxLabelChars = 45;
321 cache.screen_label = glabel.substr(0, maxLabelChars);
322 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
326 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
330 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
331 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
332 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
333 // then we will also need to change that routine.
334 docstring const tocitem = getParam("key");
335 shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
336 toc->push_back(TocItem(cpit, 0, tocitem, output_active));
340 int InsetCitation::plaintext(odocstringstream & os,
341 OutputParams const &, size_t) const
343 string const & cmd = getCmdName();
347 docstring const label = generateLabel(false);
353 static docstring const cleanupWhitespace(docstring const & citelist)
355 docstring::const_iterator it = citelist.begin();
356 docstring::const_iterator end = citelist.end();
357 // Paranoia check: make sure that there is no whitespace in here
358 // -- at least not behind commas or at the beginning
360 char_type last = ',';
361 for (; it != end; ++it) {
364 if (*it != ' ' || last != ',')
371 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
373 os << from_ascii("<citation>")
374 << cleanupWhitespace(getParam("key"))
375 << from_ascii("</citation>");
380 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
382 string const & cmd = getCmdName();
386 // have to output this raw, because generateLabel() will include tags
387 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
393 void InsetCitation::toString(odocstream & os) const
395 odocstringstream ods;
396 plaintext(ods, OutputParams(0));
401 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
407 // Have to overwrite the default InsetCommand method in order to check that
408 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
409 // citations and then changes his mind, turning natbib support off. The output
410 // should revert to the default citation command as provided by the citation
411 // engine, e.g. \cite[]{} for the basic engine.
412 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
414 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
415 CitationStyle cs = asValidLatexCommand(getCmdName(), citation_styles);
416 BiblioInfo const & bi = buffer().masterBibInfo();
418 docstring const cite_str = from_utf8(citationStyleToString(cs));
420 if (runparams.inulemcmd > 0)
423 os << "\\" << cite_str;
425 docstring const & before = getParam("before");
426 docstring const & after = getParam("after");
427 if (!before.empty() && cs.textBefore)
428 os << '[' << before << "][" << after << ']';
429 else if (!after.empty() && cs.textAfter)
430 os << '[' << after << ']';
432 if (!bi.isBibtex(getParam("key")))
433 // escape chars with bibitems
434 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
436 os << '{' << cleanupWhitespace(getParam("key")) << '}';
438 if (runparams.inulemcmd)
443 string InsetCitation::contextMenuName() const
445 return "context-citation";