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