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