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);
244 for (docstring const & key : keys) {
245 docstring const key_info = bi.getInfo(key, buffer(), ci);
246 if (key_info.empty())
248 tip += "<li>" + key_info + "</li>";
257 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
258 vector<CitationStyle> const & valid_styles)
260 CitationStyle cs = valid_styles[0];
261 cs.forceUpperCase = false;
262 cs.hasStarredVersion = false;
264 string normalized_input = input;
265 string::size_type const n = input.size() - 1;
266 if (isUpperCase(input[0]))
267 normalized_input[0] = lowercase(input[0]);
269 normalized_input = normalized_input.substr(0, n);
271 string const alias = bp.getCiteAlias(normalized_input);
273 normalized_input = alias;
275 vector<CitationStyle>::const_iterator it = valid_styles.begin();
276 vector<CitationStyle>::const_iterator end = valid_styles.end();
277 for (; it != end; ++it) {
278 CitationStyle this_cs = *it;
279 if (this_cs.name == normalized_input) {
285 cs.forceUpperCase &= input[0] == uppercase(input[0]);
286 cs.hasStarredVersion &= input[n] == '*';
292 inline docstring wrapCitation(docstring const & key,
293 docstring const & content, bool for_xhtml)
297 // we have to do the escaping here, because we will ultimately
298 // write this as a raw string, so as not to escape the tags.
299 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
300 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
303 } // anonymous namespace
305 docstring InsetCitation::generateLabel(bool for_xhtml) const
308 label = complexLabel(for_xhtml);
310 // Fallback to fail-safe
312 label = basicLabel(for_xhtml);
318 docstring InsetCitation::complexLabel(bool for_xhtml) const
320 Buffer const & buf = buffer();
321 // Only start the process off after the buffer is loaded from file.
322 if (!buf.isFullyLoaded())
325 BiblioInfo const & biblist = buf.masterBibInfo();
329 docstring const & key = getParam("key");
331 return _("No citations selected!");
333 string cite_type = getCmdName();
334 bool const uppercase = isUpperCase(cite_type[0]);
336 cite_type[0] = lowercase(cite_type[0]);
337 bool const starred = (cite_type[cite_type.size() - 1] == '*');
339 cite_type = cite_type.substr(0, cite_type.size() - 1);
342 string const alias = buf.params().getCiteAlias(cite_type);
346 // FIXME: allow to add cite macros
348 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
349 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
352 vector<docstring> keys = getVectorFromString(key);
354 ci.textBefore = getParam("before");
355 ci.textAfter = getParam("after");
356 ci.forceUpperCase = uppercase;
357 ci.Starred = starred;
358 ci.max_size = UINT_MAX;
360 ci.max_key_size = UINT_MAX;
361 ci.context = CiteItem::Export;
363 ci.richtext = for_xhtml;
364 label = biblist.getLabel(keys, buffer(), cite_type, ci);
369 docstring InsetCitation::basicLabel(bool for_xhtml) const
371 docstring keys = getParam("key");
376 // if there is no comma, then everything goes into key
377 // and keys will be empty.
378 keys = trim(split(keys, key, ','));
382 label += wrapCitation(key, key, for_xhtml);
383 } while (!keys.empty());
385 docstring const & after = getParam("after");
387 label += ", " + after;
389 return '[' + label + ']';
392 docstring InsetCitation::screenLabel() const
394 return cache.screen_label;
398 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
400 if (!cache.recalculate && buffer().citeLabelsValid())
402 // The label may have changed, so we have to re-create it.
403 docstring const glabel = generateLabel();
404 cache.recalculate = false;
405 cache.generated_label = glabel;
406 unsigned int const maxLabelChars = 45;
407 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
408 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
412 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
416 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
417 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
418 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
419 // then we will also need to change that routine.
420 docstring const tocitem = getParam("key");
421 shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
422 toc->push_back(TocItem(cpit, 0, tocitem, output_active));
426 int InsetCitation::plaintext(odocstringstream & os,
427 OutputParams const &, size_t) const
429 string const & cmd = getCmdName();
433 docstring const label = generateLabel(false);
439 static docstring const cleanupWhitespace(docstring const & citelist)
441 docstring::const_iterator it = citelist.begin();
442 docstring::const_iterator end = citelist.end();
443 // Paranoia check: make sure that there is no whitespace in here
444 // -- at least not behind commas or at the beginning
446 char_type last = ',';
447 for (; it != end; ++it) {
450 if (*it != ' ' || last != ',')
457 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
459 os << from_ascii("<citation>")
460 << cleanupWhitespace(getParam("key"))
461 << from_ascii("</citation>");
466 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
468 string const & cmd = getCmdName();
472 // have to output this raw, because generateLabel() will include tags
473 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
479 void InsetCitation::toString(odocstream & os) const
481 odocstringstream ods;
482 plaintext(ods, OutputParams(0));
487 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
493 // Have to overwrite the default InsetCommand method in order to check that
494 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
495 // citations and then changes his mind, turning natbib support off. The output
496 // should revert to the default citation command as provided by the citation
497 // engine, e.g. \cite[]{} for the basic engine.
498 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
500 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
501 CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
502 BiblioInfo const & bi = buffer().masterBibInfo();
504 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
506 if (runparams.inulemcmd > 0)
509 os << "\\" << cite_str;
511 docstring const & before = getParam("before");
512 docstring const & after = getParam("after");
513 if (!before.empty() && cs.textBefore)
514 os << '[' << before << "][" << after << ']';
515 else if (!after.empty() && cs.textAfter)
516 os << '[' << after << ']';
518 if (!bi.isBibtex(getParam("key")))
519 // escape chars with bibitems
520 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
522 os << '{' << cleanupWhitespace(getParam("key")) << '}';
524 if (runparams.inulemcmd)
529 string InsetCitation::contextMenuName() const
531 return "context-citation";