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 "FuncStatus.h"
25 #include "LaTeXFeatures.h"
26 #include "output_xhtml.h"
27 #include "ParIterator.h"
28 #include "texstream.h"
29 #include "TocBackend.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/FileNameList.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
41 using namespace lyx::support;
45 ParamInfo InsetCitation::param_info_;
48 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
49 : InsetCommand(buf, p)
51 buffer().removeBiblioTempFiles();
55 InsetCitation::~InsetCitation()
58 buffer().removeBiblioTempFiles();
62 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
64 // standard cite does only take one argument if jurabib is
65 // not used, but jurabib extends this to two arguments, so
66 // we have to allow both here. InsetCitation takes care that
67 // LaTeX output is nevertheless correct.
68 if (param_info_.empty()) {
69 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
70 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
71 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
79 vector<string> const init_possible_cite_commands()
81 char const * const possible[] = {
82 "cite", "nocite", "citet", "citep", "citealt", "citealp",
83 "citeauthor", "citeyear", "citeyearpar",
84 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
85 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
86 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
88 "footcite", "footcitet", "footcitep", "footcitealt",
89 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
90 "citefield", "citetitle", "cite*"
92 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
94 return vector<string>(possible, possible + size_possible);
98 vector<string> const & possibleCiteCommands()
100 static vector<string> const possible = init_possible_cite_commands();
108 // FIXME: use the citeCommands provided by the TextClass
109 // instead of possibleCiteCommands defined in this file.
110 bool InsetCitation::isCompatibleCommand(string const & cmd)
112 vector<string> const & possibles = possibleCiteCommands();
113 vector<string>::const_iterator const end = possibles.end();
114 return find(possibles.begin(), end, cmd) != end;
118 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
120 if (cmd.action() == LFUN_INSET_MODIFY) {
121 buffer().removeBiblioTempFiles();
122 cache.recalculate = true;
124 InsetCommand::doDispatch(cur, cmd);
128 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
129 FuncStatus & status) const
131 switch (cmd.action()) {
132 // Handle the alias case
133 case LFUN_INSET_MODIFY:
134 if (cmd.getArg(0) == "changetype") {
135 string cmdname = getCmdName();
136 string const alias = buffer().params().getCiteAlias(cmdname);
139 string const newtype = cmd.getArg(1);
140 status.setEnabled(isCompatibleCommand(newtype));
141 status.setOnOff(newtype == cmdname);
143 status.setEnabled(true);
146 return InsetCommand::getStatus(cur, cmd, status);
151 bool InsetCitation::addKey(string const & key)
153 docstring const ukey = from_utf8(key);
154 docstring const & curkeys = getParam("key");
155 if (curkeys.empty()) {
156 setParam("key", ukey);
157 cache.recalculate = true;
161 vector<docstring> keys = getVectorFromString(curkeys);
162 vector<docstring>::const_iterator it = keys.begin();
163 vector<docstring>::const_iterator en = keys.end();
164 for (; it != en; ++it) {
166 LYXERR0("Key " << key << " already present.");
170 keys.push_back(ukey);
171 setParam("key", getStringFromVector(keys));
172 cache.recalculate = true;
177 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
179 Buffer const & buf = bv.buffer();
180 // Only after the buffer is loaded from file...
181 if (!buf.isFullyLoaded())
184 BiblioInfo const & bi = buf.masterBibInfo();
186 return _("No bibliography defined!");
188 docstring const & key = getParam("key");
190 return _("No citations selected!");
192 vector<docstring> keys = getVectorFromString(key);
193 if (keys.size() == 1)
194 return bi.getInfo(keys[0], buffer(), true);
198 for (docstring const & key : keys) {
199 docstring const key_info = bi.getInfo(key, buffer(), true);
200 if (key_info.empty())
202 tip += "<li>" + key_info + "</li>";
212 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
213 vector<CitationStyle> const & valid_styles)
215 CitationStyle cs = valid_styles[0];
216 cs.forceUpperCase = false;
217 if (!InsetCitation::isCompatibleCommand(input))
219 cs.hasStarredVersion = false;
221 string normalized_input = input;
222 string::size_type const n = input.size() - 1;
223 if (isUpperCase(input[0]))
224 normalized_input[0] = lowercase(input[0]);
226 normalized_input = normalized_input.substr(0, n);
228 string const alias = bp.getCiteAlias(normalized_input);
230 normalized_input = alias;
232 vector<CitationStyle>::const_iterator it = valid_styles.begin();
233 vector<CitationStyle>::const_iterator end = valid_styles.end();
234 for (; it != end; ++it) {
235 CitationStyle this_cs = *it;
236 if (this_cs.name == normalized_input) {
242 cs.forceUpperCase &= input[0] == uppercase(input[0]);
243 cs.hasStarredVersion &= input[n] == '*';
249 inline docstring wrapCitation(docstring const & key,
250 docstring const & content, bool for_xhtml)
254 // we have to do the escaping here, because we will ultimately
255 // write this as a raw string, so as not to escape the tags.
256 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
257 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
260 } // anonymous namespace
262 docstring InsetCitation::generateLabel(bool for_xhtml) const
265 label = complexLabel(for_xhtml);
267 // Fallback to fail-safe
269 label = basicLabel(for_xhtml);
275 docstring InsetCitation::complexLabel(bool for_xhtml) const
277 Buffer const & buf = buffer();
278 // Only start the process off after the buffer is loaded from file.
279 if (!buf.isFullyLoaded())
282 BiblioInfo const & biblist = buf.masterBibInfo();
286 docstring const & key = getParam("key");
288 return _("No citations selected!");
290 // We don't currently use the full or forceUCase fields.
291 string cite_type = getCmdName();
292 if (isUpperCase(cite_type[0]))
293 // If we were going to use them, this would mean ForceUCase
294 cite_type[0] = lowercase(cite_type[0]);
295 if (cite_type[cite_type.size() - 1] == '*')
296 // and this would mean FULL
297 cite_type = cite_type.substr(0, cite_type.size() - 1);
300 string const alias = buf.params().getCiteAlias(cite_type);
304 docstring const & before = getParam("before");
305 docstring const & after = getParam("after");
307 // FIXME: allow to add cite macros
309 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
310 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
313 vector<docstring> keys = getVectorFromString(key);
314 label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
319 docstring InsetCitation::basicLabel(bool for_xhtml) const
321 docstring keys = getParam("key");
326 // if there is no comma, then everything goes into key
327 // and keys will be empty.
328 keys = trim(split(keys, key, ','));
332 label += wrapCitation(key, key, for_xhtml);
333 } while (!keys.empty());
335 docstring const & after = getParam("after");
337 label += ", " + after;
339 return '[' + label + ']';
342 docstring InsetCitation::screenLabel() const
344 return cache.screen_label;
348 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
350 if (!cache.recalculate && buffer().citeLabelsValid())
352 // The label may have changed, so we have to re-create it.
353 docstring const glabel = generateLabel();
354 cache.recalculate = false;
355 cache.generated_label = glabel;
356 unsigned int const maxLabelChars = 45;
357 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
358 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
362 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
366 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
367 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
368 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
369 // then we will also need to change that routine.
370 docstring const tocitem = getParam("key");
371 shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
372 toc->push_back(TocItem(cpit, 0, tocitem, output_active));
376 int InsetCitation::plaintext(odocstringstream & os,
377 OutputParams const &, size_t) const
379 string const & cmd = getCmdName();
383 docstring const label = generateLabel(false);
389 static docstring const cleanupWhitespace(docstring const & citelist)
391 docstring::const_iterator it = citelist.begin();
392 docstring::const_iterator end = citelist.end();
393 // Paranoia check: make sure that there is no whitespace in here
394 // -- at least not behind commas or at the beginning
396 char_type last = ',';
397 for (; it != end; ++it) {
400 if (*it != ' ' || last != ',')
407 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
409 os << from_ascii("<citation>")
410 << cleanupWhitespace(getParam("key"))
411 << from_ascii("</citation>");
416 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
418 string const & cmd = getCmdName();
422 // have to output this raw, because generateLabel() will include tags
423 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
429 void InsetCitation::toString(odocstream & os) const
431 odocstringstream ods;
432 plaintext(ods, OutputParams(0));
437 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
443 // Have to overwrite the default InsetCommand method in order to check that
444 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
445 // citations and then changes his mind, turning natbib support off. The output
446 // should revert to the default citation command as provided by the citation
447 // engine, e.g. \cite[]{} for the basic engine.
448 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
450 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
451 CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
452 BiblioInfo const & bi = buffer().masterBibInfo();
454 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
456 if (runparams.inulemcmd > 0)
459 os << "\\" << cite_str;
461 docstring const & before = getParam("before");
462 docstring const & after = getParam("after");
463 if (!before.empty() && cs.textBefore)
464 os << '[' << before << "][" << after << ']';
465 else if (!after.empty() && cs.textAfter)
466 os << '[' << after << ']';
468 if (!bi.isBibtex(getParam("key")))
469 // escape chars with bibitems
470 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
472 os << '{' << cleanupWhitespace(getParam("key")) << '}';
474 if (runparams.inulemcmd)
479 string InsetCitation::contextMenuName() const
481 return "context-citation";