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