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!");
159 vector<docstring> keys = getVectorFromString(key);
160 if (keys.size() == 1)
161 return bi.getInfo(keys[0], buffer(), true);
165 for (docstring const & key : keys) {
166 docstring const key_info = bi.getInfo(key, buffer(), true);
167 if (key_info.empty())
169 tip += "<li>" + key_info + "</li>";
179 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
180 vector<CitationStyle> const & valid_styles)
182 CitationStyle cs = valid_styles[0];
183 cs.forceUpperCase = false;
184 cs.hasStarredVersion = false;
186 string normalized_input = input;
187 string::size_type const n = input.size() - 1;
188 if (isUpperCase(input[0]))
189 normalized_input[0] = lowercase(input[0]);
191 normalized_input = normalized_input.substr(0, n);
193 string const alias = bp.getCiteAlias(normalized_input);
195 normalized_input = alias;
197 vector<CitationStyle>::const_iterator it = valid_styles.begin();
198 vector<CitationStyle>::const_iterator end = valid_styles.end();
199 for (; it != end; ++it) {
200 CitationStyle this_cs = *it;
201 if (this_cs.name == normalized_input) {
207 cs.forceUpperCase &= input[0] == uppercase(input[0]);
208 cs.hasStarredVersion &= input[n] == '*';
214 inline docstring wrapCitation(docstring const & key,
215 docstring const & content, bool for_xhtml)
219 // we have to do the escaping here, because we will ultimately
220 // write this as a raw string, so as not to escape the tags.
221 return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
222 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
225 } // anonymous namespace
227 docstring InsetCitation::generateLabel(bool for_xhtml) const
230 label = complexLabel(for_xhtml);
232 // Fallback to fail-safe
234 label = basicLabel(for_xhtml);
240 docstring InsetCitation::complexLabel(bool for_xhtml) const
242 Buffer const & buf = buffer();
243 // Only start the process off after the buffer is loaded from file.
244 if (!buf.isFullyLoaded())
247 BiblioInfo const & biblist = buf.masterBibInfo();
251 docstring const & key = getParam("key");
253 return _("No citations selected!");
255 // We don't currently use the full or forceUCase fields.
256 string cite_type = getCmdName();
257 if (isUpperCase(cite_type[0]))
258 // If we were going to use them, this would mean ForceUCase
259 cite_type[0] = lowercase(cite_type[0]);
260 if (cite_type[cite_type.size() - 1] == '*')
261 // and this would mean FULL
262 cite_type = cite_type.substr(0, cite_type.size() - 1);
265 string const alias = buf.params().getCiteAlias(cite_type);
269 docstring const & before = getParam("before");
270 docstring const & after = getParam("after");
272 // FIXME: allow to add cite macros
274 buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
275 buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
278 vector<docstring> keys = getVectorFromString(key);
279 label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
284 docstring InsetCitation::basicLabel(bool for_xhtml) const
286 docstring keys = getParam("key");
291 // if there is no comma, then everything goes into key
292 // and keys will be empty.
293 keys = trim(split(keys, key, ','));
297 label += wrapCitation(key, key, for_xhtml);
298 } while (!keys.empty());
300 docstring const & after = getParam("after");
302 label += ", " + after;
304 return '[' + label + ']';
307 docstring InsetCitation::screenLabel() const
309 return cache.screen_label;
313 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
315 if (!cache.recalculate && buffer().citeLabelsValid())
317 // The label may have changed, so we have to re-create it.
318 docstring const glabel = generateLabel();
319 cache.recalculate = false;
320 cache.generated_label = glabel;
321 unsigned int const maxLabelChars = 45;
322 cache.screen_label = glabel.substr(0, maxLabelChars + 1);
323 support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
327 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
331 // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
332 // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
333 // by both XHTML and plaintext output. So, if we change what goes into the TOC,
334 // then we will also need to change that routine.
335 docstring const tocitem = getParam("key");
336 shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
337 toc->push_back(TocItem(cpit, 0, tocitem, output_active));
341 int InsetCitation::plaintext(odocstringstream & os,
342 OutputParams const &, size_t) const
344 string const & cmd = getCmdName();
348 docstring const label = generateLabel(false);
354 static docstring const cleanupWhitespace(docstring const & citelist)
356 docstring::const_iterator it = citelist.begin();
357 docstring::const_iterator end = citelist.end();
358 // Paranoia check: make sure that there is no whitespace in here
359 // -- at least not behind commas or at the beginning
361 char_type last = ',';
362 for (; it != end; ++it) {
365 if (*it != ' ' || last != ',')
372 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
374 os << from_ascii("<citation>")
375 << cleanupWhitespace(getParam("key"))
376 << from_ascii("</citation>");
381 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
383 string const & cmd = getCmdName();
387 // have to output this raw, because generateLabel() will include tags
388 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
394 void InsetCitation::toString(odocstream & os) const
396 odocstringstream ods;
397 plaintext(ods, OutputParams(0));
402 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
408 // Have to overwrite the default InsetCommand method in order to check that
409 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
410 // citations and then changes his mind, turning natbib support off. The output
411 // should revert to the default citation command as provided by the citation
412 // engine, e.g. \cite[]{} for the basic engine.
413 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
415 vector<CitationStyle> citation_styles = buffer().params().citeStyles();
416 CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
417 BiblioInfo const & bi = buffer().masterBibInfo();
419 docstring const cite_str = from_utf8(citationStyleToString(cs, true));
421 if (runparams.inulemcmd > 0)
424 os << "\\" << cite_str;
426 docstring const & before = getParam("before");
427 docstring const & after = getParam("after");
428 if (!before.empty() && cs.textBefore)
429 os << '[' << before << "][" << after << ']';
430 else if (!after.empty() && cs.textAfter)
431 os << '[' << after << ']';
433 if (!bi.isBibtex(getParam("key")))
434 // escape chars with bibitems
435 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
437 os << '{' << cleanupWhitespace(getParam("key")) << '}';
439 if (runparams.inulemcmd)
444 string InsetCitation::contextMenuName() const
446 return "context-citation";