]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Add items to toggle "Force uppercase" and "Full author list" to the context menu
[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 "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().params().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().params().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().params().getCiteAlias(cmdname);
173                         if (!alias.empty())
174                                 cmdname = alias;
175                         vector<CitationStyle> citation_styles =
176                                 buffer().params().citeStyles();
177                         CitationStyle cs = getCitationStyle(buffer().params(),
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         for (docstring const & key : keys) {
245                 docstring const key_info = bi.getInfo(key, buffer(), ci);
246                 if (key_info.empty())
247                         continue;
248                 tip += "<li>" + key_info + "</li>";
249         }
250         tip += "</ol>";
251         return tip;
252 }
253
254
255 namespace {
256
257 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
258                                   vector<CitationStyle> const & valid_styles)
259 {
260         CitationStyle cs = valid_styles[0];
261         cs.forceUpperCase = false;
262         cs.hasStarredVersion = false;
263
264         string normalized_input = input;
265         string::size_type const n = input.size() - 1;
266         if (isUpperCase(input[0]))
267                 normalized_input[0] = lowercase(input[0]);
268         if (input[n] == '*')
269                 normalized_input = normalized_input.substr(0, n);
270
271         string const alias = bp.getCiteAlias(normalized_input);
272         if (!alias.empty())
273                 normalized_input = alias;
274
275         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
276         vector<CitationStyle>::const_iterator end = valid_styles.end();
277         for (; it != end; ++it) {
278                 CitationStyle this_cs = *it;
279                 if (this_cs.name == normalized_input) {
280                         cs = *it;
281                         break;
282                 }
283         }
284
285         cs.forceUpperCase &= input[0] == uppercase(input[0]);
286         cs.hasStarredVersion &= input[n] == '*';
287
288         return cs;
289 }
290
291
292 inline docstring wrapCitation(docstring const & key,
293                 docstring const & content, bool for_xhtml)
294 {
295         if (!for_xhtml)
296                 return content;
297         // we have to do the escaping here, because we will ultimately
298         // write this as a raw string, so as not to escape the tags.
299         return "<a href='#LyXCite-" + html::cleanAttr(key) + "'>" +
300                         html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
301 }
302
303 } // anonymous namespace
304
305 docstring InsetCitation::generateLabel(bool for_xhtml) const
306 {
307         docstring label;
308         label = complexLabel(for_xhtml);
309
310         // Fallback to fail-safe
311         if (label.empty())
312                 label = basicLabel(for_xhtml);
313
314         return label;
315 }
316
317
318 docstring InsetCitation::complexLabel(bool for_xhtml) const
319 {
320         Buffer const & buf = buffer();
321         // Only start the process off after the buffer is loaded from file.
322         if (!buf.isFullyLoaded())
323                 return docstring();
324
325         BiblioInfo const & biblist = buf.masterBibInfo();
326         if (biblist.empty())
327                 return docstring();
328
329         docstring const & key = getParam("key");
330         if (key.empty())
331                 return _("No citations selected!");
332
333         string cite_type = getCmdName();
334         bool const uppercase = isUpperCase(cite_type[0]);
335         if (uppercase)
336                 cite_type[0] = lowercase(cite_type[0]);
337         bool const starred = (cite_type[cite_type.size() - 1] == '*');
338         if (starred)
339                 cite_type = cite_type.substr(0, cite_type.size() - 1);
340
341         // handle alias
342         string const alias = buf.params().getCiteAlias(cite_type);
343         if (!alias.empty())
344                 cite_type = alias;
345
346         // FIXME: allow to add cite macros
347         /*
348         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
349         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
350         */
351         docstring label;
352         vector<docstring> keys = getVectorFromString(key);
353         CiteItem ci;
354         ci.textBefore = getParam("before");
355         ci.textAfter = getParam("after");
356         ci.forceUpperCase = uppercase;
357         ci.Starred = starred;
358         ci.max_size = UINT_MAX;
359         if (for_xhtml) {
360                 ci.max_key_size = UINT_MAX;
361                 ci.context = CiteItem::Export;
362         }
363         ci.richtext = for_xhtml;
364         label = biblist.getLabel(keys, buffer(), cite_type, ci);
365         return label;
366 }
367
368
369 docstring InsetCitation::basicLabel(bool for_xhtml) const
370 {
371         docstring keys = getParam("key");
372         docstring label;
373
374         docstring key;
375         do {
376                 // if there is no comma, then everything goes into key
377                 // and keys will be empty.
378                 keys = trim(split(keys, key, ','));
379                 key = trim(key);
380                 if (!label.empty())
381                         label += ", ";
382                 label += wrapCitation(key, key, for_xhtml);
383         } while (!keys.empty());
384
385         docstring const & after = getParam("after");
386         if (!after.empty())
387                 label += ", " + after;
388
389         return '[' + label + ']';
390 }
391
392 docstring InsetCitation::screenLabel() const
393 {
394         return cache.screen_label;
395 }
396
397
398 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
399 {
400         if (!cache.recalculate && buffer().citeLabelsValid())
401                 return;
402         // The label may have changed, so we have to re-create it.
403         docstring const glabel = generateLabel();
404         cache.recalculate = false;
405         cache.generated_label = glabel;
406         unsigned int const maxLabelChars = 45;
407         cache.screen_label = glabel.substr(0, maxLabelChars + 1);
408         support::truncateWithEllipsis(cache.screen_label, maxLabelChars);
409 }
410
411
412 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
413                                                          UpdateType) const
414 {
415         // NOTE
416         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations 
417         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
418         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
419         // then we will also need to change that routine.
420         docstring const tocitem = getParam("key");
421         shared_ptr<Toc> toc = buffer().tocBackend().toc("citation");
422         toc->push_back(TocItem(cpit, 0, tocitem, output_active));
423 }
424
425
426 int InsetCitation::plaintext(odocstringstream & os,
427        OutputParams const &, size_t) const
428 {
429         string const & cmd = getCmdName();
430         if (cmd == "nocite")
431                 return 0;
432
433         docstring const label = generateLabel(false);
434         os << label;
435         return label.size();
436 }
437
438
439 static docstring const cleanupWhitespace(docstring const & citelist)
440 {
441         docstring::const_iterator it  = citelist.begin();
442         docstring::const_iterator end = citelist.end();
443         // Paranoia check: make sure that there is no whitespace in here
444         // -- at least not behind commas or at the beginning
445         docstring result;
446         char_type last = ',';
447         for (; it != end; ++it) {
448                 if (*it != ' ')
449                         last = *it;
450                 if (*it != ' ' || last != ',')
451                         result += *it;
452         }
453         return result;
454 }
455
456
457 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
458 {
459         os << from_ascii("<citation>")
460            << cleanupWhitespace(getParam("key"))
461            << from_ascii("</citation>");
462         return 0;
463 }
464
465
466 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
467 {
468         string const & cmd = getCmdName();
469         if (cmd == "nocite")
470                 return docstring();
471
472         // have to output this raw, because generateLabel() will include tags
473         xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
474
475         return docstring();
476 }
477
478
479 void InsetCitation::toString(odocstream & os) const
480 {
481         odocstringstream ods;
482         plaintext(ods, OutputParams(0));
483         os << ods.str();
484 }
485
486
487 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
488 {
489         os += screenLabel();
490 }
491
492
493 // Have to overwrite the default InsetCommand method in order to check that
494 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
495 // citations and then changes his mind, turning natbib support off. The output
496 // should revert to the default citation command as provided by the citation
497 // engine, e.g. \cite[]{} for the basic engine.
498 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
499 {
500         vector<CitationStyle> citation_styles = buffer().params().citeStyles();
501         CitationStyle cs = asValidLatexCommand(buffer().params(), getCmdName(), citation_styles);
502         BiblioInfo const & bi = buffer().masterBibInfo();
503         // FIXME UNICODE
504         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
505
506         if (runparams.inulemcmd > 0)
507                 os << "\\mbox{";
508
509         os << "\\" << cite_str;
510
511         docstring const & before = getParam("before");
512         docstring const & after  = getParam("after");
513         if (!before.empty() && cs.textBefore)
514                 os << '[' << before << "][" << after << ']';
515         else if (!after.empty() && cs.textAfter)
516                 os << '[' << after << ']';
517
518         if (!bi.isBibtex(getParam("key")))
519                 // escape chars with bibitems
520                 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
521         else
522                 os << '{' << cleanupWhitespace(getParam("key")) << '}';
523
524         if (runparams.inulemcmd)
525                 os << "}";
526 }
527
528
529 string InsetCitation::contextMenuName() const
530 {
531         return "context-citation";
532 }
533
534
535 } // namespace lyx