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