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