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