]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Add a member to TocItem that tells us whether the item in question
[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 bool InsetCitation::addKey(string const & key)
126 {
127         docstring const ukey = from_utf8(key);
128         docstring const & curkeys = getParam("key");
129         if (curkeys.empty()) {
130                 setParam("key", ukey);
131                 cache.recalculate = true;
132                 return true;
133         }
134
135         vector<docstring> keys = getVectorFromString(curkeys);
136         vector<docstring>::const_iterator it = keys.begin();
137         vector<docstring>::const_iterator en = keys.end();
138         for (; it != en; ++it) {
139                 if (*it == ukey) {
140                         LYXERR0("Key " << key << " already present.");
141                         return false;
142                 }
143         }
144         keys.push_back(ukey);
145         setParam("key", getStringFromVector(keys));
146         cache.recalculate = true;
147         return true;
148 }
149
150
151 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
152 {
153         Buffer const & buf = bv.buffer();
154         // Only after the buffer is loaded from file...
155         if (!buf.isFullyLoaded())
156                 return docstring();
157
158         BiblioInfo const & bi = buf.masterBibInfo();
159         if (bi.empty())
160                 return _("No bibliography defined!");
161
162         docstring const & key = getParam("key");
163         if (key.empty())
164                 return _("No citations selected!");
165
166         vector<docstring> keys = getVectorFromString(key);
167         vector<docstring>::const_iterator it = keys.begin();
168         vector<docstring>::const_iterator en = keys.end();
169         docstring tip;
170         for (; it != en; ++it) {
171                 docstring const key_info = bi.getInfo(*it, buffer());
172                 if (key_info.empty())
173                         continue;
174                 if (!tip.empty())
175                         tip += "\n";
176                 tip += wrap(key_info, -4);
177         }
178         return tip;
179 }
180
181
182 namespace {
183
184
185 CitationStyle asValidLatexCommand(string const & input, vector<CitationStyle> const valid_styles)
186 {
187         CitationStyle cs = valid_styles[0];
188         cs.forceUpperCase = false;
189         cs.fullAuthorList = false;
190         if (!InsetCitation::isCompatibleCommand(input))
191                 return cs;
192
193         string normalized_input = input;
194         string::size_type const n = input.size() - 1;
195         if (input[0] == 'C')
196                 normalized_input[0] = 'c';
197         if (input[n] == '*')
198                 normalized_input = normalized_input.substr(0, n);
199
200         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
201         vector<CitationStyle>::const_iterator end = valid_styles.end();
202         for (; it != end; ++it) {
203                 CitationStyle this_cs = *it;
204                 if (this_cs.cmd == normalized_input) {
205                         cs = *it;
206                         break;
207                 }
208         }
209
210         cs.forceUpperCase &= input[0] == 'C';
211         cs.fullAuthorList &= input[n] == '*';
212
213         return cs;
214 }
215
216
217 inline docstring wrapCitation(docstring const & key,
218                 docstring const & content, bool for_xhtml)
219 {
220         if (!for_xhtml)
221                 return content;
222         // we have to do the escaping here, because we will ultimately
223         // write this as a raw string, so as not to escape the tags.
224         return "<a href='#LyXCite-" + key + "'>" +
225                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
226 }
227
228 } // anonymous namespace
229
230 docstring InsetCitation::generateLabel(bool for_xhtml) const
231 {
232         docstring label;
233         label = complexLabel(for_xhtml);
234
235         // Fallback to fail-safe
236         if (label.empty())
237                 label = basicLabel(for_xhtml);
238
239         return label;
240 }
241
242
243 docstring InsetCitation::complexLabel(bool for_xhtml) const
244 {
245         Buffer const & buf = buffer();
246         // Only start the process off after the buffer is loaded from file.
247         if (!buf.isFullyLoaded())
248                 return docstring();
249
250         BiblioInfo const & biblist = buf.masterBibInfo();
251         if (biblist.empty())
252                 return docstring();
253
254         docstring const & key = getParam("key");
255         if (key.empty())
256                 return _("No citations selected!");
257
258         // We don't currently use the full or forceUCase fields.
259         string cite_type = getCmdName();
260         if (cite_type[0] == 'C')
261                 // If we were going to use them, this would mean ForceUCase
262                 cite_type = string(1, 'c') + cite_type.substr(1);
263         if (cite_type[cite_type.size() - 1] == '*')
264                 // and this would mean FULL
265                 cite_type = cite_type.substr(0, cite_type.size() - 1);
266
267         docstring const & before = getParam("before");
268         docstring const & after = getParam("after");
269
270         // FIXME: allow to add cite macros
271         /*
272         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
273         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
274         */
275         docstring label;
276         vector<docstring> const keys = getVectorFromString(key);
277         label = biblist.getLabel(keys, buffer(), cite_type, for_xhtml, before, after);
278         return label;
279 }
280
281
282 docstring InsetCitation::basicLabel(bool for_xhtml) const
283 {
284         docstring keys = getParam("key");
285         docstring label;
286
287         docstring key;
288         do {
289                 // if there is no comma, then everything goes into key
290                 // and keys will be empty.
291                 keys = trim(split(keys, key, ','));
292                 key = trim(key);
293                 if (!label.empty())
294                         label += ", ";
295                 label += wrapCitation(key, key, for_xhtml);
296         } while (!keys.empty());
297
298         docstring const & after = getParam("after");
299         if (!after.empty())
300                 label += ", " + after;
301
302         return '[' + label + ']';
303 }
304
305 docstring InsetCitation::screenLabel() const
306 {
307         return cache.screen_label;
308 }
309
310
311 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
312 {
313         if (!cache.recalculate && buffer().citeLabelsValid())
314                 return;
315
316         // The label may have changed, so we have to re-create it.
317         docstring const glabel = generateLabel();
318
319         unsigned int const maxLabelChars = 45;
320
321         docstring label = glabel;
322         if (label.size() > maxLabelChars) {
323                 label.erase(maxLabelChars - 3);
324                 label += "...";
325         }
326
327         cache.recalculate = false;
328         cache.generated_label = glabel;
329         cache.screen_label = label;
330 }
331
332
333 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active) const
334 {
335         // NOTE
336         // XHTML output uses the TOC to collect the citations
337         // from the document. So if this gets changed, then we
338         // will need to change how the citations are collected.
339         docstring const tocitem = getParam("key");
340         Toc & toc = buffer().tocBackend().toc("citation");
341         toc.push_back(TocItem(cpit, 0, tocitem, output_active));
342 }
343
344
345 int InsetCitation::plaintext(odocstringstream & os,
346        OutputParams const &, size_t) const
347 {
348         string const & cmd = getCmdName();
349         if (cmd == "nocite")
350                 return 0;
351
352         docstring const label = generateLabel(false);
353         os << label;
354         return label.size();
355 }
356
357
358 static docstring const cleanupWhitespace(docstring const & citelist)
359 {
360         docstring::const_iterator it  = citelist.begin();
361         docstring::const_iterator end = citelist.end();
362         // Paranoia check: make sure that there is no whitespace in here
363         // -- at least not behind commas or at the beginning
364         docstring result;
365         char_type last = ',';
366         for (; it != end; ++it) {
367                 if (*it != ' ')
368                         last = *it;
369                 if (*it != ' ' || last != ',')
370                         result += *it;
371         }
372         return result;
373 }
374
375
376 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
377 {
378         os << from_ascii("<citation>")
379            << cleanupWhitespace(getParam("key"))
380            << from_ascii("</citation>");
381         return 0;
382 }
383
384
385 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
386 {
387         string const & cmd = getCmdName();
388         if (cmd == "nocite")
389                 return docstring();
390
391         // have to output this raw, because generateLabel() will include tags
392         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
393
394         return docstring();
395 }
396
397
398 void InsetCitation::toString(odocstream & os) const
399 {
400         odocstringstream ods;
401         plaintext(ods, OutputParams(0));
402         os << ods.str();
403 }
404
405
406 void InsetCitation::forToc(docstring & os, size_t) const
407 {
408         os += screenLabel();
409 }
410
411
412 // Have to overwrite the default InsetCommand method in order to check that
413 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
414 // citations and then changes his mind, turning natbib support off. The output
415 // should revert to the default citation command as provided by the citation
416 // engine, e.g. \cite[]{} for the basic engine.
417 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
418 {
419         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
420         CitationStyle cs = asValidLatexCommand(getCmdName(), citation_styles);
421         BiblioInfo const & bi = buffer().masterBibInfo();
422         // FIXME UNICODE
423         docstring const cite_str = from_utf8(citationStyleToString(cs));
424
425         if (runparams.inulemcmd)
426                 os << "\\mbox{";
427
428         os << "\\" << cite_str;
429
430         docstring const & before = getParam("before");
431         docstring const & after  = getParam("after");
432         if (!before.empty() && cs.textBefore)
433                 os << '[' << before << "][" << after << ']';
434         else if (!after.empty() && cs.textAfter)
435                 os << '[' << after << ']';
436
437         if (!bi.isBibtex(getParam("key")))
438                 // escape chars with bibitems
439                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
440         else
441                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
442
443         if (runparams.inulemcmd)
444                 os << "}";
445 }
446
447
448 string InsetCitation::contextMenuName() const
449 {
450         return "context-citation";
451 }
452
453
454 } // namespace lyx