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