]> git.lyx.org Git - features.git/blob - src/insets/InsetCitation.cpp
Regenerate previews after zoom (#11919)
[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 "Citation.h"
22 #include "DispatchResult.h"
23 #include "FuncCode.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "LyX.h"
28 #include "LyXRC.h"
29 #include "output_xhtml.h"
30 #include "output_docbook.h"
31 #include "ParIterator.h"
32 #include "texstream.h"
33 #include "TocBackend.h"
34
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/FileNameList.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
40
41 #include <algorithm>
42 #include <climits>
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48
49 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
50         : InsetCommand(buf, p)
51 {
52         buffer().removeBiblioTempFiles();
53         cleanKeys();
54 }
55
56
57 InsetCitation::~InsetCitation()
58 {
59         if (isBufferLoaded())
60                 /* We do not use buffer() because Coverity believes that this
61                  * may throw an exception. Actually this code path is not
62                  * taken when buffer_ == 0 */
63                 buffer_->removeBiblioTempFiles();
64 }
65
66
67 // May well be over-ridden when session settings are loaded
68 // in GuiCitation. Unfortunately, that will not happen until
69 // such a dialog is created.
70 bool InsetCitation::last_literal = true;
71
72
73 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
74 {
75         static ParamInfo param_info_;
76
77         // standard cite does only take one argument, but biblatex, jurabib
78         // and natbib extend this to two arguments, so
79         // we have to allow both here. InsetCitation takes care that
80         // LaTeX output is nevertheless correct.
81         if (param_info_.empty()) {
82                 param_info_.add("after", ParamInfo::LATEX_OPTIONAL,
83                                 ParamInfo::HANDLING_LATEXIFY);
84                 param_info_.add("before", ParamInfo::LATEX_OPTIONAL,
85                                 ParamInfo::HANDLING_LATEXIFY);
86                 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
87                 param_info_.add("pretextlist", ParamInfo::LATEX_OPTIONAL,
88                                 ParamInfo::HANDLING_LATEXIFY);
89                 param_info_.add("posttextlist", ParamInfo::LATEX_OPTIONAL,
90                                 ParamInfo::HANDLING_LATEXIFY);
91                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
92         }
93         return param_info_;
94 }
95
96
97 // We allow any command here, since we fall back to cite
98 // anyway if a command is not allowed by a style
99 bool InsetCitation::isCompatibleCommand(string const &)
100 {
101         return true;
102 }
103
104
105 CitationStyle InsetCitation::getCitationStyle(BufferParams const & bp, string const & input,
106                                   vector<CitationStyle> const & valid_styles) const
107 {
108         CitationStyle cs = valid_styles[0];
109         cs.forceUpperCase = false;
110         cs.hasStarredVersion = false;
111
112         string normalized_input = input;
113         string::size_type const n = input.size() - 1;
114         if (isUpperCase(input[0]))
115                 normalized_input[0] = lowercase(input[0]);
116         if (input[n] == '*')
117                 normalized_input = normalized_input.substr(0, n);
118
119         string const alias = bp.getCiteAlias(normalized_input);
120         if (!alias.empty())
121                 normalized_input = alias;
122
123         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
124         vector<CitationStyle>::const_iterator end = valid_styles.end();
125         for (; it != end; ++it) {
126                 CitationStyle this_cs = *it;
127                 if (this_cs.name == normalized_input) {
128                         cs = *it;
129                         break;
130                 }
131         }
132
133         return cs;
134 }
135
136
137 void InsetCitation::doDispatch(Cursor & cur, FuncRequest & cmd)
138 {
139         switch (cmd.action()) {
140         case LFUN_INSET_EDIT:
141                 openCitation();
142                 break;
143         case LFUN_INSET_MODIFY: {
144                 buffer().removeBiblioTempFiles();
145                 cache.recalculate = true;
146                 if (cmd.getArg(0) == "toggleparam") {
147                         string cmdname = getCmdName();
148                         string const alias =
149                                 buffer().masterParams().getCiteAlias(cmdname);
150                         if (!alias.empty())
151                                 cmdname = alias;
152                         string const par = cmd.getArg(1);
153                         string newcmdname = cmdname;
154                         if (par == "star") {
155                                 if (suffixIs(cmdname, "*"))
156                                         newcmdname = rtrim(cmdname, "*");
157                                 else
158                                         newcmdname = cmdname + "*";
159                         } else if (par == "casing") {
160                                 if (isUpperCase(cmdname[0]))
161                                         newcmdname[0] = lowercase(cmdname[0]);
162                                 else
163                                         newcmdname[0] = uppercase(newcmdname[0]);
164                         }
165                         cmd = FuncRequest(LFUN_INSET_MODIFY, "changetype " + newcmdname);
166                 }
167         }
168         // fall through
169         default:
170                 InsetCommand::doDispatch(cur, cmd);
171                 if (cmd.action() == LFUN_INSET_MODIFY)
172                         cleanKeys();
173         }
174 }
175
176 bool InsetCitation::openCitationPossible() const
177 {
178         Buffer const & buf = *buffer_;
179         // only after the buffer is loaded from file...
180         if (!buf.isFullyLoaded())
181                 return false;
182
183         BiblioInfo const & bi = buf.masterBibInfo();
184         if (bi.empty())
185                 return false;
186
187         docstring const & key = getParam("key");
188         if (key.empty())
189                 return false;
190
191         // does bibtex item contains some locator?
192         vector<docstring> keys = getVectorFromString(key);
193         docstring doi, url, file;
194         for (docstring const & kvar : keys) {
195                 bi.getLocators(kvar, doi, url, file);
196                 if (!file.empty() || !doi.empty() || !url.empty())
197                         return true;
198         }
199
200         // last resort: is external script activated?
201         return lyxrc.citation_search;
202 }
203
204 void InsetCitation::openCitation()
205 {
206         Buffer const & buf = *buffer_;
207         BiblioInfo const & bi = buf.masterBibInfo();
208         docstring const & key = getParam("key");
209
210         vector<docstring> keys = getVectorFromString(key);
211         docstring titledata, doi, url, file;
212         for (docstring const & kvar : keys) {
213                 CiteItem ci;
214                 titledata = bi.getInfo(kvar, buffer(), ci,
215                                        from_ascii(lyxrc.citation_search_pattern));
216                 // some cleanup: commas and " and ", as used in name lists,
217                 // are not expected in file names
218                 titledata = subst(titledata, from_ascii(","), docstring());
219                 titledata = subst(titledata, from_ascii(" and "), from_ascii(" "));
220                 bi.getLocators(kvar, doi, url, file);
221                 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
222                         << url << " file:" << file << " title data:" << titledata
223                         << " citation search: " << lyxrc.citation_search
224                         << " citation search pattern: " << lyxrc.citation_search_pattern);
225                 docstring locator;
226                 if (!file.empty()) {
227                         locator = file;
228                 } else if (!doi.empty()) {
229                         locator = doi;
230                 } else if (!url.empty()) {
231                         locator = url;
232                 } else {
233                         locator = "EXTERNAL " + titledata;
234                 }
235                 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
236                 lyx::dispatch(cmd);
237         }
238 }
239
240
241 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
242         FuncStatus & status) const
243 {
244         switch (cmd.action()) {
245         // Handle the alias case
246         case LFUN_INSET_MODIFY:
247                 if (cmd.getArg(0) == "changetype") {
248                         string cmdname = getCmdName();
249                         string const alias =
250                                 buffer().masterParams().getCiteAlias(cmdname);
251                         if (!alias.empty())
252                                 cmdname = alias;
253                         if (suffixIs(cmdname, "*"))
254                                 cmdname = rtrim(cmdname, "*");
255                         string const newtype = cmd.getArg(1);
256                         status.setEnabled(isCompatibleCommand(newtype));
257                         status.setOnOff(newtype == cmdname);
258                 }
259                 if (cmd.getArg(0) == "toggleparam") {
260                         string cmdname = getCmdName();
261                         string const alias =
262                                 buffer().masterParams().getCiteAlias(cmdname);
263                         if (!alias.empty())
264                                 cmdname = alias;
265                         vector<CitationStyle> citation_styles =
266                                 buffer().masterParams().citeStyles();
267                         CitationStyle cs = getCitationStyle(buffer().masterParams(),
268                                                             cmdname, citation_styles);
269                         if (cmd.getArg(1) == "star") {
270                                 status.setEnabled(cs.hasStarredVersion);
271                                 status.setOnOff(suffixIs(cmdname, "*"));
272                         }
273                         else if (cmd.getArg(1) == "casing") {
274                                 status.setEnabled(cs.forceUpperCase);
275                                 status.setOnOff(isUpperCase(cmdname[0]));
276                         }
277                 }
278                 return true;
279         case LFUN_INSET_EDIT:
280                 return openCitationPossible();
281         default:
282                 return InsetCommand::getStatus(cur, cmd, status);
283         }
284 }
285
286
287 bool InsetCitation::addKey(string const & key)
288 {
289         docstring const ukey = from_utf8(trim(key));
290         docstring const & curkeys = getParam("key");
291         if (curkeys.empty()) {
292                 setParam("key", ukey);
293                 cache.recalculate = true;
294                 return true;
295         }
296
297         vector<docstring> keys = getVectorFromString(curkeys);
298         for (auto const & k : keys) {
299                 if (k == ukey) {
300                         LYXERR0("Key " << key << " already present.");
301                         return false;
302                 }
303         }
304         keys.push_back(ukey);
305         setParam("key", getStringFromVector(keys));
306         cache.recalculate = true;
307         return true;
308 }
309
310
311 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
312 {
313         Buffer const & buf = bv.buffer();
314         // Only after the buffer is loaded from file...
315         if (!buf.isFullyLoaded())
316                 return docstring();
317
318         BiblioInfo const & bi = buf.masterBibInfo();
319         if (bi.empty())
320                 return _("No bibliography defined!");
321
322         docstring const & key = getParam("key");
323         if (key.empty())
324                 return _("No citations selected!");
325
326         CiteItem ci;
327         ci.richtext = true;
328         vector<docstring> keys = getVectorFromString(key);
329         if (keys.size() == 1)
330                 return bi.getInfo(keys[0], buffer(), ci);
331
332         docstring tip;
333         tip += "<ol>";
334         int count = 0;
335         for (docstring const & kvar : keys) {
336                 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
337                 // limit to reasonable size.
338                 if (count > 9 && keys.size() > 11) {
339                         tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
340                         tip += "<p>"
341                                 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
342                                 + "</p>";
343                         break;
344                 }
345                 if (key_info.empty())
346                         continue;
347                 tip += "<li>" + key_info + "</li>";
348                 ++count;
349         }
350         tip += "</ol>";
351         return tip;
352 }
353
354
355 namespace {
356
357 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
358                                   vector<CitationStyle> const & valid_styles)
359 {
360         CitationStyle cs = valid_styles[0];
361         cs.forceUpperCase = false;
362         cs.hasStarredVersion = false;
363
364         string normalized_input = input;
365         string::size_type const n = input.size() - 1;
366         if (isUpperCase(input[0]))
367                 normalized_input[0] = lowercase(input[0]);
368         if (input[n] == '*')
369                 normalized_input = normalized_input.substr(0, n);
370
371         string const alias = bp.getCiteAlias(normalized_input);
372         if (!alias.empty())
373                 normalized_input = alias;
374
375         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
376         vector<CitationStyle>::const_iterator end = valid_styles.end();
377         for (; it != end; ++it) {
378                 CitationStyle this_cs = *it;
379                 if (this_cs.name == normalized_input) {
380                         cs = *it;
381                         break;
382                 }
383         }
384
385         cs.forceUpperCase &= input[0] == uppercase(input[0]);
386         cs.hasStarredVersion &= input[n] == '*';
387
388         return cs;
389 }
390
391
392 inline docstring wrapCitation(docstring const & key,
393                 docstring const & content, bool for_xhtml)
394 {
395         if (!for_xhtml)
396                 return content;
397         // we have to do the escaping here, because we will ultimately
398         // write this as a raw string, so as not to escape the tags.
399         return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
400                         xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
401 }
402
403 } // anonymous namespace
404
405
406 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
407 {
408         vector<docstring> ps =
409                 getVectorFromString(p, from_ascii("\t"));
410         QualifiedList res;
411         for (docstring const & s: ps) {
412                 docstring key = s;
413                 docstring val;
414                 if (contains(s, ' '))
415                         val = split(s, key, ' ');
416                 res.push_back(make_pair(key, val));
417         }
418         return res;
419 }
420
421 docstring InsetCitation::generateLabel(bool for_xhtml) const
422 {
423         docstring label;
424         label = complexLabel(for_xhtml);
425
426         // Fallback to fail-safe
427         if (label.empty())
428                 label = basicLabel(for_xhtml);
429
430         return label;
431 }
432
433
434 docstring InsetCitation::complexLabel(bool for_xhtml) const
435 {
436         Buffer const & buf = buffer();
437         // Only start the process off after the buffer is loaded from file.
438         if (!buf.isFullyLoaded())
439                 return docstring();
440
441         docstring const & key = getParam("key");
442
443         BiblioInfo const & biblist = buf.masterBibInfo();
444
445         // mark broken citations
446         setBroken(false);
447
448         if (biblist.empty()) {
449                 setBroken(true);
450                 return docstring();
451         }
452
453         if (key.empty())
454                 return _("No citations selected!");
455
456         // check all citations
457         // we only really want the last 'false', to suppress trimming, but
458         // we need to give the other defaults, too, to set it.
459         vector<docstring> keys =
460                 getVectorFromString(key, from_ascii(","), false, false);
461         for (auto const & k : keys) {
462                 if (biblist.find(k) == biblist.end()) {
463                         setBroken(true);
464                         break;
465                 }
466         }
467         
468         string cite_type = getCmdName();
469         bool const uppercase = isUpperCase(cite_type[0]);
470         if (uppercase)
471                 cite_type[0] = lowercase(cite_type[0]);
472         bool const starred = (cite_type[cite_type.size() - 1] == '*');
473         if (starred)
474                 cite_type = cite_type.substr(0, cite_type.size() - 1);
475
476         // handle alias
477         string const alias = buf.masterParams().getCiteAlias(cite_type);
478         if (!alias.empty())
479                 cite_type = alias;
480
481         // FIXME: allow to add cite macros
482         /*
483         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
484         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
485         */
486         docstring label;
487         CitationStyle cs = getCitationStyle(buffer().masterParams(),
488                         cite_type, buffer().masterParams().citeStyles());
489         bool const qualified = cs.hasQualifiedList
490                 && (keys.size() > 1
491                     || !getParam("pretextlist").empty()
492                     || !getParam("posttextlist").empty());
493         QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
494         QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
495
496         CiteItem ci;
497         ci.textBefore = getParam("before");
498         ci.textAfter = getParam("after");
499         ci.forceUpperCase = uppercase;
500         ci.Starred = starred;
501         ci.max_size = UINT_MAX;
502         ci.isQualified = qualified;
503         ci.pretexts = pres;
504         ci.posttexts = posts;
505         if (for_xhtml) {
506                 ci.max_key_size = UINT_MAX;
507                 ci.context = CiteItem::Export;
508         }
509         ci.richtext = for_xhtml;
510         label = biblist.getLabel(keys, buffer(), cite_type, ci);
511         return label;
512 }
513
514
515 docstring InsetCitation::basicLabel(bool for_xhtml) const
516 {
517         docstring keys = getParam("key");
518         docstring label;
519
520         docstring key;
521         do {
522                 // if there is no comma, then everything goes into key
523                 // and keys will be empty.
524                 keys = split(keys, key, ',');
525                 if (!label.empty())
526                         label += ", ";
527                 label += wrapCitation(key, key, for_xhtml);
528         } while (!keys.empty());
529
530         docstring const & after = getParam("after");
531         if (!after.empty())
532                 label += ", " + after;
533
534         return '[' + label + ']';
535 }
536
537
538 bool InsetCitation::forceLTR(OutputParams const & rp) const
539 {
540         // We have to force LTR for numeric references
541         // [= bibliography, plain BibTeX, numeric natbib
542         // and biblatex]. Except for XeTeX/bidi. See #3005.
543         if (rp.useBidiPackage())
544                 return false;
545         return (buffer().masterParams().citeEngine() == "basic"
546                 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
547 }
548
549 docstring InsetCitation::screenLabel() const
550 {
551         return cache.screen_label;
552 }
553
554
555 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
556 {
557         if (!cache.recalculate && buffer().citeLabelsValid())
558                 return;
559         // The label may have changed, so we have to re-create it.
560         docstring const glabel = generateLabel();
561         cache.recalculate = false;
562         cache.generated_label = glabel;
563         unsigned int const maxLabelChars = 45;
564         cache.screen_label = glabel;
565         support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
566 }
567
568
569 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
570                                                          UpdateType, TocBackend & backend) const
571 {
572         // NOTE
573         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
574         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
575         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
576         // then we will also need to change that routine.
577         docstring tocitem;
578         if (isBroken())
579                 tocitem = _("BROKEN: ");
580         tocitem += getParam("key");
581         TocBuilder & b = backend.builder("citation");
582         b.pushItem(cpit, tocitem, output_active);
583         b.pop();
584         if (isBroken()) {
585                 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
586                 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
587         }
588 }
589
590
591 int InsetCitation::plaintext(odocstringstream & os,
592        OutputParams const &, size_t) const
593 {
594         string const & cmd = getCmdName();
595         if (cmd == "nocite")
596                 return 0;
597
598         docstring const label = generateLabel();
599         os << label;
600         return label.size();
601 }
602
603
604 static docstring const cleanupWhitespace(docstring const & citelist)
605 {
606         // Paranoia check: make sure that there is no whitespace in here
607         // -- at least not behind commas or at the beginning
608         docstring result;
609         char_type last = ',';
610         for (char_type c : citelist) {
611                 if (c != ' ')
612                         last = c;
613                 if (c != ' ' || last != ',')
614                         result += c;
615         }
616         return result;
617 }
618
619
620 void InsetCitation::cleanKeys() {
621         docstring cleankeys = cleanupWhitespace(getParam("key"));
622         setParam("key", cleankeys);
623 }
624
625 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
626 {
627         if (getCmdName() == "nocite")
628                 return;
629
630         // Split the different citations (on ","), so that one tag can be output for each of them.
631         // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
632         docstring citations = getParam("key");
633         if (citations.find(',') == string::npos) {
634                 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
635         } else {
636                 size_t pos = 0;
637                 while (pos != string::npos) {
638                         pos = citations.find(',');
639                         xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
640                         citations.erase(0, pos + 1);
641
642                         if (pos != string::npos) {
643                                 xs << ", "; 
644                         }
645                 }
646         }
647 }
648
649
650 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
651 {
652         if (getCmdName() == "nocite")
653                 return docstring();
654
655         // have to output this raw, because generateLabel() will include tags
656         xs << XMLStream::ESCAPE_NONE << generateLabel(true);
657
658         return docstring();
659 }
660
661
662 void InsetCitation::toString(odocstream & os) const
663 {
664         odocstringstream ods;
665         plaintext(ods, OutputParams(nullptr));
666         os << ods.str();
667 }
668
669
670 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
671 {
672         os += screenLabel();
673 }
674
675
676 // Have to overwrite the default InsetCommand method in order to check that
677 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
678 // citations and then changes his mind, turning natbib support off. The output
679 // should revert to the default citation command as provided by the citation
680 // engine, e.g. \cite[]{} for the basic engine.
681 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
682 {
683         // When this is a child compiled on its own, we use the children
684         // own bibinfo, else the master's
685         BiblioInfo const & bi = runparams.is_child
686                         ? buffer().masterBibInfo() : buffer().bibInfo();
687         docstring const key = getParam("key");
688         // "keyonly" command: output the plain key and stop.
689         if (getCmdName() == "keyonly") {
690                 // Special command to only return the key
691                 if (!bi.isBibtex(getParam("key")))
692                         // escape chars with bibitems
693                         os << escape(cleanupWhitespace(key));
694                 else
695                         os << cleanupWhitespace(key);
696                 return;
697         }
698         vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
699         CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
700                                                getCmdName(), citation_styles);
701         // FIXME UNICODE
702         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
703
704         // check if we have to do a qualified list
705         vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
706         bool const qualified = cs.hasQualifiedList
707                 && (!getParam("pretextlist").empty()
708                     || !getParam("posttextlist").empty());
709
710         if (runparams.inulemcmd > 0)
711                 os << "\\mbox{";
712
713         os << "\\" << cite_str;
714
715         if (qualified)
716                 os << "s";
717
718         ParamInfo const & pinfo = findInfo(string());
719         docstring before = params().prepareCommand(runparams, getParam("before"),
720                                                    pinfo["before"].handling());
721         docstring after = params().prepareCommand(runparams, getParam("after"),
722                                                    pinfo["after"].handling());
723         if (!before.empty() && cs.textBefore) {
724                 if (qualified)
725                         os << '(' << protectArgument(before, '(', ')')
726                            << ")(" << protectArgument(after, '(', ')') << ')';
727                 else
728                         os << '[' << protectArgument(before) << "]["
729                            << protectArgument(after) << ']';
730         } else if (!after.empty() && cs.textAfter) {
731                 if (qualified)
732                         os << '(' << protectArgument(after, '(', ')') << ')';
733                 else
734                         os << '[' << protectArgument(after) << ']';
735         }
736
737         if (!bi.isBibtex(key))
738                 // escape chars with bibitems
739                 os << '{' << escape(cleanupWhitespace(key)) << '}';
740         else {
741                 if (qualified) {
742                         QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
743                         QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
744                         for (docstring const & k : keys) {
745                                 docstring prenote;
746                                 QualifiedList::iterator it = pres.begin();
747                                 for (; it != pres.end() ; ++it) {
748                                         if ((*it).first == k) {
749                                                 prenote = (*it).second;
750                                                 pres.erase(it);
751                                                 break;
752                                         }
753                                 }
754                                 docstring bef = params().prepareCommand(runparams, prenote,
755                                                    pinfo["pretextlist"].handling());
756                                 docstring postnote;
757                                 QualifiedList::iterator pit = posts.begin();
758                                 for (; pit != posts.end() ; ++pit) {
759                                         if ((*pit).first == k) {
760                                                 postnote = (*pit).second;
761                                                 posts.erase(pit);
762                                                 break;
763                                         }
764                                 }
765                                 docstring aft = params().prepareCommand(runparams, postnote,
766                                                    pinfo["posttextlist"].handling());
767                                 if (!bef.empty())
768                                         os << '[' << protectArgument(bef)
769                                            << "][" << protectArgument(aft) << ']';
770                                 else if (!aft.empty())
771                                         os << '[' << protectArgument(aft) << ']';
772                                 os << '{' << k << '}';
773                         }
774                 } else
775                         os << '{' << cleanupWhitespace(key) << '}';
776         }
777
778         if (runparams.inulemcmd)
779                 os << "}";
780 }
781
782
783 pair<int, int> InsetCitation::isWords() const
784 {
785         docstring const label = generateLabel(false);
786         return pair<int, int>(label.size(), wordCount(label));
787 }
788
789
790 string InsetCitation::contextMenuName() const
791 {
792         return "context-citation";
793 }
794
795
796 } // namespace lyx