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 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
87 if (cmd.action() == LFUN_INSET_MODIFY) {
88 buffer().removeBiblioTempFiles();
89 cache.recalculate = true;
91 InsetCommand::doDispatch(cur, cmd);
95 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
96 FuncStatus & status) const
98 switch (cmd.action()) {
99 // Handle the alias case
100 case LFUN_INSET_MODIFY:
101 if (cmd.getArg(0) == "changetype") {
102 string cmdname = getCmdName();
103 string const alias = buffer().params().getCiteAlias(cmdname);
106 string const newtype = cmd.getArg(1);
107 status.setEnabled(isCompatibleCommand(newtype));
108 status.setOnOff(newtype == cmdname);
110 status.setEnabled(true);
113 return InsetCommand::getStatus(cur, cmd, status);
118 bool InsetCitation::addKey(string const & key)
120 docstring const ukey = from_utf8(key);
121 docstring const & curkeys = getParam("key");
122 if (curkeys.empty()) {
123 setParam("key", ukey);
124 cache.recalculate = true;
128 vector<docstring> keys = getVectorFromString(curkeys);
129 vector<docstring>::const_iterator it = keys.begin();
130 vector<docstring>::const_iterator en = keys.end();
131 for (; it != en; ++it) {
133 LYXERR0("Key " << key << " already present.");
137 keys.push_back(ukey);
138 setParam("key", getStringFromVector(keys));
139 cache.recalculate = true;
144 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
146 Buffer const & buf = bv.buffer();
147 // Only after the buffer is loaded from file...
148 if (!buf.isFullyLoaded())
151 BiblioInfo const & bi = buf.masterBibInfo();
153 return _("No bibliography defined!");
155 docstring const & key = getParam("key");
157 return _("No citations selected!");
161 vector<docstring> keys = getVectorFromString(key);
162 if (keys.size() == 1)
163 return bi.getInfo(keys[0], buffer(), ci);
167 for (docstring const & key : keys) {
168 docstring const key_info = bi.getInfo(key, buffer(), ci);
169 if (key_info.empty())
171 tip += "<li>" + key_info + "</li>";
180 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
181 vector<CitationStyle> const & valid_styles)
183 CitationStyle cs = valid_styles[0];
184 cs.forceUpperCase = false;
185 cs.hasStarredVersion = false;
187 string normalized_input = input;
188 string::size_type const n = input.size() - 1;
189 if (isUpperCase(input[0]))
190 normalized_input[0] = lowercase(input[0]);
192 normalized_input = normalized_input.substr(0, n);
194 string const alias = bp.getCiteAlias(normalized_input);
196 normalized_input = alias;
198 vector<CitationStyle>::const_iterator it = valid_styles.begin();
199 vector<CitationStyle>::const_iterator end = valid_styles.end();
200 for (; it != end; ++it) {
201 CitationStyle this_cs = *it;
202 if (this_cs.name == normalized_input) {
208 cs.forceUpperCase &= input[0] == uppercase(input[0]);
209 cs.hasStarredVersion &= input[n] == '*';
215 inline docstring wrapCitation(docstring const & key,
216 docstring const & content, bool for_xhtml)
220 // we have to do the escaping here, because we will ultimately
221 // write this as a raw string, so as not to escape the tags.
222 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
223 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
226 } // anonymous namespace
228 docstring InsetCitation::generateLabel(bool for_xhtml) const
231 label = complexLabel(for_xhtml);
233 // Fallback to fail-safe
235 label = basicLabel(for_xhtml);
241 docstring InsetCitation::complexLabel(bool for_xhtml) const
243 Buffer const & buf = buffer();
244 // Only start the process off after the buffer is loaded from file.
245 if (!buf.isFullyLoaded())
248 BiblioInfo const & biblist = buf.masterBibInfo();
252 docstring const & key = getParam("key");
254 return _("No citations selected!");
256 string cite_type = getCmdName();
257 bool const uppercase = isUpperCase(cite_type[0]);
259 cite_type[0] = lowercase(cite_type[0]);
260 bool const starred = (cite_type[cite_type.size() - 1] == '*');
262 cite_type = cite_type.substr(0, cite_type.size() - 1);
265 string const alias = buf.params().getCiteAlias(cite_type);
269 // FIXME: allow to add cite macros
271 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
272 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
275 vector<docstring> keys = getVectorFromString(key);
277 ci.textBefore = getParam("before");
278 ci.textAfter = getParam("after");
279 ci.forceUpperCase = uppercase;
280 ci.Starred = starred;
281 ci.max_size = UINT_MAX;
283 ci.max_key_size = UINT_MAX;
284 ci.context = CiteItem::Export;
286 ci.richtext = for_xhtml;
287 label = biblist.getLabel(keys, buffer(), cite_type, ci);
292 docstring InsetCitation::basicLabel(bool for_xhtml) const
294 docstring keys = getParam("key");
299 // if there is no comma, then everything goes into key
300 // and keys will be empty.
301 keys = trim(split(keys, key, ','));
305 label += wrapCitation(key, key, for_xhtml);
306 } while (!keys.empty());
308 docstring const & after = getParam("after");
310 label += ", " + after;
312 return '[' + label + ']';
315 docstring InsetCitation::screenLabel() const
317 return cache.screen_label;
321 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
323 if (!cache.recalculate && buffer().citeLabelsValid())
325 // The label may have changed, so we have to re-create it.
326 docstring const glabel = generateLabel();
327 cache.recalculate = false;
328 cache.generated_label = glabel;
329 unsigned int const maxLabelChars = 45;
330 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
331 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
335 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
339 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
340 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
341 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
342 // then we will also need to change that routine.
343 docstring const tocitem = getParam("key");
344 shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
345 toc->push_back(TocItem(cpit, 0, tocitem, output_active));
349 int InsetCitation::plaintext(odocstringstream & os,
350 OutputParams const &, size_t) const
352 string const & cmd = getCmdName();
356 docstring const label = generateLabel(false);
362 static docstring const cleanupWhitespace(docstring const & citelist)
364 docstring::const_iterator it = citelist.begin();
365 docstring::const_iterator end = citelist.end();
366 // Paranoia check: make sure that there is no whitespace in here
367 // -- at least not behind commas or at the beginning
369 char_type last = ',';
370 for (; it != end; ++it) {
373 if (*it != ' ' || last != ',')
380 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
382 os << from_ascii("<citation>")
383 << cleanupWhitespace(getParam("key"))
384 << from_ascii("</citation>");
389 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
391 string const & cmd = getCmdName();
395 // have to output this raw, because generateLabel() will include tags
396 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
402 void InsetCitation::toString(odocstream & os) const
404 odocstringstream ods;
405 plaintext(ods, OutputParams(0));
410 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
416 // Have to overwrite the default InsetCommand method in order to check that
417 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
418 // citations and then changes his mind, turning natbib support off. The output
419 // should revert to the default citation command as provided by the citation
420 // engine, e.g. \cite[]{} for the basic engine.
421 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
423 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
424 CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
425 BiblioInfo const & bi = buffer().masterBibInfo();
427 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
429 if (runparams.inulemcmd > 0)
432 os << "\\" << cite_str;
434 docstring const & before = getParam("before");
435 docstring const & after = getParam("after");
436 if (!before.empty() && cs.textBefore)
437 os << '[' << before << "][" << after << ']';
438 else if (!after.empty() && cs.textAfter)
439 os << '[' << after << ']';
441 if (!bi.isBibtex(getParam("key")))
442 // escape chars with bibitems
443 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
445 os << '{' << cleanupWhitespace(getParam("key")) << '}';
447 if (runparams.inulemcmd)
452 string InsetCitation::contextMenuName() const
454 return "context-citation";