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