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