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, but biblatex, jurabib
65 // and natbib extend 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);
77 // We allow any command here, since we fall back to cite
78 // anyway if a command is not allowed by a style
79 bool InsetCitation::isCompatibleCommand(string const &)
85 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
86 vector<CitationStyle> const & valid_styles) const
88 CitationStyle cs = valid_styles[0];
89 cs.forceUpperCase = false;
90 cs.hasStarredVersion = false;
92 string normalized_input = input;
93 string::size_type const n = input.size() - 1;
94 if (isUpperCase(input[0]))
95 normalized_input[0] = lowercase(input[0]);
97 normalized_input = normalized_input.substr(0, n);
99 string const alias = bp.getCiteAlias(normalized_input);
101 normalized_input = alias;
103 vector<CitationStyle>::const_iterator it = valid_styles.begin();
104 vector<CitationStyle>::const_iterator end = valid_styles.end();
105 for (; it != end; ++it) {
106 CitationStyle this_cs = *it;
107 if (this_cs.name == normalized_input) {
117 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
119 switch (cmd.action()) {
120 case LFUN_INSET_MODIFY: {
121 buffer().removeBiblioTempFiles();
122 cache.recalculate = true;
123 if (cmd.getArg(0) == "toggleparam") {
124 string cmdname = getCmdName();
126 buffer().params().getCiteAlias(cmdname);
129 string const par = cmd.getArg(1);
130 string newcmdname = cmdname;
132 if (suffixIs(cmdname, "*"))
133 newcmdname = rtrim(cmdname, "*");
135 newcmdname = cmdname + "*";
136 } else if (par == "casing") {
137 if (isUpperCase(cmdname[0]))
138 newcmdname[0] = lowercase(cmdname[0]);
140 newcmdname[0] = uppercase(newcmdname[0]);
142 cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
146 InsetCommand::doDispatch(cur, cmd);
151 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
152 FuncStatus & status) const
154 switch (cmd.action()) {
155 // Handle the alias case
156 case LFUN_INSET_MODIFY:
157 if (cmd.getArg(0) == "changetype") {
158 string cmdname = getCmdName();
160 buffer().params().getCiteAlias(cmdname);
163 if (suffixIs(cmdname, "*"))
164 cmdname = rtrim(cmdname, "*");
165 string const newtype = cmd.getArg(1);
166 status.setEnabled(isCompatibleCommand(newtype));
167 status.setOnOff(newtype == cmdname);
169 if (cmd.getArg(0) == "toggleparam") {
170 string cmdname = getCmdName();
172 buffer().params().getCiteAlias(cmdname);
175 vector<CitationStyle> citation_styles =
176 buffer().params().citeStyles();
177 CitationStyle cs = getCitationStyle(buffer().params(),
178 cmdname, citation_styles);
179 if (cmd.getArg(1) == "star") {
180 status.setEnabled(cs.hasStarredVersion);
181 status.setOnOff(suffixIs(cmdname, "*"));
183 else if (cmd.getArg(1) == "casing") {
184 status.setEnabled(cs.forceUpperCase);
185 status.setOnOff(isUpperCase(cmdname[0]));
190 return InsetCommand::getStatus(cur, cmd, status);
195 bool InsetCitation::addKey(string const & key)
197 docstring const ukey = from_utf8(key);
198 docstring const & curkeys = getParam("key");
199 if (curkeys.empty()) {
200 setParam("key", ukey);
201 cache.recalculate = true;
205 vector<docstring> keys = getVectorFromString(curkeys);
206 vector<docstring>::const_iterator it = keys.begin();
207 vector<docstring>::const_iterator en = keys.end();
208 for (; it != en; ++it) {
210 LYXERR0("Key " << key << " already present.");
214 keys.push_back(ukey);
215 setParam("key", getStringFromVector(keys));
216 cache.recalculate = true;
221 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
223 Buffer const & buf = bv.buffer();
224 // Only after the buffer is loaded from file...
225 if (!buf.isFullyLoaded())
228 BiblioInfo const & bi = buf.masterBibInfo();
230 return _("No bibliography defined!");
232 docstring const & key = getParam("key");
234 return _("No citations selected!");
238 vector<docstring> keys = getVectorFromString(key);
239 if (keys.size() == 1)
240 return bi.getInfo(keys[0], buffer(), ci);
245 for (docstring const & key : keys) {
246 docstring const key_info = bi.getInfo(key, buffer(), ci);
247 // limit to reasonable size.
248 if (count > 9 && keys.size() > 11) {
249 tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
251 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
255 if (key_info.empty())
257 tip += "<li>" + key_info + "</li>";
267 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
268 vector<CitationStyle> const & valid_styles)
270 CitationStyle cs = valid_styles[0];
271 cs.forceUpperCase = false;
272 cs.hasStarredVersion = false;
274 string normalized_input = input;
275 string::size_type const n = input.size() - 1;
276 if (isUpperCase(input[0]))
277 normalized_input[0] = lowercase(input[0]);
279 normalized_input = normalized_input.substr(0, n);
281 string const alias = bp.getCiteAlias(normalized_input);
283 normalized_input = alias;
285 vector<CitationStyle>::const_iterator it = valid_styles.begin();
286 vector<CitationStyle>::const_iterator end = valid_styles.end();
287 for (; it != end; ++it) {
288 CitationStyle this_cs = *it;
289 if (this_cs.name == normalized_input) {
295 cs.forceUpperCase &= input[0] == uppercase(input[0]);
296 cs.hasStarredVersion &= input[n] == '*';
302 inline docstring wrapCitation(docstring const & key,
303 docstring const & content, bool for_xhtml)
307 // we have to do the escaping here, because we will ultimately
308 // write this as a raw string, so as not to escape the tags.
309 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
310 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
313 } // anonymous namespace
315 docstring InsetCitation::generateLabel(bool for_xhtml) const
318 label = complexLabel(for_xhtml);
320 // Fallback to fail-safe
322 label = basicLabel(for_xhtml);
328 docstring InsetCitation::complexLabel(bool for_xhtml) const
330 Buffer const & buf = buffer();
331 // Only start the process off after the buffer is loaded from file.
332 if (!buf.isFullyLoaded())
335 BiblioInfo const & biblist = buf.masterBibInfo();
339 docstring const & key = getParam("key");
341 return _("No citations selected!");
343 string cite_type = getCmdName();
344 bool const uppercase = isUpperCase(cite_type[0]);
346 cite_type[0] = lowercase(cite_type[0]);
347 bool const starred = (cite_type[cite_type.size() - 1] == '*');
349 cite_type = cite_type.substr(0, cite_type.size() - 1);
352 string const alias = buf.params().getCiteAlias(cite_type);
356 // FIXME: allow to add cite macros
358 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
359 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
362 vector<docstring> keys = getVectorFromString(key);
364 ci.textBefore = getParam("before");
365 ci.textAfter = getParam("after");
366 ci.forceUpperCase = uppercase;
367 ci.Starred = starred;
368 ci.max_size = UINT_MAX;
370 ci.max_key_size = UINT_MAX;
371 ci.context = CiteItem::Export;
373 ci.richtext = for_xhtml;
374 label = biblist.getLabel(keys, buffer(), cite_type, ci);
379 docstring InsetCitation::basicLabel(bool for_xhtml) const
381 docstring keys = getParam("key");
386 // if there is no comma, then everything goes into key
387 // and keys will be empty.
388 keys = trim(split(keys, key, ','));
392 label += wrapCitation(key, key, for_xhtml);
393 } while (!keys.empty());
395 docstring const & after = getParam("after");
397 label += ", " + after;
399 return '[' + label + ']';
402 docstring InsetCitation::screenLabel() const
404 return cache.screen_label;
408 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
410 if (!cache.recalculate && buffer().citeLabelsValid())
412 // The label may have changed, so we have to re-create it.
413 docstring const glabel = generateLabel();
414 cache.recalculate = false;
415 cache.generated_label = glabel;
416 unsigned int const maxLabelChars = 45;
417 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
418 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
422 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
426 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
427 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
428 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
429 // then we will also need to change that routine.
430 docstring const tocitem = getParam("key");
431 TocBuilder & b = buffer().tocBackend().builder("citation");
432 b.pushItem(cpit, tocitem, output_active);
437 int InsetCitation::plaintext(odocstringstream & os,
438 OutputParams const &, size_t) const
440 string const & cmd = getCmdName();
444 docstring const label = generateLabel(false);
450 static docstring const cleanupWhitespace(docstring const & citelist)
452 docstring::const_iterator it = citelist.begin();
453 docstring::const_iterator end = citelist.end();
454 // Paranoia check: make sure that there is no whitespace in here
455 // -- at least not behind commas or at the beginning
457 char_type last = ',';
458 for (; it != end; ++it) {
461 if (*it != ' ' || last != ',')
468 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
470 os << from_ascii("<citation>")
471 << cleanupWhitespace(getParam("key"))
472 << from_ascii("</citation>");
477 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
479 string const & cmd = getCmdName();
483 // have to output this raw, because generateLabel() will include tags
484 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
490 void InsetCitation::toString(odocstream & os) const
492 odocstringstream ods;
493 plaintext(ods, OutputParams(0));
498 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
504 // Have to overwrite the default InsetCommand method in order to check that
505 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
506 // citations and then changes his mind, turning natbib support off. The output
507 // should revert to the default citation command as provided by the citation
508 // engine, e.g. \cite[]{} for the basic engine.
509 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
511 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
512 CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
513 BiblioInfo const & bi = buffer().masterBibInfo();
515 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
517 if (runparams.inulemcmd > 0)
520 os << "\\" << cite_str;
522 docstring const & before = getParam("before");
523 docstring const & after = getParam("after");
524 if (!before.empty() && cs.textBefore)
525 os << '[' << before << "][" << after << ']';
526 else if (!after.empty() && cs.textAfter)
527 os << '[' << after << ']';
529 if (!bi.isBibtex(getParam("key")))
530 // escape chars with bibitems
531 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
533 os << '{' << cleanupWhitespace(getParam("key")) << '}';
535 if (runparams.inulemcmd)
540 string InsetCitation::contextMenuName() const
542 return "context-citation";