]> git.lyx.org Git - features.git/blob - src/frontends/qt/Menus.cpp
679efe461ced015ea4b3fdbf2702b3f65078b6f5
[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                         LYXERR(Debug::GUI, "Valid Word.");
885                         docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
886                         add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
887                                         FuncRequest(LFUN_SPELLING_REMOVE, arg)));
888                 }
889                 break;
890         case SpellChecker::DOCUMENT_LEARNED_WORD: {
891                         LYXERR(Debug::GUI, "Document-Learned Word.");
892                         docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
893                         add(MenuItem(MenuItem::Command, qt_("Remove from document dictionary|r"),
894                                         FuncRequest(LFUN_SPELLING_REMOVE_LOCAL, arg)));
895                 }
896                 break;
897         case SpellChecker::NO_DICTIONARY:
898                 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
899                 // FALLTHROUGH
900         }
901 }
902
903 struct sortLanguageByName {
904         bool operator()(const Language * a, const Language * b) const {
905                 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
906         }
907 };
908
909 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
910 {
911         if (!buf)
912                 return;
913
914         std::set<Language const *> languages_buffer =
915                 buf->masterBuffer()->getLanguages();
916
917         if (languages_buffer.size() < 2) {
918                 add(MenuItem(MenuItem::Command, qt_("Switch Language...|L"),
919                              FuncRequest(LFUN_DIALOG_SHOW, "character")));
920                 return;
921         }
922
923         std::set<Language const *, sortLanguageByName> langs;
924
925         std::set<Language const *>::const_iterator const beg =
926                 languages_buffer.begin();
927         for (std::set<Language const *>::const_iterator cit = beg;
928              cit != languages_buffer.end(); ++cit) {
929                 langs.insert(*cit);
930         }
931
932         MenuItem item(MenuItem::Submenu, qt_("Language|L"));
933         item.setSubmenu(MenuDefinition(qt_("Language")));
934         QString morelangs = qt_("More Languages ...|M");
935         QStringList accelerators;
936         if (morelangs.contains('|'))
937                 accelerators.append(morelangs.section('|', -1));
938         std::set<Language const *, sortLanguageByName>::const_iterator const begin = langs.begin();
939         for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
940                          cit != langs.end(); ++cit) {
941                 QString label = qt_((*cit)->display());
942                 // try to add an accelerator
943                 bool success = false;
944                 // try capitals first
945                 for (int i = 0; i < label.size(); ++i) {
946                         QChar const ch = label[i];
947                         if (!ch.isUpper())
948                                 continue;
949                         if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
950                                 label = label + toqstr("|") + ch;
951                                 accelerators.append(ch);
952                                 success = true;
953                                 break;
954                         }
955                 }
956                 // if all capitals are taken, try the rest
957                 if (!success) {
958                         for (int i = 0; i < label.size(); ++i) {
959                                 if (label[i].isSpace())
960                                         continue;
961                                 QString const ch = QString(label[i]);
962                                 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
963                                         label = label + toqstr("|") + ch;
964                                         accelerators.append(ch);
965                                         break;
966                                 }
967                         }
968                 }
969                 MenuItem w(MenuItem::Command, label,
970                         FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
971                 item.submenu().addWithStatusCheck(w);
972         }
973         item.submenu().add(MenuItem(MenuItem::Separator));
974         item.submenu().add(MenuItem(MenuItem::Command, morelangs,
975                         FuncRequest(LFUN_DIALOG_SHOW, "character")));
976         add(item);
977 }
978
979
980 void MenuDefinition::expandLastfiles()
981 {
982         LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
983         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
984
985         unsigned int ii = 1;
986
987         for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
988                 string const file = lfit->absFileName();
989                 QString const short_path = toqstr(makeDisplayPath(file, 30));
990                 QString const long_path = toqstr(makeDisplayPath(file));
991                 QString label;
992                 if (ii < 10)
993                         label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
994                 else
995                         label = QString("%1. %2").arg(ii).arg(short_path);
996                 add(MenuItem(MenuItem::Command, label,
997                         FuncRequest(LFUN_FILE_OPEN, file), long_path));
998         }
999 }
1000
1001
1002 void MenuDefinition::expandDocuments()
1003 {
1004         MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
1005         item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
1006
1007         Buffer * const first = theBufferList().first();
1008         if (!first) {
1009                 add(MenuItem(MenuItem::Info, qt_("(No Documents Open)")));
1010                 return;
1011         }
1012
1013         int i = 0;
1014         while (true) {
1015                 if (!guiApp->currentView())
1016                         break;
1017                 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
1018                 if (!wa)
1019                         break;
1020                 Buffer const & b = wa->bufferView().buffer();
1021                 QString label = toqstr(b.fileName().displayName(20));
1022                 if (!b.isClean())
1023                         label += "*";
1024                 if (b.notifiesExternalModification())
1025                         label += QChar(0x26a0); // warning sign ⚠
1026                 if (i < 10)
1027                         label = QString::number(i) + ". " + label + '|' + QString::number(i);
1028                 add(MenuItem(MenuItem::Command, label,
1029                         FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1030                 ++i;
1031         }
1032
1033
1034         i = 0;
1035         Buffer * b = first;
1036         // We cannot use a for loop as the buffer list cycles.
1037         do {
1038                 if (!(guiApp->currentView()
1039                     && guiApp->currentView()->workArea(*b))) {
1040                         QString label = toqstr(b->fileName().displayName(20));
1041                         if (!b->isClean())
1042                                 label += "*";
1043                         if (b->notifiesExternalModification())
1044                                 label += QChar(0x26a0);
1045                         if (i < 10)
1046                                 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1047                         item.submenu().add(MenuItem(MenuItem::Command, label,
1048                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1049                         ++i;
1050                 }
1051                 b = theBufferList().next(b);
1052         } while (b != first);
1053
1054         if (!item.submenu().empty())
1055                 add(item);
1056 }
1057
1058
1059 void MenuDefinition::expandBookmarks()
1060 {
1061         lyx::BookmarksSection const & bm = theSession().bookmarks();
1062
1063         bool empty = true;
1064         for (size_t i = 1; i <= bm.size(); ++i) {
1065                 if (bm.isValid(i)) {
1066                         string const file = bm.bookmark(i).filename.absFileName();
1067                         QString const label = QString("%1. %2|%3").arg(i)
1068                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1069                         add(MenuItem(MenuItem::Command, label,
1070                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1071                         empty = false;
1072                 }
1073         }
1074         if (empty)
1075                 add(MenuItem(MenuItem::Info, qt_("(No Bookmarks Saved Yet)")));
1076 }
1077
1078
1079 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1080 {
1081         if (!buf && kind != MenuItem::ImportFormats)
1082                 return;
1083
1084         FormatList formats;
1085         FuncCode action = LFUN_NOACTION;
1086
1087         switch (kind) {
1088         case MenuItem::ImportFormats:
1089                 formats = theConverters().importableFormats();
1090                 action = LFUN_BUFFER_IMPORT;
1091                 break;
1092         case MenuItem::ViewFormats:
1093                 formats = buf->params().exportableFormats(true);
1094                 action = LFUN_BUFFER_VIEW;
1095                 break;
1096         case MenuItem::UpdateFormats:
1097                 formats = buf->params().exportableFormats(true);
1098                 action = LFUN_BUFFER_UPDATE;
1099                 break;
1100         case MenuItem::ExportFormats:
1101                 formats = buf->params().exportableFormats(false);
1102                 action = LFUN_BUFFER_EXPORT;
1103                 break;
1104         default:
1105                 LATTEST(false);
1106                 return;
1107         }
1108
1109         bool const view_update = (kind == MenuItem::ViewFormats
1110                         || kind == MenuItem::UpdateFormats);
1111
1112         QString smenue;
1113         if (view_update)
1114                 smenue = (kind == MenuItem::ViewFormats
1115                         ? qt_("View (Other Formats)|F")
1116                         : qt_("Update (Other Formats)|p"));
1117         MenuItem item(MenuItem::Submenu, smenue);
1118         item.setSubmenu(MenuDefinition(smenue));
1119
1120         for (Format const * f : formats) {
1121                 if (f->dummy())
1122                         continue;
1123
1124                 docstring lab = f->prettyname();
1125                 docstring const scut = from_utf8(f->shortcut());
1126                 docstring const tmplab = lab;
1127
1128                 if (!scut.empty())
1129                         lab += char_type('|') + scut;
1130                 docstring const lab_i18n = translateIfPossible(lab);
1131                 docstring const shortcut = split(lab_i18n, lab, '|');
1132
1133                 bool const untranslated = (lab == lab_i18n);
1134                 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1135
1136                 switch (kind) {
1137                 case MenuItem::ImportFormats:
1138                         if (f->noMenu())
1139                                 continue;
1140                         label += from_ascii("...");
1141                         break;
1142                 case MenuItem::ViewFormats:
1143                 case MenuItem::UpdateFormats:
1144                         if (f->name() == buf->params().getDefaultOutputFormat()) {
1145                                 docstring lbl = (kind == MenuItem::ViewFormats
1146                                         ? bformat(_("View [%1$s]|V"), label)
1147                                         : bformat(_("Update [%1$s]|U"), label));
1148                                 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1149                                 continue;
1150                         }
1151                         break;
1152                 case MenuItem::ExportFormats:
1153                         if (!f->inExportMenu())
1154                                 continue;
1155                         break;
1156                 default:
1157                         // we already asserted earlier in this case
1158                         // LATTEST(false);
1159                         continue;
1160                 }
1161                 if (!shortcut.empty())
1162                         label += '|' + shortcut;
1163
1164                 if (view_update) {
1165                         // note that at this point, we know that buf is not null
1166                         LATTEST(buf);
1167                         item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1168                                 toqstr(label), FuncRequest(action, f->name())));
1169                 } else {
1170                         if (buf)
1171                                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1172                                         FuncRequest(action, f->name())));
1173                         else
1174                                 add(MenuItem(MenuItem::Command, toqstr(label),
1175                                         FuncRequest(action, f->name())));
1176                 }
1177         }
1178         if (view_update)
1179                 add(item);
1180 }
1181
1182
1183 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1184 {
1185         if (!buf)
1186                 return;
1187
1188         FloatList const & floats = buf->params().documentClass().floats();
1189         FloatList::const_iterator cit = floats.begin();
1190         FloatList::const_iterator end = floats.end();
1191         set<string> seen;
1192         for (; cit != end; ++cit) {
1193                 if (!cit->second.usesFloatPkg()) {
1194                         // Different floats could declare the same ListCommand. We only
1195                         // want it on the list once, though.
1196                         string const & list_cmd = cit->second.listCommand();
1197                         if (list_cmd.empty())
1198                                 // we do not know how to generate such a list
1199                                 continue;
1200                         // This form of insert returns an iterator pointing to the newly
1201                         // inserted element OR the existing element with that value, and
1202                         // a bool indicating whether we inserted a new element. So we can
1203                         // see if one is there and insert it if not all at once.
1204                         pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1205                         if (!ret.second)
1206                                 continue;
1207                 }
1208                 string const & list_name = cit->second.listName();
1209                 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1210                         FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1211         }
1212 }
1213
1214
1215 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1216 {
1217         if (!buf)
1218                 return;
1219
1220         FloatList const & floats = buf->params().documentClass().floats();
1221         FloatList::const_iterator cit = floats.begin();
1222         FloatList::const_iterator end = floats.end();
1223         for (; cit != end; ++cit) {
1224                 // normal float
1225                 if (cit->second.name().empty())
1226                         continue;
1227                 QString const label = qt_(cit->second.name());
1228                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1229                                     FuncRequest(LFUN_FLOAT_INSERT,
1230                                                 cit->second.floattype())));
1231         }
1232 }
1233
1234
1235 void MenuDefinition::expandFlexInsert(
1236                 Buffer const * buf, InsetLyXType type)
1237 {
1238         if (!buf)
1239                 return;
1240
1241         TextClass::InsetLayouts const & insetLayouts =
1242                 buf->params().documentClass().insetLayouts();
1243         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1244         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1245         for (; cit != end; ++cit) {
1246                 if (cit->second.lyxtype() == type) {
1247                         if (!cit->second.obsoleted_by().empty())
1248                                 continue;
1249                         docstring name = cit->first;
1250                         // we remove the "Flex:" prefix, if it is present
1251                         if (prefixIs(name, from_ascii("Flex:")))
1252                                 name = name.substr(5);
1253                         docstring const label = (cit->second.menustring().empty()) ?
1254                                                 name
1255                                               : cit->second.menustring();
1256                         addWithStatusCheck(MenuItem(MenuItem::Command,
1257                                 toqstr(translateIfPossible(label)),
1258                                 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(name))));
1259                 }
1260         }
1261         // FIXME This is a little clunky.
1262         if (items_.empty() && type == InsetLyXType::CUSTOM && !buf->hasReadonlyFlag())
1263                 add(MenuItem(MenuItem::Help, qt_("(No Custom Insets Defined)")));
1264 }
1265
1266
1267 // Threshold before we stop displaying sub-items alongside items
1268 // (for display purposes). Ideally this should fit on a screen.
1269 size_t const max_number_of_items = 30;
1270 // Size limit for the menu. This is for performance purposes,
1271 // because qt already displays a scrollable menu when necessary.
1272 // Ideally this should be the menu size from which scrollable
1273 // menus become unpractical.
1274 size_t const menu_size_limit = 80;
1275
1276 void MenuDefinition::expandToc2(Toc const & toc_list,
1277                                 size_t from, size_t to, int depth,
1278                                 string const & toc_type)
1279 {
1280         int shortcut_count = 0;
1281
1282         // check whether depth is smaller than the smallest depth in toc.
1283         int min_depth = 1000;
1284         for (size_t i = from; i < to; ++i)
1285                 min_depth = min(min_depth, toc_list[i].depth());
1286         if (min_depth > depth)
1287                 depth = min_depth;
1288
1289         if (to - from <= max_number_of_items) {
1290                 for (size_t i = from; i < to; ++i) {
1291                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1292                         label += limitStringLength(toc_list[i].asString());
1293                         if (toc_list[i].depth() == depth) {
1294                                 label += '|';
1295                             if (shortcut_count < 9) {
1296                                         if (label.contains(QString::number(shortcut_count + 1)))
1297                                                 label += QString::number(++shortcut_count);
1298                                 }
1299                         }
1300                         add(MenuItem(MenuItem::Command, label, toc_list[i].action()));
1301                         // separator after the menu heading
1302                         if (toc_list[i].depth() < depth)
1303                                 add(MenuItem(MenuItem::Separator));
1304                 }
1305         } else {
1306                 size_t pos = from;
1307                 size_t size = 1;
1308                 while (pos < to) {
1309                         size_t new_pos = pos + 1;
1310                         while (new_pos < to && toc_list[new_pos].depth() > depth)
1311                                 ++new_pos;
1312
1313                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1314                         label += limitStringLength(toc_list[pos].asString());
1315                         if (toc_list[pos].depth() == depth) {
1316                                 label += '|';
1317                             if (shortcut_count < 9) {
1318                                         if (label.contains(QString::number(shortcut_count + 1)))
1319                                                 label += QString::number(++shortcut_count);
1320                                 }
1321                         }
1322                         if (size >= menu_size_limit) {
1323                                 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1324                                 add(MenuItem(MenuItem::Command, "...", f));
1325                                 break;
1326                         }
1327                         if (new_pos == pos + 1) {
1328                                 add(MenuItem(MenuItem::Command, label, toc_list[pos].action()));
1329                         } else {
1330                                 MenuDefinition sub;
1331                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1332                                 MenuItem item(MenuItem::Submenu, label);
1333                                 item.setSubmenu(sub);
1334                                 add(item);
1335                         }
1336                         ++size;
1337                         pos = new_pos;
1338                 }
1339         }
1340 }
1341
1342
1343 void MenuDefinition::expandToc(Buffer const * buf)
1344 {
1345         // To make things very cleanly, we would have to pass buf to
1346         // all MenuItem constructors and to expandToc2. However, we
1347         // know that all the entries in a TOC will be have status_ ==
1348         // OK, so we avoid this unnecessary overhead (JMarc)
1349         if (!buf) {
1350                 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1351                 return;
1352         }
1353         // Add an entry for the master doc if this is a child doc
1354         Buffer const * const master = buf->masterBuffer();
1355         if (buf != master) {
1356                 ParIterator const pit = par_iterator_begin(master->inset());
1357                 string const arg = convert<string>(pit->id());
1358                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1359                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1360         }
1361
1362         MenuDefinition other_lists;
1363         // In the navigation menu, only add tocs from this document
1364         TocBackend const & backend = buf->tocBackend();
1365         TocList const & toc_list = backend.tocs();
1366         for (pair<const string, shared_ptr<Toc>> const & toc : toc_list) {
1367                 // Handle table of contents later
1368                 if (toc.first == "tableofcontents" || toc.second->empty())
1369                         continue;
1370                 MenuDefinition submenu;
1371                 submenu.expandTocSubmenu(toc.first, *toc.second);
1372                 docstring const toc_name = backend.outlinerName(toc.first);
1373                 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1374                 item.setSubmenu(submenu);
1375                 // deserves to be in the main menu?
1376                 if (!TocBackend::isOther(toc.first))
1377                         add(item);
1378                 else
1379                         other_lists.add(item);
1380         }
1381         if (!other_lists.empty()) {
1382                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1383                 item.setSubmenu(other_lists);
1384                 add(item);
1385         }
1386         // Handle normal TOC
1387         add(MenuItem(MenuItem::Separator));
1388         TocList::const_iterator const cit = toc_list.find("tableofcontents");
1389         if (cit == toc_list.end())
1390                 LYXERR(Debug::GUI, "No table of contents.");
1391         else {
1392                 if (!cit->second->empty())
1393                         expandToc2(*cit->second, 0, cit->second->size(), 0,
1394                                    "tableofcontents");
1395                 else
1396                         add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1397         }
1398 }
1399
1400
1401 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1402 {
1403         // "Open outliner..." entry
1404         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1405         add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1406         add(MenuItem(MenuItem::Separator));
1407         // add entries
1408         expandToc2(toc, 0, toc.size(), 0, type);
1409 }
1410
1411
1412 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1413 {
1414         docstring_list const sel = cap::availableSelections(buf);
1415
1416         docstring_list::const_iterator cit = sel.begin();
1417         docstring_list::const_iterator end = sel.end();
1418
1419         for (unsigned int index = 0; cit != end; ++cit, ++index) {
1420                 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1421                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1422         }
1423 }
1424
1425
1426 void MenuDefinition::expandToolbars()
1427 {
1428         MenuDefinition other_lists;
1429         // extracts the toolbars from the backend
1430         Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1431         Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1432         for (; cit != end; ++cit) {
1433                 MenuItem item(MenuItem::Command, toqstr(cit->gui_name),
1434                               FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1435                 if (cit->allow_auto) {
1436                         MenuDefinition tristate;
1437                         tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]On|O"),
1438                                               FuncRequest(LFUN_TOOLBAR_SET, cit->name + " on")));
1439                         tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]Off|f"),
1440                                               FuncRequest(LFUN_TOOLBAR_SET, cit->name + " off")));
1441                         tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]Automatic|A"),
1442                                               FuncRequest(LFUN_TOOLBAR_SET, cit->name + " auto")));
1443                         item = MenuItem(MenuItem::Submenu,toqstr(cit->gui_name));
1444                         item.setSubmenu(tristate);
1445                 }
1446                 if (guiApp->toolbars().isMainToolbar(cit->name))
1447                         add(item);
1448                 else
1449                         other_lists.add(item);
1450         }
1451
1452         if (!other_lists.empty()) {
1453                 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1454                 item.setSubmenu(other_lists);
1455                 add(item);
1456         }
1457 }
1458
1459
1460 void MenuDefinition::expandBranches(Buffer const * buf)
1461 {
1462         if (!buf || buf->hasReadonlyFlag())
1463                 return;
1464
1465         BranchList const & child_list = buf->params().branchlist();
1466         set<docstring> brset;
1467         int ii = 1;
1468         for (auto const & b : child_list) {
1469                 docstring const & bname = b.branch();
1470                 // NUM. Branch Name + "|", which triggers an empty shortcut in
1471                 // case that character should be in the branch name.
1472                 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1473                 // Add NUM as a keyboard shortcut if it's a single digit
1474                 if (ii < 10)
1475                         label += convert<docstring>(ii);
1476
1477                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1478                         FuncRequest(LFUN_BRANCH_INSERT, bname)));
1479
1480                 brset.insert(bname);
1481                 ++ii;
1482         }
1483
1484         set<Buffer const *> bufset;
1485         Buffer const * nextbuf = buf->parent();
1486         MenuDefinition master_branches;
1487         ii = 1;
1488         while (nextbuf) {
1489                 // recursive includes are a bad idea, but let's not crash
1490                 // if we find one.
1491                 if (bufset.count(nextbuf))
1492                         break;
1493
1494                 for (auto const & b : nextbuf->params().branchlist()) {
1495                         docstring const & bname = b.branch();
1496                         // do not add it if we've already seen it
1497                         if (brset.count(bname))
1498                                 continue;
1499
1500                         docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1501                         if (ii < 10)
1502                                 label += convert<docstring>(ii);
1503
1504                         master_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1505                                 toqstr(label), FuncRequest(LFUN_BRANCH_INSERT, bname)));
1506
1507                         bufset.insert(nextbuf);
1508                         brset.insert(bname);
1509                         ++ii;
1510                 }
1511
1512                 nextbuf = nextbuf->parent();
1513         }
1514
1515         if (!master_branches.empty()) {
1516                 MenuItem item(MenuItem::Submenu, qt_("Master Documents"));
1517                 item.setSubmenu(master_branches);
1518                 add(item);
1519         }
1520 }
1521
1522
1523 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1524 {
1525         if (!buf)
1526                 return;
1527
1528         BufferParams const & params = buf->masterBuffer()->params();
1529         if (!params.use_indices) {
1530                 if (listof)
1531                         addWithStatusCheck(MenuItem(MenuItem::Command,
1532                                            qt_("Index List|I"),
1533                                            FuncRequest(LFUN_INDEX_PRINT,
1534                                                   from_ascii("idx"))));
1535                 else
1536                         addWithStatusCheck(MenuItem(MenuItem::Command,
1537                                            qt_("Index Entry|d"),
1538                                            FuncRequest(LFUN_INDEX_INSERT,
1539                                                   from_ascii("idx"))));
1540                 return;
1541         }
1542
1543         if (params.indiceslist().empty())
1544                 return;
1545
1546         IndicesList::const_iterator cit = params.indiceslist().begin();
1547         IndicesList::const_iterator end = params.indiceslist().end();
1548
1549         for (int ii = 1; cit != end; ++cit, ++ii) {
1550                 if (listof) {
1551                         docstring const label =
1552                                 bformat(_("Index: %1$s"), cit->index());
1553                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1554                                            FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1555                 } else {
1556                         docstring const label =
1557                                 bformat(_("Index Entry (%1$s)"), cit->index());
1558                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1559                                            FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1560                 }
1561         }
1562 }
1563
1564
1565 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1566 {
1567         if (!buf)
1568                 return;
1569
1570         BufferParams const & params = buf->masterBuffer()->params();
1571         if (!params.use_indices || params.indiceslist().empty())
1572                 return;
1573
1574         IndicesList::const_iterator cit = params.indiceslist().begin();
1575         IndicesList::const_iterator end = params.indiceslist().end();
1576
1577         for (int ii = 1; cit != end; ++cit, ++ii) {
1578                 if (listof) {
1579                         InsetCommandParams p(INDEX_PRINT_CODE);
1580                         p["type"] = cit->shortcut();
1581                         string const data = InsetCommand::params2string(p);
1582                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1583                                            FuncRequest(LFUN_INSET_MODIFY, data)));
1584                 } else {
1585                         docstring const label =
1586                                         bformat(_("Index Entry (%1$s)"), cit->index());
1587                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1588                                            FuncRequest(LFUN_INSET_MODIFY,
1589                                                   from_ascii("changetype ") + cit->shortcut())));
1590                 }
1591         }
1592 }
1593
1594
1595 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1596 {
1597         if (!bv)
1598                 return;
1599
1600         Inset const * inset = bv->cursor().nextInset();
1601         if (!inset || inset->lyxCode() != CITE_CODE) {
1602                 add(MenuItem(MenuItem::Command,
1603                                     qt_("No Citation in Scope!"),
1604                                     FuncRequest(LFUN_NOACTION)));
1605                 return;
1606         }
1607         InsetCitation const * citinset =
1608                                 static_cast<InsetCitation const *>(inset);
1609
1610         Buffer const * buf = &bv->buffer();
1611         BufferParams const & bp = buf->masterParams();
1612         string const cmd = citinset->params().getCmdName();
1613
1614         docstring const & key = citinset->getParam("key");
1615         if (key.empty()) {
1616                 add(MenuItem(MenuItem::Command,
1617                                     qt_("No citations selected!"),
1618                                     FuncRequest(LFUN_NOACTION)));
1619                 return;
1620         }
1621
1622         bool const force = isUpperCase(cmd[0]);
1623         bool const star = suffixIs(cmd, '*');
1624
1625         vector<docstring> const keys = getVectorFromString(key);
1626
1627         vector<CitationStyle> const citeStyleList = bp.citeStyles();
1628
1629         CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1630         bool const qualified = cs.hasQualifiedList
1631                 && (keys.size() > 1
1632                     || !citinset->getParam("pretextlist").empty()
1633                     || !citinset->getParam("posttextlist").empty());
1634         vector<pair<docstring, docstring>> pres =
1635                 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1636         vector<pair<docstring, docstring>> posts =
1637                 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1638
1639         CiteItem ci;
1640         ci.textBefore = citinset->getParam("before");
1641         ci.textAfter = citinset->getParam("after");
1642         ci.forceUpperCase = force;
1643         ci.Starred = star;
1644         ci.context = CiteItem::Dialog;
1645         ci.max_size = 40;
1646         ci.isQualified = qualified;
1647         ci.pretexts = pres;
1648         ci.posttexts = posts;
1649         BiblioInfo::CiteStringMap citeStrings =
1650                 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1651
1652         BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1653         BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1654
1655         for (int ii = 1; cit != end; ++cit, ++ii) {
1656                 docstring label = cit->second;
1657                 CitationStyle ccs = citeStyleList[ii - 1];
1658                 ccs.forceUpperCase &= force;
1659                 ccs.hasStarredVersion &= star;
1660                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1661                                     FuncRequest(LFUN_INSET_MODIFY,
1662                                                 "changetype " + from_utf8(citationStyleToString(ccs)))));
1663         }
1664
1665         if (cs.hasStarredVersion) {
1666                 docstring starred = _("All authors|h");
1667                 // Check if we have a custom string/tooltip for the starred version
1668                 if (!cs.stardesc.empty()) {
1669                         string val =
1670                                 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1671                         if (!val.empty())
1672                                 starred = translateIfPossible(from_utf8(val));
1673                         // Transform qt-style accelerators to menu-style
1674                         int const amps = count_char(starred, '&');
1675                         if (amps > 0) {
1676                                 if (amps > 1)
1677                                         starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1678                                 size_t nn = starred.find('&');
1679                                 char_type accel = char_type();
1680                                 if (nn != docstring::npos && nn < starred.size() - 1)
1681                                         accel = starred[nn + 1];
1682                                 starred = subst(starred, from_ascii("&"), from_ascii(""));
1683                                 if (amps > 1)
1684                                         starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1685                                 if (accel != char_type())
1686                                         starred = starred + '|' + accel;
1687                         }
1688                 }
1689                 add(MenuItem(MenuItem::Separator));
1690                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1691                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1692         }
1693
1694         if (cs.forceUpperCase) {
1695                 if (!cs.hasStarredVersion)
1696                         add(MenuItem(MenuItem::Separator));
1697                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1698                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1699         }
1700 }
1701
1702
1703 void MenuDefinition::expandInfoArguments(BufferView const * bv)
1704 {
1705         if (!bv)
1706                 return;
1707
1708         Inset const * inset = bv->cursor().nextInset();
1709         if (!inset || inset->lyxCode() != INFO_CODE) {
1710                 add(MenuItem(MenuItem::Command,
1711                                     qt_("No Text Field in Scope!"),
1712                                     FuncRequest(LFUN_NOACTION)));
1713                 return;
1714         }
1715         InsetInfo const * iinset = static_cast<InsetInfo const *>(inset);
1716
1717         string const type = iinset->params().infoType();
1718         vector<pair<string,docstring>> const args =
1719                         iinset->params().getArguments(&bv->buffer(), type);
1720
1721         // Don't generate a menu for big lists (such as lfuns and rcs)
1722         if (args.size() > 15)
1723                 return;
1724
1725         for (auto const & p : args) {
1726                 if (p.first == "invalid")
1727                         // non-selectable
1728                         continue;
1729                 if (p.first == "custom") {
1730                         add(MenuItem(MenuItem::Command, qt_("Custom..."),
1731                                      FuncRequest(LFUN_INSET_SETTINGS, "info")));
1732                         continue;
1733                 }
1734                 docstring label = p.second;
1735                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1736                                     FuncRequest(LFUN_INSET_MODIFY, type + " " + p.first)));
1737         }
1738 }
1739
1740
1741
1742 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1743 {
1744         if (!bv)
1745                 return;
1746
1747         if (!bv->cursor().inTexted())
1748                 return;
1749
1750         Inset const * inset = &bv->cursor().inset();
1751         Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1752         if (inset && args.empty())
1753                 args = inset->getLayout().args();
1754         if (args.empty() || (switcharg && args.size() == 1))
1755                 return;
1756         Layout::LaTeXArgMap::const_iterator lait = args.begin();
1757         Layout::LaTeXArgMap::const_iterator const laend = args.end();
1758         for (; lait != laend; ++lait) {
1759                 Layout::latexarg arg = (*lait).second;
1760                 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1761                 QString item = toqstr(translateIfPossible(str));
1762                 if (switcharg)
1763                         add(MenuItem(MenuItem::Command, item,
1764                                      FuncRequest(LFUN_INSET_MODIFY,
1765                                                  from_ascii("changetype ")
1766                                                  + from_ascii((*lait).first))));
1767                 else
1768                         add(MenuItem(MenuItem::Command, item,
1769                                      FuncRequest(LFUN_ARGUMENT_INSERT,
1770                                                  from_ascii((*lait).first))));
1771         }
1772 }
1773
1774
1775 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1776 {
1777         if (!buf)
1778                 return;
1779
1780         DocumentClass const & dc = buf->params().documentClass();
1781         vector< pair<docstring, FuncRequest> > caps;
1782         for (pair<const docstring, InsetLayout> const & il : dc.insetLayouts()) {
1783                 docstring instype;
1784                 docstring const type = split(il.first, instype, ':');
1785                 if (instype == from_ascii("Caption")) {
1786                         // skip forbidden caption types
1787                         FuncRequest const cmd = switchcap
1788                                 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1789                                 : FuncRequest(LFUN_CAPTION_INSERT, type);
1790                         if (getStatus(cmd).enabled())
1791                                 caps.push_back(make_pair(type, cmd));
1792                 }
1793         }
1794
1795         if (caps.empty() || (switchcap && caps.size() == 1))
1796                 return;
1797         if (caps.size() == 1) {
1798                 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1799                 return;
1800         }
1801
1802         MenuDefinition captions;
1803         for (pair<docstring, FuncRequest> const & cap : caps) {
1804                 docstring const type = cap.first;
1805                 docstring const trtype = translateIfPossible(type);
1806                 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1807                 if (switchcap)
1808                         add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1809                 else
1810                         captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1811         }
1812         if (!captions.empty()) {
1813                 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1814                 item.setSubmenu(captions);
1815                 add(item);
1816         }
1817 }
1818
1819
1820 void MenuDefinition::expandZoomOptions(BufferView const * bv)
1821 {
1822         if (!bv)
1823                 return;
1824
1825         add(MenuItem(MenuItem::Command,
1826                      toqstr(bformat(_("Reset to Default (%1$d%)|R"),
1827                                     lyxrc.defaultZoom)),
1828                      FuncRequest(LFUN_BUFFER_ZOOM)));
1829         add(MenuItem(MenuItem::Command, qt_("Zoom In|I"),
1830                      FuncRequest(LFUN_BUFFER_ZOOM_IN)));
1831         add(MenuItem(MenuItem::Command, qt_("Zoom Out|O"),
1832                      FuncRequest(LFUN_BUFFER_ZOOM_OUT)));
1833         add(MenuItem(MenuItem::Separator));
1834         // Offer some fractional values of the default
1835         int z = lyxrc.defaultZoom * 1.75;
1836         add(MenuItem(MenuItem::Command,
1837                      toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1838                      FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1839         z = lyxrc.defaultZoom * 1.5;
1840         add(MenuItem(MenuItem::Command,
1841                      toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1842                      FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1843         z = lyxrc.defaultZoom * 1.25;
1844         add(MenuItem(MenuItem::Command,
1845                      toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1846                      FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1847         z = lyxrc.defaultZoom * 0.75;
1848         add(MenuItem(MenuItem::Command,
1849                      toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1850                      FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1851         z = lyxrc.defaultZoom * 0.5;
1852         add(MenuItem(MenuItem::Command,
1853                      toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1854                      FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1855         z = lyxrc.defaultZoom * 0.25;
1856         add(MenuItem(MenuItem::Command,
1857                      toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1858                      FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1859 }
1860
1861
1862 void MenuDefinition::expandQuotes(BufferView const * bv)
1863 {
1864         if (!bv)
1865                 return;
1866
1867         if (!bv->cursor().inTexted())
1868                 return;
1869
1870         Inset const * inset = bv->cursor().nextInset();
1871         if (!inset || inset->lyxCode() != QUOTE_CODE) {
1872                 add(MenuItem(MenuItem::Command,
1873                                     qt_("No Quote in Scope!"),
1874                                     FuncRequest(LFUN_NOACTION)));
1875                 return;
1876         }
1877         InsetQuotes const * qinset =
1878                 static_cast<InsetQuotes const *>(inset);
1879
1880         string const qtype = qinset->getType();
1881
1882         MenuDefinition aqs;
1883
1884         BufferParams const & bp = bv->buffer().masterBuffer()->params();
1885
1886         // The global setting
1887         QuoteStyle globalqs = bp.quotes_style;
1888         char const globalqsc = quoteparams.getStyleChar(globalqs);
1889
1890         // The current language's default
1891         QuoteStyle langdefqs =
1892                 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1893         char const langqs = quoteparams.getStyleChar(langdefqs);
1894
1895         bool main_global_qs = false;
1896         bool main_langdef_qs = false;
1897         bool main_dynamic_qs = false;
1898         docstring const subcmd = from_ascii("changetype ");
1899         docstring const wildcards = from_ascii("..");
1900         // Add the items
1901         // First the top level menu (all glyphs of the current style) ...
1902         // Begin with dynamic (if they are current style),
1903         if (qtype[0] == 'x') {
1904                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1905                 docstring desc = bformat(_("%1$s (dynamic)"),
1906                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1907                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1908                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1909                 desc = bformat(_("%1$s (dynamic)"),
1910                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1911                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1912                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1913                 desc = bformat(_("%1$s (dynamic)"),
1914                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1915                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1916                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1917                 desc = bformat(_("%1$s (dynamic)"),
1918                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1919                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1920                 main_dynamic_qs = true;
1921         }
1922         // now traverse through the static styles ...
1923         map<string, docstring> styles = quoteparams.getTypes();
1924         for (auto const & s : styles) {
1925                 char style_char = (s.first)[0];
1926                 bool langdef = (style_char == langqs);
1927                 bool globaldef = (style_char == globalqsc);
1928                 docstring const style = from_ascii(s.first);
1929
1930                 if (prefixIs(style, qtype[0])) {
1931                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1932                         docstring const desc = quoteparams.getShortGuiLabel(style);
1933                         add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1934                         main_global_qs = globaldef;
1935                         main_langdef_qs = langdef;
1936                 }
1937                 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1938                         docstring const desc =
1939                                 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1940                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1941                         aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1942                 }
1943         }
1944
1945         add(MenuItem(MenuItem::Separator));
1946
1947         bool display_static = false;
1948         // ... then potentially items to reset to the defaults and to dynamic style ...
1949         if (!main_dynamic_qs && globalqsc != 'x') {
1950                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1951                 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1952                                                 quoteparams.getGuiLabel(globalqs));
1953                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1954                 display_static = true;
1955         }
1956         if (!main_global_qs && langdefqs != globalqs) {
1957                 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1958                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1959                 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1960                                                 quoteparams.getGuiLabel(globalqs), variant);
1961                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1962         }
1963         if (!main_langdef_qs) {
1964                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1965                 docstring const desc = (main_dynamic_qs || display_static)
1966                                         ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1967                                                   quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1968                                         : bformat(_("Reset to language default (%1$s)|l"),
1969                                                   quoteparams.getGuiLabel(langdefqs));
1970                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1971         }
1972
1973         add(MenuItem(MenuItem::Separator));
1974
1975         // ... and a subitem with the rest
1976         MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1977         item.setSubmenu(aqs);
1978         add(item);
1979 }
1980
1981
1982 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1983                                                  bool contextmenu)
1984 {
1985         if (!bv)
1986                 return;
1987         Text const * text = bv->cursor().text();
1988         // no paragraphs and no separators exist in math
1989         if (!text)
1990                 return;
1991
1992         pit_type pit = bv->cursor().selBegin().pit();
1993         Paragraph const & par = text->getPar(pit);
1994         docstring const curlayout = par.layout().name();
1995         docstring outerlayout;
1996         docstring prevlayout;
1997         depth_type current_depth = par.params().depth();
1998         // check if we have an environment in our scope
1999         while (true) {
2000                 if (pit == 0)
2001                         break;
2002                 --pit;
2003                 Paragraph cpar = text->getPar(pit);
2004                 if (cpar.layout().isEnvironment() && prevlayout.empty()
2005                     && cpar.params().depth() <= current_depth)
2006                                 prevlayout = cpar.layout().name();
2007                 if (cpar.params().depth() < current_depth
2008                     && cpar.layout().isEnvironment()) {
2009                                 outerlayout = cpar.layout().name();
2010                                 current_depth = cpar.params().depth();
2011                 }
2012                 if (cpar.params().depth() == 0)
2013                         break;
2014         }
2015         if (par.layout().isEnvironment()) {
2016                 docstring label = contextmenu ?
2017                                         bformat(_("Insert Separated %1$s Above"),
2018                                                 translateIfPossible(curlayout)) :
2019                                         bformat(_("Separated %1$s Above"),
2020                                                 translateIfPossible(curlayout));
2021                 add(MenuItem(MenuItem::Command, toqstr(label),
2022                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2023                                          from_ascii("before"))));
2024                 label = contextmenu ?
2025                                 bformat(_("Insert Separated %1$s Below"),
2026                                         translateIfPossible(curlayout)):
2027                                 bformat(_("Separated %1$s Below"),
2028                                         translateIfPossible(curlayout));
2029                 // We use command-alternatives here since this is how the binding is defined
2030                 // (otherwise, the binding is not displayed in the menu)
2031                 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
2032                         add(MenuItem(MenuItem::Command, toqstr(label),
2033                                      FuncRequest(LFUN_COMMAND_ALTERNATIVES,
2034                                                  from_ascii("environment-split ; environment-split previous"))));
2035         }
2036         else if (!prevlayout.empty()) {
2037                 docstring const label = contextmenu ?
2038                         bformat(_("Insert Separated %1$s Below"),
2039                                 translateIfPossible(prevlayout)) :
2040                         bformat(_("Separated %1$s Below"),
2041                                 translateIfPossible(prevlayout));
2042                 // We use command-alternatives here since this is how the binding is defined
2043                 // (otherwise, the binding is not displayed in the menu)
2044                 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
2045                         add(MenuItem(MenuItem::Command, toqstr(label),
2046                                      FuncRequest(LFUN_COMMAND_ALTERNATIVES,
2047                                                  from_ascii("environment-split ; environment-split previous"))));
2048         }
2049         if (!outerlayout.empty()) {
2050                 docstring label;
2051                 if (contextmenu) {
2052                         label = (outerlayout == curlayout) ?
2053                                 bformat(_("Insert Separated Outer %1$s Below"),
2054                                         translateIfPossible(outerlayout)) :
2055                                 bformat(_("Insert Separated %1$s Below"),
2056                                         translateIfPossible(outerlayout));
2057                 } else {
2058                         label = (outerlayout == curlayout) ?
2059                                 bformat(_("Separated Outer %1$s Below"),
2060                                         translateIfPossible(outerlayout)) :
2061                                 bformat(_("Separated %1$s Below"),
2062                                         translateIfPossible(outerlayout));
2063                 }
2064                 add(MenuItem(MenuItem::Command, toqstr(label),
2065                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2066                                          from_ascii("outer"))));
2067         }
2068 }
2069
2070 } // namespace
2071
2072
2073 /////////////////////////////////////////////////////////////////////
2074 // Menu::Impl definition and implementation
2075 /////////////////////////////////////////////////////////////////////
2076
2077 struct Menu::Impl
2078 {
2079         /// populates the menu or one of its submenu
2080         /// This is used as a recursive function
2081         void populate(QMenu * qMenu, MenuDefinition const & menu);
2082
2083         /// Only needed for top level menus.
2084         MenuDefinition * top_level_menu;
2085         /// our owning view
2086         GuiView * view;
2087         /// the name of this menu
2088         QString name;
2089 };
2090
2091
2092
2093 /// Get a MenuDefinition item label from the menu backend
2094 static QString label(MenuItem const & mi)
2095 {
2096         QString label = mi.label();
2097         label.replace("&", "&&");
2098
2099         QString shortcut = mi.shortcut();
2100         if (!shortcut.isEmpty()) {
2101                 int pos = label.indexOf(shortcut);
2102                 if (pos != -1)
2103                         //label.insert(pos, 1, char_type('&'));
2104                         label.replace(pos, 0, "&");
2105         }
2106
2107         QString const binding = mi.binding();
2108         if (!binding.isEmpty())
2109                 label += '\t' + binding;
2110
2111         return label;
2112 }
2113
2114 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
2115 {
2116         LYXERR(Debug::GUI, "populating menu " << menu.name());
2117         if (menu.empty()) {
2118                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
2119                 return;
2120         }
2121         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
2122         for (MenuItem const & m : menu)
2123                 switch (m.kind()) {
2124                 case MenuItem::Separator:
2125                         qMenu->addSeparator();
2126                         break;
2127                 case MenuItem::Submenu: {
2128                         QMenu * subMenu = qMenu->addMenu(label(m));
2129                         populate(subMenu, m.submenu());
2130                         subMenu->setEnabled(!subMenu->isEmpty());
2131                         break;
2132                 }
2133                 case MenuItem::Command:
2134                 default:
2135                         // FIXME: A previous comment assured that MenuItem::Command was the
2136                         // only possible case in practice, but this is wrong.  It would be
2137                         // good to document which cases are actually treated here.
2138                         qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2139                                                     m.tooltip(), qMenu));
2140                         break;
2141                 }
2142 }
2143
2144 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2145 class AlwaysMnemonicStyle : public QProxyStyle {
2146 public:
2147         int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2148                 QStyleHintReturn *returnData = 0) const override
2149         {
2150                 if (hint == QStyle::SH_UnderlineShortcut)
2151                         return 1;
2152                 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2153         }
2154 };
2155 #endif
2156
2157 /////////////////////////////////////////////////////////////////////
2158 // Menu implementation
2159 /////////////////////////////////////////////////////////////////////
2160
2161 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2162 : QMenu(gv), d(new Menu::Impl)
2163 {
2164 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2165         if (keyboard)
2166                 setStyle(new AlwaysMnemonicStyle);
2167 #else
2168         (void) keyboard;
2169 #endif
2170         d->top_level_menu = top_level? new MenuDefinition : 0;
2171         d->view = gv;
2172         d->name = name;
2173         setTitle(name);
2174         if (d->top_level_menu)
2175                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2176 }
2177
2178
2179 Menu::~Menu()
2180 {
2181         delete d->top_level_menu;
2182         delete d;
2183 }
2184
2185
2186 void Menu::updateView()
2187 {
2188         guiApp->menus().updateMenu(this);
2189 }
2190
2191
2192 void Menu::clear()
2193 {
2194         QList<QAction *> items = actions();
2195         for (int i = 0; i != items.size(); ++i) {
2196                 // QAction::menu() returns 0 if there's no submenu.
2197                 delete items.at(i)->menu();
2198         }
2199         QMenu::clear();
2200 }
2201
2202
2203 /////////////////////////////////////////////////////////////////////
2204 // Menus::Impl definition and implementation
2205 /////////////////////////////////////////////////////////////////////
2206
2207 struct Menus::Impl {
2208         ///
2209         bool hasMenu(QString const &) const;
2210         ///
2211         MenuDefinition & getMenu(QString const &);
2212         ///
2213         MenuDefinition const & getMenu(QString const &) const;
2214
2215         /// Expands some special entries of the menu
2216         /** The entries with the following kind are expanded to a
2217             sequence of Command MenuItems: Lastfiles, Documents,
2218             ViewFormats, ExportFormats, UpdateFormats, Branches,
2219             Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2220             EnvironmentSeparators
2221         */
2222         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2223                 BufferView const *) const;
2224
2225         /// Initialize specific MACOS X menubar
2226         void macxMenuBarInit(QMenuBar * qmb);
2227
2228         /// Mac special menu.
2229         /** This defines a menu whose entries list the FuncRequests
2230             that will be removed by expand() in other menus. This is
2231             used by the Qt/Mac code.
2232
2233             NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2234             such that the items will keep accessing the FuncRequests in
2235             the MenuDefinition. While Menus::Impl might be recreated,
2236             we keep mac_special_menu_ in memory by making it static.
2237         */
2238         static MenuDefinition mac_special_menu_;
2239
2240         ///
2241         MenuList menulist_;
2242         ///
2243         MenuDefinition menubar_;
2244
2245         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2246
2247         /// name to menu for \c menu() method.
2248         NameMap name_map_;
2249 };
2250
2251
2252 MenuDefinition Menus::Impl::mac_special_menu_;
2253
2254
2255 /*
2256   Here is what the Qt documentation says about how a menubar is chosen:
2257
2258      1) If the window has a QMenuBar then it is used. 2) If the window
2259      is a modal then its menubar is used. If no menubar is specified
2260      then a default menubar is used (as documented below) 3) If the
2261      window has no parent then the default menubar is used (as
2262      documented below).
2263
2264      The above 3 steps are applied all the way up the parent window
2265      chain until one of the above are satisfied. If all else fails a
2266      default menubar will be created, the default menubar on Qt/Mac is
2267      an empty menubar, however you can create a different default
2268      menubar by creating a parentless QMenuBar, the first one created
2269      will thus be designated the default menubar, and will be used
2270      whenever a default menubar is needed.
2271
2272   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2273   that this menubar will be used also when one of LyX' dialogs has
2274   focus. (JMarc)
2275 */
2276 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2277 {
2278         /* Since Qt 4.2, the qt/mac menu code has special code for
2279            specifying the role of a menu entry. However, it does not
2280            work very well with our scheme of creating menus on demand,
2281            and therefore we need to put these entries in a special
2282            invisible menu. (JMarc)
2283         */
2284
2285         /* The entries of our special mac menu. If we add support for
2286          * special entries in Menus, we could imagine something
2287          * like
2288          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
2289          * and therefore avoid hardcoding. I am not sure it is worth
2290          * the hassle, though. (JMarc)
2291          */
2292         struct MacMenuEntry {
2293                 FuncCode action;
2294                 char const * arg;
2295                 char const * label;
2296                 QAction::MenuRole role;
2297         };
2298
2299         static const MacMenuEntry entries[] = {
2300                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2301                  QAction::AboutRole},
2302                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2303                  QAction::PreferencesRole},
2304 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2305                 /* This doesn't work with Cocoa. */
2306                 {LFUN_RECONFIGURE, "", "Reconfigure",
2307                  QAction::ApplicationSpecificRole},
2308 #endif
2309                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2310         };
2311         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2312         const bool first_call = mac_special_menu_.empty();
2313
2314         LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2315         // the special menu for Menus. Fill it up only once.
2316         if (first_call) {
2317                 for (size_t i = 0 ; i < num_entries ; ++i) {
2318                         FuncRequest const func(entries[i].action,
2319                                 from_utf8(entries[i].arg));
2320                         mac_special_menu_.add(MenuItem(MenuItem::Command,
2321                                 entries[i].label, func));
2322                 }
2323         }
2324
2325         // add the entries to a QMenu that will eventually be empty
2326         // and therefore invisible.
2327         QMenu * qMenu = qmb->addMenu("special");
2328         size_t i = 0;
2329         for (MenuItem const & m : mac_special_menu_) {
2330                 Action * action = new Action(m.func(), QIcon(), m.label(),
2331                                              QString(), qMenu);
2332                 action->setMenuRole(entries[i].role);
2333                 qMenu->addAction(action);
2334                 ++i;
2335         }
2336 }
2337
2338
2339 void Menus::Impl::expand(MenuDefinition const & frommenu,
2340         MenuDefinition & tomenu, BufferView const * bv) const
2341 {
2342         if (!tomenu.empty())
2343                 tomenu.clear();
2344
2345         for (MenuDefinition::const_iterator cit = frommenu.begin();
2346              cit != frommenu.end() ; ++cit) {
2347                 Buffer const * buf = bv ? &bv->buffer() : 0;
2348                 switch (cit->kind()) {
2349                 case MenuItem::Lastfiles:
2350                         tomenu.expandLastfiles();
2351                         break;
2352
2353                 case MenuItem::Documents:
2354                         tomenu.expandDocuments();
2355                         break;
2356
2357                 case MenuItem::Bookmarks:
2358                         tomenu.expandBookmarks();
2359                         break;
2360
2361                 case MenuItem::ImportFormats:
2362                 case MenuItem::ViewFormats:
2363                 case MenuItem::UpdateFormats:
2364                 case MenuItem::ExportFormats:
2365                         tomenu.expandFormats(cit->kind(), buf);
2366                         break;
2367
2368                 case MenuItem::ExportFormat: {
2369                         if (!buf)
2370                                 break;
2371                         string const format = buf->params().getDefaultOutputFormat();
2372                         Format const * f = theFormats().getFormat(format);
2373                         docstring const name = f ? translateIfPossible(f->prettyname())
2374                                                  : from_utf8(format);
2375                         docstring const label = bformat(_("Export [%1$s]|E"), name);
2376                         MenuItem item(MenuItem::Command, toqstr(label),
2377                                       FuncRequest(LFUN_BUFFER_EXPORT));
2378                         tomenu.addWithStatusCheck(item);
2379                         break;
2380                 }
2381
2382                 case MenuItem::CharStyles:
2383                         tomenu.expandFlexInsert(buf, InsetLyXType::CHARSTYLE);
2384                         break;
2385
2386                 case MenuItem::Custom:
2387                         tomenu.expandFlexInsert(buf, InsetLyXType::CUSTOM);
2388                         break;
2389
2390                 case MenuItem::FloatListInsert:
2391                         tomenu.expandFloatListInsert(buf);
2392                         break;
2393
2394                 case MenuItem::FloatInsert:
2395                         tomenu.expandFloatInsert(buf);
2396                         break;
2397
2398                 case MenuItem::PasteRecent:
2399                         tomenu.expandPasteRecent(buf);
2400                         break;
2401
2402                 case MenuItem::Toolbars:
2403                         tomenu.expandToolbars();
2404                         break;
2405
2406                 case MenuItem::Branches:
2407                         tomenu.expandBranches(buf);
2408                         break;
2409
2410                 case MenuItem::Indices:
2411                         tomenu.expandIndices(buf);
2412                         break;
2413
2414                 case MenuItem::IndicesContext:
2415                         tomenu.expandIndicesContext(buf);
2416                         break;
2417
2418                 case MenuItem::IndicesLists:
2419                         tomenu.expandIndices(buf, true);
2420                         break;
2421
2422                 case MenuItem::IndicesListsContext:
2423                         tomenu.expandIndicesContext(buf, true);
2424                         break;
2425
2426                 case MenuItem::CiteStyles:
2427                         tomenu.expandCiteStyles(bv);
2428                         break;
2429
2430                 case MenuItem::InfoArguments:
2431                         tomenu.expandInfoArguments(bv);
2432                         break;
2433                         
2434
2435                 case MenuItem::Toc:
2436                         tomenu.expandToc(buf);
2437                         break;
2438
2439                 case MenuItem::GraphicsGroups:
2440                         tomenu.expandGraphicsGroups(bv);
2441                         break;
2442
2443                 case MenuItem::SpellingSuggestions:
2444                         tomenu.expandSpellingSuggestions(bv);
2445                         break;
2446
2447                 case MenuItem::LanguageSelector:
2448                         tomenu.expandLanguageSelector(buf);
2449                         break;
2450
2451                 case MenuItem::Arguments:
2452                         tomenu.expandArguments(bv, false);
2453                         break;
2454
2455                 case MenuItem::SwitchArguments:
2456                         tomenu.expandArguments(bv, true);
2457                         break;
2458
2459                 case MenuItem::Captions:
2460                         tomenu.expandCaptions(buf, false);
2461                         break;
2462
2463                 case MenuItem::SwitchCaptions:
2464                         tomenu.expandCaptions(buf, true);
2465                         break;
2466
2467                 case MenuItem::EnvironmentSeparators:
2468                         tomenu.expandEnvironmentSeparators(bv);
2469                         break;
2470
2471                 case MenuItem::EnvironmentSeparatorsContext:
2472                         tomenu.expandEnvironmentSeparators(bv, true);
2473                         break;
2474
2475                 case MenuItem::SwitchQuotes:
2476                         tomenu.expandQuotes(bv);
2477                         break;
2478
2479                 case MenuItem::ZoomOptions:
2480                         tomenu.expandZoomOptions(bv);
2481                         break;
2482
2483                 case MenuItem::Submenu: {
2484                         MenuItem item(*cit);
2485                         item.setSubmenu(MenuDefinition(cit->submenuname()));
2486                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
2487                         tomenu.addWithStatusCheck(item);
2488                 }
2489                 break;
2490
2491                 case MenuItem::Info:
2492                 case MenuItem::Help:
2493                 case MenuItem::Separator:
2494                         tomenu.addWithStatusCheck(*cit);
2495                         break;
2496
2497                 case MenuItem::Command:
2498                         if (!mac_special_menu_.hasFunc(*cit->func()))
2499                                 tomenu.addWithStatusCheck(*cit);
2500                 }
2501         }
2502
2503         // we do not want the menu to end with a separator
2504         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2505                 tomenu.items_.pop_back();
2506
2507         // Check whether the shortcuts are unique
2508         tomenu.checkShortcuts();
2509 }
2510
2511
2512 bool Menus::Impl::hasMenu(QString const & name) const
2513 {
2514         return find_if(menulist_.begin(), menulist_.end(),
2515                 MenuNamesEqual(name)) != menulist_.end();
2516 }
2517
2518
2519 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2520 {
2521         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2522                 MenuNamesEqual(name));
2523         if (cit == menulist_.end()) {
2524                 LYXERR0("No submenu named " << name);
2525                 LASSERT(false, { static const MenuDefinition m; return m; });
2526         }
2527         return (*cit);
2528 }
2529
2530
2531 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2532 {
2533         iterator it = find_if(menulist_.begin(), menulist_.end(),
2534                 MenuNamesEqual(name));
2535         if (it == menulist_.end()) {
2536                 LYXERR0("No submenu named " << name);
2537                 LASSERT(false, { static MenuDefinition m; return m; });
2538         }
2539         return (*it);
2540 }
2541
2542
2543 /////////////////////////////////////////////////////////////////////
2544 //
2545 // Menus
2546 //
2547 /////////////////////////////////////////////////////////////////////
2548
2549 Menus::Menus() : d(new Impl) {}
2550
2551
2552 Menus::~Menus()
2553 {
2554         delete d;
2555 }
2556
2557
2558 void Menus::reset()
2559 {
2560         delete d;
2561         d = new Impl;
2562 }
2563
2564
2565 void Menus::read(Lexer & lex)
2566 {
2567         enum {
2568                 md_menu,
2569                 md_menubar,
2570                 md_endmenuset
2571         };
2572
2573         LexerKeyword menutags[] = {
2574                 { "end", md_endmenuset },
2575                 { "menu", md_menu },
2576                 { "menubar", md_menubar }
2577         };
2578
2579         // consistency check
2580         if (compare_ascii_no_case(lex.getString(), "menuset"))
2581                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2582
2583         lex.pushTable(menutags);
2584         lex.setContext("Menus::read");
2585
2586         bool quit = false;
2587
2588         while (lex.isOK() && !quit) {
2589                 switch (lex.lex()) {
2590                 case md_menubar:
2591                         d->menubar_.read(lex);
2592                         break;
2593                 case md_menu: {
2594                         lex.next(true);
2595                         QString const name = toqstr(lex.getDocString());
2596                         if (d->hasMenu(name))
2597                                 d->getMenu(name).read(lex);
2598                         else {
2599                                 MenuDefinition menu(name);
2600                                 menu.read(lex);
2601                                 d->menulist_.push_back(menu);
2602                         }
2603                         break;
2604                 }
2605                 case md_endmenuset:
2606                         quit = true;
2607                         break;
2608                 default:
2609                         lex.printError("Unknown menu tag");
2610                         break;
2611                 }
2612         }
2613         lex.popTable();
2614 }
2615
2616
2617 bool Menus::searchMenu(FuncRequest const & func,
2618         docstring_list & names, BufferView const * bv) const
2619 {
2620         MenuDefinition menu;
2621         d->expand(d->menubar_, menu, bv);
2622         return menu.searchMenu(func, names);
2623 }
2624
2625
2626 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2627 {
2628         if (initial) {
2629 #ifdef Q_OS_MAC
2630                 // setup special mac specific menu items, but only do this
2631                 // the first time a QMenuBar is created. Otherwise Qt will
2632                 // create duplicate items in the application menu. It seems
2633                 // that Qt does not remove them when the QMenubar is cleared.
2634                 d->macxMenuBarInit(qmb);
2635 #endif
2636         } else {
2637                 // Clear all menubar contents before filling it.
2638                 qmb->clear();
2639 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2640                 d->macxMenuBarInit(qmb);
2641 #endif
2642         }
2643
2644         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2645
2646         if (d->menubar_.empty()) {
2647                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2648                         << d->menubar_.name());
2649                 return;
2650         }
2651         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2652
2653         MenuDefinition menu;
2654         BufferView * bv = 0;
2655         if (view)
2656                 bv = view->currentBufferView();
2657         d->expand(d->menubar_, menu, bv);
2658
2659         MenuDefinition::const_iterator m = menu.begin();
2660         MenuDefinition::const_iterator end = menu.end();
2661
2662         for (; m != end; ++m) {
2663
2664                 if (m->kind() != MenuItem::Submenu) {
2665                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2666                         continue;
2667                 }
2668
2669                 LYXERR(Debug::GUI, "menu bar item " << m->label()
2670                         << " is a submenu named " << m->submenuname());
2671
2672                 QString name = m->submenuname();
2673                 if (!d->hasMenu(name)) {
2674                         LYXERR(Debug::GUI, "\tERROR: " << name
2675                                 << " submenu has no menu!");
2676                         continue;
2677                 }
2678
2679                 Menu * menuptr = new Menu(view, m->submenuname(), true);
2680                 menuptr->setTitle(label(*m));
2681
2682 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2683                 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2684                 // so we create a temporary one here
2685                 QAction * action = new QAction(menuptr);
2686                 menuptr->addAction(action);
2687 #endif
2688
2689                 qmb->addMenu(menuptr);
2690
2691                 d->name_map_[view][name] = menuptr;
2692         }
2693 }
2694
2695
2696 void Menus::updateMenu(Menu * qmenu)
2697 {
2698         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2699         qmenu->clear();
2700
2701         if (qmenu->d->name.isEmpty())
2702                 return;
2703
2704         docstring identifier = qstring_to_ucs4(qmenu->d->name);
2705         MenuDefinition fromLyxMenu(qmenu->d->name);
2706         while (!identifier.empty()) {
2707                 docstring menu_name;
2708                 identifier = split(identifier, menu_name, ';');
2709
2710                 if (!d->hasMenu(toqstr(menu_name))) {
2711                         LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2712                                 << menu_name);
2713                         continue;
2714                 }
2715
2716                 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2717                 //FIXME: 50 is a wild guess. We should take into account here
2718                 //the expansion of menu items, disabled optional items etc.
2719                 bool const in_sub_menu = !fromLyxMenu.empty()
2720                         && fromLyxMenu.size() + cat_menu.size() > 50 ;
2721                 if (in_sub_menu)
2722                         fromLyxMenu.catSub(menu_name);
2723                 else
2724                         fromLyxMenu.cat(cat_menu);
2725                 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2726         }
2727
2728         if (fromLyxMenu.empty()) {
2729                 qmenu->addAction(qt_("No Action Defined!"));
2730                 return;
2731         }
2732
2733         BufferView * bv = 0;
2734         if (qmenu->d->view)
2735                 bv = qmenu->d->view->currentBufferView();
2736         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2737         qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2738 }
2739
2740
2741 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2742 {
2743         LYXERR(Debug::GUI, "Context menu requested: " << name);
2744         Menu * menu = d->name_map_[&view].value(name, 0);
2745         if (!menu && !name.startsWith("context-")) {
2746                 LYXERR0("requested context menu not found: " << name);
2747                 return 0;
2748         }
2749
2750         menu = new Menu(&view, name, true, keyboard);
2751         d->name_map_[&view][name] = menu;
2752         return menu;
2753 }
2754
2755 } // namespace frontend
2756 } // namespace lyx
2757
2758 #include "moc_Menus.cpp"