]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
Some master/child biblio fixes.
[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 "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 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
86                                   vector<CitationStyle> const & valid_styles) const
87 {
88         CitationStyle cs = valid_styles[0];
89         cs.forceUpperCase = false;
90         cs.hasStarredVersion = false;
91
92         string normalized_input = input;
93         string::size_type const n = input.size() - 1;
94         if (isUpperCase(input[0]))
95                 normalized_input[0] = lowercase(input[0]);
96         if (input[n] == '*')
97                 normalized_input = normalized_input.substr(0, n);
98
99         string const alias = bp.getCiteAlias(normalized_input);
100         if (!alias.empty())
101                 normalized_input = alias;
102
103         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
104         vector<CitationStyle>::const_iterator end = valid_styles.end();
105         for (; it != end; ++it) {
106                 CitationStyle this_cs = *it;
107                 if (this_cs.name == normalized_input) {
108                         cs = *it;
109                         break;
110                 }
111         }
112
113         return cs;
114 }
115
116
117 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
118 {
119         switch (cmd.action()) {
120         case LFUN_INSET_MODIFY: {
121                 buffer().removeBiblioTempFiles();
122                 cache.recalculate = true;
123                 if (cmd.getArg(0) == "toggleparam") {
124                         string cmdname = getCmdName();
125                         string const alias =
126                                 buffer().masterParams().getCiteAlias(cmdname);
127                         if (!alias.empty())
128                                 cmdname = alias;
129                         string const par = cmd.getArg(1);
130                         string newcmdname = cmdname;
131                         if (par == "star") {
132                                 if (suffixIs(cmdname, "*"))
133                                         newcmdname = rtrim(cmdname, "*");
134                                 else
135                                         newcmdname = cmdname + "*";
136                         } else if (par == "casing") {
137                                 if (isUpperCase(cmdname[0]))
138                                         newcmdname[0] = lowercase(cmdname[0]);
139                                 else
140                                         newcmdname[0] = uppercase(newcmdname[0]);
141                         }
142                         cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
143                 }
144         }
145         default:
146                 InsetCommand::doDispatch(cur, cmd);
147         }
148 }
149
150
151 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
152         FuncStatus & status) const
153 {
154         switch (cmd.action()) {
155         // Handle the alias case
156         case LFUN_INSET_MODIFY:
157                 if (cmd.getArg(0) == "changetype") {
158                         string cmdname = getCmdName();
159                         string const alias =
160                                 buffer().masterParams().getCiteAlias(cmdname);
161                         if (!alias.empty())
162                                 cmdname = alias;
163                         if (suffixIs(cmdname, "*"))
164                                 cmdname = rtrim(cmdname, "*");
165                         string const newtype = cmd.getArg(1);
166                         status.setEnabled(isCompatibleCommand(newtype));
167                         status.setOnOff(newtype == cmdname);
168                 }
169                 if (cmd.getArg(0) == "toggleparam") {
170                         string cmdname = getCmdName();
171                         string const alias =
172                                 buffer().masterParams().getCiteAlias(cmdname);
173                         if (!alias.empty())
174                                 cmdname = alias;
175                         vector<CitationStyle> citation_styles =
176                                 buffer().masterParams().citeStyles();
177                         CitationStyle cs = getCitationStyle(buffer().masterParams(),
178                                                             cmdname, citation_styles);
179                         if (cmd.getArg(1) == "star") {
180                                 status.setEnabled(cs.hasStarredVersion);
181                                 status.setOnOff(suffixIs(cmdname, "*"));
182                         }
183                         else if (cmd.getArg(1) == "casing") {
184                                 status.setEnabled(cs.forceUpperCase);
185                                 status.setOnOff(isUpperCase(cmdname[0]));
186                         }
187                 }
188                 return true;
189         default:
190                 return InsetCommand::getStatus(cur, cmd, status);
191         }
192 }
193
194
195 bool InsetCitation::addKey(string const & key)
196 {
197         docstring const ukey = from_utf8(key);
198         docstring const & curkeys = getParam("key");
199         if (curkeys.empty()) {
200                 setParam("key", ukey);
201                 cache.recalculate = true;
202                 return true;
203         }
204
205         vector<docstring> keys = getVectorFromString(curkeys);
206         vector<docstring>::const_iterator it = keys.begin();
207         vector<docstring>::const_iterator en = keys.end();
208         for (; it != en; ++it) {
209                 if (*it == ukey) {
210                         LYXERR0("Key " << key << " already present.");
211                         return false;
212                 }
213         }
214         keys.push_back(ukey);
215         setParam("key", getStringFromVector(keys));
216         cache.recalculate = true;
217         return true;
218 }
219
220
221 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
222 {
223         Buffer const & buf = bv.buffer();
224         // Only after the buffer is loaded from file...
225         if (!buf.isFullyLoaded())
226                 return docstring();
227
228         BiblioInfo const & bi = buf.masterBibInfo();
229         if (bi.empty())
230                 return _("No bibliography defined!");
231
232         docstring const & key = getParam("key");
233         if (key.empty())
234                 return _("No citations selected!");
235
236         CiteItem ci;
237         ci.richtext = true;
238         vector<docstring> keys = getVectorFromString(key);
239         if (keys.size() == 1)
240                 return bi.getInfo(keys[0], buffer(), ci);
241
242         docstring tip;
243         tip += "<ol>";
244         int count = 0;
245         for (docstring const & key : keys) {
246                 docstring const key_info = bi.getInfo(key, buffer(), ci);
247                 // limit to reasonable size.
248                 if (count > 9 && keys.size() > 11) {
249                         tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
250                         tip += "<p>"
251                                 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
252                                 + "</p>";
253                         break;
254                 }
255                 if (key_info.empty())
256                         continue;
257                 tip += "<li>" + key_info + "</li>";
258                 ++count;
259         }
260         tip += "</ol>";
261         return tip;
262 }
263
264
265 namespace {
266
267 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
268                                   vector<CitationStyle> const & valid_styles)
269 {
270         CitationStyle cs = valid_styles[0];
271         cs.forceUpperCase = false;
272         cs.hasStarredVersion = false;
273
274         string normalized_input = input;
275         string::size_type const n = input.size() - 1;
276         if (isUpperCase(input[0]))
277                 normalized_input[0] = lowercase(input[0]);
278         if (input[n] == '*')
279                 normalized_input = normalized_input.substr(0, n);
280
281         string const alias = bp.getCiteAlias(normalized_input);
282         if (!alias.empty())
283                 normalized_input = alias;
284
285         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
286         vector<CitationStyle>::const_iterator end = valid_styles.end();
287         for (; it != end; ++it) {
288                 CitationStyle this_cs = *it;
289                 if (this_cs.name == normalized_input) {
290                         cs = *it;
291                         break;
292                 }
293         }
294
295         cs.forceUpperCase &= input[0] == uppercase(input[0]);
296         cs.hasStarredVersion &= input[n] == '*';
297
298         return cs;
299 }
300
301
302 inline docstring wrapCitation(docstring const & key,
303                 docstring const & content, bool for_xhtml)
304 {
305         if (!for_xhtml)
306                 return content;
307         // we have to do the escaping here, because we will ultimately
308         // write this as a raw string, so as not to escape the tags.
309         return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
310                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
311 }
312
313 } // anonymous namespace
314
315 docstring InsetCitation::generateLabel(bool for_xhtml) const
316 {
317         docstring label;
318         label = complexLabel(for_xhtml);
319
320         // Fallback to fail-safe
321         if (label.empty())
322                 label = basicLabel(for_xhtml);
323
324         return label;
325 }
326
327
328 docstring InsetCitation::complexLabel(bool for_xhtml) const
329 {
330         Buffer const & buf = buffer();
331         // Only start the process off after the buffer is loaded from file.
332         if (!buf.isFullyLoaded())
333                 return docstring();
334
335         BiblioInfo const & biblist = buf.masterBibInfo();
336         if (biblist.empty())
337                 return docstring();
338
339         docstring const & key = getParam("key");
340         if (key.empty())
341                 return _("No citations selected!");
342
343         string cite_type = getCmdName();
344         bool const uppercase = isUpperCase(cite_type[0]);
345         if (uppercase)
346                 cite_type[0] = lowercase(cite_type[0]);
347         bool const starred = (cite_type[cite_type.size() - 1] == '*');
348         if (starred)
349                 cite_type = cite_type.substr(0, cite_type.size() - 1);
350
351         // handle alias
352         string const alias = buf.masterParams().getCiteAlias(cite_type);
353         if (!alias.empty())
354                 cite_type = alias;
355
356         // FIXME: allow to add cite macros
357         /*
358         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
359         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
360         */
361         docstring label;
362         vector<docstring> keys = getVectorFromString(key);
363         CiteItem ci;
364         ci.textBefore = getParam("before");
365         ci.textAfter = getParam("after");
366         ci.forceUpperCase = uppercase;
367         ci.Starred = starred;
368         ci.max_size = UINT_MAX;
369         if (for_xhtml) {
370                 ci.max_key_size = UINT_MAX;
371                 ci.context = CiteItem::Export;
372         }
373         ci.richtext = for_xhtml;
374         label = biblist.getLabel(keys, buffer(), cite_type, ci);
375         return label;
376 }
377
378
379 docstring InsetCitation::basicLabel(bool for_xhtml) const
380 {
381         docstring keys = getParam("key");
382         docstring label;
383
384         docstring key;
385         do {
386                 // if there is no comma, then everything goes into key
387                 // and keys will be empty.
388                 keys = trim(split(keys, key, ','));
389                 key = trim(key);
390                 if (!label.empty())
391                         label += ", ";
392                 label += wrapCitation(key, key, for_xhtml);
393         } while (!keys.empty());
394
395         docstring const & after = getParam("after");
396         if (!after.empty())
397                 label += ", " + after;
398
399         return '[' + label + ']';
400 }
401
402 docstring InsetCitation::screenLabel() const
403 {
404         return cache.screen_label;
405 }
406
407
408 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
409 {
410         if (!cache.recalculate && buffer().citeLabelsValid())
411                 return;
412         // The label may have changed, so we have to re-create it.
413         docstring const glabel = generateLabel();
414         cache.recalculate = false;
415         cache.generated_label = glabel;
416         unsigned int const maxLabelChars = 45;
417         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
418         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
419 }
420
421
422 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
423                                                          UpdateType) const
424 {
425         // NOTE
426         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations 
427         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
428         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
429         // then we will also need to change that routine.
430         docstring const tocitem = getParam("key");
431         TocBuilder & b = buffer().tocBackend().builder("citation");
432         b.pushItem(cpit, tocitem, output_active);
433         b.pop();
434 }
435
436
437 int InsetCitation::plaintext(odocstringstream & os,
438        OutputParams const &, size_t) const
439 {
440         string const & cmd = getCmdName();
441         if (cmd == "nocite")
442                 return 0;
443
444         docstring const label = generateLabel(false);
445         os << label;
446         return label.size();
447 }
448
449
450 static docstring const cleanupWhitespace(docstring const & citelist)
451 {
452         docstring::const_iterator it  = citelist.begin();
453         docstring::const_iterator end = citelist.end();
454         // Paranoia check: make sure that there is no whitespace in here
455         // -- at least not behind commas or at the beginning
456         docstring result;
457         char_type last = ',';
458         for (; it != end; ++it) {
459                 if (*it != ' ')
460                         last = *it;
461                 if (*it != ' ' || last != ',')
462                         result += *it;
463         }
464         return result;
465 }
466
467
468 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
469 {
470         os << from_ascii("<citation>")
471            << cleanupWhitespace(getParam("key"))
472            << from_ascii("</citation>");
473         return 0;
474 }
475
476
477 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
478 {
479         string const & cmd = getCmdName();
480         if (cmd == "nocite")
481                 return docstring();
482
483         // have to output this raw, because generateLabel() will include tags
484         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
485
486         return docstring();
487 }
488
489
490 void InsetCitation::toString(odocstream & os) const
491 {
492         odocstringstream ods;
493         plaintext(ods, OutputParams(0));
494         os << ods.str();
495 }
496
497
498 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
499 {
500         os += screenLabel();
501 }
502
503
504 // Have to overwrite the default InsetCommand method in order to check that
505 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
506 // citations and then changes his mind, turning natbib support off. The output
507 // should revert to the default citation command as provided by the citation
508 // engine, e.g. \cite[]{} for the basic engine.
509 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
510 {
511         BiblioInfo const & bi = buffer().masterBibInfo();
512         if (getCmdName() == "keyonly") {
513                 // Special command to only return the key
514                 if (!bi.isBibtex(getParam("key")))
515                         // escape chars with bibitems
516                         os << escape(cleanupWhitespace(getParam("key")));
517                 else
518                         os << cleanupWhitespace(getParam("key"));
519                 return;
520         }
521         vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
522         CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
523                                                getCmdName(), citation_styles);
524         // FIXME UNICODE
525         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
526
527         if (runparams.inulemcmd > 0)
528                 os << "\\mbox{";
529
530         os << "\\" << cite_str;
531
532         docstring const & before = getParam("before");
533         docstring const & after  = getParam("after");
534         if (!before.empty() && cs.textBefore)
535                 os << '[' << before << "][" << after << ']';
536         else if (!after.empty() && cs.textAfter)
537                 os << '[' << after << ']';
538
539         if (!bi.isBibtex(getParam("key")))
540                 // escape chars with bibitems
541                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
542         else
543                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
544
545         if (runparams.inulemcmd)
546                 os << "}";
547 }
548
549
550 string InsetCitation::contextMenuName() const
551 {
552         return "context-citation";
553 }
554
555
556 } // namespace lyx