3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Asger Alstrup
8 * \author Lars Gullik Bjønnes
9 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Martin Vermeer
14 * Full author contact details are available in file CREDITS.
22 #include "GuiApplication.h"
24 #include "GuiWorkArea.h"
25 #include "qt_helpers.h"
27 #include "BiblioInfo.h"
28 #include "BranchList.h"
30 #include "BufferList.h"
31 #include "BufferParams.h"
32 #include "BufferView.h"
33 #include "Converter.h"
35 #include "CutAndPaste.h"
37 #include "FloatList.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "IndicesList.h"
46 #include "LyXAction.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
54 #include "SpellChecker.h"
55 #include "TextClass.h"
57 #include "TocBackend.h"
59 #include "WordLangTuple.h"
61 #include "insets/Inset.h"
62 #include "insets/InsetCitation.h"
63 #include "insets/InsetGraphics.h"
64 #include "insets/InsetInfo.h"
65 #include "insets/InsetQuotes.h"
67 #include "support/lassert.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/docstring_list.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
80 #if QT_VERSION >= 0x040600
81 #include <QProxyStyle>
89 using namespace lyx::support;
97 // MacOSX specific stuff is at the end.
104 /// The type of elements that can be in a menu
112 /** This type of item explains why something is unavailable. If this
113 menuitem is in a submenu, the submenu is enabled to make sure the
114 user sees the information. */
116 /** This type of item merely shows that there might be a list or
117 something alike at this position, but the list is still empty.
118 If this item is in a submenu, the submenu will not always be
121 /** This is the list of last opened file,
122 typically for the File menu. */
124 /** This is the list of opened Documents,
125 typically for the Documents menu. */
127 /** This is the bookmarks */
131 /** This is a list of viewable formats
132 typically for the File->View menu. */
134 /** This is a list of updatable formats
135 typically for the File->Update menu. */
137 /** This is a list of exportable formats
138 typically for the File->Export menu. */
140 /** This exports the document default format
141 typically for the File->Export menu. */
143 /** This is a list of importable formats
144 typically for the File->Import menu. */
146 /** This is the list of elements available
147 * for insertion into document. */
149 /** This is the list of user-configurable
150 insets to insert into document */
152 /** This is the list of floats that we can
153 insert a list for. */
155 /** This is the list of floats that we can
158 /** This is the list of selections that can
163 /** Available branches in document */
165 /** Available indices in document */
167 /** Context menu for indices in document */
169 /** Available index lists in document */
171 /** Context menu for available indices lists in document */
173 /** Available citation styles for a given citation */
175 /** Available arguments for a given info inset */
177 /** Available graphics groups */
179 /// Words suggested by the spellchecker.
181 /** Used Languages */
183 /** This is the list of arguments available
184 for insertion into the current layout. */
186 /** This is the list of arguments available
187 in the InsetArgument context menu. */
189 /** This is the list of captions available
190 in the current layout. */
192 /** This is the list of captions available
193 in the InsetCaption context menu. */
195 /** Commands to separate environments. */
196 EnvironmentSeparators,
197 /** Commands to separate environments (context menu version). */
198 EnvironmentSeparatorsContext,
199 /** This is the list of quotation marks available */
201 /** Options in the Zoom menu **/
205 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
208 QString const & label,
209 QString const & submenu = QString(),
210 QString const & tooltip = QString(),
211 bool optional = false)
212 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
213 submenuname_(submenu), tooltip_(tooltip), optional_(optional)
215 LATTEST(kind == Submenu || kind == Help || kind == Info);
219 QString const & label,
220 FuncRequest const & func,
221 QString const & tooltip = QString(),
222 bool optional = false,
223 FuncRequest::Origin origin = FuncRequest::MENU)
224 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
225 tooltip_(tooltip), optional_(optional)
227 func_->setOrigin(origin);
230 /// The label of a given menuitem
231 QString label() const
233 int const index = label_.lastIndexOf('|');
234 return index == -1 ? label_ : label_.left(index);
237 /// The keyboard shortcut (usually underlined in the entry)
238 QString shortcut() const
240 int const index = label_.lastIndexOf('|');
241 return index == -1 ? QString() : label_.mid(index + 1);
243 /// The complete label, with label and shortcut separated by a '|'
244 QString fulllabel() const { return label_; }
245 /// The kind of entry
246 Kind kind() const { return kind_; }
247 /// the action (if relevant)
248 shared_ptr<FuncRequest const> func() const { return func_; }
250 QString const & tooltip() const { return tooltip_; }
251 /// returns true if the entry should be omitted when disabled
252 bool optional() const { return optional_; }
253 /// returns the status of the lfun associated with this entry
254 FuncStatus const & status() const { return status_; }
255 /// returns the status of the lfun associated with this entry
256 FuncStatus & status() { return status_; }
257 /// returns the status of the lfun associated with this entry
258 void status(FuncStatus const & status) { status_ = status; }
260 ///returns the binding associated to this action.
261 QString binding() const
263 if (kind_ != Command)
265 // Get the keys bound to this action, but keep only the
267 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
268 if (!bindings.empty())
269 return toqstr(bindings.begin()->print(KeySequence::ForGui));
271 LYXERR(Debug::KBMAP, "No binding for "
272 << lyxaction.getActionName(func_->action())
273 << '(' << func_->argument() << ')');
277 /// the description of the submenu (if relevant)
278 QString const & submenuname() const { return submenuname_; }
279 /// set the description of the submenu
280 void submenuname(QString const & name) { submenuname_ = name; }
282 bool hasSubmenu() const { return !submenu_.isEmpty(); }
284 MenuDefinition const & submenu() const { return submenu_.at(0); }
285 MenuDefinition & submenu() { return submenu_[0]; }
287 void setSubmenu(MenuDefinition const & menu)
290 submenu_.append(menu);
299 shared_ptr<FuncRequest> func_;// non-null
301 QString submenuname_;
308 /// contains 0 or 1 item.
309 QList<MenuDefinition> submenu_;
313 class MenuDefinition {
316 typedef std::vector<MenuItem> ItemList;
318 typedef ItemList::const_iterator const_iterator;
320 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
325 QString const & name() const { return name_; }
327 bool empty() const { return items_.empty(); }
328 /// Clear the menu content.
329 void clear() { items_.clear(); }
331 size_t size() const { return items_.size(); }
333 const_iterator begin() const { return items_.begin(); }
335 const_iterator end() const { return items_.end(); }
337 void cat(MenuDefinition const & other);
339 void catSub(docstring const & name);
341 // search for func in this menu iteratively, and put menu
343 bool searchMenu(FuncRequest const & func, docstring_list & names)
346 bool hasFunc(FuncRequest const &) const;
347 /// Add the menu item unconditionally
348 void add(MenuItem const & item) { items_.push_back(item); }
349 /// Checks the associated FuncRequest status before adding the
351 void addWithStatusCheck(MenuItem const &);
352 // Check whether the menu shortcuts are unique
353 void checkShortcuts() const;
355 void expandLastfiles();
356 void expandDocuments();
357 void expandBookmarks();
358 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
359 void expandFloatListInsert(Buffer const * buf);
360 void expandFloatInsert(Buffer const * buf);
361 void expandFlexInsert(Buffer const * buf, InsetLyXType type);
362 void expandTocSubmenu(std::string const & type, Toc const & toc_list);
363 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, const string & toc_type);
364 void expandToc(Buffer const * buf);
365 void expandPasteRecent(Buffer const * buf);
366 void expandToolbars();
367 void expandBranches(Buffer const * buf);
368 void expandIndices(Buffer const * buf, bool listof = false);
369 void expandIndicesContext(Buffer const * buf, bool listof = false);
370 void expandCiteStyles(BufferView const *);
371 void expandInfoArguments(BufferView const *);
372 void expandGraphicsGroups(BufferView const *);
373 void expandSpellingSuggestions(BufferView const *);
374 void expandLanguageSelector(Buffer const * buf);
375 void expandArguments(BufferView const *, bool switcharg = false);
376 void expandCaptions(Buffer const * buf, bool switchcap = false);
377 void expandEnvironmentSeparators(BufferView const *, bool contextmenu = false);
378 void expandQuotes(BufferView const *);
379 void expandZoomOptions(BufferView const *);
387 /// Helper for std::find_if
391 MenuNamesEqual(QString const & name) : name_(name) {}
392 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
399 typedef std::vector<MenuDefinition> MenuList;
401 typedef MenuList::const_iterator const_iterator;
403 typedef MenuList::iterator iterator;
405 /////////////////////////////////////////////////////////////////////
406 // MenuDefinition implementation
407 /////////////////////////////////////////////////////////////////////
409 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
413 case MenuItem::Command: {
414 FuncStatus status = lyx::getStatus(*i.func());
415 if (status.unknown() || (!status.enabled() && i.optional()))
418 items_.back().status(status);
422 case MenuItem::Submenu: {
423 bool enabled = false;
424 if (i.hasSubmenu()) {
425 for (const_iterator cit = i.submenu().begin();
426 cit != i.submenu().end(); ++cit) {
427 // Only these kind of items affect the status of the submenu
428 if ((cit->kind() == MenuItem::Command
429 || cit->kind() == MenuItem::Submenu
430 || cit->kind() == MenuItem::Help)
431 && cit->status().enabled()) {
437 if (enabled || !i.optional()) {
439 items_.back().status().setEnabled(enabled);
444 case MenuItem::Separator:
445 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
455 void MenuDefinition::read(Lexer & lex)
472 md_indiceslistscontext,
487 md_spellingsuggestions,
494 md_env_separatorscontext,
499 LexerKeyword menutags[] = {
500 { "arguments", md_arguments },
501 { "bookmarks", md_bookmarks },
502 { "branches", md_branches },
503 { "captions", md_captions },
504 { "charstyles", md_charstyles },
505 { "citestyles", md_citestyles },
506 { "custom", md_custom },
507 { "documents", md_documents },
508 { "end", md_endmenu },
509 { "environmentseparators", md_env_separators },
510 { "environmentseparatorscontext", md_env_separatorscontext },
511 { "exportformat", md_exportformat },
512 { "exportformats", md_exportformats },
513 { "floatinsert", md_floatinsert },
514 { "floatlistinsert", md_floatlistinsert },
515 { "graphicsgroups", md_graphicsgroups },
516 { "importformats", md_importformats },
517 { "indices", md_indices },
518 { "indicescontext", md_indicescontext },
519 { "indiceslists", md_indiceslists },
520 { "indiceslistscontext", md_indiceslistscontext },
521 { "infoarguments", md_infoarguments },
523 { "languageselector", md_languageselector },
524 { "lastfiles", md_lastfiles },
525 { "optitem", md_optitem },
526 { "optsubmenu", md_optsubmenu },
527 { "pasterecent", md_pasterecent },
528 { "separator", md_separator },
529 { "spellingsuggestions", md_spellingsuggestions },
530 { "submenu", md_submenu },
531 { "switcharguments", md_switcharguments },
532 { "switchcaptions", md_switchcaptions },
533 { "switchquotes", md_switchquotes },
535 { "toolbars", md_toolbars },
536 { "updateformats", md_updateformats },
537 { "viewformats", md_viewformats },
538 { "zoomoptions", md_zoomoptions }
541 lex.pushTable(menutags);
542 lex.setContext("MenuDefinition::read: ");
545 while (lex.isOK() && md_type != md_endmenu) {
546 switch (md_type = lex.lex()) {
550 docstring const name = translateIfPossible(lex.getDocString());
552 string const command = lex.getString();
553 FuncRequest func = lyxaction.lookupFunc(command);
554 FuncRequest::Origin origin = FuncRequest::MENU;
555 if (name_.startsWith("context-toc-"))
556 origin = FuncRequest::TOC;
557 bool const optional = (md_type == md_optitem);
558 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
563 add(MenuItem(MenuItem::Separator));
567 add(MenuItem(MenuItem::Lastfiles));
571 add(MenuItem(MenuItem::CharStyles));
575 add(MenuItem(MenuItem::Custom));
579 add(MenuItem(MenuItem::Documents));
583 add(MenuItem(MenuItem::Bookmarks));
587 add(MenuItem(MenuItem::Toc));
591 add(MenuItem(MenuItem::ViewFormats));
594 case md_updateformats:
595 add(MenuItem(MenuItem::UpdateFormats));
598 case md_exportformats:
599 add(MenuItem(MenuItem::ExportFormats));
602 case md_exportformat:
603 add(MenuItem(MenuItem::ExportFormat));
606 case md_importformats:
607 add(MenuItem(MenuItem::ImportFormats));
610 case md_floatlistinsert:
611 add(MenuItem(MenuItem::FloatListInsert));
615 add(MenuItem(MenuItem::FloatInsert));
619 add(MenuItem(MenuItem::PasteRecent));
623 add(MenuItem(MenuItem::Toolbars));
627 add(MenuItem(MenuItem::Branches));
631 add(MenuItem(MenuItem::CiteStyles));
634 case md_infoarguments:
635 add(MenuItem(MenuItem::InfoArguments));
639 case md_graphicsgroups:
640 add(MenuItem(MenuItem::GraphicsGroups));
643 case md_spellingsuggestions:
644 add(MenuItem(MenuItem::SpellingSuggestions));
647 case md_languageselector:
648 add(MenuItem(MenuItem::LanguageSelector));
652 add(MenuItem(MenuItem::Indices));
655 case md_indicescontext:
656 add(MenuItem(MenuItem::IndicesContext));
659 case md_indiceslists:
660 add(MenuItem(MenuItem::IndicesLists));
663 case md_indiceslistscontext:
664 add(MenuItem(MenuItem::IndicesListsContext));
668 add(MenuItem(MenuItem::Arguments));
671 case md_switcharguments:
672 add(MenuItem(MenuItem::SwitchArguments));
676 add(MenuItem(MenuItem::Captions));
679 case md_switchcaptions:
680 add(MenuItem(MenuItem::SwitchCaptions));
683 case md_env_separators:
684 add(MenuItem(MenuItem::EnvironmentSeparators));
687 case md_env_separatorscontext:
688 add(MenuItem(MenuItem::EnvironmentSeparatorsContext));
691 case md_switchquotes:
692 add(MenuItem(MenuItem::SwitchQuotes));
696 add(MenuItem(MenuItem::ZoomOptions));
702 docstring const mlabel = translateIfPossible(lex.getDocString());
704 docstring const mname = lex.getDocString();
705 bool const optional = (md_type == md_optsubmenu);
706 add(MenuItem(MenuItem::Submenu,
707 toqstr(mlabel), toqstr(mname), QString(), optional));
715 lex.printError("Unknown menu tag");
723 bool MenuDefinition::hasFunc(FuncRequest const & func) const
725 for (auto const & it : *this)
726 if (*it.func() == func)
732 void MenuDefinition::catSub(docstring const & name)
734 add(MenuItem(MenuItem::Submenu,
735 qt_("More...|M"), toqstr(name), QString(), false));
738 void MenuDefinition::cat(MenuDefinition const & other)
740 const_iterator et = other.end();
741 for (const_iterator it = other.begin(); it != et; ++it)
746 void MenuDefinition::checkShortcuts() const
748 // This is a quadratic algorithm, but we do not care because
749 // menus are short enough
750 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
751 QString shortcut = it1->shortcut();
752 if (shortcut.isEmpty())
754 if (!it1->label().contains(shortcut))
755 LYXERR0("Menu warning: menu entry \""
757 << "\" does not contain shortcut `"
758 << shortcut << "'.");
759 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
760 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
761 LYXERR0("Menu warning: menu entries "
762 << '"' << it1->fulllabel()
763 << "\" and \"" << it2->fulllabel()
764 << "\" share the same shortcut.");
771 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
773 const_iterator m = begin();
774 const_iterator m_end = end();
775 for (; m != m_end; ++m) {
776 if (m->kind() == MenuItem::Command && *m->func() == func) {
777 names.push_back(qstring_to_ucs4(m->label()));
780 if (m->kind() == MenuItem::Submenu) {
781 names.push_back(qstring_to_ucs4(m->label()));
782 if (!m->hasSubmenu()) {
783 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
784 << m->label() << " name=" << m->submenuname());
788 if (m->submenu().searchMenu(func, names))
797 QString limitStringLength(docstring const & str)
799 size_t const max_item_length = 45;
800 docstring ret = str.substr(0, max_item_length + 1);
801 support::truncateWithEllipsis(ret, max_item_length);
806 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
811 graphics::getGraphicsGroups(bv->buffer(), grp);
815 set<string>::const_iterator it = grp.begin();
816 set<string>::const_iterator end = grp.end();
817 add(MenuItem(MenuItem::Command, qt_("No Group"),
818 FuncRequest(LFUN_GRAPHICS_SET_GROUP)));
819 for (; it != end; ++it) {
820 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
821 FuncRequest(LFUN_GRAPHICS_SET_GROUP, *it)));
826 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
830 Cursor const & cur = bv->cursor();
834 docstring_list suggestions;
835 Paragraph const & par = cur.paragraph();
836 pos_type from = cur.pos();
838 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
840 case SpellChecker::UNKNOWN_WORD:
841 if (lyxrc.spellcheck_continuously) {
842 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
843 docstring const & selection = cur.selectionAsString(false);
844 if (!cur.selection() || selection == wl.word()) {
846 size_t m = 10; // first submenu index
847 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
848 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
849 for (; i != suggestions.size(); ++i) {
850 docstring const & suggestion = suggestions[i];
851 LYXERR(Debug::GUI, suggestion);
852 MenuItem w(MenuItem::Command, toqstr(suggestion),
853 FuncRequest(LFUN_WORD_REPLACE,
854 replace2string(suggestion, selection,
855 true, // case sensitive
861 false))); // only selection
865 item.submenu().add(w);
870 add(MenuItem(MenuItem::Separator));
871 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
872 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
873 FuncRequest(LFUN_SPELLING_ADD, arg)));
874 add(MenuItem(MenuItem::Command, qt_("Ignore this occurrence|g"),
875 FuncRequest(LFUN_FONT_NO_SPELLCHECK, arg)));
876 add(MenuItem(MenuItem::Command, qt_("Ignore all for this session|I"),
877 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
878 add(MenuItem(MenuItem::Command, qt_("Ignore all in this document|d"),
879 FuncRequest(LFUN_SPELLING_ADD_LOCAL, arg)));
883 case SpellChecker::LEARNED_WORD: {
884 LYXERR(Debug::GUI, "Learned Word.");
885 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
886 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
887 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
890 case SpellChecker::DOCUMENT_LEARNED_WORD: {
891 LYXERR(Debug::GUI, "Document-Learned Word.");
892 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
893 add(MenuItem(MenuItem::Command, qt_("Remove from document dictionary|r"),
894 FuncRequest(LFUN_SPELLING_REMOVE_LOCAL, arg)));
897 case SpellChecker::NO_DICTIONARY:
898 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
900 case SpellChecker::WORD_OK:
901 case SpellChecker::COMPOUND_WORD:
902 case SpellChecker::ROOT_FOUND:
903 case SpellChecker::IGNORED_WORD:
908 struct sortLanguageByName {
909 bool operator()(const Language * a, const Language * b) const {
910 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
914 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
919 std::set<Language const *> languages_buffer =
920 buf->masterBuffer()->getLanguages();
922 if (languages_buffer.size() < 2) {
923 add(MenuItem(MenuItem::Command, qt_("Switch Language...|L"),
924 FuncRequest(LFUN_DIALOG_SHOW, "character")));
928 std::set<Language const *, sortLanguageByName> langs;
930 std::set<Language const *>::const_iterator const beg =
931 languages_buffer.begin();
932 for (std::set<Language const *>::const_iterator cit = beg;
933 cit != languages_buffer.end(); ++cit) {
937 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
938 item.setSubmenu(MenuDefinition(qt_("Language")));
939 QString morelangs = qt_("More Languages ...|M");
940 QStringList accelerators;
941 if (morelangs.contains('|'))
942 accelerators.append(morelangs.section('|', -1));
943 std::set<Language const *, sortLanguageByName>::const_iterator const begin = langs.begin();
944 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
945 cit != langs.end(); ++cit) {
946 QString label = qt_((*cit)->display());
947 // try to add an accelerator
948 bool success = false;
949 // try capitals first
950 for (int i = 0; i < label.size(); ++i) {
951 QChar const ch = label[i];
954 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
955 label = label + toqstr("|") + ch;
956 accelerators.append(ch);
961 // if all capitals are taken, try the rest
963 for (int i = 0; i < label.size(); ++i) {
964 if (label[i].isSpace())
966 QString const ch = QString(label[i]);
967 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
968 label = label + toqstr("|") + ch;
969 accelerators.append(ch);
974 MenuItem w(MenuItem::Command, label,
975 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
976 item.submenu().addWithStatusCheck(w);
978 item.submenu().add(MenuItem(MenuItem::Separator));
979 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
980 FuncRequest(LFUN_DIALOG_SHOW, "character")));
985 void MenuDefinition::expandLastfiles()
987 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
988 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
992 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
993 string const file = lfit->absFileName();
994 QString const short_path = toqstr(makeDisplayPath(file, 30));
995 QString const long_path = toqstr(makeDisplayPath(file));
998 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
1000 label = QString("%1. %2").arg(ii).arg(short_path);
1001 add(MenuItem(MenuItem::Command, label,
1002 FuncRequest(LFUN_FILE_OPEN, file), long_path));
1007 void MenuDefinition::expandDocuments()
1009 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
1010 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
1012 Buffer * const first = theBufferList().first();
1014 add(MenuItem(MenuItem::Info, qt_("(No Documents Open)")));
1020 if (!guiApp->currentView())
1022 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
1025 Buffer const & b = wa->bufferView().buffer();
1026 QString label = toqstr(b.fileName().displayName(20));
1029 if (b.notifiesExternalModification())
1030 label += QChar(0x26a0); // warning sign ⚠
1032 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1033 add(MenuItem(MenuItem::Command, label,
1034 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1041 // We cannot use a for loop as the buffer list cycles.
1043 if (!(guiApp->currentView()
1044 && guiApp->currentView()->workArea(*b))) {
1045 QString label = toqstr(b->fileName().displayName(20));
1048 if (b->notifiesExternalModification())
1049 label += QChar(0x26a0);
1051 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1052 item.submenu().add(MenuItem(MenuItem::Command, label,
1053 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1056 b = theBufferList().next(b);
1057 } while (b != first);
1059 if (!item.submenu().empty())
1064 void MenuDefinition::expandBookmarks()
1066 lyx::BookmarksSection const & bm = theSession().bookmarks();
1069 for (size_t i = 1; i <= bm.size(); ++i) {
1070 if (bm.isValid(i)) {
1071 string const file = bm.bookmark(i).filename.absFileName();
1072 QString const label = QString("%1. %2|%3").arg(i)
1073 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1074 add(MenuItem(MenuItem::Command, label,
1075 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1080 add(MenuItem(MenuItem::Info, qt_("(No Bookmarks Saved Yet)")));
1084 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1086 if (!buf && kind != MenuItem::ImportFormats)
1090 FuncCode action = LFUN_NOACTION;
1093 case MenuItem::ImportFormats:
1094 formats = theConverters().importableFormats();
1095 action = LFUN_BUFFER_IMPORT;
1097 case MenuItem::ViewFormats:
1098 formats = buf->params().exportableFormats(true);
1099 action = LFUN_BUFFER_VIEW;
1101 case MenuItem::UpdateFormats:
1102 formats = buf->params().exportableFormats(true);
1103 action = LFUN_BUFFER_UPDATE;
1105 case MenuItem::ExportFormats:
1106 formats = buf->params().exportableFormats(false);
1107 action = LFUN_BUFFER_EXPORT;
1114 bool const view_update = (kind == MenuItem::ViewFormats
1115 || kind == MenuItem::UpdateFormats);
1119 smenue = (kind == MenuItem::ViewFormats
1120 ? qt_("View (Other Formats)|F")
1121 : qt_("Update (Other Formats)|p"));
1122 MenuItem item(MenuItem::Submenu, smenue);
1123 item.setSubmenu(MenuDefinition(smenue));
1125 for (Format const * f : formats) {
1129 docstring lab = f->prettyname();
1130 docstring const scut = from_utf8(f->shortcut());
1131 docstring const tmplab = lab;
1134 lab += char_type('|') + scut;
1135 docstring const lab_i18n = translateIfPossible(lab);
1136 docstring const shortcut = split(lab_i18n, lab, '|');
1138 bool const untranslated = (lab == lab_i18n);
1139 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1142 case MenuItem::ImportFormats:
1145 label += from_ascii("...");
1147 case MenuItem::ViewFormats:
1148 case MenuItem::UpdateFormats:
1149 if (f->name() == buf->params().getDefaultOutputFormat()) {
1150 docstring lbl = (kind == MenuItem::ViewFormats
1151 ? bformat(_("View [%1$s]|V"), label)
1152 : bformat(_("Update [%1$s]|U"), label));
1153 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1157 case MenuItem::ExportFormats:
1158 if (!f->inExportMenu())
1162 // we already asserted earlier in this case
1166 if (!shortcut.empty())
1167 label += '|' + shortcut;
1170 // note that at this point, we know that buf is not null
1172 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1173 toqstr(label), FuncRequest(action, f->name())));
1176 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1177 FuncRequest(action, f->name())));
1179 add(MenuItem(MenuItem::Command, toqstr(label),
1180 FuncRequest(action, f->name())));
1188 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1193 FloatList const & floats = buf->params().documentClass().floats();
1194 FloatList::const_iterator cit = floats.begin();
1195 FloatList::const_iterator end = floats.end();
1197 for (; cit != end; ++cit) {
1198 if (!cit->second.usesFloatPkg()) {
1199 // Different floats could declare the same ListCommand. We only
1200 // want it on the list once, though.
1201 string const & list_cmd = cit->second.listCommand();
1202 if (list_cmd.empty())
1203 // we do not know how to generate such a list
1205 // This form of insert returns an iterator pointing to the newly
1206 // inserted element OR the existing element with that value, and
1207 // a bool indicating whether we inserted a new element. So we can
1208 // see if one is there and insert it if not all at once.
1209 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1213 string const & list_name = cit->second.listName();
1214 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1215 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1220 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1225 FloatList const & floats = buf->params().documentClass().floats();
1226 FloatList::const_iterator cit = floats.begin();
1227 FloatList::const_iterator end = floats.end();
1228 for (; cit != end; ++cit) {
1230 if (cit->second.name().empty())
1232 QString const label = qt_(cit->second.name());
1233 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1234 FuncRequest(LFUN_FLOAT_INSERT,
1235 cit->second.floattype())));
1240 void MenuDefinition::expandFlexInsert(
1241 Buffer const * buf, InsetLyXType type)
1246 TextClass::InsetLayouts const & insetLayouts =
1247 buf->params().documentClass().insetLayouts();
1248 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1249 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1250 for (; cit != end; ++cit) {
1251 if (cit->second.lyxtype() == type) {
1252 if (!cit->second.obsoleted_by().empty())
1254 docstring name = cit->first;
1255 // we remove the "Flex:" prefix, if it is present
1256 if (prefixIs(name, from_ascii("Flex:")))
1257 name = name.substr(5);
1258 docstring const label = (cit->second.menustring().empty()) ?
1260 : cit->second.menustring();
1261 addWithStatusCheck(MenuItem(MenuItem::Command,
1262 toqstr(translateIfPossible(label)),
1263 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(name))));
1266 // FIXME This is a little clunky.
1267 if (items_.empty() && type == InsetLyXType::CUSTOM && !buf->hasReadonlyFlag())
1268 add(MenuItem(MenuItem::Help, qt_("(No Custom Insets Defined)")));
1272 // Threshold before we stop displaying sub-items alongside items
1273 // (for display purposes). Ideally this should fit on a screen.
1274 size_t const max_number_of_items = 30;
1275 // Size limit for the menu. This is for performance purposes,
1276 // because qt already displays a scrollable menu when necessary.
1277 // Ideally this should be the menu size from which scrollable
1278 // menus become unpractical.
1279 size_t const menu_size_limit = 80;
1281 void MenuDefinition::expandToc2(Toc const & toc_list,
1282 size_t from, size_t to, int depth,
1283 string const & toc_type)
1285 int shortcut_count = 0;
1287 // check whether depth is smaller than the smallest depth in toc.
1288 int min_depth = 1000;
1289 for (size_t i = from; i < to; ++i)
1290 min_depth = min(min_depth, toc_list[i].depth());
1291 if (min_depth > depth)
1294 if (to - from <= max_number_of_items) {
1295 for (size_t i = from; i < to; ++i) {
1296 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1297 label += limitStringLength(toc_list[i].asString());
1298 if (toc_list[i].depth() == depth) {
1300 if (shortcut_count < 9) {
1301 if (label.contains(QString::number(shortcut_count + 1)))
1302 label += QString::number(++shortcut_count);
1305 add(MenuItem(MenuItem::Command, label, toc_list[i].action()));
1306 // separator after the menu heading
1307 if (toc_list[i].depth() < depth)
1308 add(MenuItem(MenuItem::Separator));
1314 size_t new_pos = pos + 1;
1315 while (new_pos < to && toc_list[new_pos].depth() > depth)
1318 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1319 label += limitStringLength(toc_list[pos].asString());
1320 if (toc_list[pos].depth() == depth) {
1322 if (shortcut_count < 9) {
1323 if (label.contains(QString::number(shortcut_count + 1)))
1324 label += QString::number(++shortcut_count);
1327 if (size >= menu_size_limit) {
1328 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1329 add(MenuItem(MenuItem::Command, "...", f));
1332 if (new_pos == pos + 1) {
1333 add(MenuItem(MenuItem::Command, label, toc_list[pos].action()));
1336 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1337 MenuItem item(MenuItem::Submenu, label);
1338 item.setSubmenu(sub);
1348 void MenuDefinition::expandToc(Buffer const * buf)
1350 // To make things very cleanly, we would have to pass buf to
1351 // all MenuItem constructors and to expandToc2. However, we
1352 // know that all the entries in a TOC will be have status_ ==
1353 // OK, so we avoid this unnecessary overhead (JMarc)
1355 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1358 // Add an entry for the master doc if this is a child doc
1359 Buffer const * const master = buf->masterBuffer();
1360 if (buf != master) {
1361 ParIterator const pit = par_iterator_begin(master->inset());
1362 string const arg = convert<string>(pit->id());
1363 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1364 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1367 MenuDefinition other_lists;
1368 // In the navigation menu, only add tocs from this document
1369 TocBackend const & backend = buf->tocBackend();
1370 TocList const & toc_list = backend.tocs();
1371 for (pair<const string, shared_ptr<Toc>> const & toc : toc_list) {
1372 // Handle table of contents later
1373 if (toc.first == "tableofcontents" || toc.second->empty())
1375 MenuDefinition submenu;
1376 submenu.expandTocSubmenu(toc.first, *toc.second);
1377 docstring const toc_name = backend.outlinerName(toc.first);
1378 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1379 item.setSubmenu(submenu);
1380 // deserves to be in the main menu?
1381 if (!TocBackend::isOther(toc.first))
1384 other_lists.add(item);
1386 if (!other_lists.empty()) {
1387 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1388 item.setSubmenu(other_lists);
1391 // Handle normal TOC
1392 add(MenuItem(MenuItem::Separator));
1393 TocList::const_iterator const cit = toc_list.find("tableofcontents");
1394 if (cit == toc_list.end())
1395 LYXERR(Debug::GUI, "No table of contents.");
1397 if (!cit->second->empty())
1398 expandToc2(*cit->second, 0, cit->second->size(), 0,
1401 add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1406 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1408 // "Open outliner..." entry
1409 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1410 add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1411 add(MenuItem(MenuItem::Separator));
1413 expandToc2(toc, 0, toc.size(), 0, type);
1417 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1419 docstring_list const sel = cap::availableSelections(buf);
1421 docstring_list::const_iterator cit = sel.begin();
1422 docstring_list::const_iterator end = sel.end();
1424 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1425 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1426 FuncRequest(LFUN_PASTE, convert<string>(index))));
1431 void MenuDefinition::expandToolbars()
1433 MenuDefinition other_lists;
1434 // extracts the toolbars from the backend
1435 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1436 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1437 for (; cit != end; ++cit) {
1438 MenuItem item(MenuItem::Command, toqstr(cit->gui_name),
1439 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1440 if (cit->allow_auto) {
1441 MenuDefinition tristate;
1442 tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]On|O"),
1443 FuncRequest(LFUN_TOOLBAR_SET, cit->name + " on")));
1444 tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]Off|f"),
1445 FuncRequest(LFUN_TOOLBAR_SET, cit->name + " off")));
1446 tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]Automatic|A"),
1447 FuncRequest(LFUN_TOOLBAR_SET, cit->name + " auto")));
1448 item = MenuItem(MenuItem::Submenu,toqstr(cit->gui_name));
1449 item.setSubmenu(tristate);
1451 if (guiApp->toolbars().isMainToolbar(cit->name))
1454 other_lists.add(item);
1457 if (!other_lists.empty()) {
1458 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1459 item.setSubmenu(other_lists);
1465 void MenuDefinition::expandBranches(Buffer const * buf)
1467 if (!buf || buf->hasReadonlyFlag())
1470 BranchList const & child_list = buf->params().branchlist();
1471 set<docstring> brset;
1473 for (auto const & b : child_list) {
1474 docstring const & bname = b.branch();
1475 // NUM. Branch Name + "|", which triggers an empty shortcut in
1476 // case that character should be in the branch name.
1477 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1478 // Add NUM as a keyboard shortcut if it's a single digit
1480 label += convert<docstring>(ii);
1482 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1483 FuncRequest(LFUN_BRANCH_INSERT, bname)));
1485 brset.insert(bname);
1489 set<Buffer const *> bufset;
1490 Buffer const * nextbuf = buf->parent();
1491 MenuDefinition master_branches;
1494 // recursive includes are a bad idea, but let's not crash
1496 if (bufset.count(nextbuf))
1499 for (auto const & b : nextbuf->params().branchlist()) {
1500 docstring const & bname = b.branch();
1501 // do not add it if we've already seen it
1502 if (brset.count(bname))
1505 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1507 label += convert<docstring>(ii);
1509 master_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1510 toqstr(label), FuncRequest(LFUN_BRANCH_INSERT, bname)));
1512 bufset.insert(nextbuf);
1513 brset.insert(bname);
1517 nextbuf = nextbuf->parent();
1520 if (!master_branches.empty()) {
1521 MenuItem item(MenuItem::Submenu, qt_("Master Documents"));
1522 item.setSubmenu(master_branches);
1528 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1533 BufferParams const & params = buf->masterBuffer()->params();
1534 if (!params.use_indices) {
1536 addWithStatusCheck(MenuItem(MenuItem::Command,
1537 qt_("Index List|I"),
1538 FuncRequest(LFUN_INDEX_PRINT,
1539 from_ascii("idx"))));
1541 addWithStatusCheck(MenuItem(MenuItem::Command,
1542 qt_("Index Entry|d"),
1543 FuncRequest(LFUN_INDEX_INSERT,
1544 from_ascii("idx"))));
1548 if (params.indiceslist().empty())
1551 IndicesList::const_iterator cit = params.indiceslist().begin();
1552 IndicesList::const_iterator end = params.indiceslist().end();
1554 for (int ii = 1; cit != end; ++cit, ++ii) {
1556 docstring const label =
1557 bformat(_("Index: %1$s"), cit->index());
1558 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1559 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1561 docstring const label =
1562 bformat(_("Index Entry (%1$s)"), cit->index());
1563 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1564 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1570 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1575 BufferParams const & params = buf->masterBuffer()->params();
1576 if (!params.use_indices || params.indiceslist().empty())
1579 IndicesList::const_iterator cit = params.indiceslist().begin();
1580 IndicesList::const_iterator end = params.indiceslist().end();
1582 for (int ii = 1; cit != end; ++cit, ++ii) {
1584 InsetCommandParams p(INDEX_PRINT_CODE);
1585 p["type"] = cit->shortcut();
1586 string const data = InsetCommand::params2string(p);
1587 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1588 FuncRequest(LFUN_INSET_MODIFY, data)));
1590 docstring const label =
1591 bformat(_("Index Entry (%1$s)"), cit->index());
1592 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1593 FuncRequest(LFUN_INSET_MODIFY,
1594 from_ascii("changetype ") + cit->shortcut())));
1600 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1605 Inset const * inset = bv->cursor().nextInset();
1606 if (!inset || inset->lyxCode() != CITE_CODE) {
1607 add(MenuItem(MenuItem::Command,
1608 qt_("No Citation in Scope!"),
1609 FuncRequest(LFUN_NOACTION)));
1612 InsetCitation const * citinset =
1613 static_cast<InsetCitation const *>(inset);
1615 Buffer const * buf = &bv->buffer();
1616 BufferParams const & bp = buf->masterParams();
1617 string const cmd = citinset->params().getCmdName();
1619 docstring const & key = citinset->getParam("key");
1621 add(MenuItem(MenuItem::Command,
1622 qt_("No citations selected!"),
1623 FuncRequest(LFUN_NOACTION)));
1627 bool const force = isUpperCase(cmd[0]);
1628 bool const star = suffixIs(cmd, '*');
1630 vector<docstring> const keys = getVectorFromString(key);
1632 vector<CitationStyle> const citeStyleList = bp.citeStyles();
1634 CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1635 bool const qualified = cs.hasQualifiedList
1637 || !citinset->getParam("pretextlist").empty()
1638 || !citinset->getParam("posttextlist").empty());
1639 vector<pair<docstring, docstring>> pres =
1640 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1641 vector<pair<docstring, docstring>> posts =
1642 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1645 ci.textBefore = citinset->getParam("before");
1646 ci.textAfter = citinset->getParam("after");
1647 ci.forceUpperCase = force;
1649 ci.context = CiteItem::Dialog;
1651 ci.isQualified = qualified;
1653 ci.posttexts = posts;
1654 BiblioInfo::CiteStringMap citeStrings =
1655 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1657 BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1658 BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1660 for (int ii = 1; cit != end; ++cit, ++ii) {
1661 docstring label = cit->second;
1662 CitationStyle ccs = citeStyleList[ii - 1];
1663 ccs.forceUpperCase &= force;
1664 ccs.hasStarredVersion &= star;
1665 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1666 FuncRequest(LFUN_INSET_MODIFY,
1667 "changetype " + from_utf8(citationStyleToString(ccs)))));
1670 if (cs.hasStarredVersion) {
1671 docstring starred = _("All authors|h");
1672 // Check if we have a custom string/tooltip for the starred version
1673 if (!cs.stardesc.empty()) {
1675 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1677 starred = translateIfPossible(from_utf8(val));
1678 // Transform qt-style accelerators to menu-style
1679 int const amps = count_char(starred, '&');
1682 starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1683 size_t nn = starred.find('&');
1684 char_type accel = char_type();
1685 if (nn != docstring::npos && nn < starred.size() - 1)
1686 accel = starred[nn + 1];
1687 starred = subst(starred, from_ascii("&"), from_ascii(""));
1689 starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1690 if (accel != char_type())
1691 starred = starred + '|' + accel;
1694 add(MenuItem(MenuItem::Separator));
1695 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1696 FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1699 if (cs.forceUpperCase) {
1700 if (!cs.hasStarredVersion)
1701 add(MenuItem(MenuItem::Separator));
1702 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1703 FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1708 void MenuDefinition::expandInfoArguments(BufferView const * bv)
1713 Inset const * inset = bv->cursor().nextInset();
1714 if (!inset || inset->lyxCode() != INFO_CODE) {
1715 add(MenuItem(MenuItem::Command,
1716 qt_("No Text Field in Scope!"),
1717 FuncRequest(LFUN_NOACTION)));
1720 InsetInfo const * iinset = static_cast<InsetInfo const *>(inset);
1722 string const type = iinset->params().infoType();
1723 vector<pair<string,docstring>> const args =
1724 iinset->params().getArguments(&bv->buffer(), type);
1726 // Don't generate a menu for big lists (such as lfuns and rcs)
1727 if (args.size() > 15)
1730 for (auto const & p : args) {
1731 if (p.first == "invalid")
1734 if (p.first == "custom") {
1735 add(MenuItem(MenuItem::Command, qt_("Custom..."),
1736 FuncRequest(LFUN_INSET_SETTINGS, "info")));
1739 docstring label = p.second;
1740 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1741 FuncRequest(LFUN_INSET_MODIFY, type + " " + p.first)));
1747 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1752 if (!bv->cursor().inTexted())
1755 Inset const * inset = &bv->cursor().inset();
1756 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1757 if (inset && args.empty())
1758 args = inset->getLayout().args();
1759 if (args.empty() || (switcharg && args.size() == 1))
1761 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1762 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1763 for (; lait != laend; ++lait) {
1764 Layout::latexarg arg = (*lait).second;
1765 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1766 QString item = toqstr(translateIfPossible(str));
1768 add(MenuItem(MenuItem::Command, item,
1769 FuncRequest(LFUN_INSET_MODIFY,
1770 from_ascii("changetype ")
1771 + from_ascii((*lait).first))));
1773 add(MenuItem(MenuItem::Command, item,
1774 FuncRequest(LFUN_ARGUMENT_INSERT,
1775 from_ascii((*lait).first))));
1780 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1785 DocumentClass const & dc = buf->params().documentClass();
1786 vector< pair<docstring, FuncRequest> > caps;
1787 for (pair<const docstring, InsetLayout> const & il : dc.insetLayouts()) {
1789 docstring const type = split(il.first, instype, ':');
1790 if (instype == from_ascii("Caption")) {
1791 // skip forbidden caption types
1792 FuncRequest const cmd = switchcap
1793 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1794 : FuncRequest(LFUN_CAPTION_INSERT, type);
1795 if (getStatus(cmd).enabled())
1796 caps.push_back(make_pair(type, cmd));
1800 if (caps.empty() || (switchcap && caps.size() == 1))
1802 if (caps.size() == 1) {
1803 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1807 MenuDefinition captions;
1808 for (pair<docstring, FuncRequest> const & cap : caps) {
1809 docstring const type = cap.first;
1810 docstring const trtype = translateIfPossible(type);
1811 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1813 add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1815 captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1817 if (!captions.empty()) {
1818 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1819 item.setSubmenu(captions);
1825 void MenuDefinition::expandZoomOptions(BufferView const * bv)
1830 add(MenuItem(MenuItem::Command,
1831 toqstr(bformat(_("Reset to Default (%1$d%)|R"),
1832 lyxrc.defaultZoom)),
1833 FuncRequest(LFUN_BUFFER_ZOOM)));
1834 add(MenuItem(MenuItem::Command, qt_("Zoom In|I"),
1835 FuncRequest(LFUN_BUFFER_ZOOM_IN)));
1836 add(MenuItem(MenuItem::Command, qt_("Zoom Out|O"),
1837 FuncRequest(LFUN_BUFFER_ZOOM_OUT)));
1838 add(MenuItem(MenuItem::Separator));
1839 // Offer some fractional values of the default
1840 int z = lyxrc.defaultZoom * 1.75;
1841 add(MenuItem(MenuItem::Command,
1842 toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1843 FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1844 z = lyxrc.defaultZoom * 1.5;
1845 add(MenuItem(MenuItem::Command,
1846 toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1847 FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1848 z = lyxrc.defaultZoom * 1.25;
1849 add(MenuItem(MenuItem::Command,
1850 toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1851 FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1852 z = lyxrc.defaultZoom * 0.75;
1853 add(MenuItem(MenuItem::Command,
1854 toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1855 FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1856 z = lyxrc.defaultZoom * 0.5;
1857 add(MenuItem(MenuItem::Command,
1858 toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1859 FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1860 z = lyxrc.defaultZoom * 0.25;
1861 add(MenuItem(MenuItem::Command,
1862 toqstr(bformat(_("[[ZOOM]]%1$d%"), z)),
1863 FuncRequest(LFUN_BUFFER_ZOOM, convert<string>(z))));
1867 void MenuDefinition::expandQuotes(BufferView const * bv)
1872 if (!bv->cursor().inTexted())
1875 Inset const * inset = bv->cursor().nextInset();
1876 if (!inset || inset->lyxCode() != QUOTE_CODE) {
1877 add(MenuItem(MenuItem::Command,
1878 qt_("No Quote in Scope!"),
1879 FuncRequest(LFUN_NOACTION)));
1882 InsetQuotes const * qinset =
1883 static_cast<InsetQuotes const *>(inset);
1885 string const qtype = qinset->getType();
1889 BufferParams const & bp = bv->buffer().masterBuffer()->params();
1891 // The global setting
1892 QuoteStyle globalqs = bp.quotes_style;
1893 char const globalqsc = quoteparams.getStyleChar(globalqs);
1895 // The current language's default
1896 QuoteStyle langdefqs =
1897 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1898 char const langqs = quoteparams.getStyleChar(langdefqs);
1900 bool main_global_qs = false;
1901 bool main_langdef_qs = false;
1902 bool main_dynamic_qs = false;
1903 docstring const subcmd = from_ascii("changetype ");
1904 docstring const wildcards = from_ascii("..");
1906 // First the top level menu (all glyphs of the current style) ...
1907 // Begin with dynamic (if they are current style),
1908 if (qtype[0] == 'x') {
1909 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1910 docstring desc = bformat(_("%1$s (dynamic)"),
1911 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1912 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1913 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1914 desc = bformat(_("%1$s (dynamic)"),
1915 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1916 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1917 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1918 desc = bformat(_("%1$s (dynamic)"),
1919 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1920 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1921 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1922 desc = bformat(_("%1$s (dynamic)"),
1923 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1924 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1925 main_dynamic_qs = true;
1927 // now traverse through the static styles ...
1928 map<string, docstring> styles = quoteparams.getTypes();
1929 for (auto const & s : styles) {
1930 char style_char = (s.first)[0];
1931 bool langdef = (style_char == langqs);
1932 bool globaldef = (style_char == globalqsc);
1933 docstring const style = from_ascii(s.first);
1935 if (prefixIs(style, qtype[0])) {
1936 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1937 docstring const desc = quoteparams.getShortGuiLabel(style);
1938 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1939 main_global_qs = globaldef;
1940 main_langdef_qs = langdef;
1942 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1943 docstring const desc =
1944 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1945 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1946 aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1950 add(MenuItem(MenuItem::Separator));
1952 bool display_static = false;
1953 // ... then potentially items to reset to the defaults and to dynamic style ...
1954 if (!main_dynamic_qs && globalqsc != 'x') {
1955 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1956 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1957 quoteparams.getGuiLabel(globalqs));
1958 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1959 display_static = true;
1961 if (!main_global_qs && langdefqs != globalqs) {
1962 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1963 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1964 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1965 quoteparams.getGuiLabel(globalqs), variant);
1966 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1968 if (!main_langdef_qs) {
1969 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1970 docstring const desc = (main_dynamic_qs || display_static)
1971 ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1972 quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1973 : bformat(_("Reset to language default (%1$s)|l"),
1974 quoteparams.getGuiLabel(langdefqs));
1975 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1978 add(MenuItem(MenuItem::Separator));
1980 // ... and a subitem with the rest
1981 MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1982 item.setSubmenu(aqs);
1987 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1992 Text const * text = bv->cursor().text();
1993 // no paragraphs and no separators exist in math
1997 pit_type pit = bv->cursor().selBegin().pit();
1998 Paragraph const & par = text->getPar(pit);
1999 docstring const curlayout = par.layout().name();
2000 docstring outerlayout;
2001 docstring prevlayout;
2002 depth_type current_depth = par.params().depth();
2003 // check if we have an environment in our scope
2008 Paragraph cpar = text->getPar(pit);
2009 if (cpar.layout().isEnvironment() && prevlayout.empty()
2010 && cpar.params().depth() <= current_depth)
2011 prevlayout = cpar.layout().name();
2012 if (cpar.params().depth() < current_depth
2013 && cpar.layout().isEnvironment()) {
2014 outerlayout = cpar.layout().name();
2015 current_depth = cpar.params().depth();
2017 if (cpar.params().depth() == 0)
2020 if (par.layout().isEnvironment()) {
2021 docstring label = contextmenu ?
2022 bformat(_("Insert Separated %1$s Above"),
2023 translateIfPossible(curlayout)) :
2024 bformat(_("Separated %1$s Above"),
2025 translateIfPossible(curlayout));
2026 add(MenuItem(MenuItem::Command, toqstr(label),
2027 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2028 from_ascii("before"))));
2029 label = contextmenu ?
2030 bformat(_("Insert Separated %1$s Below"),
2031 translateIfPossible(curlayout)):
2032 bformat(_("Separated %1$s Below"),
2033 translateIfPossible(curlayout));
2034 // We use command-alternatives here since this is how the binding is defined
2035 // (otherwise, the binding is not displayed in the menu)
2036 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
2037 add(MenuItem(MenuItem::Command, toqstr(label),
2038 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
2039 from_ascii("environment-split ; environment-split previous"))));
2041 else if (!prevlayout.empty()) {
2042 docstring const label = contextmenu ?
2043 bformat(_("Insert Separated %1$s Below"),
2044 translateIfPossible(prevlayout)) :
2045 bformat(_("Separated %1$s Below"),
2046 translateIfPossible(prevlayout));
2047 // We use command-alternatives here since this is how the binding is defined
2048 // (otherwise, the binding is not displayed in the menu)
2049 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
2050 add(MenuItem(MenuItem::Command, toqstr(label),
2051 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
2052 from_ascii("environment-split ; environment-split previous"))));
2054 if (!outerlayout.empty()) {
2057 label = (outerlayout == curlayout) ?
2058 bformat(_("Insert Separated Outer %1$s Below"),
2059 translateIfPossible(outerlayout)) :
2060 bformat(_("Insert Separated %1$s Below"),
2061 translateIfPossible(outerlayout));
2063 label = (outerlayout == curlayout) ?
2064 bformat(_("Separated Outer %1$s Below"),
2065 translateIfPossible(outerlayout)) :
2066 bformat(_("Separated %1$s Below"),
2067 translateIfPossible(outerlayout));
2069 add(MenuItem(MenuItem::Command, toqstr(label),
2070 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2071 from_ascii("outer"))));
2078 /////////////////////////////////////////////////////////////////////
2079 // Menu::Impl definition and implementation
2080 /////////////////////////////////////////////////////////////////////
2084 /// populates the menu or one of its submenu
2085 /// This is used as a recursive function
2086 void populate(QMenu * qMenu, MenuDefinition const & menu);
2088 /// Only needed for top level menus.
2089 MenuDefinition * top_level_menu;
2092 /// the name of this menu
2098 /// Get a MenuDefinition item label from the menu backend
2099 static QString label(MenuItem const & mi)
2101 QString label = mi.label();
2102 label.replace("&", "&&");
2104 QString shortcut = mi.shortcut();
2105 if (!shortcut.isEmpty()) {
2106 int pos = label.indexOf(shortcut);
2108 //label.insert(pos, 1, char_type('&'));
2109 label.replace(pos, 0, "&");
2112 QString const binding = mi.binding();
2113 if (!binding.isEmpty())
2114 label += '\t' + binding;
2119 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
2121 LYXERR(Debug::GUI, "populating menu " << menu.name());
2123 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
2126 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
2127 for (MenuItem const & m : menu)
2129 case MenuItem::Separator:
2130 qMenu->addSeparator();
2132 case MenuItem::Submenu: {
2133 QMenu * subMenu = qMenu->addMenu(label(m));
2134 populate(subMenu, m.submenu());
2135 subMenu->setEnabled(!subMenu->isEmpty());
2138 case MenuItem::Command:
2140 // FIXME: A previous comment assured that MenuItem::Command was the
2141 // only possible case in practice, but this is wrong. It would be
2142 // good to document which cases are actually treated here.
2143 qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2144 m.tooltip(), qMenu));
2149 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2150 class AlwaysMnemonicStyle : public QProxyStyle {
2152 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2153 QStyleHintReturn *returnData = 0) const override
2155 if (hint == QStyle::SH_UnderlineShortcut)
2157 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2162 /////////////////////////////////////////////////////////////////////
2163 // Menu implementation
2164 /////////////////////////////////////////////////////////////////////
2166 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2167 : QMenu(gv), d(new Menu::Impl)
2169 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2171 setStyle(new AlwaysMnemonicStyle);
2175 d->top_level_menu = top_level? new MenuDefinition : 0;
2179 if (d->top_level_menu)
2180 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2186 delete d->top_level_menu;
2191 void Menu::updateView()
2193 guiApp->menus().updateMenu(this);
2199 QList<QAction *> items = actions();
2200 for (int i = 0; i != items.size(); ++i) {
2201 // QAction::menu() returns 0 if there's no submenu.
2202 delete items.at(i)->menu();
2208 /////////////////////////////////////////////////////////////////////
2209 // Menus::Impl definition and implementation
2210 /////////////////////////////////////////////////////////////////////
2212 struct Menus::Impl {
2214 bool hasMenu(QString const &) const;
2216 MenuDefinition & getMenu(QString const &);
2218 MenuDefinition const & getMenu(QString const &) const;
2220 /// Expands some special entries of the menu
2221 /** The entries with the following kind are expanded to a
2222 sequence of Command MenuItems: Lastfiles, Documents,
2223 ViewFormats, ExportFormats, UpdateFormats, Branches,
2224 Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2225 EnvironmentSeparators
2227 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2228 BufferView const *) const;
2230 /// Initialize specific MACOS X menubar
2231 void macxMenuBarInit(QMenuBar * qmb);
2233 /// Mac special menu.
2234 /** This defines a menu whose entries list the FuncRequests
2235 that will be removed by expand() in other menus. This is
2236 used by the Qt/Mac code.
2238 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2239 such that the items will keep accessing the FuncRequests in
2240 the MenuDefinition. While Menus::Impl might be recreated,
2241 we keep mac_special_menu_ in memory by making it static.
2243 static MenuDefinition mac_special_menu_;
2248 MenuDefinition menubar_;
2250 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2252 /// name to menu for \c menu() method.
2257 MenuDefinition Menus::Impl::mac_special_menu_;
2261 Here is what the Qt documentation says about how a menubar is chosen:
2263 1) If the window has a QMenuBar then it is used. 2) If the window
2264 is a modal then its menubar is used. If no menubar is specified
2265 then a default menubar is used (as documented below) 3) If the
2266 window has no parent then the default menubar is used (as
2269 The above 3 steps are applied all the way up the parent window
2270 chain until one of the above are satisfied. If all else fails a
2271 default menubar will be created, the default menubar on Qt/Mac is
2272 an empty menubar, however you can create a different default
2273 menubar by creating a parentless QMenuBar, the first one created
2274 will thus be designated the default menubar, and will be used
2275 whenever a default menubar is needed.
2277 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2278 that this menubar will be used also when one of LyX' dialogs has
2281 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2283 /* Since Qt 4.2, the qt/mac menu code has special code for
2284 specifying the role of a menu entry. However, it does not
2285 work very well with our scheme of creating menus on demand,
2286 and therefore we need to put these entries in a special
2287 invisible menu. (JMarc)
2290 /* The entries of our special mac menu. If we add support for
2291 * special entries in Menus, we could imagine something
2293 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
2294 * and therefore avoid hardcoding. I am not sure it is worth
2295 * the hassle, though. (JMarc)
2297 struct MacMenuEntry {
2301 QAction::MenuRole role;
2304 static const MacMenuEntry entries[] = {
2305 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2306 QAction::AboutRole},
2307 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2308 QAction::PreferencesRole},
2309 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2310 /* This doesn't work with Cocoa. */
2311 {LFUN_RECONFIGURE, "", "Reconfigure",
2312 QAction::ApplicationSpecificRole},
2314 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2316 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2317 const bool first_call = mac_special_menu_.empty();
2319 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2320 // the special menu for Menus. Fill it up only once.
2322 for (size_t i = 0 ; i < num_entries ; ++i) {
2323 FuncRequest const func(entries[i].action,
2324 from_utf8(entries[i].arg));
2325 mac_special_menu_.add(MenuItem(MenuItem::Command,
2326 entries[i].label, func));
2330 // add the entries to a QMenu that will eventually be empty
2331 // and therefore invisible.
2332 QMenu * qMenu = qmb->addMenu("special");
2334 for (MenuItem const & m : mac_special_menu_) {
2335 Action * action = new Action(m.func(), QIcon(), m.label(),
2337 action->setMenuRole(entries[i].role);
2338 qMenu->addAction(action);
2344 void Menus::Impl::expand(MenuDefinition const & frommenu,
2345 MenuDefinition & tomenu, BufferView const * bv) const
2347 if (!tomenu.empty())
2350 for (MenuDefinition::const_iterator cit = frommenu.begin();
2351 cit != frommenu.end() ; ++cit) {
2352 Buffer const * buf = bv ? &bv->buffer() : 0;
2353 switch (cit->kind()) {
2354 case MenuItem::Lastfiles:
2355 tomenu.expandLastfiles();
2358 case MenuItem::Documents:
2359 tomenu.expandDocuments();
2362 case MenuItem::Bookmarks:
2363 tomenu.expandBookmarks();
2366 case MenuItem::ImportFormats:
2367 case MenuItem::ViewFormats:
2368 case MenuItem::UpdateFormats:
2369 case MenuItem::ExportFormats:
2370 tomenu.expandFormats(cit->kind(), buf);
2373 case MenuItem::ExportFormat: {
2376 string const format = buf->params().getDefaultOutputFormat();
2377 Format const * f = theFormats().getFormat(format);
2378 docstring const name = f ? translateIfPossible(f->prettyname())
2379 : from_utf8(format);
2380 docstring const label = bformat(_("Export [%1$s]|E"), name);
2381 MenuItem item(MenuItem::Command, toqstr(label),
2382 FuncRequest(LFUN_BUFFER_EXPORT));
2383 tomenu.addWithStatusCheck(item);
2387 case MenuItem::CharStyles:
2388 tomenu.expandFlexInsert(buf, InsetLyXType::CHARSTYLE);
2391 case MenuItem::Custom:
2392 tomenu.expandFlexInsert(buf, InsetLyXType::CUSTOM);
2395 case MenuItem::FloatListInsert:
2396 tomenu.expandFloatListInsert(buf);
2399 case MenuItem::FloatInsert:
2400 tomenu.expandFloatInsert(buf);
2403 case MenuItem::PasteRecent:
2404 tomenu.expandPasteRecent(buf);
2407 case MenuItem::Toolbars:
2408 tomenu.expandToolbars();
2411 case MenuItem::Branches:
2412 tomenu.expandBranches(buf);
2415 case MenuItem::Indices:
2416 tomenu.expandIndices(buf);
2419 case MenuItem::IndicesContext:
2420 tomenu.expandIndicesContext(buf);
2423 case MenuItem::IndicesLists:
2424 tomenu.expandIndices(buf, true);
2427 case MenuItem::IndicesListsContext:
2428 tomenu.expandIndicesContext(buf, true);
2431 case MenuItem::CiteStyles:
2432 tomenu.expandCiteStyles(bv);
2435 case MenuItem::InfoArguments:
2436 tomenu.expandInfoArguments(bv);
2441 tomenu.expandToc(buf);
2444 case MenuItem::GraphicsGroups:
2445 tomenu.expandGraphicsGroups(bv);
2448 case MenuItem::SpellingSuggestions:
2449 tomenu.expandSpellingSuggestions(bv);
2452 case MenuItem::LanguageSelector:
2453 tomenu.expandLanguageSelector(buf);
2456 case MenuItem::Arguments:
2457 tomenu.expandArguments(bv, false);
2460 case MenuItem::SwitchArguments:
2461 tomenu.expandArguments(bv, true);
2464 case MenuItem::Captions:
2465 tomenu.expandCaptions(buf, false);
2468 case MenuItem::SwitchCaptions:
2469 tomenu.expandCaptions(buf, true);
2472 case MenuItem::EnvironmentSeparators:
2473 tomenu.expandEnvironmentSeparators(bv);
2476 case MenuItem::EnvironmentSeparatorsContext:
2477 tomenu.expandEnvironmentSeparators(bv, true);
2480 case MenuItem::SwitchQuotes:
2481 tomenu.expandQuotes(bv);
2484 case MenuItem::ZoomOptions:
2485 tomenu.expandZoomOptions(bv);
2488 case MenuItem::Submenu: {
2489 MenuItem item(*cit);
2490 item.setSubmenu(MenuDefinition(cit->submenuname()));
2491 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2492 tomenu.addWithStatusCheck(item);
2496 case MenuItem::Info:
2497 case MenuItem::Help:
2498 case MenuItem::Separator:
2499 tomenu.addWithStatusCheck(*cit);
2502 case MenuItem::Command:
2503 if (!mac_special_menu_.hasFunc(*cit->func()))
2504 tomenu.addWithStatusCheck(*cit);
2508 // we do not want the menu to end with a separator
2509 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2510 tomenu.items_.pop_back();
2512 // Check whether the shortcuts are unique
2513 tomenu.checkShortcuts();
2517 bool Menus::Impl::hasMenu(QString const & name) const
2519 return find_if(menulist_.begin(), menulist_.end(),
2520 MenuNamesEqual(name)) != menulist_.end();
2524 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2526 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2527 MenuNamesEqual(name));
2528 if (cit == menulist_.end()) {
2529 LYXERR0("No submenu named " << name);
2530 LASSERT(false, { static const MenuDefinition m; return m; });
2536 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2538 iterator it = find_if(menulist_.begin(), menulist_.end(),
2539 MenuNamesEqual(name));
2540 if (it == menulist_.end()) {
2541 LYXERR0("No submenu named " << name);
2542 LASSERT(false, { static MenuDefinition m; return m; });
2548 /////////////////////////////////////////////////////////////////////
2552 /////////////////////////////////////////////////////////////////////
2554 Menus::Menus() : d(new Impl) {}
2570 void Menus::read(Lexer & lex)
2578 LexerKeyword menutags[] = {
2579 { "end", md_endmenuset },
2580 { "menu", md_menu },
2581 { "menubar", md_menubar }
2584 // consistency check
2585 if (compare_ascii_no_case(lex.getString(), "menuset"))
2586 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2588 lex.pushTable(menutags);
2589 lex.setContext("Menus::read");
2593 while (lex.isOK() && !quit) {
2594 switch (lex.lex()) {
2596 d->menubar_.read(lex);
2600 QString const name = toqstr(lex.getDocString());
2601 if (d->hasMenu(name))
2602 d->getMenu(name).read(lex);
2604 MenuDefinition menu(name);
2606 d->menulist_.push_back(menu);
2614 lex.printError("Unknown menu tag");
2622 bool Menus::searchMenu(FuncRequest const & func,
2623 docstring_list & names, BufferView const * bv) const
2625 MenuDefinition menu;
2626 d->expand(d->menubar_, menu, bv);
2627 return menu.searchMenu(func, names);
2631 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2635 // setup special mac specific menu items, but only do this
2636 // the first time a QMenuBar is created. Otherwise Qt will
2637 // create duplicate items in the application menu. It seems
2638 // that Qt does not remove them when the QMenubar is cleared.
2639 d->macxMenuBarInit(qmb);
2642 // Clear all menubar contents before filling it.
2644 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2645 d->macxMenuBarInit(qmb);
2649 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2651 if (d->menubar_.empty()) {
2652 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2653 << d->menubar_.name());
2656 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2658 MenuDefinition menu;
2659 BufferView * bv = 0;
2661 bv = view->currentBufferView();
2662 d->expand(d->menubar_, menu, bv);
2664 MenuDefinition::const_iterator m = menu.begin();
2665 MenuDefinition::const_iterator end = menu.end();
2667 for (; m != end; ++m) {
2669 if (m->kind() != MenuItem::Submenu) {
2670 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2674 LYXERR(Debug::GUI, "menu bar item " << m->label()
2675 << " is a submenu named " << m->submenuname());
2677 QString name = m->submenuname();
2678 if (!d->hasMenu(name)) {
2679 LYXERR(Debug::GUI, "\tERROR: " << name
2680 << " submenu has no menu!");
2684 Menu * menuptr = new Menu(view, m->submenuname(), true);
2685 menuptr->setTitle(label(*m));
2687 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2688 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2689 // so we create a temporary one here
2690 QAction * action = new QAction(menuptr);
2691 menuptr->addAction(action);
2694 qmb->addMenu(menuptr);
2696 d->name_map_[view][name] = menuptr;
2701 void Menus::updateMenu(Menu * qmenu)
2703 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2706 if (qmenu->d->name.isEmpty())
2709 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2710 MenuDefinition fromLyxMenu(qmenu->d->name);
2711 while (!identifier.empty()) {
2712 docstring menu_name;
2713 identifier = split(identifier, menu_name, ';');
2715 if (!d->hasMenu(toqstr(menu_name))) {
2716 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2721 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2722 //FIXME: 50 is a wild guess. We should take into account here
2723 //the expansion of menu items, disabled optional items etc.
2724 bool const in_sub_menu = !fromLyxMenu.empty()
2725 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2727 fromLyxMenu.catSub(menu_name);
2729 fromLyxMenu.cat(cat_menu);
2730 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2733 if (fromLyxMenu.empty()) {
2734 qmenu->addAction(qt_("No Action Defined!"));
2738 BufferView * bv = 0;
2740 bv = qmenu->d->view->currentBufferView();
2741 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2742 qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2746 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2748 LYXERR(Debug::GUI, "Context menu requested: " << name);
2749 Menu * menu = d->name_map_[&view].value(name, 0);
2750 if (!menu && !name.startsWith("context-")) {
2751 LYXERR0("requested context menu not found: " << name);
2755 menu = new Menu(&view, name, true, keyboard);
2756 d->name_map_[&view][name] = menu;
2760 } // namespace frontend
2763 #include "moc_Menus.cpp"