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