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