]> git.lyx.org Git - lyx.git/blob - src/MenuBackend.cpp
Revert part of 21965 which was debugging code.
[lyx.git] / src / MenuBackend.cpp
1 /**
2  * \file MenuBackend.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author André Pönitz
10  * \author Dekel Tsur
11  * \author Martin Vermeer
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "MenuBackend.h"
19
20 #include "BranchList.h"
21 #include "Buffer.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "Converter.h"
25 #include "CutAndPaste.h"
26 #include "support/debug.h"
27 #include "Floating.h"
28 #include "FloatList.h"
29 #include "Format.h"
30 #include "support/gettext.h"
31 #include "KeyMap.h"
32 #include "Session.h"
33 #include "LyXAction.h"
34 #include "LyX.h" // for lastfiles
35 #include "LyXFunc.h"
36 #include "Lexer.h"
37 #include "Paragraph.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
40 #include "ToolbarBackend.h"
41
42 #include "support/filetools.h"
43 #include "support/lstrings.h"
44 #include "support/convert.h"
45
46 #include <boost/bind.hpp>
47
48 #include <algorithm>
49 #include <ostream>
50
51
52 namespace lyx {
53
54 using support::compare_ascii_no_case;
55 using support::contains;
56 using support::makeDisplayPath;
57 using support::token;
58
59 using boost::bind;
60
61 using std::auto_ptr;
62 using std::endl;
63 using std::equal_to;
64 using std::find_if;
65 using std::max;
66 using std::sort;
67 using std::string;
68 using std::vector;
69 using std::stack;
70
71 namespace {
72
73 class MenuNamesEqual : public std::unary_function<Menu, bool> {
74 public:
75         MenuNamesEqual(docstring const & name)
76                 : name_(name) {}
77         bool operator()(Menu const & menu) const {
78                 return menu.name() == name_;
79         }
80 private:
81         docstring name_;
82 };
83
84 } // namespace anon
85
86
87 // This is the global menu definition
88 MenuBackend menubackend;
89
90
91 MenuItem::MenuItem(Kind kind)
92         : kind_(kind), optional_(false)
93 {}
94
95
96 MenuItem::MenuItem(Kind kind, docstring const & label,
97                    docstring const & submenu, bool optional)
98         : kind_(kind), label_(label),
99           submenuname_(submenu), optional_(optional)
100 {
101         BOOST_ASSERT(kind == Submenu);
102 }
103
104
105 MenuItem::MenuItem(Kind kind, docstring const & label,
106                    FuncRequest const & func, bool optional)
107         : kind_(kind), label_(label), func_(func), optional_(optional)
108 {
109         func_.origin = FuncRequest::MENU;
110 }
111
112
113 MenuItem::~MenuItem()
114 {}
115
116
117 void MenuItem::submenu(Menu * menu)
118 {
119         submenu_.reset(menu);
120 }
121
122
123 docstring const MenuItem::label() const
124 {
125         return token(label_, char_type('|'), 0);
126 }
127
128
129 docstring const MenuItem::shortcut() const
130 {
131         return token(label_, char_type('|'), 1);
132 }
133
134
135 docstring const MenuItem::binding(bool forgui) const
136 {
137         if (kind_ != Command)
138                 return docstring();
139
140         // Get the keys bound to this action, but keep only the
141         // first one later
142         KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
143
144         if (bindings.size())
145                 return bindings.begin()->print(KeySequence::ForGui);
146
147         LYXERR(Debug::KBMAP, "No binding for "
148                 << lyxaction.getActionName(func_.action)
149                 << '(' << to_utf8(func_.argument()) << ')');
150         return docstring();
151 }
152
153
154 Menu & Menu::add(MenuItem const & i)
155 {
156         items_.push_back(i);
157         return *this;
158 }
159
160
161 Menu & Menu::addWithStatusCheck(MenuItem const & i)
162 {
163         switch (i.kind()) {
164
165         case MenuItem::Command: {
166                 FuncStatus status = lyx::getStatus(i.func());
167                 if (status.unknown() || (!status.enabled() && i.optional()))
168                         break;
169                 items_.push_back(i);
170                 items_.back().status(status);
171                 break;
172         }
173
174         case MenuItem::Submenu: {
175                 if (i.submenu()) {
176                         bool enabled = false;
177                         for (const_iterator cit = i.submenu()->begin();
178                              cit != i.submenu()->end(); ++cit) {
179                                 if ((cit->kind() == MenuItem::Command
180                                      || cit->kind() == MenuItem::Submenu)
181                                     && cit->status().enabled()) {
182                                         enabled = true;
183                                         break;
184                                 }
185                         }
186                         if (enabled || !i.optional()) {
187                                 items_.push_back(i);
188                                 items_.back().status().enabled(enabled);
189                         }
190                 }
191                 else
192                         items_.push_back(i);
193                 break;
194         }
195
196         case MenuItem::Separator:
197                 if (!items_.empty()
198                     && items_.back().kind() != MenuItem::Separator)
199                         items_.push_back(i);
200                 break;
201
202         default:
203                 items_.push_back(i);
204         }
205
206         return *this;
207 }
208
209
210 Menu & Menu::read(Lexer & lex)
211 {
212         enum Menutags {
213                 md_item = 1,
214                 md_branches,
215                 md_documents,
216                 md_bookmarks,
217                 md_charstyles,
218                 md_custom,
219                 md_elements,
220                 md_endmenu,
221                 md_exportformats,
222                 md_importformats,
223                 md_lastfiles,
224                 md_optitem,
225                 md_optsubmenu,
226                 md_separator,
227                 md_submenu,
228                 md_toc,
229                 md_updateformats,
230                 md_viewformats,
231                 md_floatlistinsert,
232                 md_floatinsert,
233                 md_pasterecent,
234                 md_toolbars,
235                 md_last
236         };
237
238         struct keyword_item menutags[md_last - 1] = {
239                 { "bookmarks", md_bookmarks },
240                 { "branches", md_branches },
241                 { "charstyles", md_charstyles },
242                 { "custom", md_custom },
243                 { "documents", md_documents },
244                 { "elements", md_elements },
245                 { "end", md_endmenu },
246                 { "exportformats", md_exportformats },
247                 { "floatinsert", md_floatinsert },
248                 { "floatlistinsert", md_floatlistinsert },
249                 { "importformats", md_importformats },
250                 { "item", md_item },
251                 { "lastfiles", md_lastfiles },
252                 { "optitem", md_optitem },
253                 { "optsubmenu", md_optsubmenu },
254                 { "pasterecent", md_pasterecent },
255                 { "separator", md_separator },
256                 { "submenu", md_submenu },
257                 { "toc", md_toc },
258                 { "toolbars", md_toolbars },
259                 { "updateformats", md_updateformats },
260                 { "viewformats", md_viewformats }
261         };
262
263         lex.pushTable(menutags, md_last - 1);
264         if (lyxerr.debugging(Debug::PARSER))
265                 lex.printTable(lyxerr);
266
267         bool quit = false;
268         bool optional = false;
269
270         while (lex.isOK() && !quit) {
271                 switch (lex.lex()) {
272                 case md_optitem:
273                         optional = true;
274                         // fallback to md_item
275                 case md_item: {
276                         lex.next(true);
277                         docstring const name = translateIfPossible(lex.getDocString());
278                         lex.next(true);
279                         string const command = lex.getString();
280                         FuncRequest func = lyxaction.lookupFunc(command);
281                         add(MenuItem(MenuItem::Command, name, func, optional));
282                         optional = false;
283                         break;
284                 }
285
286                 case md_separator:
287                         add(MenuItem(MenuItem::Separator));
288                         break;
289
290                 case md_lastfiles:
291                         add(MenuItem(MenuItem::Lastfiles));
292                         break;
293
294                 case md_charstyles:
295                         add(MenuItem(MenuItem::CharStyles));
296                         break;
297
298                 case md_custom:
299                         add(MenuItem(MenuItem::Custom));
300                         break;
301
302                 case md_elements:
303                         add(MenuItem(MenuItem::Elements));
304                         break;
305
306                 case md_documents:
307                         add(MenuItem(MenuItem::Documents));
308                         break;
309
310                 case md_bookmarks:
311                         add(MenuItem(MenuItem::Bookmarks));
312                         break;
313
314                 case md_toc:
315                         add(MenuItem(MenuItem::Toc));
316                         break;
317
318                 case md_viewformats:
319                         add(MenuItem(MenuItem::ViewFormats));
320                         break;
321
322                 case md_updateformats:
323                         add(MenuItem(MenuItem::UpdateFormats));
324                         break;
325
326                 case md_exportformats:
327                         add(MenuItem(MenuItem::ExportFormats));
328                         break;
329
330                 case md_importformats:
331                         add(MenuItem(MenuItem::ImportFormats));
332                         break;
333
334                 case md_floatlistinsert:
335                         add(MenuItem(MenuItem::FloatListInsert));
336                         break;
337
338                 case md_floatinsert:
339                         add(MenuItem(MenuItem::FloatInsert));
340                         break;
341
342                 case md_pasterecent:
343                         add(MenuItem(MenuItem::PasteRecent));
344                         break;
345
346                 case md_toolbars:
347                         add(MenuItem(MenuItem::Toolbars));
348                         break;
349
350                 case md_branches:
351                         add(MenuItem(MenuItem::Branches));
352                         break;
353
354                 case md_optsubmenu:
355                         optional = true;
356                         // fallback to md_submenu
357                 case md_submenu: {
358                         lex.next(true);
359                         docstring const mlabel = translateIfPossible(lex.getDocString());
360                         lex.next(true);
361                         docstring const mname = lex.getDocString();
362                         add(MenuItem(MenuItem::Submenu, mlabel, mname,
363                                      optional));
364                         optional = false;
365                         break;
366                 }
367
368                 case md_endmenu:
369                         quit = true;
370                         break;
371
372                 default:
373                         lex.printError("Menu::read: "
374                                        "Unknown menu tag: `$$Token'");
375                         break;
376                 }
377         }
378         lex.popTable();
379         return *this;
380 }
381
382
383 MenuItem const & Menu::operator[](size_type i) const
384 {
385         return items_[i];
386 }
387
388
389 bool Menu::hasFunc(FuncRequest const & func) const
390 {
391         return find_if(begin(), end(),
392                        bind(std::equal_to<FuncRequest>(),
393                             bind(&MenuItem::func, _1),
394                             func)) != end();
395 }
396
397 void Menu::checkShortcuts() const
398 {
399         // This is a quadratic algorithm, but we do not care because
400         // menus are short enough
401         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
402                 docstring shortcut = it1->shortcut();
403                 if (shortcut.empty())
404                         continue;
405                 if (!contains(it1->label(), shortcut))
406                         lyxerr << "Menu warning: menu entry \""
407                                << to_utf8(it1->label())
408                                << "\" does not contain shortcut `"
409                                << to_utf8(shortcut) << "'." << endl;
410                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
411                         if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
412                                 lyxerr << "Menu warning: menu entries "
413                                        << '"' << to_utf8(it1->fulllabel())
414                                        << "\" and \"" << to_utf8(it2->fulllabel())
415                                        << "\" share the same shortcut."
416                                        << endl;
417                         }
418                 }
419         }
420 }
421
422
423 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names)
424 {
425         const_iterator m = begin();
426         const_iterator m_end = end();
427         for (; m != m_end; ++m) {
428                 if (m->kind() == MenuItem::Command && m->func() == func) {
429                         names.push(m->label());
430                         return true;
431                 } else if (m->kind() == MenuItem::Submenu) {
432                         names.push(m->label());
433                         Menu submenu = menubackend.getMenu(m->submenuname());
434                         if (submenu.searchFunc(func, names))
435                                 return true;
436                         else
437                                 names.pop();
438                 }
439         }
440         return false;
441 }
442
443
444 void MenuBackend::specialMenu(Menu const & menu)
445 {
446         specialmenu_ = menu;
447 }
448
449
450 namespace {
451
452 class compare_format {
453 public:
454         bool operator()(Format const * p1, Format const * p2) {
455                 return *p1 < *p2;
456         }
457 };
458
459 docstring const limit_string_length(docstring const & str)
460 {
461         docstring::size_type const max_item_length = 45;
462
463         if (str.size() > max_item_length)
464                 return str.substr(0, max_item_length - 3) + "...";
465         else
466                 return str;
467 }
468
469
470 void expandLastfiles(Menu & tomenu)
471 {
472         lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
473         lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
474
475         int ii = 1;
476
477         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
478                 string const file = lfit->absFilename();
479                 docstring const label = convert<docstring>(ii) + ". "
480                         + makeDisplayPath(file, 30)
481                         + char_type('|') + convert<docstring>(ii);
482                 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
483         }
484 }
485
486
487 void expandDocuments(Menu & tomenu)
488 {
489         Buffer * first = theBufferList().first();
490         if (first) {
491                 Buffer * b = first;
492                 int ii = 1;
493                 
494                 // We cannot use a for loop as the buffer list cycles.
495                 do {
496                         docstring label = b->fileName().displayName(20);
497                         if (!b->isClean())
498                                 label = label + "*";
499                         if (ii < 10)
500                                 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
501                         tomenu.add(MenuItem(MenuItem::Command, label,
502                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
503                         
504                         b = theBufferList().next(b);
505                         ++ii;
506                 } while (b != first); 
507         } else {
508                 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
509                            FuncRequest(LFUN_NOACTION)));
510         }
511 }
512
513
514 void expandBookmarks(Menu & tomenu)
515 {
516         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
517
518         for (size_t i = 1; i <= bm.size(); ++i) {
519                 if (bm.isValid(i)) {
520                         docstring const label = convert<docstring>(i) + ". "
521                                 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
522                                 + char_type('|') + convert<docstring>(i);
523                         tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
524                                 convert<docstring>(i))));
525                 }
526         }
527 }
528
529
530 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
531 {
532         if (!buf && kind != MenuItem::ImportFormats) {
533                 tomenu.add(MenuItem(MenuItem::Command,
534                                     _("No Document Open!"),
535                                     FuncRequest(LFUN_NOACTION)));
536                 return;
537         }
538
539         typedef vector<Format const *> Formats;
540         Formats formats;
541         kb_action action;
542
543         switch (kind) {
544         case MenuItem::ImportFormats:
545                 formats = theConverters().importableFormats();
546                 action = LFUN_BUFFER_IMPORT;
547                 break;
548         case MenuItem::ViewFormats:
549                 formats = buf->exportableFormats(true);
550                 action = LFUN_BUFFER_VIEW;
551                 break;
552         case MenuItem::UpdateFormats:
553                 formats = buf->exportableFormats(true);
554                 action = LFUN_BUFFER_UPDATE;
555                 break;
556         default:
557                 formats = buf->exportableFormats(false);
558                 action = LFUN_BUFFER_EXPORT;
559         }
560         sort(formats.begin(), formats.end(), compare_format());
561
562         Formats::const_iterator fit = formats.begin();
563         Formats::const_iterator end = formats.end();
564         for (; fit != end ; ++fit) {
565                 if ((*fit)->dummy())
566                         continue;
567                 docstring label = from_utf8((*fit)->prettyname());
568
569                 switch (kind) {
570                 case MenuItem::ImportFormats:
571                         // FIXME: This is a hack, we should rather solve
572                         // FIXME: bug 2488 instead.
573                         if ((*fit)->name() == "text")
574                                 label = _("Plain Text");
575                         else if ((*fit)->name() == "textparagraph")
576                                 label = _("Plain Text, Join Lines");
577                         label += "...";
578                         break;
579                 case MenuItem::ViewFormats:
580                 case MenuItem::ExportFormats:
581                 case MenuItem::UpdateFormats:
582                         if (!(*fit)->documentFormat())
583                                 continue;
584                         break;
585                 default:
586                         BOOST_ASSERT(false);
587                         break;
588                 }
589                 if (!(*fit)->shortcut().empty())
590                         label += char_type('|') + from_utf8((*fit)->shortcut());
591
592                 if (buf)
593                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
594                                 FuncRequest(action, (*fit)->name())));
595                 else
596                         tomenu.add(MenuItem(MenuItem::Command, label,
597                                 FuncRequest(action, (*fit)->name())));
598         }
599 }
600
601
602 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
603 {
604         if (!buf) {
605                 tomenu.add(MenuItem(MenuItem::Command,
606                                     _("No Document Open!"),
607                                     FuncRequest(LFUN_NOACTION)));
608                 return;
609         }
610
611         FloatList const & floats =
612                 buf->params().getTextClass().floats();
613         FloatList::const_iterator cit = floats.begin();
614         FloatList::const_iterator end = floats.end();
615         for (; cit != end; ++cit) {
616                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
617                                     _(cit->second.listName()),
618                                     FuncRequest(LFUN_FLOAT_LIST,
619                                                 cit->second.type())));
620         }
621 }
622
623
624 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
625 {
626         if (!buf) {
627                 tomenu.add(MenuItem(MenuItem::Command,
628                                     _("No Document Open!"),
629                                     FuncRequest(LFUN_NOACTION)));
630                 return;
631         }
632
633         FloatList const & floats =
634                 buf->params().getTextClass().floats();
635         FloatList::const_iterator cit = floats.begin();
636         FloatList::const_iterator end = floats.end();
637         for (; cit != end; ++cit) {
638                 // normal float
639                 docstring const label = _(cit->second.name());
640                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
641                                     FuncRequest(LFUN_FLOAT_INSERT,
642                                                 cit->second.type())));
643         }
644 }
645
646
647 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
648 {
649         if (!buf) {
650                 tomenu.add(MenuItem(MenuItem::Command,
651                                     _("No Document Open!"),
652                                     FuncRequest(LFUN_NOACTION)));
653                 return;
654         }
655         InsetLayouts const & insetlayouts =
656                 buf->params().getTextClass().insetlayouts();
657         InsetLayouts::const_iterator cit = insetlayouts.begin();
658         InsetLayouts::const_iterator end = insetlayouts.end();
659         for (; cit != end; ++cit) {
660                 docstring const label = cit->first;
661                 if (cit->second.lyxtype == s)
662                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, 
663                                 label, FuncRequest(LFUN_FLEX_INSERT,
664                                                 label)));
665         }
666 }
667
668
669 Menu::size_type const max_number_of_items = 25;
670
671 void expandToc2(Menu & tomenu,
672                 Toc const & toc_list,
673                 Toc::size_type from,
674                 Toc::size_type to, int depth)
675 {
676         int shortcut_count = 0;
677
678         // check whether depth is smaller than the smallest depth in toc.
679         int min_depth = 1000;
680         for (Toc::size_type i = from; i < to; ++i)
681                 min_depth = std::min(min_depth, toc_list[i].depth());
682         if (min_depth > depth)
683                 depth = min_depth;
684
685
686         if (to - from <= max_number_of_items) {
687                 for (Toc::size_type i = from; i < to; ++i) {
688                         docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
689                         label += limit_string_length(toc_list[i].str());
690                         if (toc_list[i].depth() == depth
691                             && shortcut_count < 9) {
692                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
693                                         label += char_type('|') + convert<docstring>(++shortcut_count);
694                         }
695                         tomenu.add(MenuItem(MenuItem::Command, label,
696                                             FuncRequest(toc_list[i].action())));
697                 }
698         } else {
699                 Toc::size_type pos = from;
700                 while (pos < to) {
701                         Toc::size_type new_pos = pos + 1;
702                         while (new_pos < to &&
703                                toc_list[new_pos].depth() > depth)
704                                 ++new_pos;
705
706                         docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
707                         label += limit_string_length(toc_list[pos].str());
708                         if (toc_list[pos].depth() == depth &&
709                             shortcut_count < 9) {
710                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
711                                         label += char_type('|') + convert<docstring>(++shortcut_count);
712                         }
713                         if (new_pos == pos + 1) {
714                                 tomenu.add(MenuItem(MenuItem::Command,
715                                                     label, FuncRequest(toc_list[pos].action())));
716                         } else {
717                                 MenuItem item(MenuItem::Submenu, label);
718                                 item.submenu(new Menu);
719                                 expandToc2(*item.submenu(),
720                                            toc_list, pos, new_pos, depth + 1);
721                                 tomenu.add(item);
722                         }
723                         pos = new_pos;
724                 }
725         }
726 }
727
728
729 void expandToc(Menu & tomenu, Buffer const * buf)
730 {
731         // To make things very cleanly, we would have to pass buf to
732         // all MenuItem constructors and to expandToc2. However, we
733         // know that all the entries in a TOC will be have status_ ==
734         // OK, so we avoid this unnecessary overhead (JMarc)
735
736         if (!buf) {
737                 tomenu.add(MenuItem(MenuItem::Command,
738                                     _("No Document Open!"),
739                                     FuncRequest(LFUN_NOACTION)));
740                 return;
741         }
742
743         Buffer* cbuf = const_cast<Buffer*>(buf);
744         cbuf->tocBackend().update();
745         cbuf->structureChanged();
746
747         // Add an entry for the master doc if this is a child doc
748         Buffer const * const master = buf->masterBuffer();
749         if (buf != master) {
750                 ParIterator const pit = par_iterator_begin(master->inset());
751                 string const arg = convert<string>(pit->id());
752                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
753                 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
754         }
755
756         FloatList const & floatlist = buf->params().getTextClass().floats();
757         TocList const & toc_list = buf->tocBackend().tocs();
758         TocList::const_iterator cit = toc_list.begin();
759         TocList::const_iterator end = toc_list.end();
760         for (; cit != end; ++cit) {
761                 // Handle this later
762                 if (cit->first == "tableofcontents")
763                         continue;
764
765                 // All the rest is for floats
766                 auto_ptr<Menu> menu(new Menu);
767                 TocIterator ccit = cit->second.begin();
768                 TocIterator eend = cit->second.end();
769                 for (; ccit != eend; ++ccit) {
770                         docstring const label = limit_string_length(ccit->str());
771                         menu->add(MenuItem(MenuItem::Command,
772                                            label,
773                                            FuncRequest(ccit->action())));
774                 }
775                 string const & floatName = floatlist.getType(cit->first).listName();
776                 docstring label;
777                 if (!floatName.empty())
778                         label = _(floatName);
779                 // BUG3633: listings is not a proper float so its name
780                 // is not shown in floatlist.
781                 else if (cit->first == "listing")
782                         label = _("List of listings");
783                 // this should not happen now, but if something else like
784                 // listings is added later, this can avoid an empty menu name.
785                 else
786                         label = _("Other floats");
787                 MenuItem item(MenuItem::Submenu, label);
788                 item.submenu(menu.release());
789                 tomenu.add(item);
790         }
791
792         // Handle normal TOC
793         cit = toc_list.find("tableofcontents");
794         if (cit == end) {
795                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
796                                     _("No Table of contents"),
797                                     FuncRequest()));
798         } else {
799                 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
800         }
801 }
802
803
804 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
805 {
806         if (!buf)
807                 return;
808
809         vector<docstring> const sel =
810                 cap::availableSelections(*buf);
811
812         vector<docstring>::const_iterator cit = sel.begin();
813         vector<docstring>::const_iterator end = sel.end();
814
815         for (unsigned int index = 0; cit != end; ++cit, ++index) {
816                 tomenu.add(MenuItem(MenuItem::Command, *cit,
817                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
818         }
819 }
820
821
822 void expandToolbars(Menu & tomenu)
823 {
824         //
825         // extracts the toolbars from the backend
826         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
827         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
828
829         for (; cit != end; ++cit) {
830                 docstring label = _(cit->gui_name);
831                 // frontends are not supposed to turn on/off toolbars,
832                 // if they cannot update ToolbarBackend::flags. That
833                 // is to say, ToolbarsBackend::flags should reflect
834                 // the true state of toolbars.
835                 //
836                 // menu is displayed as
837                 //       on/off review
838                 // and
839                 //              review (auto)
840                 // in the case of auto.
841                 if (cit->flags & ToolbarInfo::AUTO)
842                         label += _(" (auto)");
843                 tomenu.add(MenuItem(MenuItem::Command, label,
844                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
845         }
846 }
847
848
849 void expandBranches(Menu & tomenu, Buffer const * buf)
850 {
851         if (!buf) {
852                 tomenu.add(MenuItem(MenuItem::Command,
853                                     _("No Document Open!"),
854                                     FuncRequest(LFUN_NOACTION)));
855                 return;
856         }
857
858         BufferParams const & params = buf->masterBuffer()->params();
859         if (params.branchlist().empty()) {
860                 tomenu.add(MenuItem(MenuItem::Command,
861                                     _("No Branch in Document!"),
862                                     FuncRequest(LFUN_NOACTION)));
863                 return;
864         }
865
866         BranchList::const_iterator cit = params.branchlist().begin();
867         BranchList::const_iterator end = params.branchlist().end();
868
869         for (int ii = 1; cit != end; ++cit, ++ii) {
870                 docstring label = cit->getBranch();
871                 if (ii < 10)
872                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
873                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
874                                     FuncRequest(LFUN_BRANCH_INSERT,
875                                                 cit->getBranch())));
876         }
877 }
878
879
880 } // namespace anon
881
882
883 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
884                          Buffer const * buf) const
885 {
886         if (!tomenu.empty())
887                 tomenu.clear();
888
889         for (Menu::const_iterator cit = frommenu.begin();
890              cit != frommenu.end() ; ++cit) {
891                 switch (cit->kind()) {
892                 case MenuItem::Lastfiles:
893                         expandLastfiles(tomenu);
894                         break;
895
896                 case MenuItem::Documents:
897                         expandDocuments(tomenu);
898                         break;
899
900                 case MenuItem::Bookmarks:
901                         expandBookmarks(tomenu);
902                         break;
903
904                 case MenuItem::ImportFormats:
905                 case MenuItem::ViewFormats:
906                 case MenuItem::UpdateFormats:
907                 case MenuItem::ExportFormats:
908                         expandFormats(cit->kind(), tomenu, buf);
909                         break;
910
911                 case MenuItem::CharStyles:
912                         expandFlexInsert(tomenu, buf, "charstyle");
913                         break;
914
915                 case MenuItem::Custom:
916                         expandFlexInsert(tomenu, buf, "custom");
917                         break;
918
919                 case MenuItem::Elements:
920                         expandFlexInsert(tomenu, buf, "element");
921                         break;
922
923                 case MenuItem::FloatListInsert:
924                         expandFloatListInsert(tomenu, buf);
925                         break;
926
927                 case MenuItem::FloatInsert:
928                         expandFloatInsert(tomenu, buf);
929                         break;
930
931                 case MenuItem::PasteRecent:
932                         expandPasteRecent(tomenu, buf);
933                         break;
934
935                 case MenuItem::Toolbars:
936                         expandToolbars(tomenu);
937                         break;
938
939                 case MenuItem::Branches:
940                         expandBranches(tomenu, buf);
941                         break;
942
943                 case MenuItem::Toc:
944                         expandToc(tomenu, buf);
945                         break;
946
947                 case MenuItem::Submenu: {
948                         MenuItem item(*cit);
949                         item.submenu(new Menu(cit->submenuname()));
950                         expand(getMenu(cit->submenuname()),
951                                *item.submenu(), buf);
952                         tomenu.addWithStatusCheck(item);
953                 }
954                 break;
955
956                 case MenuItem::Separator:
957                         tomenu.addWithStatusCheck(*cit);
958                         break;
959
960                 case MenuItem::Command:
961                         if (!specialmenu_.hasFunc(cit->func()))
962                                 tomenu.addWithStatusCheck(*cit);
963                 }
964         }
965
966         // we do not want the menu to end with a separator
967         if (!tomenu.empty()
968             && tomenu.items_.back().kind() == MenuItem::Separator)
969                 tomenu.items_.pop_back();
970
971         // Check whether the shortcuts are unique
972         tomenu.checkShortcuts();
973 }
974
975
976 void MenuBackend::read(Lexer & lex)
977 {
978         enum Menutags {
979                 md_menu = 1,
980                 md_menubar,
981                 md_endmenuset,
982                 md_last
983         };
984
985         struct keyword_item menutags[md_last - 1] = {
986                 { "end", md_endmenuset },
987                 { "menu", md_menu },
988                 { "menubar", md_menubar }
989         };
990
991         //consistency check
992         if (compare_ascii_no_case(lex.getString(), "menuset")) {
993                 lyxerr << "Menubackend::read: ERROR wrong token:`"
994                        << lex.getString() << '\'' << endl;
995         }
996
997         lex.pushTable(menutags, md_last - 1);
998         if (lyxerr.debugging(Debug::PARSER))
999                 lex.printTable(lyxerr);
1000
1001         bool quit = false;
1002
1003         while (lex.isOK() && !quit) {
1004                 switch (lex.lex()) {
1005                 case md_menubar:
1006                         menubar_.read(lex);
1007                         break;
1008                 case md_menu: {
1009                         lex.next(true);
1010                         docstring const name = lex.getDocString();
1011                         if (hasMenu(name)) {
1012                                 getMenu(name).read(lex);
1013                         } else {
1014                                 Menu menu(name);
1015                                 menu.read(lex);
1016                                 add(menu);
1017                         }
1018                         break;
1019                 }
1020                 case md_endmenuset:
1021                         quit = true;
1022                         break;
1023                 default:
1024                         lex.printError("menubackend::read: "
1025                                        "Unknown menu tag: `$$Token'");
1026                         break;
1027                 }
1028         }
1029         lex.popTable();
1030 }
1031
1032
1033 void MenuBackend::add(Menu const & menu)
1034 {
1035         menulist_.push_back(menu);
1036 }
1037
1038
1039 bool MenuBackend::hasMenu(docstring const & name) const
1040 {
1041         return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1042 }
1043
1044
1045 Menu const & MenuBackend::getMenu(docstring const & name) const
1046 {
1047         const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1048         if (cit == end())
1049                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1050         BOOST_ASSERT(cit != end());
1051         return (*cit);
1052 }
1053
1054
1055 Menu & MenuBackend::getMenu(docstring const & name)
1056 {
1057         iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1058         if (it == end())
1059                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1060         BOOST_ASSERT(it != end());
1061         return (*it);
1062 }
1063
1064
1065 Menu const & MenuBackend::getMenubar() const
1066 {
1067         return menubar_;
1068 }
1069
1070
1071 } // namespace lyx