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