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