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