]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCitation.cpp
Improve keyval highlighter
[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 "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 " et al.", 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                 titledata = subst(titledata, from_ascii(" et al."), docstring());
221                 bi.getLocators(kvar, doi, url, file);
222                 LYXERR(Debug::INSETS, "Locators: doi:" << doi << " url:"
223                         << url << " file:" << file << " title data:" << titledata
224                         << " citation search: " << lyxrc.citation_search
225                         << " citation search pattern: " << lyxrc.citation_search_pattern);
226                 docstring locator;
227                 if (!file.empty()) {
228                         locator = file;
229                 } else if (!doi.empty()) {
230                         locator = doi;
231                 } else if (!url.empty()) {
232                         locator = url;
233                 } else {
234                         locator = "EXTERNAL " + titledata;
235                 }
236                 FuncRequest cmd = FuncRequest(LFUN_CITATION_OPEN, locator);
237                 lyx::dispatch(cmd);
238         }
239 }
240
241
242 bool InsetCitation::getStatus(Cursor & cur, FuncRequest const & cmd,
243         FuncStatus & status) const
244 {
245         switch (cmd.action()) {
246         // Handle the alias case
247         case LFUN_INSET_MODIFY:
248                 if (cmd.getArg(0) == "changetype") {
249                         string cmdname = getCmdName();
250                         string const alias =
251                                 buffer().masterParams().getCiteAlias(cmdname);
252                         if (!alias.empty())
253                                 cmdname = alias;
254                         if (suffixIs(cmdname, "*"))
255                                 cmdname = rtrim(cmdname, "*");
256                         string const newtype = cmd.getArg(1);
257                         status.setEnabled(isCompatibleCommand(newtype));
258                         status.setOnOff(newtype == cmdname);
259                 }
260                 if (cmd.getArg(0) == "toggleparam") {
261                         string cmdname = getCmdName();
262                         string const alias =
263                                 buffer().masterParams().getCiteAlias(cmdname);
264                         if (!alias.empty())
265                                 cmdname = alias;
266                         vector<CitationStyle> citation_styles =
267                                 buffer().masterParams().citeStyles();
268                         CitationStyle cs = getCitationStyle(buffer().masterParams(),
269                                                             cmdname, citation_styles);
270                         if (cmd.getArg(1) == "star") {
271                                 status.setEnabled(cs.hasStarredVersion);
272                                 status.setOnOff(suffixIs(cmdname, "*"));
273                         }
274                         else if (cmd.getArg(1) == "casing") {
275                                 status.setEnabled(cs.forceUpperCase);
276                                 status.setOnOff(isUpperCase(cmdname[0]));
277                         }
278                 }
279                 return true;
280         case LFUN_INSET_EDIT:
281                 return openCitationPossible();
282         default:
283                 return InsetCommand::getStatus(cur, cmd, status);
284         }
285 }
286
287
288 bool InsetCitation::addKey(string const & key)
289 {
290         docstring const ukey = from_utf8(trim(key));
291         docstring const & curkeys = getParam("key");
292         if (curkeys.empty()) {
293                 setParam("key", ukey);
294                 cache.recalculate = true;
295                 return true;
296         }
297
298         vector<docstring> keys = getVectorFromString(curkeys);
299         for (auto const & k : keys) {
300                 if (k == ukey) {
301                         LYXERR0("Key " << key << " already present.");
302                         return false;
303                 }
304         }
305         keys.push_back(ukey);
306         setParam("key", getStringFromVector(keys));
307         cache.recalculate = true;
308         return true;
309 }
310
311
312 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
313 {
314         Buffer const & buf = bv.buffer();
315         // Only after the buffer is loaded from file...
316         if (!buf.isFullyLoaded())
317                 return docstring();
318
319         BiblioInfo const & bi = buf.masterBibInfo();
320         if (bi.empty())
321                 return _("No bibliography defined!");
322
323         docstring const & key = getParam("key");
324         if (key.empty())
325                 return _("No citations selected!");
326
327         CiteItem ci;
328         ci.richtext = true;
329         vector<docstring> keys = getVectorFromString(key);
330         if (keys.size() == 1)
331                 return bi.getInfo(keys[0], buffer(), ci);
332
333         docstring tip;
334         tip += "<ol>";
335         int count = 0;
336         for (docstring const & kvar : keys) {
337                 docstring const key_info = bi.getInfo(kvar, buffer(), ci);
338                 // limit to reasonable size.
339                 if (count > 9 && keys.size() > 11) {
340                         tip.push_back(0x2026);// HORIZONTAL ELLIPSIS
341                         tip += "<p>"
342                                 + bformat(_("+ %1$d more entries."), int(keys.size() - count))
343                                 + "</p>";
344                         break;
345                 }
346                 if (key_info.empty())
347                         continue;
348                 tip += "<li>" + key_info + "</li>";
349                 ++count;
350         }
351         tip += "</ol>";
352         return tip;
353 }
354
355
356 namespace {
357
358 CitationStyle asValidLatexCommand(BufferParams const & bp, string const & input,
359                                   vector<CitationStyle> const & valid_styles)
360 {
361         CitationStyle cs = valid_styles[0];
362         cs.forceUpperCase = false;
363         cs.hasStarredVersion = false;
364
365         string normalized_input = input;
366         string::size_type const n = input.size() - 1;
367         if (isUpperCase(input[0]))
368                 normalized_input[0] = lowercase(input[0]);
369         if (input[n] == '*')
370                 normalized_input = normalized_input.substr(0, n);
371
372         string const alias = bp.getCiteAlias(normalized_input);
373         if (!alias.empty())
374                 normalized_input = alias;
375
376         vector<CitationStyle>::const_iterator it  = valid_styles.begin();
377         vector<CitationStyle>::const_iterator end = valid_styles.end();
378         for (; it != end; ++it) {
379                 CitationStyle this_cs = *it;
380                 if (this_cs.name == normalized_input) {
381                         cs = *it;
382                         break;
383                 }
384         }
385
386         cs.forceUpperCase &= input[0] == uppercase(input[0]);
387         cs.hasStarredVersion &= input[n] == '*';
388
389         return cs;
390 }
391
392
393 inline docstring wrapCitation(docstring const & key,
394                 docstring const & content, bool for_xhtml)
395 {
396         if (!for_xhtml)
397                 return content;
398         // we have to do the escaping here, because we will ultimately
399         // write this as a raw string, so as not to escape the tags.
400         return "<a href='#LyXCite-" + xml::cleanAttr(key) + "'>" +
401                         xml::escapeString(content, XMLStream::ESCAPE_ALL) + "</a>";
402 }
403
404 } // anonymous namespace
405
406
407 vector<pair<docstring, docstring>> InsetCitation::getQualifiedLists(docstring const & p) const
408 {
409         vector<docstring> ps =
410                 getVectorFromString(p, from_ascii("\t"));
411         QualifiedList res;
412         for (docstring const & s: ps) {
413                 docstring key = s;
414                 docstring val;
415                 if (contains(s, ' '))
416                         val = split(s, key, ' ');
417                 res.push_back(make_pair(key, val));
418         }
419         return res;
420 }
421
422 docstring InsetCitation::generateLabel(bool for_xhtml) const
423 {
424         docstring label;
425         label = complexLabel(for_xhtml);
426
427         // Fallback to fail-safe
428         if (label.empty())
429                 label = basicLabel(for_xhtml);
430
431         return label;
432 }
433
434
435 docstring InsetCitation::complexLabel(bool for_xhtml) const
436 {
437         Buffer const & buf = buffer();
438         // Only start the process off after the buffer is loaded from file.
439         if (!buf.isFullyLoaded())
440                 return docstring();
441
442         docstring const & key = getParam("key");
443
444         BiblioInfo const & biblist = buf.masterBibInfo();
445
446         // mark broken citations
447         setBroken(false);
448
449         if (biblist.empty()) {
450                 setBroken(true);
451                 return docstring();
452         }
453
454         if (key.empty())
455                 return _("No citations selected!");
456
457         // check all citations
458         // we only really want the last 'false', to suppress trimming, but
459         // we need to give the other defaults, too, to set it.
460         vector<docstring> keys =
461                 getVectorFromString(key, from_ascii(","), false, false);
462         for (auto const & k : keys) {
463                 if (biblist.find(k) == biblist.end()) {
464                         setBroken(true);
465                         break;
466                 }
467         }
468         
469         string cite_type = getCmdName();
470         bool const uppercase = isUpperCase(cite_type[0]);
471         if (uppercase)
472                 cite_type[0] = lowercase(cite_type[0]);
473         bool const starred = (cite_type[cite_type.size() - 1] == '*');
474         if (starred)
475                 cite_type = cite_type.substr(0, cite_type.size() - 1);
476
477         // handle alias
478         string const alias = buf.masterParams().getCiteAlias(cite_type);
479         if (!alias.empty())
480                 cite_type = alias;
481
482         // FIXME: allow to add cite macros
483         /*
484         buffer().params().documentClass().addCiteMacro("!textbefore", to_utf8(before));
485         buffer().params().documentClass().addCiteMacro("!textafter", to_utf8(after));
486         */
487         docstring label;
488         CitationStyle cs = getCitationStyle(buffer().masterParams(),
489                         cite_type, buffer().masterParams().citeStyles());
490         bool const qualified = cs.hasQualifiedList
491                 && (keys.size() > 1
492                     || !getParam("pretextlist").empty()
493                     || !getParam("posttextlist").empty());
494         QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
495         QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
496
497         CiteItem ci;
498         ci.textBefore = getParam("before");
499         ci.textAfter = getParam("after");
500         ci.forceUpperCase = uppercase;
501         ci.Starred = starred;
502         ci.max_size = UINT_MAX;
503         ci.isQualified = qualified;
504         ci.pretexts = pres;
505         ci.posttexts = posts;
506         if (for_xhtml) {
507                 ci.max_key_size = UINT_MAX;
508                 ci.context = CiteItem::Export;
509         }
510         ci.richtext = for_xhtml;
511         label = biblist.getLabel(keys, buffer(), cite_type, ci);
512         return label;
513 }
514
515
516 docstring InsetCitation::basicLabel(bool for_xhtml) const
517 {
518         docstring keys = getParam("key");
519         docstring label;
520
521         docstring key;
522         do {
523                 // if there is no comma, then everything goes into key
524                 // and keys will be empty.
525                 keys = split(keys, key, ',');
526                 if (!label.empty())
527                         label += ", ";
528                 label += wrapCitation(key, key, for_xhtml);
529         } while (!keys.empty());
530
531         docstring const & after = getParam("after");
532         if (!after.empty())
533                 label += ", " + after;
534
535         return '[' + label + ']';
536 }
537
538
539 bool InsetCitation::forceLTR(OutputParams const & rp) const
540 {
541         // We have to force LTR for numeric references
542         // [= bibliography, plain BibTeX, numeric natbib
543         // and biblatex]. Except for XeTeX/bidi. See #3005.
544         if (rp.useBidiPackage())
545                 return false;
546         return (buffer().masterParams().citeEngine() == "basic"
547                 || buffer().masterParams().citeEngineType() == ENGINE_TYPE_NUMERICAL);
548 }
549
550 docstring InsetCitation::screenLabel() const
551 {
552         return cache.screen_label;
553 }
554
555
556 void InsetCitation::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
557 {
558         if (!cache.recalculate && buffer().citeLabelsValid())
559                 return;
560         // The label may have changed, so we have to re-create it.
561         docstring const glabel = generateLabel();
562         cache.recalculate = false;
563         cache.generated_label = glabel;
564         unsigned int const maxLabelChars = 45;
565         cache.screen_label = glabel;
566         support::truncateWithEllipsis(cache.screen_label, maxLabelChars, true);
567 }
568
569
570 void InsetCitation::addToToc(DocIterator const & cpit, bool output_active,
571                                                          UpdateType, TocBackend & backend) const
572 {
573         // NOTE
574         // BiblioInfo::collectCitedEntries() uses the TOC to collect the citations
575         // from the document. It is used indirectly, via BiblioInfo::makeCitationLables,
576         // by both XHTML and plaintext output. So, if we change what goes into the TOC,
577         // then we will also need to change that routine.
578         docstring tocitem;
579         if (isBroken())
580                 tocitem = _("BROKEN: ");
581         tocitem += getParam("key");
582         TocBuilder & b = backend.builder("citation");
583         b.pushItem(cpit, tocitem, output_active);
584         b.pop();
585         if (isBroken()) {
586                 shared_ptr<Toc> toc2 = backend.toc("brokenrefs");
587                 toc2->push_back(TocItem(cpit, 0, tocitem, output_active));
588         }
589 }
590
591
592 int InsetCitation::plaintext(odocstringstream & os,
593        OutputParams const &, size_t) const
594 {
595         string const & cmd = getCmdName();
596         if (cmd == "nocite")
597                 return 0;
598
599         docstring const label = generateLabel();
600         os << label;
601         return label.size();
602 }
603
604
605 static docstring const cleanupWhitespace(docstring const & citelist)
606 {
607         // Paranoia check: make sure that there is no whitespace in here
608         // -- at least not behind commas or at the beginning
609         docstring result;
610         char_type last = ',';
611         for (char_type c : citelist) {
612                 if (c != ' ')
613                         last = c;
614                 if (c != ' ' || last != ',')
615                         result += c;
616         }
617         return result;
618 }
619
620
621 void InsetCitation::cleanKeys() {
622         docstring cleankeys = cleanupWhitespace(getParam("key"));
623         setParam("key", cleankeys);
624 }
625
626 void InsetCitation::docbook(XMLStream & xs, OutputParams const &) const
627 {
628         if (getCmdName() == "nocite")
629                 return;
630
631         // Split the different citations (on ","), so that one tag can be output for each of them.
632         // DocBook does not support having multiple citations in one tag, so that we have to deal with formatting here.
633         docstring citations = getParam("key");
634         if (citations.find(',') == string::npos) {
635                 xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations)) + "\"");
636         } else {
637                 size_t pos = 0;
638                 while (pos != string::npos) {
639                         pos = citations.find(',');
640                         xs << xml::CompTag("biblioref", "endterm=\"" + to_utf8(xml::cleanID(citations.substr(0, pos))) + "\"");
641                         citations.erase(0, pos + 1);
642
643                         if (pos != string::npos) {
644                                 xs << ", "; 
645                         }
646                 }
647         }
648 }
649
650
651 docstring InsetCitation::xhtml(XMLStream & xs, OutputParams const &) const
652 {
653         if (getCmdName() == "nocite")
654                 return docstring();
655
656         // have to output this raw, because generateLabel() will include tags
657         xs << XMLStream::ESCAPE_NONE << generateLabel(true);
658
659         return docstring();
660 }
661
662
663 void InsetCitation::toString(odocstream & os) const
664 {
665         odocstringstream ods;
666         plaintext(ods, OutputParams(nullptr));
667         os << ods.str();
668 }
669
670
671 void InsetCitation::forOutliner(docstring & os, size_t const, bool const) const
672 {
673         os += screenLabel();
674 }
675
676
677 // Have to overwrite the default InsetCommand method in order to check that
678 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
679 // citations and then changes his mind, turning natbib support off. The output
680 // should revert to the default citation command as provided by the citation
681 // engine, e.g. \cite[]{} for the basic engine.
682 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
683 {
684         // When this is a child compiled on its own, we use the children
685         // own bibinfo, else the master's
686         BiblioInfo const & bi = runparams.is_child
687                         ? buffer().masterBibInfo() : buffer().bibInfo();
688         docstring const key = getParam("key");
689         // "keyonly" command: output the plain key and stop.
690         if (getCmdName() == "keyonly") {
691                 // Special command to only return the key
692                 if (!bi.isBibtex(getParam("key")))
693                         // escape chars with bibitems
694                         os << escape(cleanupWhitespace(key));
695                 else
696                         os << cleanupWhitespace(key);
697                 return;
698         }
699         vector<CitationStyle> citation_styles = buffer().masterParams().citeStyles();
700         CitationStyle cs = asValidLatexCommand(buffer().masterParams(),
701                                                getCmdName(), citation_styles);
702         // FIXME UNICODE
703         docstring const cite_str = from_utf8(citationStyleToString(cs, true));
704
705         // check if we have to do a qualified list
706         vector<docstring> keys = getVectorFromString(cleanupWhitespace(key));
707         bool const qualified = cs.hasQualifiedList
708                 && (!getParam("pretextlist").empty()
709                     || !getParam("posttextlist").empty());
710
711         if (runparams.inulemcmd > 0)
712                 os << "\\mbox{";
713
714         os << "\\" << cite_str;
715
716         if (qualified)
717                 os << "s";
718
719         ParamInfo const & pinfo = findInfo(string());
720         docstring before = params().prepareCommand(runparams, getParam("before"),
721                                                    pinfo["before"].handling());
722         docstring after = params().prepareCommand(runparams, getParam("after"),
723                                                    pinfo["after"].handling());
724         if (!before.empty() && cs.textBefore) {
725                 if (qualified)
726                         os << '(' << protectArgument(before, '(', ')')
727                            << ")(" << protectArgument(after, '(', ')') << ')';
728                 else
729                         os << '[' << protectArgument(before) << "]["
730                            << protectArgument(after) << ']';
731         } else if (!after.empty() && cs.textAfter) {
732                 if (qualified)
733                         os << '(' << protectArgument(after, '(', ')') << ')';
734                 else
735                         os << '[' << protectArgument(after) << ']';
736         }
737
738         if (!bi.isBibtex(key))
739                 // escape chars with bibitems
740                 os << '{' << escape(cleanupWhitespace(key)) << '}';
741         else {
742                 if (qualified) {
743                         QualifiedList pres = getQualifiedLists(getParam("pretextlist"));
744                         QualifiedList posts = getQualifiedLists(getParam("posttextlist"));
745                         for (docstring const & k : keys) {
746                                 docstring prenote;
747                                 QualifiedList::iterator it = pres.begin();
748                                 for (; it != pres.end() ; ++it) {
749                                         if ((*it).first == k) {
750                                                 prenote = (*it).second;
751                                                 pres.erase(it);
752                                                 break;
753                                         }
754                                 }
755                                 docstring bef = params().prepareCommand(runparams, prenote,
756                                                    pinfo["pretextlist"].handling());
757                                 docstring postnote;
758                                 QualifiedList::iterator pit = posts.begin();
759                                 for (; pit != posts.end() ; ++pit) {
760                                         if ((*pit).first == k) {
761                                                 postnote = (*pit).second;
762                                                 posts.erase(pit);
763                                                 break;
764                                         }
765                                 }
766                                 docstring aft = params().prepareCommand(runparams, postnote,
767                                                    pinfo["posttextlist"].handling());
768                                 if (!bef.empty())
769                                         os << '[' << protectArgument(bef)
770                                            << "][" << protectArgument(aft) << ']';
771                                 else if (!aft.empty())
772                                         os << '[' << protectArgument(aft) << ']';
773                                 os << '{' << k << '}';
774                         }
775                 } else
776                         os << '{' << cleanupWhitespace(key) << '}';
777         }
778
779         if (runparams.inulemcmd)
780                 os << "}";
781 }
782
783
784 pair<int, int> InsetCitation::isWords() const
785 {
786         docstring const label = generateLabel(false);
787         return pair<int, int>(label.size(), wordCount(label));
788 }
789
790
791 string InsetCitation::contextMenuName() const
792 {
793         return "context-citation";
794 }
795
796
797 } // namespace lyx