]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Force BibTeX rerun upon add/remove/change citation (fixes #6955).
[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 "LaTeXFeatures.h"
25 #include "output_xhtml.h"
26 #include "ParIterator.h"
27 #include "TocBackend.h"
28
29 #include "support/debug.h"
30 #include "support/docstream.h"
31 #include "support/FileNameList.h"
32 #include "support/gettext.h"
33 #include "support/lstrings.h"
34
35 #include <algorithm>
36
37 using namespace std;
38 using namespace lyx::support;
39
40 namespace lyx {
41
42 ParamInfo InsetCitation::param_info_;
43
44
45 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
46         : InsetCommand(buf, p)
47 {
48         buffer().removeBiblioTempFiles();
49 }
50
51
52 InsetCitation::~InsetCitation()
53 {
54         if (isBufferLoaded())
55                 buffer().removeBiblioTempFiles();
56 }
57
58
59 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
60 {
61         // standard cite does only take one argument if jurabib is
62         // not used, but jurabib extends this to two arguments, so
63         // we have to allow both here. InsetCitation takes care that
64         // LaTeX output is nevertheless correct.
65         if (param_info_.empty()) {
66                 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
67                 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
68                 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
69         }
70         return param_info_;
71 }
72
73
74 namespace {
75
76 vector<string> const init_possible_cite_commands()
77 {
78         char const * const possible[] = {
79                 "cite", "nocite", "citet", "citep", "citealt", "citealp",
80                 "citeauthor", "citeyear", "citeyearpar",
81                 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
82                 "Citet",  "Citep",  "Citealt",  "Citealp",  "Citeauthor",
83                 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
84                 "fullcite",
85                 "footcite", "footcitet", "footcitep", "footcitealt",
86                 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
87                 "citefield", "citetitle", "cite*"
88         };
89         size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
90
91         return vector<string>(possible, possible + size_possible);
92 }
93
94
95 vector<string> const & possibleCiteCommands()
96 {
97         static vector<string> const possible = init_possible_cite_commands();
98         return possible;
99 }
100
101
102 } // anon namespace
103
104
105 // FIXME: use the citeCommands provided by the TextClass
106 // instead of possibleCiteCommands defined in this file.
107 bool InsetCitation::isCompatibleCommand(string const & cmd)
108 {
109         vector<string> const & possibles = possibleCiteCommands();
110         vector<string>::const_iterator const end = possibles.end();
111         return find(possibles.begin(), end, cmd) != end;
112 }
113
114
115 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
116 {
117         if (cmd.action() == LFUN_INSET_MODIFY) {
118                 buffer().removeBiblioTempFiles();
119                 cache.recalculate = true;
120         }
121         InsetCommand::doDispatch(cur, cmd);
122 }
123
124
125 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
126 {
127         Buffer const & buf = bv.buffer();
128         // Only after the buffer is loaded from file...
129         if (!buf.isFullyLoaded())
130                 return docstring();
131
132         BiblioInfo const & bi = buf.masterBibInfo();
133         if (bi.empty())
134                 return _("No bibliography defined!");
135
136         docstring const & key = getParam("key");
137         if (key.empty())
138                 return _("No citations selected!");
139
140         vector<docstring> keys = getVectorFromString(key);
141         vector<docstring>::const_iterator it = keys.begin();
142         vector<docstring>::const_iterator en = keys.end();
143         docstring tip;
144         for (; it != en; ++it) {
145                 docstring const key_info = bi.getInfo(*it, buffer());
146                 if (key_info.empty())
147                         continue;
148                 if (!tip.empty())
149                         tip += "\n";
150                 tip += wrap(key_info, -4);
151         }
152         return tip;
153 }
154
155
156 namespace {
157
158
159 CitationStyle asValidLatexCommand(string const & input, vector<CitationStyle> const valid_styles)
160 {
161         CitationStyle cs = valid_styles[0];
162         cs.forceUpperCase = false;
163         cs.fullAuthorList = false;
164         if (!InsetCitation::isCompatibleCommand(input))
165                 return cs;
166
167         string normalized_input = input;
168         string::size_type const n = input.size() - 1;
169         if (input[0] == 'C')
170                 normalized_input[0] = 'c';
171         if (input[n] == '*')
172                 normalized_input = normalized_input.substr(0, n);
173
174         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
175         vector<CitationStyle>::const_iterator end = valid_styles.end();
176         for (; it != end; ++it) {
177                 CitationStyle this_cs = *it;
178                 if (this_cs.cmd == normalized_input) {
179                         cs = *it;
180                         break;
181                 }
182         }
183
184         cs.forceUpperCase &= input[0] == 'C';
185         cs.fullAuthorList &= input[n] == '*';
186
187         return cs;
188 }
189
190
191 inline docstring wrapCitation(docstring const & key,
192                 docstring const & content, bool for_xhtml)
193 {
194         if (!for_xhtml)
195                 return content;
196         // we have to do the escaping here, because we will ultimately
197         // write this as a raw string, so as not to escape the tags.
198         return "<a href='#LyXCite-" + key + "'>" +
199                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
200 }
201
202 } // anonymous namespace
203
204 docstring InsetCitation::generateLabel(bool for_xhtml) const
205 {
206         docstring label;
207         label = complexLabel(for_xhtml);
208
209         // Fallback to fail-safe
210         if (label.empty())
211                 label = basicLabel(for_xhtml);
212
213         return label;
214 }
215
216
217 docstring InsetCitation::complexLabel(bool for_xhtml) const
218 {
219         Buffer const & buf = buffer();
220         // Only start the process off after the buffer is loaded from file.
221         if (!buf.isFullyLoaded())
222                 return docstring();
223
224         BiblioInfo const & biblist = buf.masterBibInfo();
225         if (biblist.empty())
226                 return docstring();
227
228         docstring const & key = getParam("key");
229         if (key.empty())
230                 return _("No citations selected!");
231
232         // We don't currently use the full or forceUCase fields.
233         string cite_type = getCmdName();
234         if (cite_type[0] == 'C')
235                 // If we were going to use them, this would mean ForceUCase
236                 cite_type = string(1, 'c') + cite_type.substr(1);
237         if (cite_type[cite_type.size() - 1] == '*')
238                 // and this would mean FULL
239                 cite_type = cite_type.substr(0, cite_type.size() - 1);
240
241         docstring const & before = getParam("before");
242         docstring const & after = getParam("after");
243
244         // FIXME: allow to add cite macros
245         /*
246         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
247         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
248         */
249         docstring label;
250         vector<docstring> const keys = getVectorFromString(key);
251         label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, before, after);
252         return label;
253 }
254
255
256 docstring InsetCitation::basicLabel(bool for_xhtml) const
257 {
258         docstring keys = getParam("key");
259         docstring label;
260
261         docstring key;
262         do {
263                 // if there is no comma, then everything goes into key
264                 // and keys will be empty.
265                 keys = trim(split(keys, key, ','));
266                 key = trim(key);
267                 if (!label.empty())
268                         label += ", ";
269                 label += wrapCitation(key, key, for_xhtml);
270         } while (!keys.empty());
271
272         docstring const & after = getParam("after");
273         if (!after.empty())
274                 label += ", " + after;
275
276         return '[' + label + ']';
277 }
278
279 docstring InsetCitation::screenLabel() const
280 {
281         return cache.screen_label;
282 }
283
284
285 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
286 {
287         if (!cache.recalculate && buffer().citeLabelsValid())
288                 return;
289
290         // The label may have changed, so we have to re-create it.
291         docstring const glabel = generateLabel();
292
293         unsigned int const maxLabelChars = 45;
294
295         docstring label = glabel;
296         if (label.size() > maxLabelChars) {
297                 label.erase(maxLabelChars - 3);
298                 label += "...";
299         }
300
301         cache.recalculate = false;
302         cache.generated_label = glabel;
303         cache.screen_label = label;
304 }
305
306
307 void InsetCitation::addToToc(DocIterator const & cpit) const
308 {
309         // NOTE
310         // XHTML output uses the TOC to collect the citations
311         // from the document. So if this gets changed, then we
312         // will need to change how the citations are collected.
313         docstring const tocitem = getParam("key");
314         Toc & toc = buffer().tocBackend().toc("citation");
315         toc.push_back(TocItem(cpit, 0, tocitem));
316 }
317
318
319 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
320 {
321         os << cache.generated_label;
322         return cache.generated_label.size();
323 }
324
325
326 static docstring const cleanupWhitespace(docstring const & citelist)
327 {
328         docstring::const_iterator it  = citelist.begin();
329         docstring::const_iterator end = citelist.end();
330         // Paranoia check: make sure that there is no whitespace in here
331         // -- at least not behind commas or at the beginning
332         docstring result;
333         char_type last = ',';
334         for (; it != end; ++it) {
335                 if (*it != ' ')
336                         last = *it;
337                 if (*it != ' ' || last != ',')
338                         result += *it;
339         }
340         return result;
341 }
342
343
344 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
345 {
346         os << from_ascii("<citation>")
347            << cleanupWhitespace(getParam("key"))
348            << from_ascii("</citation>");
349         return 0;
350 }
351
352
353 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
354 {
355         string const & cmd = getCmdName();
356         if (cmd == "nocite")
357                 return docstring();
358
359         // have to output this raw, because generateLabel() will include tags
360         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
361
362         return docstring();
363 }
364
365
366 void InsetCitation::toString(odocstream & os) const
367 {
368         plaintext(os, OutputParams(0));
369 }
370
371
372 void InsetCitation::forToc(docstring & os, size_t) const
373 {
374         os += screenLabel();
375 }
376
377
378 // Have to overwrite the default InsetCommand method in order to check that
379 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
380 // citations and then changes his mind, turning natbib support off. The output
381 // should revert to the default citation command as provided by the citation
382 // engine, e.g. \cite[]{} for the basic engine.
383 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
384 {
385         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
386         CitationStyle cs = asValidLatexCommand(getCmdName(), citation_styles);
387         BiblioInfo const & bi = buffer().masterBibInfo();
388         // FIXME UNICODE
389         docstring const cite_str = from_utf8(citationStyleToString(cs));
390
391         if (runparams.inulemcmd)
392                 os << "\\mbox{";
393
394         os << "\\" << cite_str;
395
396         docstring const & before = getParam("before");
397         docstring const & after  = getParam("after");
398         if (!before.empty() && cs.textBefore)
399                 os << '[' << before << "][" << after << ']';
400         else if (!after.empty() && cs.textAfter)
401                 os << '[' << after << ']';
402
403         if (!bi.isBibtex(getParam("key")))
404                 // escape chars with bibitems
405                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
406         else
407                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
408
409         if (runparams.inulemcmd)
410                 os << "}";
411 }
412
413
414 string InsetCitation::contextMenuName() const
415 {
416         return "context-citation";
417 }
418
419
420 } // namespace lyx