]> git.lyx.org Git - features.git/blob - src/frontends/qt/Menus.cpp
Unify naming of menu items
[features.git] / src / frontends / qt / Menus.cpp
1 /**
2  * \file qt/Menus.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Asger Alstrup
8  * \author Lars Gullik Bjønnes
9  * \author Jean-Marc Lasgouttes
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Martin Vermeer
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "Menus.h"
20
21 #include "Action.h"
22 #include "GuiApplication.h"
23 #include "GuiView.h"
24 #include "GuiWorkArea.h"
25 #include "qt_helpers.h"
26
27 #include "BiblioInfo.h"
28 #include "BranchList.h"
29 #include "Buffer.h"
30 #include "BufferList.h"
31 #include "BufferParams.h"
32 #include "BufferView.h"
33 #include "Converter.h"
34 #include "Cursor.h"
35 #include "CutAndPaste.h"
36 #include "Floating.h"
37 #include "FloatList.h"
38 #include "Format.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "IndicesList.h"
42 #include "KeyMap.h"
43 #include "Language.h"
44 #include "Layout.h"
45 #include "Lexer.h"
46 #include "LyXAction.h"
47 #include "LyX.h"
48 #include "LyXRC.h"
49 #include "lyxfind.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
53 #include "Session.h"
54 #include "SpellChecker.h"
55 #include "TextClass.h"
56 #include "Text.h"
57 #include "TocBackend.h"
58 #include "Toolbars.h"
59 #include "WordLangTuple.h"
60
61 #include "insets/Inset.h"
62 #include "insets/InsetCitation.h"
63 #include "insets/InsetGraphics.h"
64 #include "insets/InsetInfo.h"
65 #include "insets/InsetQuotes.h"
66
67 #include "support/lassert.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/docstring_list.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
74
75 #include <QCursor>
76 #include <QHash>
77 #include <QList>
78 #include <QMenuBar>
79 #include <QString>
80 #if QT_VERSION >= 0x040600
81 #include <QProxyStyle>
82 #endif
83
84 #include <algorithm>
85 #include <memory>
86 #include <vector>
87
88 using namespace std;
89 using namespace lyx::support;
90
91
92 namespace lyx {
93 namespace frontend {
94
95 namespace {
96
97 // MacOSX specific stuff is at the end.
98
99 class MenuDefinition;
100
101 ///
102 class MenuItem {
103 public:
104         /// The type of elements that can be in a menu
105         enum Kind {
106                 ///
107                 Command,
108                 ///
109                 Submenu,
110                 ///
111                 Separator,
112                 /** This type of item explains why something is unavailable. If this
113                     menuitem is in a submenu, the submenu is enabled to make sure the
114                     user sees the information. */
115                 Help,
116                 /** This type of item merely shows that there might be a list or
117                     something alike at this position, but the list is still empty.
118                     If this item is in a submenu, the submenu will not always be
119                     enabled. */
120                 Info,
121                 /** This is the list of last opened file,
122                     typically for the File menu. */
123                 Lastfiles,
124                 /** This is the list of opened Documents,
125                     typically for the Documents menu. */
126                 Documents,
127                 /** This is the bookmarks */
128                 Bookmarks,
129                 ///
130                 Toc,
131                 /** This is a list of viewable formats
132                     typically for the File->View menu. */
133                 ViewFormats,
134                 /** This is a list of updatable formats
135                     typically for the File->Update menu. */
136                 UpdateFormats,
137                 /** This is a list of exportable formats
138                     typically for the File->Export menu. */
139                 ExportFormats,
140                 /** This exports the document default format
141                     typically for the File->Export menu. */
142                 ExportFormat,
143                 /** This is a list of importable formats
144                     typically for the File->Import menu. */
145                 ImportFormats,
146                 /** This is the list of elements available
147                  * for insertion into document. */
148                 CharStyles,
149                 /** This is the list of user-configurable
150                 insets to insert into document */
151                 Custom,
152                 /** This is the list of floats that we can
153                     insert a list for. */
154                 FloatListInsert,
155                 /** This is the list of floats that we can
156                     insert. */
157                 FloatInsert,
158                 /** This is the list of selections that can
159                     be pasted. */
160                 PasteRecent,
161                 /** toolbars */
162                 Toolbars,
163                 /** Available branches in document */
164                 Branches,
165                 /** Available indices in document */
166                 Indices,
167                 /** Context menu for indices in document */
168                 IndicesContext,
169                 /** Available index lists in document */
170                 IndicesLists,
171                 /** Context menu for available indices lists in document */
172                 IndicesListsContext,
173                 /** Available citation styles for a given citation */
174                 CiteStyles,
175                 /** Available arguments for a given info inset */
176                 InfoArguments,
177                 /** Available graphics groups */
178                 GraphicsGroups,
179                 /// Words suggested by the spellchecker.
180                 SpellingSuggestions,
181                 /** Used Languages */
182                 LanguageSelector,
183                 /** This is the list of arguments available
184                     for insertion into the current layout. */
185                 Arguments,
186                 /** This is the list of arguments available
187                     in the InsetArgument context menu. */
188                 SwitchArguments,
189                 /** This is the list of captions available
190                 in the current layout. */
191                 Captions,
192                 /** This is the list of captions available
193                 in the InsetCaption context menu. */
194                 SwitchCaptions,
195                 /** Commands to separate environments. */
196                 EnvironmentSeparators,
197                 /** Commands to separate environments (context menu version). */
198                 EnvironmentSeparatorsContext,
199                 /** This is the list of quotation marks available */
200                 SwitchQuotes
201         };
202
203         explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
204
205         MenuItem(Kind kind,
206                  QString const & label,
207                  QString const & submenu = QString(),
208                  QString const & tooltip = QString(),
209                  bool optional = false)
210                 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
211                   submenuname_(submenu), tooltip_(tooltip), optional_(optional)
212         {
213                 LATTEST(kind == Submenu || kind == Help || kind == Info);
214         }
215
216         MenuItem(Kind kind,
217                  QString const & label,
218                  FuncRequest const & func,
219                  QString const & tooltip = QString(),
220                  bool optional = false,
221                  FuncRequest::Origin origin = FuncRequest::MENU)
222                 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
223                   tooltip_(tooltip), optional_(optional)
224         {
225                 func_->setOrigin(origin);
226         }
227
228         /// The label of a given menuitem
229         QString label() const
230         {
231                 int const index = label_.lastIndexOf('|');
232                 return index == -1 ? label_ : label_.left(index);
233         }
234
235         /// The keyboard shortcut (usually underlined in the entry)
236         QString shortcut() const
237         {
238                 int const index = label_.lastIndexOf('|');
239                 return index == -1 ? QString() : label_.mid(index + 1);
240         }
241         /// The complete label, with label and shortcut separated by a '|'
242         QString fulllabel() const { return label_; }
243         /// The kind of entry
244         Kind kind() const { return kind_; }
245         /// the action (if relevant)
246         shared_ptr<FuncRequest const> func() const { return func_; }
247         /// the tooltip
248         QString const & tooltip() const { return tooltip_; }
249         /// returns true if the entry should be omitted when disabled
250         bool optional() const { return optional_; }
251         /// returns the status of the lfun associated with this entry
252         FuncStatus const & status() const { return status_; }
253         /// returns the status of the lfun associated with this entry
254         FuncStatus & status() { return status_; }
255         /// returns the status of the lfun associated with this entry
256         void status(FuncStatus const & status) { status_ = status; }
257
258         ///returns the binding associated to this action.
259         QString binding() const
260         {
261                 if (kind_ != Command)
262                         return QString();
263                 // Get the keys bound to this action, but keep only the
264                 // first one later
265                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
266                 if (!bindings.empty())
267                         return toqstr(bindings.begin()->print(KeySequence::ForGui));
268
269                 LYXERR(Debug::KBMAP, "No binding for "
270                         << lyxaction.getActionName(func_->action())
271                         << '(' << func_->argument() << ')');
272                 return QString();
273         }
274
275         /// the description of the  submenu (if relevant)
276         QString const & submenuname() const { return submenuname_; }
277         /// set the description of the  submenu
278         void submenuname(QString const & name) { submenuname_ = name; }
279         ///
280         bool hasSubmenu() const { return !submenu_.isEmpty(); }
281         ///
282         MenuDefinition const & submenu() const { return submenu_.at(0); }
283         MenuDefinition & submenu() { return submenu_[0]; }
284         ///
285         void setSubmenu(MenuDefinition const & menu)
286         {
287                 submenu_.clear();
288                 submenu_.append(menu);
289         }
290
291 private:
292         ///
293         Kind kind_;
294         ///
295         QString label_;
296         ///
297         shared_ptr<FuncRequest> func_;// non-null
298         ///
299         QString submenuname_;
300         ///
301         QString tooltip_;
302         ///
303         bool optional_;
304         ///
305         FuncStatus status_;
306         /// contains 0 or 1 item.
307         QList<MenuDefinition> submenu_;
308 };
309
310 ///
311 class MenuDefinition {
312 public:
313         ///
314         typedef std::vector<MenuItem> ItemList;
315         ///
316         typedef ItemList::const_iterator const_iterator;
317         ///
318         explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
319
320         ///
321         void read(Lexer &);
322         ///
323         QString const & name() const { return name_; }
324         ///
325         bool empty() const { return items_.empty(); }
326         /// Clear the menu content.
327         void clear() { items_.clear(); }
328         ///
329         size_t size() const { return items_.size(); }
330         ///
331         const_iterator begin() const { return items_.begin(); }
332         ///
333         const_iterator end() const { return items_.end(); }
334         ///
335         void cat(MenuDefinition const & other);
336         ///
337         void catSub(docstring const & name);
338
339         // search for func in this menu iteratively, and put menu
340         // names in a stack.
341         bool searchMenu(FuncRequest const & func, docstring_list & names)
342                 const;
343         ///
344         bool hasFunc(FuncRequest const &) const;
345         /// Add the menu item unconditionally
346         void add(MenuItem const & item) { items_.push_back(item); }
347         /// Checks the associated FuncRequest status before adding the
348         /// menu item.
349         void addWithStatusCheck(MenuItem const &);
350         // Check whether the menu shortcuts are unique
351         void checkShortcuts() const;
352         ///
353         void expandLastfiles();
354         void expandDocuments();
355         void expandBookmarks();
356         void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
357         void expandFloatListInsert(Buffer const * buf);
358         void expandFloatInsert(Buffer const * buf);
359         void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
360         void expandTocSubmenu(std::string const & type, Toc const & toc_list);
361         void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
362         void expandToc(Buffer const * buf);
363         void expandPasteRecent(Buffer const * buf);
364         void expandToolbars();
365         void expandBranches(Buffer const * buf);
366         void expandIndices(Buffer const * buf, bool listof = false);
367         void expandIndicesContext(Buffer const * buf, bool listof = false);
368         void expandCiteStyles(BufferView const *);
369         void expandInfoArguments(BufferView const *);
370         void expandGraphicsGroups(BufferView const *);
371         void expandSpellingSuggestions(BufferView const *);
372         void expandLanguageSelector(Buffer const * buf);
373         void expandArguments(BufferView const *, bool switcharg = false);
374         void expandCaptions(Buffer const * buf, bool switchcap = false);
375         void expandEnvironmentSeparators(BufferView const *, bool contextmenu = false);
376         void expandQuotes(BufferView const *);
377         ///
378         ItemList items_;
379         ///
380         QString name_;
381 };
382
383
384 /// Helper for std::find_if
385 class MenuNamesEqual
386 {
387 public:
388         MenuNamesEqual(QString const & name) : name_(name) {}
389         bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
390 private:
391         QString name_;
392 };
393
394
395 ///
396 typedef std::vector<MenuDefinition> MenuList;
397 ///
398 typedef MenuList::const_iterator const_iterator;
399 ///
400 typedef MenuList::iterator iterator;
401
402 /////////////////////////////////////////////////////////////////////
403 // MenuDefinition implementation
404 /////////////////////////////////////////////////////////////////////
405
406 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
407 {
408         switch (i.kind()) {
409
410         case MenuItem::Command: {
411                 FuncStatus status = lyx::getStatus(*i.func());
412                 if (status.unknown() || (!status.enabled() && i.optional()))
413                         break;
414                 items_.push_back(i);
415                 items_.back().status(status);
416                 break;
417         }
418
419         case MenuItem::Submenu: {
420                 bool enabled = false;
421                 if (i.hasSubmenu()) {
422                         for (const_iterator cit = i.submenu().begin();
423                                   cit != i.submenu().end(); ++cit) {
424                                 // Only these kind of items affect the status of the submenu
425                                 if ((cit->kind() == MenuItem::Command
426                                      || cit->kind() == MenuItem::Submenu
427                                      || cit->kind() == MenuItem::Help)
428                                     && cit->status().enabled()) {
429                                         enabled = true;
430                                         break;
431                                 }
432                         }
433                 }
434                 if (enabled || !i.optional()) {
435                         items_.push_back(i);
436                         items_.back().status().setEnabled(enabled);
437                 }
438                 break;
439         }
440
441         case MenuItem::Separator:
442                 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
443                         items_.push_back(i);
444                 break;
445
446         default:
447                 items_.push_back(i);
448         }
449 }
450
451
452 void MenuDefinition::read(Lexer & lex)
453 {
454         enum {
455                 md_item = 1,
456                 md_branches,
457                 md_citestyles,
458                 md_documents,
459                 md_bookmarks,
460                 md_charstyles,
461                 md_custom,
462                 md_endmenu,
463                 md_exportformat,
464                 md_exportformats,
465                 md_importformats,
466                 md_indices,
467                 md_indicescontext,
468                 md_indiceslists,
469                 md_indiceslistscontext,
470                 md_infoarguments,
471                 md_lastfiles,
472                 md_optitem,
473                 md_optsubmenu,
474                 md_separator,
475                 md_submenu,
476                 md_toc,
477                 md_updateformats,
478                 md_viewformats,
479                 md_floatlistinsert,
480                 md_floatinsert,
481                 md_pasterecent,
482                 md_toolbars,
483                 md_graphicsgroups,
484                 md_spellingsuggestions,
485                 md_languageselector,
486                 md_arguments,
487                 md_switcharguments,
488                 md_captions,
489                 md_switchcaptions,
490                 md_env_separators,
491                 md_env_separatorscontext,
492                 md_switchquotes
493         };
494
495         LexerKeyword menutags[] = {
496                 { "arguments", md_arguments },
497                 { "bookmarks", md_bookmarks },
498                 { "branches", md_branches },
499                 { "captions", md_captions },
500                 { "charstyles", md_charstyles },
501                 { "citestyles", md_citestyles },
502                 { "custom", md_custom },
503                 { "documents", md_documents },
504                 { "end", md_endmenu },
505                 { "environmentseparators", md_env_separators },
506                 { "environmentseparatorscontext", md_env_separatorscontext },
507                 { "exportformat", md_exportformat },
508                 { "exportformats", md_exportformats },
509                 { "floatinsert", md_floatinsert },
510                 { "floatlistinsert", md_floatlistinsert },
511                 { "graphicsgroups", md_graphicsgroups },
512                 { "importformats", md_importformats },
513                 { "indices", md_indices },
514                 { "indicescontext", md_indicescontext },
515                 { "indiceslists", md_indiceslists },
516                 { "indiceslistscontext", md_indiceslistscontext },
517                 { "infoarguments", md_infoarguments },
518                 { "item", md_item },
519                 { "languageselector", md_languageselector },
520                 { "lastfiles", md_lastfiles },
521                 { "optitem", md_optitem },
522                 { "optsubmenu", md_optsubmenu },
523                 { "pasterecent", md_pasterecent },
524                 { "separator", md_separator },
525                 { "spellingsuggestions", md_spellingsuggestions },
526                 { "submenu", md_submenu },
527                 { "switcharguments", md_switcharguments },
528                 { "switchcaptions", md_switchcaptions },
529                 { "switchquotes", md_switchquotes },
530                 { "toc", md_toc },
531                 { "toolbars", md_toolbars },
532                 { "updateformats", md_updateformats },
533                 { "viewformats", md_viewformats }
534         };
535
536         lex.pushTable(menutags);
537         lex.setContext("MenuDefinition::read: ");
538
539         int md_type = 0;
540         while (lex.isOK() && md_type != md_endmenu) {
541                 switch (md_type = lex.lex()) {
542                 case md_optitem:
543                 case md_item: {
544                         lex.next(true);
545                         docstring const name = translateIfPossible(lex.getDocString());
546                         lex.next(true);
547                         string const command = lex.getString();
548                         FuncRequest func = lyxaction.lookupFunc(command);
549                         FuncRequest::Origin origin = FuncRequest::MENU;
550                         if (name_.startsWith("context-toc-"))
551                                 origin = FuncRequest::TOC;
552                         bool const optional = (md_type == md_optitem);
553                         add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
554                         break;
555                 }
556
557                 case md_separator:
558                         add(MenuItem(MenuItem::Separator));
559                         break;
560
561                 case md_lastfiles:
562                         add(MenuItem(MenuItem::Lastfiles));
563                         break;
564
565                 case md_charstyles:
566                         add(MenuItem(MenuItem::CharStyles));
567                         break;
568
569                 case md_custom:
570                         add(MenuItem(MenuItem::Custom));
571                         break;
572
573                 case md_documents:
574                         add(MenuItem(MenuItem::Documents));
575                         break;
576
577                 case md_bookmarks:
578                         add(MenuItem(MenuItem::Bookmarks));
579                         break;
580
581                 case md_toc:
582                         add(MenuItem(MenuItem::Toc));
583                         break;
584
585                 case md_viewformats:
586                         add(MenuItem(MenuItem::ViewFormats));
587                         break;
588
589                 case md_updateformats:
590                         add(MenuItem(MenuItem::UpdateFormats));
591                         break;
592
593                 case md_exportformats:
594                         add(MenuItem(MenuItem::ExportFormats));
595                         break;
596
597                 case md_exportformat:
598                         add(MenuItem(MenuItem::ExportFormat));
599                         break;
600
601                 case md_importformats:
602                         add(MenuItem(MenuItem::ImportFormats));
603                         break;
604
605                 case md_floatlistinsert:
606                         add(MenuItem(MenuItem::FloatListInsert));
607                         break;
608
609                 case md_floatinsert:
610                         add(MenuItem(MenuItem::FloatInsert));
611                         break;
612
613                 case md_pasterecent:
614                         add(MenuItem(MenuItem::PasteRecent));
615                         break;
616
617                 case md_toolbars:
618                         add(MenuItem(MenuItem::Toolbars));
619                         break;
620
621                 case md_branches:
622                         add(MenuItem(MenuItem::Branches));
623                         break;
624
625                 case md_citestyles:
626                         add(MenuItem(MenuItem::CiteStyles));
627                         break;
628
629                 case md_infoarguments:
630                         add(MenuItem(MenuItem::InfoArguments));
631                         break;
632                         
633
634                 case md_graphicsgroups:
635                         add(MenuItem(MenuItem::GraphicsGroups));
636                         break;
637
638                 case md_spellingsuggestions:
639                         add(MenuItem(MenuItem::SpellingSuggestions));
640                         break;
641
642                 case md_languageselector:
643                         add(MenuItem(MenuItem::LanguageSelector));
644                         break;
645
646                 case md_indices:
647                         add(MenuItem(MenuItem::Indices));
648                         break;
649
650                 case md_indicescontext:
651                         add(MenuItem(MenuItem::IndicesContext));
652                         break;
653
654                 case md_indiceslists:
655                         add(MenuItem(MenuItem::IndicesLists));
656                         break;
657
658                 case md_indiceslistscontext:
659                         add(MenuItem(MenuItem::IndicesListsContext));
660                         break;
661
662                 case md_arguments:
663                         add(MenuItem(MenuItem::Arguments));
664                         break;
665
666                 case md_switcharguments:
667                         add(MenuItem(MenuItem::SwitchArguments));
668                         break;
669
670                 case md_captions:
671                         add(MenuItem(MenuItem::Captions));
672                         break;
673
674                 case md_switchcaptions:
675                         add(MenuItem(MenuItem::SwitchCaptions));
676                         break;
677
678                 case md_env_separators:
679                         add(MenuItem(MenuItem::EnvironmentSeparators));
680                         break;
681
682                 case md_env_separatorscontext:
683                         add(MenuItem(MenuItem::EnvironmentSeparatorsContext));
684                         break;
685
686                 case md_switchquotes:
687                         add(MenuItem(MenuItem::SwitchQuotes));
688                         break;
689
690                 case md_optsubmenu:
691                 case md_submenu: {
692                         lex.next(true);
693                         docstring const mlabel = translateIfPossible(lex.getDocString());
694                         lex.next(true);
695                         docstring const mname = lex.getDocString();
696                         bool const optional = (md_type == md_optsubmenu);
697                         add(MenuItem(MenuItem::Submenu,
698                                 toqstr(mlabel), toqstr(mname), QString(), optional));
699                         break;
700                 }
701
702                 case md_endmenu:
703                         break;
704
705                 default:
706                         lex.printError("Unknown menu tag");
707                         break;
708                 }
709         }
710         lex.popTable();
711 }
712
713
714 bool MenuDefinition::hasFunc(FuncRequest const & func) const
715 {
716         for (auto const & it : *this)
717                 if (*it.func() == func)
718                         return true;
719         return false;
720 }
721
722
723 void MenuDefinition::catSub(docstring const & name)
724 {
725         add(MenuItem(MenuItem::Submenu,
726                      qt_("More...|M"), toqstr(name), QString(), false));
727 }
728
729 void MenuDefinition::cat(MenuDefinition const & other)
730 {
731         const_iterator et = other.end();
732         for (const_iterator it = other.begin(); it != et; ++it)
733                 add(*it);
734 }
735
736
737 void MenuDefinition::checkShortcuts() const
738 {
739         // This is a quadratic algorithm, but we do not care because
740         // menus are short enough
741         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
742                 QString shortcut = it1->shortcut();
743                 if (shortcut.isEmpty())
744                         continue;
745                 if (!it1->label().contains(shortcut))
746                         LYXERR0("Menu warning: menu entry \""
747                                << it1->label()
748                                << "\" does not contain shortcut `"
749                                << shortcut << "'.");
750                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
751                         if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
752                                 LYXERR0("Menu warning: menu entries "
753                                        << '"' << it1->fulllabel()
754                                        << "\" and \"" << it2->fulllabel()
755                                        << "\" share the same shortcut.");
756                         }
757                 }
758         }
759 }
760
761
762 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
763 {
764         const_iterator m = begin();
765         const_iterator m_end = end();
766         for (; m != m_end; ++m) {
767                 if (m->kind() == MenuItem::Command && *m->func() == func) {
768                         names.push_back(qstring_to_ucs4(m->label()));
769                         return true;
770                 }
771                 if (m->kind() == MenuItem::Submenu) {
772                         names.push_back(qstring_to_ucs4(m->label()));
773                         if (!m->hasSubmenu()) {
774                                 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
775                                         << m->label() << " name=" << m->submenuname());
776                                 names.pop_back();
777                                 continue;
778                         }
779                         if (m->submenu().searchMenu(func, names))
780                                 return true;
781                         names.pop_back();
782                 }
783         }
784         return false;
785 }
786
787
788 QString limitStringLength(docstring const & str)
789 {
790         size_t const max_item_length = 45;
791         docstring ret = str.substr(0, max_item_length + 1);
792         support::truncateWithEllipsis(ret, max_item_length);
793         return toqstr(ret);
794 }
795
796
797 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
798 {
799         if (!bv)
800                 return;
801         set<string> grp;
802         graphics::getGraphicsGroups(bv->buffer(), grp);
803         if (grp.empty())
804                 return;
805
806         set<string>::const_iterator it = grp.begin();
807         set<string>::const_iterator end = grp.end();
808         add(MenuItem(MenuItem::Command, qt_("No Group"),
809                      FuncRequest(LFUN_GRAPHICS_SET_GROUP)));
810         for (; it != end; ++it) {
811                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
812                                 FuncRequest(LFUN_GRAPHICS_SET_GROUP, *it)));
813         }
814 }
815
816
817 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
818 {
819         if (!bv)
820                 return;
821         Cursor const & cur = bv->cursor();
822         if (!cur.inTexted())
823                 return;
824         WordLangTuple wl;
825         docstring_list suggestions;
826         Paragraph const & par = cur.paragraph();
827         pos_type from = cur.pos();
828         pos_type to = from;
829         SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
830         switch (res) {
831         case SpellChecker::UNKNOWN_WORD:
832                 if (lyxrc.spellcheck_continuously) {
833                         LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
834                         docstring const & selection = cur.selectionAsString(false);
835                         if (!cur.selection() || selection == wl.word()) {
836                                 size_t i = 0;
837                                 size_t m = 10; // first submenu index
838                                 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
839                                 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
840                                 for (; i != suggestions.size(); ++i) {
841                                         docstring const & suggestion = suggestions[i];
842                                         LYXERR(Debug::GUI, suggestion);
843                                         MenuItem w(MenuItem::Command, toqstr(suggestion),
844                                                 FuncRequest(LFUN_WORD_REPLACE,
845                                                         replace2string(suggestion, selection,
846                                                                 true,     // case sensitive
847                                                                 true,     // match word
848                                                                 false,    // all words
849                                                                 true,     // forward
850                                                                 false))); // find next
851                                         if (i < m)
852                                                 add(w);
853                                         else
854                                                 item.submenu().add(w);
855                                 }
856                                 if (i > m)
857                                         add(item);
858                                 if (i > 0)
859                                         add(MenuItem(MenuItem::Separator));
860                                 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
861                                 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
862                                                 FuncRequest(LFUN_SPELLING_ADD, arg)));
863                                 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
864                                                 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
865                         }
866                 }
867                 break;
868         case SpellChecker::LEARNED_WORD: {
869                         LYXERR(Debug::GUI, "Learned Word.");
870                         docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
871                         add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
872                                         FuncRequest(LFUN_SPELLING_REMOVE, arg)));
873                 }
874                 break;
875         case SpellChecker::NO_DICTIONARY:
876                 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
877                 // FALLTHROUGH
878         case SpellChecker::WORD_OK:
879         case SpellChecker::COMPOUND_WORD:
880         case SpellChecker::ROOT_FOUND:
881         case SpellChecker::IGNORED_WORD:
882                 break;
883         }
884 }
885
886 struct sortLanguageByName {
887         bool operator()(const Language * a, const Language * b) const {
888                 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
889         }
890 };
891
892 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
893 {
894         if (!buf)
895                 return;
896
897         std::set<Language const *> languages_buffer =
898                 buf->masterBuffer()->getLanguages();
899
900         if (languages_buffer.size() < 2) {
901                 add(MenuItem(MenuItem::Command, qt_("Switch Language...|L"),
902                              FuncRequest(LFUN_DIALOG_SHOW, "character")));
903                 return;
904         }
905
906         std::set<Language const *, sortLanguageByName> langs;
907
908         std::set<Language const *>::const_iterator const beg =
909                 languages_buffer.begin();
910         for (std::set<Language const *>::const_iterator cit = beg;
911              cit != languages_buffer.end(); ++cit) {
912                 langs.insert(*cit);
913         }
914
915         MenuItem item(MenuItem::Submenu, qt_("Language|L"));
916         item.setSubmenu(MenuDefinition(qt_("Language")));
917         QString morelangs = qt_("More Languages ...|M");
918         QStringList accelerators;
919         if (morelangs.contains('|'))
920                 accelerators.append(morelangs.section('|', -1));
921         std::set<Language const *, sortLanguageByName>::const_iterator const begin = langs.begin();
922         for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
923                          cit != langs.end(); ++cit) {
924                 QString label = qt_((*cit)->display());
925                 // try to add an accelerator
926                 bool success = false;
927                 // try capitals first
928                 for (int i = 0; i < label.size(); ++i) {
929                         QChar const ch = label[i];
930                         if (!ch.isUpper())
931                                 continue;
932                         if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
933                                 label = label + toqstr("|") + ch;
934                                 accelerators.append(ch);
935                                 success = true;
936                                 break;
937                         }
938                 }
939                 // if all capitals are taken, try the rest
940                 if (!success) {
941                         for (int i = 0; i < label.size(); ++i) {
942                                 if (label[i].isSpace())
943                                         continue;
944                                 QString const ch = QString(label[i]);
945                                 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
946                                         label = label + toqstr("|") + ch;
947                                         accelerators.append(ch);
948                                         break;
949                                 }
950                         }
951                 }
952                 MenuItem w(MenuItem::Command, label,
953                         FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
954                 item.submenu().addWithStatusCheck(w);
955         }
956         item.submenu().add(MenuItem(MenuItem::Separator));
957         item.submenu().add(MenuItem(MenuItem::Command, morelangs,
958                         FuncRequest(LFUN_DIALOG_SHOW, "character")));
959         add(item);
960 }
961
962
963 void MenuDefinition::expandLastfiles()
964 {
965         LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
966         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
967
968         unsigned int ii = 1;
969
970         for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
971                 string const file = lfit->absFileName();
972                 QString const short_path = toqstr(makeDisplayPath(file, 30));
973                 QString const long_path = toqstr(makeDisplayPath(file));
974                 QString label;
975                 if (ii < 10)
976                         label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
977                 else
978                         label = QString("%1. %2").arg(ii).arg(short_path);
979                 add(MenuItem(MenuItem::Command, label,
980                         FuncRequest(LFUN_FILE_OPEN, file), long_path));
981         }
982 }
983
984
985 void MenuDefinition::expandDocuments()
986 {
987         MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
988         item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
989
990         Buffer * first = theBufferList().first();
991         if (!first) {
992                 add(MenuItem(MenuItem::Info, qt_("(No Documents Open)")));
993                 return;
994         }
995
996         int i = 0;
997         while (true) {
998                 if (!guiApp->currentView())
999                         break;
1000                 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
1001                 if (!wa)
1002                         break;
1003                 Buffer const & b = wa->bufferView().buffer();
1004                 QString label = toqstr(b.fileName().displayName(20));
1005                 if (!b.isClean())
1006                         label += "*";
1007                 if (b.notifiesExternalModification())
1008                         label += QChar(0x26a0);
1009                 if (i < 10)
1010                         label = QString::number(i) + ". " + label + '|' + QString::number(i);
1011                 add(MenuItem(MenuItem::Command, label,
1012                         FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1013                 ++i;
1014         }
1015
1016
1017         i = 0;
1018         Buffer * b = first;
1019         // We cannot use a for loop as the buffer list cycles.
1020         do {
1021                 if (!(guiApp->currentView()
1022                     && guiApp->currentView()->workArea(*b))) {
1023                         QString label = toqstr(b->fileName().displayName(20));
1024                         if (!b->isClean())
1025                                 label += "*";
1026                         if (b->notifiesExternalModification())
1027                                 label += QChar(0x26a0);
1028                         if (i < 10)
1029                                 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1030                         item.submenu().add(MenuItem(MenuItem::Command, label,
1031                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1032                         ++i;
1033                 }
1034                 b = theBufferList().next(b);
1035         } while (b != first);
1036
1037         if (!item.submenu().empty())
1038                 add(item);
1039 }
1040
1041
1042 void MenuDefinition::expandBookmarks()
1043 {
1044         lyx::BookmarksSection const & bm = theSession().bookmarks();
1045
1046         bool empty = true;
1047         for (size_t i = 1; i <= bm.size(); ++i) {
1048                 if (bm.isValid(i)) {
1049                         string const file = bm.bookmark(i).filename.absFileName();
1050                         QString const label = QString("%1. %2|%3").arg(i)
1051                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1052                         add(MenuItem(MenuItem::Command, label,
1053                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1054                         empty = false;
1055                 }
1056         }
1057         if (empty)
1058                 add(MenuItem(MenuItem::Info, qt_("(No Bookmarks Saved Yet)")));
1059 }
1060
1061
1062 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1063 {
1064         if (!buf && kind != MenuItem::ImportFormats)
1065                 return;
1066
1067         FormatList formats;
1068         FuncCode action = LFUN_NOACTION;
1069
1070         switch (kind) {
1071         case MenuItem::ImportFormats:
1072                 formats = theConverters().importableFormats();
1073                 action = LFUN_BUFFER_IMPORT;
1074                 break;
1075         case MenuItem::ViewFormats:
1076                 formats = buf->params().exportableFormats(true);
1077                 action = LFUN_BUFFER_VIEW;
1078                 break;
1079         case MenuItem::UpdateFormats:
1080                 formats = buf->params().exportableFormats(true);
1081                 action = LFUN_BUFFER_UPDATE;
1082                 break;
1083         case MenuItem::ExportFormats:
1084                 formats = buf->params().exportableFormats(false);
1085                 action = LFUN_BUFFER_EXPORT;
1086                 break;
1087         default:
1088                 LATTEST(false);
1089                 return;
1090         }
1091
1092         bool const view_update = (kind == MenuItem::ViewFormats
1093                         || kind == MenuItem::UpdateFormats);
1094
1095         QString smenue;
1096         if (view_update)
1097                 smenue = (kind == MenuItem::ViewFormats
1098                         ? qt_("View (Other Formats)|F")
1099                         : qt_("Update (Other Formats)|p"));
1100         MenuItem item(MenuItem::Submenu, smenue);
1101         item.setSubmenu(MenuDefinition(smenue));
1102
1103         for (Format const * f : formats) {
1104                 if (f->dummy())
1105                         continue;
1106
1107                 docstring lab = f->prettyname();
1108                 docstring const scut = from_utf8(f->shortcut());
1109                 docstring const tmplab = lab;
1110
1111                 if (!scut.empty())
1112                         lab += char_type('|') + scut;
1113                 docstring const lab_i18n = translateIfPossible(lab);
1114                 docstring const shortcut = split(lab_i18n, lab, '|');
1115
1116                 bool const untranslated = (lab == lab_i18n);
1117                 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1118
1119                 switch (kind) {
1120                 case MenuItem::ImportFormats:
1121                         if (f->noMenu())
1122                                 continue;
1123                         label += from_ascii("...");
1124                         break;
1125                 case MenuItem::ViewFormats:
1126                 case MenuItem::UpdateFormats:
1127                         if (f->name() == buf->params().getDefaultOutputFormat()) {
1128                                 docstring lbl = (kind == MenuItem::ViewFormats
1129                                         ? bformat(_("View [%1$s]|V"), label)
1130                                         : bformat(_("Update [%1$s]|U"), label));
1131                                 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1132                                 continue;
1133                         }
1134                         break;
1135                 case MenuItem::ExportFormats:
1136                         if (!f->inExportMenu())
1137                                 continue;
1138                         break;
1139                 default:
1140                         // we already asserted earlier in this case
1141                         // LATTEST(false);
1142                         continue;
1143                 }
1144                 if (!shortcut.empty())
1145                         label += '|' + shortcut;
1146
1147                 if (view_update) {
1148                         // note that at this point, we know that buf is not null
1149                         LATTEST(buf);
1150                         item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1151                                 toqstr(label), FuncRequest(action, f->name())));
1152                 } else {
1153                         if (buf)
1154                                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1155                                         FuncRequest(action, f->name())));
1156                         else
1157                                 add(MenuItem(MenuItem::Command, toqstr(label),
1158                                         FuncRequest(action, f->name())));
1159                 }
1160         }
1161         if (view_update)
1162                 add(item);
1163 }
1164
1165
1166 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1167 {
1168         if (!buf)
1169                 return;
1170
1171         FloatList const & floats = buf->params().documentClass().floats();
1172         FloatList::const_iterator cit = floats.begin();
1173         FloatList::const_iterator end = floats.end();
1174         set<string> seen;
1175         for (; cit != end; ++cit) {
1176                 if (!cit->second.usesFloatPkg()) {
1177                         // Different floats could declare the same ListCommand. We only
1178                         // want it on the list once, though.
1179                         string const & list_cmd = cit->second.listCommand();
1180                         if (list_cmd.empty())
1181                                 // we do not know how to generate such a list
1182                                 continue;
1183                         // This form of insert returns an iterator pointing to the newly
1184                         // inserted element OR the existing element with that value, and
1185                         // a bool indicating whether we inserted a new element. So we can
1186                         // see if one is there and insert it if not all at once.
1187                         pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1188                         if (!ret.second)
1189                                 continue;
1190                 }
1191                 string const & list_name = cit->second.listName();
1192                 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1193                         FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1194         }
1195 }
1196
1197
1198 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1199 {
1200         if (!buf)
1201                 return;
1202
1203         FloatList const & floats = buf->params().documentClass().floats();
1204         FloatList::const_iterator cit = floats.begin();
1205         FloatList::const_iterator end = floats.end();
1206         for (; cit != end; ++cit) {
1207                 // normal float
1208                 if (cit->second.name().empty())
1209                         continue;
1210                 QString const label = qt_(cit->second.name());
1211                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1212                                     FuncRequest(LFUN_FLOAT_INSERT,
1213                                                 cit->second.floattype())));
1214         }
1215 }
1216
1217
1218 void MenuDefinition::expandFlexInsert(
1219                 Buffer const * buf, InsetLayout::InsetLyXType type)
1220 {
1221         if (!buf)
1222                 return;
1223
1224         TextClass::InsetLayouts const & insetLayouts =
1225                 buf->params().documentClass().insetLayouts();
1226         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1227         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1228         for (; cit != end; ++cit) {
1229                 if (cit->second.lyxtype() == type) {
1230                         if (!cit->second.obsoleted_by().empty())
1231                                 continue;
1232                         docstring name = cit->first;
1233                         // we remove the "Flex:" prefix, if it is present
1234                         if (prefixIs(name, from_ascii("Flex:")))
1235                                 name = name.substr(5);
1236                         docstring const label = (cit->second.menustring().empty()) ?
1237                                                 name
1238                                               : cit->second.menustring();
1239                         addWithStatusCheck(MenuItem(MenuItem::Command,
1240                                 toqstr(translateIfPossible(label)),
1241                                 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(name))));
1242                 }
1243         }
1244         // FIXME This is a little clunky.
1245         if (items_.empty() && type == InsetLayout::CUSTOM && !buf->hasReadonlyFlag())
1246                 add(MenuItem(MenuItem::Help, qt_("(No Custom Insets Defined)")));
1247 }
1248
1249
1250 // Threshold before we stop displaying sub-items alongside items
1251 // (for display purposes). Ideally this should fit on a screen.
1252 size_t const max_number_of_items = 30;
1253 // Size limit for the menu. This is for performance purposes,
1254 // because qt already displays a scrollable menu when necessary.
1255 // Ideally this should be the menu size from which scrollable
1256 // menus become unpractical.
1257 size_t const menu_size_limit = 80;
1258
1259 void MenuDefinition::expandToc2(Toc const & toc_list,
1260                                 size_t from, size_t to, int depth,
1261                                 string toc_type)
1262 {
1263         int shortcut_count = 0;
1264
1265         // check whether depth is smaller than the smallest depth in toc.
1266         int min_depth = 1000;
1267         for (size_t i = from; i < to; ++i)
1268                 min_depth = min(min_depth, toc_list[i].depth());
1269         if (min_depth > depth)
1270                 depth = min_depth;
1271
1272         if (to - from <= max_number_of_items) {
1273                 for (size_t i = from; i < to; ++i) {
1274                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1275                         label += limitStringLength(toc_list[i].asString());
1276                         if (toc_list[i].depth() == depth) {
1277                                 label += '|';
1278                             if (shortcut_count < 9) {
1279                                         if (label.contains(QString::number(shortcut_count + 1)))
1280                                                 label += QString::number(++shortcut_count);
1281                                 }
1282                         }
1283                         add(MenuItem(MenuItem::Command, label,
1284                                             FuncRequest(toc_list[i].action())));
1285                         // separator after the menu heading
1286                         if (toc_list[i].depth() < depth)
1287                                 add(MenuItem(MenuItem::Separator));
1288                 }
1289         } else {
1290                 size_t pos = from;
1291                 size_t size = 1;
1292                 while (pos < to) {
1293                         size_t new_pos = pos + 1;
1294                         while (new_pos < to && toc_list[new_pos].depth() > depth)
1295                                 ++new_pos;
1296
1297                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1298                         label += limitStringLength(toc_list[pos].asString());
1299                         if (toc_list[pos].depth() == depth) {
1300                                 label += '|';
1301                             if (shortcut_count < 9) {
1302                                         if (label.contains(QString::number(shortcut_count + 1)))
1303                                                 label += QString::number(++shortcut_count);
1304                                 }
1305                         }
1306                         if (size >= menu_size_limit) {
1307                                 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1308                                 add(MenuItem(MenuItem::Command, "...", f));
1309                                 break;
1310                         }
1311                         if (new_pos == pos + 1) {
1312                                 add(MenuItem(MenuItem::Command,
1313                                                     label, FuncRequest(toc_list[pos].action())));
1314                         } else {
1315                                 MenuDefinition sub;
1316                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1317                                 MenuItem item(MenuItem::Submenu, label);
1318                                 item.setSubmenu(sub);
1319                                 add(item);
1320                         }
1321                         ++size;
1322                         pos = new_pos;
1323                 }
1324         }
1325 }
1326
1327
1328 void MenuDefinition::expandToc(Buffer const * buf)
1329 {
1330         // To make things very cleanly, we would have to pass buf to
1331         // all MenuItem constructors and to expandToc2. However, we
1332         // know that all the entries in a TOC will be have status_ ==
1333         // OK, so we avoid this unnecessary overhead (JMarc)
1334         if (!buf) {
1335                 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1336                 return;
1337         }
1338         // Add an entry for the master doc if this is a child doc
1339         Buffer const * const master = buf->masterBuffer();
1340         if (buf != master) {
1341                 ParIterator const pit = par_iterator_begin(master->inset());
1342                 string const arg = convert<string>(pit->id());
1343                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1344                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1345         }
1346
1347         MenuDefinition other_lists;
1348         // In the navigation menu, only add tocs from this document
1349         TocBackend const & backend = buf->tocBackend();
1350         TocList const & toc_list = backend.tocs();
1351         for (pair<const string, shared_ptr<Toc>> const & toc : toc_list) {
1352                 // Handle table of contents later
1353                 if (toc.first == "tableofcontents" || toc.second->empty())
1354                         continue;
1355                 MenuDefinition submenu;
1356                 submenu.expandTocSubmenu(toc.first, *toc.second);
1357                 docstring const toc_name = backend.outlinerName(toc.first);
1358                 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1359                 item.setSubmenu(submenu);
1360                 // deserves to be in the main menu?
1361                 if (!TocBackend::isOther(toc.first))
1362                         add(item);
1363                 else
1364                         other_lists.add(item);
1365         }
1366         if (!other_lists.empty()) {
1367                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1368                 item.setSubmenu(other_lists);
1369                 add(item);
1370         }
1371         // Handle normal TOC
1372         add(MenuItem(MenuItem::Separator));
1373         TocList::const_iterator cit = toc_list.find("tableofcontents");
1374         if (cit == toc_list.end())
1375                 LYXERR(Debug::GUI, "No table of contents.");
1376         else {
1377                 if (!cit->second->empty())
1378                         expandToc2(*cit->second, 0, cit->second->size(), 0,
1379                                    "tableofcontents");
1380                 else
1381                         add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1382         }
1383 }
1384
1385
1386 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1387 {
1388         // "Open outliner..." entry
1389         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1390         add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1391         add(MenuItem(MenuItem::Separator));
1392         // add entries
1393         expandToc2(toc, 0, toc.size(), 0, type);
1394 }
1395
1396
1397 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1398 {
1399         docstring_list const sel = cap::availableSelections(buf);
1400
1401         docstring_list::const_iterator cit = sel.begin();
1402         docstring_list::const_iterator end = sel.end();
1403
1404         for (unsigned int index = 0; cit != end; ++cit, ++index) {
1405                 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1406                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1407         }
1408 }
1409
1410
1411 void MenuDefinition::expandToolbars()
1412 {
1413         MenuDefinition other_lists;
1414         // extracts the toolbars from the backend
1415         Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1416         Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1417         for (; cit != end; ++cit) {
1418                 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1419                                 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1420                 if (guiApp->toolbars().isMainToolbar(cit->name))
1421                         add(item);
1422                 else
1423                         other_lists.add(item);
1424         }
1425
1426         if (!other_lists.empty()) {
1427                 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1428                 item.setSubmenu(other_lists);
1429                 add(item);
1430         }
1431 }
1432
1433
1434 void MenuDefinition::expandBranches(Buffer const * buf)
1435 {
1436         if (!buf || buf->hasReadonlyFlag())
1437                 return;
1438
1439         BranchList const & child_list = buf->params().branchlist();
1440         set<docstring> brset;
1441         int ii = 1;
1442         for (auto const & b : child_list) {
1443                 docstring const & bname = b.branch();
1444                 // NUM. Branch Name + "|", which triggers an empty shortcut in
1445                 // case that character should be in the branch name.
1446                 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1447                 // Add NUM as a keyboard shortcut if it's a single digit
1448                 if (ii < 10)
1449                         label += convert<docstring>(ii);
1450
1451                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1452                         FuncRequest(LFUN_BRANCH_INSERT, bname)));
1453
1454                 brset.insert(bname);
1455                 ++ii;
1456         }
1457
1458         set<Buffer const *> bufset;
1459         Buffer const * nextbuf = buf->parent();
1460         MenuDefinition master_branches;
1461         ii = 1;
1462         while (nextbuf) {
1463                 // recursive includes are a bad idea, but let's not crash
1464                 // if we find one.
1465                 if (bufset.count(nextbuf))
1466                         break;
1467
1468                 for (auto const & b : nextbuf->params().branchlist()) {
1469                         docstring const & bname = b.branch();
1470                         // do not add it if we've already seen it
1471                         if (brset.count(bname))
1472                                 continue;
1473
1474                         docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1475                         if (ii < 10)
1476                                 label += convert<docstring>(ii);
1477
1478                         master_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1479                                 toqstr(label), FuncRequest(LFUN_BRANCH_INSERT, bname)));
1480
1481                         bufset.insert(nextbuf);
1482                         brset.insert(bname);
1483                         ++ii;
1484                 }
1485
1486                 nextbuf = nextbuf->parent();
1487         }
1488
1489         if (!master_branches.empty()) {
1490                 MenuItem item(MenuItem::Submenu, qt_("Master Documents"));
1491                 item.setSubmenu(master_branches);
1492                 add(item);
1493         }
1494 }
1495
1496
1497 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1498 {
1499         if (!buf)
1500                 return;
1501
1502         BufferParams const & params = buf->masterBuffer()->params();
1503         if (!params.use_indices) {
1504                 if (listof)
1505                         addWithStatusCheck(MenuItem(MenuItem::Command,
1506                                            qt_("Index List|I"),
1507                                            FuncRequest(LFUN_INDEX_PRINT,
1508                                                   from_ascii("idx"))));
1509                 else
1510                         addWithStatusCheck(MenuItem(MenuItem::Command,
1511                                            qt_("Index Entry|d"),
1512                                            FuncRequest(LFUN_INDEX_INSERT,
1513                                                   from_ascii("idx"))));
1514                 return;
1515         }
1516
1517         if (params.indiceslist().empty())
1518                 return;
1519
1520         IndicesList::const_iterator cit = params.indiceslist().begin();
1521         IndicesList::const_iterator end = params.indiceslist().end();
1522
1523         for (int ii = 1; cit != end; ++cit, ++ii) {
1524                 if (listof) {
1525                         docstring const label =
1526                                 bformat(_("Index: %1$s"), cit->index());
1527                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1528                                            FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1529                 } else {
1530                         docstring const label =
1531                                 bformat(_("Index Entry (%1$s)"), cit->index());
1532                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1533                                            FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1534                 }
1535         }
1536 }
1537
1538
1539 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1540 {
1541         if (!buf)
1542                 return;
1543
1544         BufferParams const & params = buf->masterBuffer()->params();
1545         if (!params.use_indices || params.indiceslist().empty())
1546                 return;
1547
1548         IndicesList::const_iterator cit = params.indiceslist().begin();
1549         IndicesList::const_iterator end = params.indiceslist().end();
1550
1551         for (int ii = 1; cit != end; ++cit, ++ii) {
1552                 if (listof) {
1553                         InsetCommandParams p(INDEX_PRINT_CODE);
1554                         p["type"] = cit->shortcut();
1555                         string const data = InsetCommand::params2string(p);
1556                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1557                                            FuncRequest(LFUN_INSET_MODIFY, data)));
1558                 } else {
1559                         docstring const label =
1560                                         bformat(_("Index Entry (%1$s)"), cit->index());
1561                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1562                                            FuncRequest(LFUN_INSET_MODIFY,
1563                                                   from_ascii("changetype ") + cit->shortcut())));
1564                 }
1565         }
1566 }
1567
1568
1569 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1570 {
1571         if (!bv)
1572                 return;
1573
1574         Inset const * inset = bv->cursor().nextInset();
1575         if (!inset || inset->lyxCode() != CITE_CODE) {
1576                 add(MenuItem(MenuItem::Command,
1577                                     qt_("No Citation in Scope!"),
1578                                     FuncRequest(LFUN_NOACTION)));
1579                 return;
1580         }
1581         InsetCitation const * citinset =
1582                                 static_cast<InsetCitation const *>(inset);
1583
1584         Buffer const * buf = &bv->buffer();
1585         BufferParams const & bp = buf->masterParams();
1586         string const cmd = citinset->params().getCmdName();
1587
1588         docstring const & key = citinset->getParam("key");
1589         if (key.empty()) {
1590                 add(MenuItem(MenuItem::Command,
1591                                     qt_("No citations selected!"),
1592                                     FuncRequest(LFUN_NOACTION)));
1593                 return;
1594         }
1595
1596         bool const force = isUpperCase(cmd[0]);
1597         bool const star = suffixIs(cmd, '*');
1598
1599         vector<docstring> const keys = getVectorFromString(key);
1600
1601         vector<CitationStyle> const citeStyleList = bp.citeStyles();
1602
1603         CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1604         bool const qualified = cs.hasQualifiedList
1605                 && (keys.size() > 1
1606                     || !citinset->getParam("pretextlist").empty()
1607                     || !citinset->getParam("posttextlist").empty());
1608         vector<pair<docstring, docstring>> pres =
1609                 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1610         vector<pair<docstring, docstring>> posts =
1611                 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1612
1613         CiteItem ci;
1614         ci.textBefore = citinset->getParam("before");
1615         ci.textAfter = citinset->getParam("after");
1616         ci.forceUpperCase = force;
1617         ci.Starred = star;
1618         ci.context = CiteItem::Dialog;
1619         ci.max_size = 40;
1620         ci.isQualified = qualified;
1621         ci.pretexts = pres;
1622         ci.posttexts = posts;
1623         BiblioInfo::CiteStringMap citeStrings =
1624                 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1625
1626         BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1627         BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1628
1629         for (int ii = 1; cit != end; ++cit, ++ii) {
1630                 docstring label = cit->second;
1631                 CitationStyle ccs = citeStyleList[ii - 1];
1632                 ccs.forceUpperCase &= force;
1633                 ccs.hasStarredVersion &= star;
1634                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1635                                     FuncRequest(LFUN_INSET_MODIFY,
1636                                                 "changetype " + from_utf8(citationStyleToString(ccs)))));
1637         }
1638
1639         if (cs.hasStarredVersion) {
1640                 docstring starred = _("All authors|h");
1641                 // Check if we have a custom string/tooltip for the starred version
1642                 if (!cs.stardesc.empty()) {
1643                         string val =
1644                                 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1645                         if (!val.empty())
1646                                 starred = translateIfPossible(from_utf8(val));
1647                         // Transform qt-style accelerators to menu-style
1648                         int const amps = count_char(starred, '&');
1649                         if (amps > 0) {
1650                                 if (amps > 1)
1651                                         starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1652                                 size_t nn = starred.find('&');
1653                                 char_type accel = char_type();
1654                                 if (nn != docstring::npos && nn < starred.size() - 1)
1655                                         accel = starred[nn + 1];
1656                                 starred = subst(starred, from_ascii("&"), from_ascii(""));
1657                                 if (amps > 1)
1658                                         starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1659                                 if (accel != char_type())
1660                                         starred = starred + '|' + accel;
1661                         }
1662                 }
1663                 add(MenuItem(MenuItem::Separator));
1664                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1665                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1666         }
1667
1668         if (cs.forceUpperCase) {
1669                 if (!cs.hasStarredVersion)
1670                         add(MenuItem(MenuItem::Separator));
1671                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1672                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1673         }
1674 }
1675
1676
1677 void MenuDefinition::expandInfoArguments(BufferView const * bv)
1678 {
1679         if (!bv)
1680                 return;
1681
1682         Inset const * inset = bv->cursor().nextInset();
1683         if (!inset || inset->lyxCode() != INFO_CODE) {
1684                 add(MenuItem(MenuItem::Command,
1685                                     qt_("No Text Field in Scope!"),
1686                                     FuncRequest(LFUN_NOACTION)));
1687                 return;
1688         }
1689         InsetInfo const * iinset = static_cast<InsetInfo const *>(inset);
1690
1691         string const type = iinset->params().infoType();
1692         vector<pair<string,docstring>> const args =
1693                         iinset->params().getArguments(&bv->buffer(), type);
1694
1695         // Don't generate a menu for big lists (such as lfuns and rcs)
1696         if (args.size() > 15)
1697                 return;
1698
1699         for (auto const & p : args) {
1700                 if (p.first == "invalid")
1701                         // non-selectable
1702                         continue;
1703                 if (p.first == "custom") {
1704                         add(MenuItem(MenuItem::Command, qt_("Custom..."),
1705                                      FuncRequest(LFUN_INSET_SETTINGS, "info")));
1706                         continue;
1707                 }
1708                 docstring label = p.second;
1709                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1710                                     FuncRequest(LFUN_INSET_MODIFY, type + " " + p.first)));
1711         }
1712 }
1713
1714
1715
1716 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1717 {
1718         if (!bv)
1719                 return;
1720
1721         if (!bv->cursor().inTexted())
1722                 return;
1723
1724         Inset const * inset = &bv->cursor().inset();
1725         Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1726         if (inset && args.empty())
1727                 args = inset->getLayout().args();
1728         if (args.empty() || (switcharg && args.size() == 1))
1729                 return;
1730         Layout::LaTeXArgMap::const_iterator lait = args.begin();
1731         Layout::LaTeXArgMap::const_iterator const laend = args.end();
1732         for (; lait != laend; ++lait) {
1733                 Layout::latexarg arg = (*lait).second;
1734                 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1735                 QString item = toqstr(translateIfPossible(str));
1736                 if (switcharg)
1737                         add(MenuItem(MenuItem::Command, item,
1738                                      FuncRequest(LFUN_INSET_MODIFY,
1739                                                  from_ascii("changetype ")
1740                                                  + from_ascii((*lait).first))));
1741                 else
1742                         add(MenuItem(MenuItem::Command, item,
1743                                      FuncRequest(LFUN_ARGUMENT_INSERT,
1744                                                  from_ascii((*lait).first))));
1745         }
1746 }
1747
1748
1749 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1750 {
1751         if (!buf)
1752                 return;
1753
1754         DocumentClass const & dc = buf->params().documentClass();
1755         vector< pair<docstring, FuncRequest> > caps;
1756         for (pair<const docstring, InsetLayout> const & il : dc.insetLayouts()) {
1757                 docstring instype;
1758                 docstring const type = split(il.first, instype, ':');
1759                 if (instype == from_ascii("Caption")) {
1760                         // skip forbidden caption types
1761                         FuncRequest const cmd = switchcap
1762                                 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1763                                 : FuncRequest(LFUN_CAPTION_INSERT, type);
1764                         if (getStatus(cmd).enabled())
1765                                 caps.push_back(make_pair(type, cmd));
1766                 }
1767         }
1768
1769         if (caps.empty() || (switchcap && caps.size() == 1))
1770                 return;
1771         if (caps.size() == 1) {
1772                 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1773                 return;
1774         }
1775
1776         MenuDefinition captions;
1777         for (pair<docstring, FuncRequest> const & cap : caps) {
1778                 docstring const type = cap.first;
1779                 docstring const trtype = translateIfPossible(type);
1780                 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1781                 if (switchcap)
1782                         add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1783                 else
1784                         captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1785         }
1786         if (!captions.empty()) {
1787                 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1788                 item.setSubmenu(captions);
1789                 add(item);
1790         }
1791 }
1792
1793
1794 void MenuDefinition::expandQuotes(BufferView const * bv)
1795 {
1796         if (!bv)
1797                 return;
1798
1799         if (!bv->cursor().inTexted())
1800                 return;
1801
1802         Inset const * inset = bv->cursor().nextInset();
1803         if (!inset || inset->lyxCode() != QUOTE_CODE) {
1804                 add(MenuItem(MenuItem::Command,
1805                                     qt_("No Quote in Scope!"),
1806                                     FuncRequest(LFUN_NOACTION)));
1807                 return;
1808         }
1809         InsetQuotes const * qinset =
1810                 static_cast<InsetQuotes const *>(inset);
1811
1812         map<string, docstring> styles = quoteparams.getTypes();
1813         string const qtype = qinset->getType();
1814
1815         map<string, docstring>::const_iterator qq = styles.begin();
1816         map<string, docstring>::const_iterator end = styles.end();
1817
1818         MenuDefinition aqs;
1819
1820         BufferParams const & bp = bv->buffer().masterBuffer()->params();
1821
1822         // The global setting
1823         InsetQuotesParams::QuoteStyle globalqs = bp.quotes_style;
1824         char const globalqsc = quoteparams.getStyleChar(globalqs);
1825
1826         // The current language's default
1827         InsetQuotesParams::QuoteStyle langdefqs =
1828                 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1829         char const langqs = quoteparams.getStyleChar(langdefqs);
1830
1831         bool main_global_qs = false;
1832         bool main_langdef_qs = false;
1833         bool main_dynamic_qs = false;
1834         docstring const subcmd = from_ascii("changetype ");
1835         docstring const wildcards = from_ascii("..");
1836         // Add the items
1837         // First the top level menu (all glyphs of the current style) ...
1838         // Begin with dynamic (if they are current style),
1839         if (qtype[0] == 'x') {
1840                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1841                 docstring desc = bformat(_("%1$s (dynamic)"),
1842                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1843                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1844                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1845                 desc = bformat(_("%1$s (dynamic)"),
1846                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1847                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1848                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1849                 desc = bformat(_("%1$s (dynamic)"),
1850                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1851                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1852                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1853                 desc = bformat(_("%1$s (dynamic)"),
1854                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1855                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1856                 main_dynamic_qs = true;
1857         }
1858         // now traverse through the static styles ...
1859         for (; qq != end; ++qq) {
1860                 docstring const style = from_ascii(qq->first);
1861                 bool langdef = (style[0] == langqs);
1862                 bool globaldef = (style[0] == globalqsc);
1863
1864                 if (prefixIs(style, qtype[0])) {
1865                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1866                         docstring const desc = quoteparams.getShortGuiLabel(style);
1867                         add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1868                         main_global_qs = globaldef;
1869                         main_langdef_qs = langdef;
1870                 }
1871                 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1872                         docstring const desc =
1873                                 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1874                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1875                         aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1876                 }
1877         }
1878
1879         add(MenuItem(MenuItem::Separator));
1880
1881         bool display_static = false;
1882         // ... then potentially items to reset to the defaults and to dynamic style ...
1883         if (!main_dynamic_qs && globalqsc != 'x') {
1884                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1885                 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1886                                                 quoteparams.getGuiLabel(globalqs));
1887                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1888                 display_static = true;
1889         }
1890         if (!main_global_qs && langdefqs != globalqs) {
1891                 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1892                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1893                 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1894                                                 quoteparams.getGuiLabel(globalqs), variant);
1895                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1896         }
1897         if (!main_langdef_qs) {
1898                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1899                 docstring const desc = (main_dynamic_qs || display_static)
1900                                         ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1901                                                   quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1902                                         : bformat(_("Reset to language default (%1$s)|l"),
1903                                                   quoteparams.getGuiLabel(langdefqs));
1904                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1905         }
1906
1907         add(MenuItem(MenuItem::Separator));
1908
1909         // ... and a subitem with the rest
1910         MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1911         item.setSubmenu(aqs);
1912         add(item);
1913 }
1914
1915
1916 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1917                                                  bool contextmenu)
1918 {
1919         if (!bv)
1920                 return;
1921         Text const * text = bv->cursor().text();
1922         // no paragraphs and no separators exist in math
1923         if (!text)
1924                 return;
1925
1926         pit_type pit = bv->cursor().selBegin().pit();
1927         Paragraph const & par = text->getPar(pit);
1928         docstring const curlayout = par.layout().name();
1929         docstring outerlayout;
1930         docstring prevlayout;
1931         depth_type current_depth = par.params().depth();
1932         // check if we have an environment in our scope
1933         while (true) {
1934                 if (pit == 0)
1935                         break;
1936                 --pit;
1937                 Paragraph cpar = text->getPar(pit);
1938                 if (cpar.layout().isEnvironment() && prevlayout.empty()
1939                     && cpar.params().depth() <= current_depth)
1940                                 prevlayout = cpar.layout().name();
1941                 if (cpar.params().depth() < current_depth
1942                     && cpar.layout().isEnvironment()) {
1943                                 outerlayout = cpar.layout().name();
1944                                 current_depth = cpar.params().depth();
1945                 }
1946                 if (cpar.params().depth() == 0)
1947                         break;
1948         }
1949         if (par.layout().isEnvironment()) {
1950                 docstring label = contextmenu ?
1951                                         bformat(_("Insert Separated %1$s Above"),
1952                                                 translateIfPossible(curlayout)) :
1953                                         bformat(_("Separated %1$s Above"),
1954                                                 translateIfPossible(curlayout));
1955                 add(MenuItem(MenuItem::Command, toqstr(label),
1956                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1957                                          from_ascii("before"))));
1958                 label = contextmenu ?
1959                                 bformat(_("Insert Separated %1$s Below"),
1960                                         translateIfPossible(curlayout)):
1961                                 bformat(_("Separated %1$s Below"),
1962                                         translateIfPossible(curlayout));
1963                 // We use command-alternatives here since this is how the binding is defined
1964                 // (otherwise, the binding is not displayed in the menu)
1965                 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1966                         add(MenuItem(MenuItem::Command, toqstr(label),
1967                                      FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1968                                                  from_ascii("environment-split ; environment-split previous"))));
1969         }
1970         else if (!prevlayout.empty()) {
1971                 docstring const label = contextmenu ?
1972                         bformat(_("Insert Separated %1$s Below"),
1973                                 translateIfPossible(prevlayout)) :
1974                         bformat(_("Separated %1$s Below"),
1975                                 translateIfPossible(prevlayout));
1976                 // We use command-alternatives here since this is how the binding is defined
1977                 // (otherwise, the binding is not displayed in the menu)
1978                 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1979                         add(MenuItem(MenuItem::Command, toqstr(label),
1980                                      FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1981                                                  from_ascii("environment-split ; environment-split previous"))));
1982         }
1983         if (!outerlayout.empty()) {
1984                 docstring label;
1985                 if (contextmenu) {
1986                         label = (outerlayout == curlayout) ?
1987                                 bformat(_("Insert Separated Outer %1$s Below"),
1988                                         translateIfPossible(outerlayout)) :
1989                                 bformat(_("Insert Separated %1$s Below"),
1990                                         translateIfPossible(outerlayout));
1991                 } else {
1992                         label = (outerlayout == curlayout) ?
1993                                 bformat(_("Separated Outer %1$s Below"),
1994                                         translateIfPossible(outerlayout)) :
1995                                 bformat(_("Separated %1$s Below"),
1996                                         translateIfPossible(outerlayout));
1997                 }
1998                 add(MenuItem(MenuItem::Command, toqstr(label),
1999                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2000                                          from_ascii("outer"))));
2001         }
2002 }
2003
2004 } // namespace
2005
2006
2007 /////////////////////////////////////////////////////////////////////
2008 // Menu::Impl definition and implementation
2009 /////////////////////////////////////////////////////////////////////
2010
2011 struct Menu::Impl
2012 {
2013         /// populates the menu or one of its submenu
2014         /// This is used as a recursive function
2015         void populate(QMenu * qMenu, MenuDefinition const & menu);
2016
2017         /// Only needed for top level menus.
2018         MenuDefinition * top_level_menu;
2019         /// our owning view
2020         GuiView * view;
2021         /// the name of this menu
2022         QString name;
2023 };
2024
2025
2026
2027 /// Get a MenuDefinition item label from the menu backend
2028 static QString label(MenuItem const & mi)
2029 {
2030         QString label = mi.label();
2031         label.replace("&", "&&");
2032
2033         QString shortcut = mi.shortcut();
2034         if (!shortcut.isEmpty()) {
2035                 int pos = label.indexOf(shortcut);
2036                 if (pos != -1)
2037                         //label.insert(pos, 1, char_type('&'));
2038                         label.replace(pos, 0, "&");
2039         }
2040
2041         QString const binding = mi.binding();
2042         if (!binding.isEmpty())
2043                 label += '\t' + binding;
2044
2045         return label;
2046 }
2047
2048 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
2049 {
2050         LYXERR(Debug::GUI, "populating menu " << menu.name());
2051         if (menu.empty()) {
2052                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
2053                 return;
2054         }
2055         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
2056         for (MenuItem const & m : menu)
2057                 switch (m.kind()) {
2058                 case MenuItem::Separator:
2059                         qMenu->addSeparator();
2060                         break;
2061                 case MenuItem::Submenu: {
2062                         QMenu * subMenu = qMenu->addMenu(label(m));
2063                         populate(subMenu, m.submenu());
2064                         subMenu->setEnabled(!subMenu->isEmpty());
2065                         break;
2066                 }
2067                 case MenuItem::Command:
2068                 default:
2069                         // FIXME: A previous comment assured that MenuItem::Command was the
2070                         // only possible case in practice, but this is wrong.  It would be
2071                         // good to document which cases are actually treated here.
2072                         qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2073                                                     m.tooltip(), qMenu));
2074                         break;
2075                 }
2076 }
2077
2078 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2079 class AlwaysMnemonicStyle : public QProxyStyle {
2080 public:
2081         int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2082                 QStyleHintReturn *returnData = 0) const override
2083         {
2084                 if (hint == QStyle::SH_UnderlineShortcut)
2085                         return 1;
2086                 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2087         }
2088 };
2089 #endif
2090
2091 /////////////////////////////////////////////////////////////////////
2092 // Menu implementation
2093 /////////////////////////////////////////////////////////////////////
2094
2095 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2096 : QMenu(gv), d(new Menu::Impl)
2097 {
2098 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2099         if (keyboard)
2100                 setStyle(new AlwaysMnemonicStyle);
2101 #else
2102         (void) keyboard;
2103 #endif
2104         d->top_level_menu = top_level? new MenuDefinition : 0;
2105         d->view = gv;
2106         d->name = name;
2107         setTitle(name);
2108         if (d->top_level_menu)
2109                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2110 }
2111
2112
2113 Menu::~Menu()
2114 {
2115         delete d->top_level_menu;
2116         delete d;
2117 }
2118
2119
2120 void Menu::updateView()
2121 {
2122         guiApp->menus().updateMenu(this);
2123 }
2124
2125
2126 void Menu::clear()
2127 {
2128         QList<QAction *> items = actions();
2129         for (int i = 0; i != items.size(); ++i) {
2130                 // QAction::menu() returns 0 if there's no submenu.
2131                 delete items.at(i)->menu();
2132         }
2133         QMenu::clear();
2134 }
2135
2136
2137 /////////////////////////////////////////////////////////////////////
2138 // Menus::Impl definition and implementation
2139 /////////////////////////////////////////////////////////////////////
2140
2141 struct Menus::Impl {
2142         ///
2143         bool hasMenu(QString const &) const;
2144         ///
2145         MenuDefinition & getMenu(QString const &);
2146         ///
2147         MenuDefinition const & getMenu(QString const &) const;
2148
2149         /// Expands some special entries of the menu
2150         /** The entries with the following kind are expanded to a
2151             sequence of Command MenuItems: Lastfiles, Documents,
2152             ViewFormats, ExportFormats, UpdateFormats, Branches,
2153             Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2154             EnvironmentSeparators
2155         */
2156         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2157                 BufferView const *) const;
2158
2159         /// Initialize specific MACOS X menubar
2160         void macxMenuBarInit(QMenuBar * qmb);
2161
2162         /// Mac special menu.
2163         /** This defines a menu whose entries list the FuncRequests
2164             that will be removed by expand() in other menus. This is
2165             used by the Qt/Mac code.
2166
2167             NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2168             such that the items will keep accessing the FuncRequests in
2169             the MenuDefinition. While Menus::Impl might be recreated,
2170             we keep mac_special_menu_ in memory by making it static.
2171         */
2172         static MenuDefinition mac_special_menu_;
2173
2174         ///
2175         MenuList menulist_;
2176         ///
2177         MenuDefinition menubar_;
2178
2179         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2180
2181         /// name to menu for \c menu() method.
2182         NameMap name_map_;
2183 };
2184
2185
2186 MenuDefinition Menus::Impl::mac_special_menu_;
2187
2188
2189 /*
2190   Here is what the Qt documentation says about how a menubar is chosen:
2191
2192      1) If the window has a QMenuBar then it is used. 2) If the window
2193      is a modal then its menubar is used. If no menubar is specified
2194      then a default menubar is used (as documented below) 3) If the
2195      window has no parent then the default menubar is used (as
2196      documented below).
2197
2198      The above 3 steps are applied all the way up the parent window
2199      chain until one of the above are satisfied. If all else fails a
2200      default menubar will be created, the default menubar on Qt/Mac is
2201      an empty menubar, however you can create a different default
2202      menubar by creating a parentless QMenuBar, the first one created
2203      will thus be designated the default menubar, and will be used
2204      whenever a default menubar is needed.
2205
2206   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2207   that this menubar will be used also when one of LyX' dialogs has
2208   focus. (JMarc)
2209 */
2210 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2211 {
2212         /* Since Qt 4.2, the qt/mac menu code has special code for
2213            specifying the role of a menu entry. However, it does not
2214            work very well with our scheme of creating menus on demand,
2215            and therefore we need to put these entries in a special
2216            invisible menu. (JMarc)
2217         */
2218
2219         /* The entries of our special mac menu. If we add support for
2220          * special entries in Menus, we could imagine something
2221          * like
2222          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
2223          * and therefore avoid hardcoding. I am not sure it is worth
2224          * the hassle, though. (JMarc)
2225          */
2226         struct MacMenuEntry {
2227                 FuncCode action;
2228                 char const * arg;
2229                 char const * label;
2230                 QAction::MenuRole role;
2231         };
2232
2233         static const MacMenuEntry entries[] = {
2234                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2235                  QAction::AboutRole},
2236                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2237                  QAction::PreferencesRole},
2238 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2239                 /* This doesn't work with Cocoa. */
2240                 {LFUN_RECONFIGURE, "", "Reconfigure",
2241                  QAction::ApplicationSpecificRole},
2242 #endif
2243                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2244         };
2245         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2246         const bool first_call = mac_special_menu_.empty();
2247
2248         LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2249         // the special menu for Menus. Fill it up only once.
2250         if (first_call) {
2251                 for (size_t i = 0 ; i < num_entries ; ++i) {
2252                         FuncRequest const func(entries[i].action,
2253                                 from_utf8(entries[i].arg));
2254                         mac_special_menu_.add(MenuItem(MenuItem::Command,
2255                                 entries[i].label, func));
2256                 }
2257         }
2258
2259         // add the entries to a QMenu that will eventually be empty
2260         // and therefore invisible.
2261         QMenu * qMenu = qmb->addMenu("special");
2262         size_t i = 0;
2263         for (MenuItem const & m : mac_special_menu_) {
2264                 Action * action = new Action(m.func(), QIcon(), m.label(),
2265                                              QString(), qMenu);
2266                 action->setMenuRole(entries[i].role);
2267                 qMenu->addAction(action);
2268                 ++i;
2269         }
2270 }
2271
2272
2273 void Menus::Impl::expand(MenuDefinition const & frommenu,
2274         MenuDefinition & tomenu, BufferView const * bv) const
2275 {
2276         if (!tomenu.empty())
2277                 tomenu.clear();
2278
2279         for (MenuDefinition::const_iterator cit = frommenu.begin();
2280              cit != frommenu.end() ; ++cit) {
2281                 Buffer const * buf = bv ? &bv->buffer() : 0;
2282                 switch (cit->kind()) {
2283                 case MenuItem::Lastfiles:
2284                         tomenu.expandLastfiles();
2285                         break;
2286
2287                 case MenuItem::Documents:
2288                         tomenu.expandDocuments();
2289                         break;
2290
2291                 case MenuItem::Bookmarks:
2292                         tomenu.expandBookmarks();
2293                         break;
2294
2295                 case MenuItem::ImportFormats:
2296                 case MenuItem::ViewFormats:
2297                 case MenuItem::UpdateFormats:
2298                 case MenuItem::ExportFormats:
2299                         tomenu.expandFormats(cit->kind(), buf);
2300                         break;
2301
2302                 case MenuItem::ExportFormat: {
2303                         if (!buf)
2304                                 break;
2305                         string const format = buf->params().getDefaultOutputFormat();
2306                         Format const * f = theFormats().getFormat(format);
2307                         docstring const name = f ? translateIfPossible(f->prettyname())
2308                                                  : from_utf8(format);
2309                         docstring const label = bformat(_("Export [%1$s]|E"), name);
2310                         MenuItem item(MenuItem::Command, toqstr(label),
2311                                       FuncRequest(LFUN_BUFFER_EXPORT));
2312                         tomenu.addWithStatusCheck(item);
2313                         break;
2314                 }
2315
2316                 case MenuItem::CharStyles:
2317                         tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2318                         break;
2319
2320                 case MenuItem::Custom:
2321                         tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2322                         break;
2323
2324                 case MenuItem::FloatListInsert:
2325                         tomenu.expandFloatListInsert(buf);
2326                         break;
2327
2328                 case MenuItem::FloatInsert:
2329                         tomenu.expandFloatInsert(buf);
2330                         break;
2331
2332                 case MenuItem::PasteRecent:
2333                         tomenu.expandPasteRecent(buf);
2334                         break;
2335
2336                 case MenuItem::Toolbars:
2337                         tomenu.expandToolbars();
2338                         break;
2339
2340                 case MenuItem::Branches:
2341                         tomenu.expandBranches(buf);
2342                         break;
2343
2344                 case MenuItem::Indices:
2345                         tomenu.expandIndices(buf);
2346                         break;
2347
2348                 case MenuItem::IndicesContext:
2349                         tomenu.expandIndicesContext(buf);
2350                         break;
2351
2352                 case MenuItem::IndicesLists:
2353                         tomenu.expandIndices(buf, true);
2354                         break;
2355
2356                 case MenuItem::IndicesListsContext:
2357                         tomenu.expandIndicesContext(buf, true);
2358                         break;
2359
2360                 case MenuItem::CiteStyles:
2361                         tomenu.expandCiteStyles(bv);
2362                         break;
2363
2364                 case MenuItem::InfoArguments:
2365                         tomenu.expandInfoArguments(bv);
2366                         break;
2367                         
2368
2369                 case MenuItem::Toc:
2370                         tomenu.expandToc(buf);
2371                         break;
2372
2373                 case MenuItem::GraphicsGroups:
2374                         tomenu.expandGraphicsGroups(bv);
2375                         break;
2376
2377                 case MenuItem::SpellingSuggestions:
2378                         tomenu.expandSpellingSuggestions(bv);
2379                         break;
2380
2381                 case MenuItem::LanguageSelector:
2382                         tomenu.expandLanguageSelector(buf);
2383                         break;
2384
2385                 case MenuItem::Arguments:
2386                         tomenu.expandArguments(bv, false);
2387                         break;
2388
2389                 case MenuItem::SwitchArguments:
2390                         tomenu.expandArguments(bv, true);
2391                         break;
2392
2393                 case MenuItem::Captions:
2394                         tomenu.expandCaptions(buf, false);
2395                         break;
2396
2397                 case MenuItem::SwitchCaptions:
2398                         tomenu.expandCaptions(buf, true);
2399                         break;
2400
2401                 case MenuItem::EnvironmentSeparators:
2402                         tomenu.expandEnvironmentSeparators(bv);
2403                         break;
2404
2405                 case MenuItem::EnvironmentSeparatorsContext:
2406                         tomenu.expandEnvironmentSeparators(bv, true);
2407                         break;
2408
2409                 case MenuItem::SwitchQuotes:
2410                         tomenu.expandQuotes(bv);
2411                         break;
2412
2413                 case MenuItem::Submenu: {
2414                         MenuItem item(*cit);
2415                         item.setSubmenu(MenuDefinition(cit->submenuname()));
2416                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
2417                         tomenu.addWithStatusCheck(item);
2418                 }
2419                 break;
2420
2421                 case MenuItem::Info:
2422                 case MenuItem::Help:
2423                 case MenuItem::Separator:
2424                         tomenu.addWithStatusCheck(*cit);
2425                         break;
2426
2427                 case MenuItem::Command:
2428                         if (!mac_special_menu_.hasFunc(*cit->func()))
2429                                 tomenu.addWithStatusCheck(*cit);
2430                 }
2431         }
2432
2433         // we do not want the menu to end with a separator
2434         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2435                 tomenu.items_.pop_back();
2436
2437         // Check whether the shortcuts are unique
2438         tomenu.checkShortcuts();
2439 }
2440
2441
2442 bool Menus::Impl::hasMenu(QString const & name) const
2443 {
2444         return find_if(menulist_.begin(), menulist_.end(),
2445                 MenuNamesEqual(name)) != menulist_.end();
2446 }
2447
2448
2449 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2450 {
2451         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2452                 MenuNamesEqual(name));
2453         if (cit == menulist_.end()) {
2454                 LYXERR0("No submenu named " << name);
2455                 LASSERT(false, { static const MenuDefinition m; return m; });
2456         }
2457         return (*cit);
2458 }
2459
2460
2461 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2462 {
2463         iterator it = find_if(menulist_.begin(), menulist_.end(),
2464                 MenuNamesEqual(name));
2465         if (it == menulist_.end()) {
2466                 LYXERR0("No submenu named " << name);
2467                 LASSERT(false, { static MenuDefinition m; return m; });
2468         }
2469         return (*it);
2470 }
2471
2472
2473 /////////////////////////////////////////////////////////////////////
2474 //
2475 // Menus
2476 //
2477 /////////////////////////////////////////////////////////////////////
2478
2479 Menus::Menus() : d(new Impl) {}
2480
2481
2482 Menus::~Menus()
2483 {
2484         delete d;
2485 }
2486
2487
2488 void Menus::reset()
2489 {
2490         delete d;
2491         d = new Impl;
2492 }
2493
2494
2495 void Menus::read(Lexer & lex)
2496 {
2497         enum {
2498                 md_menu,
2499                 md_menubar,
2500                 md_endmenuset
2501         };
2502
2503         LexerKeyword menutags[] = {
2504                 { "end", md_endmenuset },
2505                 { "menu", md_menu },
2506                 { "menubar", md_menubar }
2507         };
2508
2509         // consistency check
2510         if (compare_ascii_no_case(lex.getString(), "menuset"))
2511                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2512
2513         lex.pushTable(menutags);
2514         lex.setContext("Menus::read");
2515
2516         bool quit = false;
2517
2518         while (lex.isOK() && !quit) {
2519                 switch (lex.lex()) {
2520                 case md_menubar:
2521                         d->menubar_.read(lex);
2522                         break;
2523                 case md_menu: {
2524                         lex.next(true);
2525                         QString const name = toqstr(lex.getDocString());
2526                         if (d->hasMenu(name))
2527                                 d->getMenu(name).read(lex);
2528                         else {
2529                                 MenuDefinition menu(name);
2530                                 menu.read(lex);
2531                                 d->menulist_.push_back(menu);
2532                         }
2533                         break;
2534                 }
2535                 case md_endmenuset:
2536                         quit = true;
2537                         break;
2538                 default:
2539                         lex.printError("Unknown menu tag");
2540                         break;
2541                 }
2542         }
2543         lex.popTable();
2544 }
2545
2546
2547 bool Menus::searchMenu(FuncRequest const & func,
2548         docstring_list & names, BufferView const * bv) const
2549 {
2550         MenuDefinition menu;
2551         d->expand(d->menubar_, menu, bv);
2552         return menu.searchMenu(func, names);
2553 }
2554
2555
2556 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2557 {
2558         if (initial) {
2559 #ifdef Q_OS_MAC
2560                 // setup special mac specific menu items, but only do this
2561                 // the first time a QMenuBar is created. Otherwise Qt will
2562                 // create duplicate items in the application menu. It seems
2563                 // that Qt does not remove them when the QMenubar is cleared.
2564                 d->macxMenuBarInit(qmb);
2565 #endif
2566         } else {
2567                 // Clear all menubar contents before filling it.
2568                 qmb->clear();
2569 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2570                 d->macxMenuBarInit(qmb);
2571 #endif
2572         }
2573
2574         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2575
2576         if (d->menubar_.empty()) {
2577                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2578                         << d->menubar_.name());
2579                 return;
2580         }
2581         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2582
2583         MenuDefinition menu;
2584         BufferView * bv = 0;
2585         if (view)
2586                 bv = view->currentBufferView();
2587         d->expand(d->menubar_, menu, bv);
2588
2589         MenuDefinition::const_iterator m = menu.begin();
2590         MenuDefinition::const_iterator end = menu.end();
2591
2592         for (; m != end; ++m) {
2593
2594                 if (m->kind() != MenuItem::Submenu) {
2595                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2596                         continue;
2597                 }
2598
2599                 LYXERR(Debug::GUI, "menu bar item " << m->label()
2600                         << " is a submenu named " << m->submenuname());
2601
2602                 QString name = m->submenuname();
2603                 if (!d->hasMenu(name)) {
2604                         LYXERR(Debug::GUI, "\tERROR: " << name
2605                                 << " submenu has no menu!");
2606                         continue;
2607                 }
2608
2609                 Menu * menuptr = new Menu(view, m->submenuname(), true);
2610                 menuptr->setTitle(label(*m));
2611
2612 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2613                 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2614                 // so we create a temporary one here
2615                 QAction * action = new QAction(menuptr);
2616                 menuptr->addAction(action);
2617 #endif
2618
2619                 qmb->addMenu(menuptr);
2620
2621                 d->name_map_[view][name] = menuptr;
2622         }
2623 }
2624
2625
2626 void Menus::updateMenu(Menu * qmenu)
2627 {
2628         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2629         qmenu->clear();
2630
2631         if (qmenu->d->name.isEmpty())
2632                 return;
2633
2634         docstring identifier = qstring_to_ucs4(qmenu->d->name);
2635         MenuDefinition fromLyxMenu(qmenu->d->name);
2636         while (!identifier.empty()) {
2637                 docstring menu_name;
2638                 identifier = split(identifier, menu_name, ';');
2639
2640                 if (!d->hasMenu(toqstr(menu_name))) {
2641                         LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2642                                 << menu_name);
2643                         continue;
2644                 }
2645
2646                 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2647                 //FIXME: 50 is a wild guess. We should take into account here
2648                 //the expansion of menu items, disabled optional items etc.
2649                 bool const in_sub_menu = !fromLyxMenu.empty()
2650                         && fromLyxMenu.size() + cat_menu.size() > 50 ;
2651                 if (in_sub_menu)
2652                         fromLyxMenu.catSub(menu_name);
2653                 else
2654                         fromLyxMenu.cat(cat_menu);
2655                 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2656         }
2657
2658         if (fromLyxMenu.empty()) {
2659                 qmenu->addAction(qt_("No Action Defined!"));
2660                 return;
2661         }
2662
2663         BufferView * bv = 0;
2664         if (qmenu->d->view)
2665                 bv = qmenu->d->view->currentBufferView();
2666         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2667         qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2668 }
2669
2670
2671 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2672 {
2673         LYXERR(Debug::GUI, "Context menu requested: " << name);
2674         Menu * menu = d->name_map_[&view].value(name, 0);
2675         if (!menu && !name.startsWith("context-")) {
2676                 LYXERR0("requested context menu not found: " << name);
2677                 return 0;
2678         }
2679
2680         menu = new Menu(&view, name, true, keyboard);
2681         d->name_map_[&view][name] = menu;
2682         return menu;
2683 }
2684
2685 } // namespace frontend
2686 } // namespace lyx
2687
2688 #include "moc_Menus.cpp"