]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
No need to hardcode the possible cite commands
[features.git] / src / insets / InsetCitation.cpp
1 /**
2  * \file InsetCitation.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Herbert Voß
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetCitation.h"
15
16 #include "BiblioInfo.h"
17 #include "Buffer.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "DispatchResult.h"
22 #include "FuncCode.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"
30
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"
36
37 #include <algorithm>
38 #include <climits>
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44
45 ParamInfo InsetCitation::param_info_;
46
47
48 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
49         : InsetCommand(buf, p)
50 {
51         buffer().removeBiblioTempFiles();
52 }
53
54
55 InsetCitation::~InsetCitation()
56 {
57         if (isBufferLoaded())
58                 buffer().removeBiblioTempFiles();
59 }
60
61
62 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
63 {
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);
72         }
73         return param_info_;
74 }
75
76
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 &)
80 {
81         return true;
82 }
83
84
85 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
86 {
87         if (cmd.action() == LFUN_INSET_MODIFY) {
88                 buffer().removeBiblioTempFiles();
89                 cache.recalculate = true;
90         }
91         InsetCommand::doDispatch(cur, cmd);
92 }
93
94
95 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
96         FuncStatus & status) const
97 {
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);
104                         if (!alias.empty())
105                                 cmdname = alias;
106                         string const newtype = cmd.getArg(1);
107                         status.setEnabled(isCompatibleCommand(newtype));
108                         status.setOnOff(newtype == cmdname);
109                 }
110                 status.setEnabled(true);
111                 return true;
112         default:
113                 return InsetCommand::getStatus(cur, cmd, status);
114         }
115 }
116
117
118 bool InsetCitation::addKey(string const & key)
119 {
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;
125                 return true;
126         }
127
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) {
132                 if (*it == ukey) {
133                         LYXERR0("Key " << key << " already present.");
134                         return false;
135                 }
136         }
137         keys.push_back(ukey);
138         setParam("key", getStringFromVector(keys));
139         cache.recalculate = true;
140         return true;
141 }
142
143
144 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
145 {
146         Buffer const & buf = bv.buffer();
147         // Only after the buffer is loaded from file...
148         if (!buf.isFullyLoaded())
149                 return docstring();
150
151         BiblioInfo const & bi = buf.masterBibInfo();
152         if (bi.empty())
153                 return _("No bibliography defined!");
154
155         docstring const & key = getParam("key");
156         if (key.empty())
157                 return _("No citations selected!");
158
159         vector<docstring> keys = getVectorFromString(key);
160         if (keys.size() == 1)
161                 return bi.getInfo(keys[0], buffer(), true);
162
163         docstring tip;
164         tip += "<ol>";
165         for (docstring const & key : keys) {
166                 docstring const key_info = bi.getInfo(key, buffer(), true);
167                 if (key_info.empty())
168                         continue;
169                 tip += "<li>" + key_info + "</li>";
170         }
171         tip += "</ol>";
172         return tip;
173 }
174
175
176 namespace {
177
178
179 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
180                                   vector<CitationStyle> const & valid_styles)
181 {
182         CitationStyle cs = valid_styles[0];
183         cs.forceUpperCase = false;
184         cs.hasStarredVersion = false;
185
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]);
190         if (input[n] == '*')
191                 normalized_input = normalized_input.substr(0, n);
192
193         string const alias = bp.getCiteAlias(normalized_input);
194         if (!alias.empty())
195                 normalized_input = alias;
196
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) {
202                         cs = *it;
203                         break;
204                 }
205         }
206
207         cs.forceUpperCase &= input[0] == uppercase(input[0]);
208         cs.hasStarredVersion &= input[n] == '*';
209
210         return cs;
211 }
212
213
214 inline docstring wrapCitation(docstring const & key,
215                 docstring const & content, bool for_xhtml)
216 {
217         if (!for_xhtml)
218                 return content;
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>";
223 }
224
225 } // anonymous namespace
226
227 docstring InsetCitation::generateLabel(bool for_xhtml) const
228 {
229         docstring label;
230         label = complexLabel(for_xhtml);
231
232         // Fallback to fail-safe
233         if (label.empty())
234                 label = basicLabel(for_xhtml);
235
236         return label;
237 }
238
239
240 docstring InsetCitation::complexLabel(bool for_xhtml) const
241 {
242         Buffer const & buf = buffer();
243         // Only start the process off after the buffer is loaded from file.
244         if (!buf.isFullyLoaded())
245                 return docstring();
246
247         BiblioInfo const & biblist = buf.masterBibInfo();
248         if (biblist.empty())
249                 return docstring();
250
251         docstring const & key = getParam("key");
252         if (key.empty())
253                 return _("No citations selected!");
254
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);
263
264         // handle alias
265         string const alias = buf.params().getCiteAlias(cite_type);
266         if (!alias.empty())
267                 cite_type = alias;
268
269         docstring const & before = getParam("before");
270         docstring const & after = getParam("after");
271
272         // FIXME: allow to add cite macros
273         /*
274         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
275         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
276         */
277         docstring label;
278         vector<docstring> keys = getVectorFromString(key);
279         label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, UINT_MAX, before, after);
280         return label;
281 }
282
283
284 docstring InsetCitation::basicLabel(bool for_xhtml) const
285 {
286         docstring keys = getParam("key");
287         docstring label;
288
289         docstring key;
290         do {
291                 // if there is no comma, then everything goes into key
292                 // and keys will be empty.
293                 keys = trim(split(keys, key, ','));
294                 key = trim(key);
295                 if (!label.empty())
296                         label += ", ";
297                 label += wrapCitation(key, key, for_xhtml);
298         } while (!keys.empty());
299
300         docstring const & after = getParam("after");
301         if (!after.empty())
302                 label += ", " + after;
303
304         return '[' + label + ']';
305 }
306
307 docstring InsetCitation::screenLabel() const
308 {
309         return cache.screen_label;
310 }
311
312
313 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
314 {
315         if (!cache.recalculate && buffer().citeLabelsValid())
316                 return;
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);
324 }
325
326
327 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
328                                                          UpdateType) const
329 {
330         // NOTE
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));
338 }
339
340
341 int InsetCitation::plaintext(odocstringstream & os,
342        OutputParams const &, size_t) const
343 {
344         string const & cmd = getCmdName();
345         if (cmd == "nocite")
346                 return 0;
347
348         docstring const label = generateLabel(false);
349         os << label;
350         return label.size();
351 }
352
353
354 static docstring const cleanupWhitespace(docstring const & citelist)
355 {
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
360         docstring result;
361         char_type last = ',';
362         for (; it != end; ++it) {
363                 if (*it != ' ')
364                         last = *it;
365                 if (*it != ' ' || last != ',')
366                         result += *it;
367         }
368         return result;
369 }
370
371
372 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
373 {
374         os << from_ascii("<citation>")
375            << cleanupWhitespace(getParam("key"))
376            << from_ascii("</citation>");
377         return 0;
378 }
379
380
381 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
382 {
383         string const & cmd = getCmdName();
384         if (cmd == "nocite")
385                 return docstring();
386
387         // have to output this raw, because generateLabel() will include tags
388         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
389
390         return docstring();
391 }
392
393
394 void InsetCitation::toString(odocstream & os) const
395 {
396         odocstringstream ods;
397         plaintext(ods, OutputParams(0));
398         os << ods.str();
399 }
400
401
402 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
403 {
404         os += screenLabel();
405 }
406
407
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
414 {
415         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
416         CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
417         BiblioInfo const & bi = buffer().masterBibInfo();
418         // FIXME UNICODE
419         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
420
421         if (runparams.inulemcmd > 0)
422                 os << "\\mbox{";
423
424         os << "\\" << cite_str;
425
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 << ']';
432
433         if (!bi.isBibtex(getParam("key")))
434                 // escape chars with bibitems
435                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
436         else
437                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
438
439         if (runparams.inulemcmd)
440                 os << "}";
441 }
442
443
444 string InsetCitation::contextMenuName() const
445 {
446         return "context-citation";
447 }
448
449
450 } // namespace lyx