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