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"
34 #include "CutAndPaste.h"
36 #include "FloatList.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
40 #include "IndicesList.h"
45 #include "LyXAction.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
53 #include "SpellChecker.h"
54 #include "TextClass.h"
56 #include "TocBackend.h"
58 #include "WordLangTuple.h"
60 #include "insets/Inset.h"
61 #include "insets/InsetCitation.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetQuotes.h"
65 #include "support/lassert.h"
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/docstring_list.h"
69 #include "support/filetools.h"
70 #include "support/gettext.h"
71 #include "support/lstrings.h"
78 #if QT_VERSION >= 0x040600
79 #include <QProxyStyle>
87 using namespace lyx::support;
95 // MacOSX specific stuff is at the end.
102 /// The type of elements that can be in a menu
110 /** This type of item explains why something is unavailable. If this
111 menuitem is in a submenu, the submenu is enabled to make sure the
112 user sees the information. */
114 /** This type of item merely shows that there might be a list or
115 something alike at this position, but the list is still empty.
116 If this item is in a submenu, the submenu will not always be
119 /** This is the list of last opened file,
120 typically for the File menu. */
122 /** This is the list of opened Documents,
123 typically for the Documents menu. */
125 /** This is the bookmarks */
129 /** This is a list of viewable formats
130 typically for the File->View menu. */
132 /** This is a list of updatable formats
133 typically for the File->Update menu. */
135 /** This is a list of exportable formats
136 typically for the File->Export menu. */
138 /** This is a list of importable formats
139 typically for the File->Import menu. */
141 /** This is the list of elements available
142 * for insertion into document. */
144 /** This is the list of user-configurable
145 insets to insert into document */
147 /** This is the list of XML elements to
148 insert into the document */
150 /** This is the list of floats that we can
151 insert a list for. */
153 /** This is the list of floats that we can
156 /** This is the list of selections that can
161 /** Available branches in document */
163 /** Available indices in document */
165 /** Context menu for indices in document */
167 /** Available index lists in document */
169 /** Context menu for available indices lists in document */
171 /** Available citation styles for a given citation */
173 /** Available graphics groups */
175 /// Words suggested by the spellchecker.
177 /** Used Languages */
179 /** This is the list of arguments available
180 for insertion into the current layout. */
182 /** This is the list of arguments available
183 in the InsetArgument context menu. */
185 /** This is the list of captions available
186 in the current layout. */
188 /** This is the list of captions available
189 in the InsetCaption context menu. */
191 /** Commands to separate environments. */
192 EnvironmentSeparators,
193 /** This is the list of quotation marks available */
197 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
200 QString const & label,
201 QString const & submenu = QString(),
202 QString const & tooltip = QString(),
203 bool optional = false)
204 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
205 submenuname_(submenu), tooltip_(tooltip), optional_(optional)
207 LATTEST(kind == Submenu || kind == Help || kind == Info);
211 QString const & label,
212 FuncRequest const & func,
213 QString const & tooltip = QString(),
214 bool optional = false,
215 FuncRequest::Origin origin = FuncRequest::MENU)
216 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
217 tooltip_(tooltip), optional_(optional)
219 func_->setOrigin(origin);
222 /// The label of a given menuitem
223 QString label() const
225 int const index = label_.lastIndexOf('|');
226 return index == -1 ? label_ : label_.left(index);
229 /// The keyboard shortcut (usually underlined in the entry)
230 QString shortcut() const
232 int const index = label_.lastIndexOf('|');
233 return index == -1 ? QString() : label_.mid(index + 1);
235 /// The complete label, with label and shortcut separated by a '|'
236 QString fulllabel() const { return label_; }
237 /// The kind of entry
238 Kind kind() const { return kind_; }
239 /// the action (if relevant)
240 shared_ptr<FuncRequest const> func() const { return func_; }
242 QString const & tooltip() const { return tooltip_; }
243 /// returns true if the entry should be omitted when disabled
244 bool optional() const { return optional_; }
245 /// returns the status of the lfun associated with this entry
246 FuncStatus const & status() const { return status_; }
247 /// returns the status of the lfun associated with this entry
248 FuncStatus & status() { return status_; }
249 /// returns the status of the lfun associated with this entry
250 void status(FuncStatus const & status) { status_ = status; }
252 ///returns the binding associated to this action.
253 QString binding() const
255 if (kind_ != Command)
257 // Get the keys bound to this action, but keep only the
259 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
260 if (!bindings.empty())
261 return toqstr(bindings.begin()->print(KeySequence::ForGui));
263 LYXERR(Debug::KBMAP, "No binding for "
264 << lyxaction.getActionName(func_->action())
265 << '(' << func_->argument() << ')');
269 /// the description of the submenu (if relevant)
270 QString const & submenuname() const { return submenuname_; }
271 /// set the description of the submenu
272 void submenuname(QString const & name) { submenuname_ = name; }
274 bool hasSubmenu() const { return !submenu_.isEmpty(); }
276 MenuDefinition const & submenu() const { return submenu_.at(0); }
277 MenuDefinition & submenu() { return submenu_[0]; }
279 void setSubmenu(MenuDefinition const & menu)
282 submenu_.append(menu);
291 shared_ptr<FuncRequest> func_;// non-null
293 QString submenuname_;
300 /// contains 0 or 1 item.
301 QList<MenuDefinition> submenu_;
305 class MenuDefinition {
308 typedef std::vector<MenuItem> ItemList;
310 typedef ItemList::const_iterator const_iterator;
312 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
317 QString const & name() const { return name_; }
319 bool empty() const { return items_.empty(); }
320 /// Clear the menu content.
321 void clear() { items_.clear(); }
323 size_t size() const { return items_.size(); }
325 const_iterator begin() const { return items_.begin(); }
327 const_iterator end() const { return items_.end(); }
329 void cat(MenuDefinition const & other);
331 void catSub(docstring const & name);
333 // search for func in this menu iteratively, and put menu
335 bool searchMenu(FuncRequest const & func, docstring_list & names)
338 bool hasFunc(FuncRequest const &) const;
339 /// Add the menu item unconditionally
340 void add(MenuItem const & item) { items_.push_back(item); }
341 /// Checks the associated FuncRequest status before adding the
343 void addWithStatusCheck(MenuItem const &);
344 // Check whether the menu shortcuts are unique
345 void checkShortcuts() const;
347 void expandLastfiles();
348 void expandDocuments();
349 void expandBookmarks();
350 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
351 void expandFloatListInsert(Buffer const * buf);
352 void expandFloatInsert(Buffer const * buf);
353 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
354 void expandTocSubmenu(std::string const & type, Toc const & toc_list);
355 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
356 void expandToc(Buffer const * buf);
357 void expandPasteRecent(Buffer const * buf);
358 void expandToolbars();
359 void expandBranches(Buffer const * buf);
360 void expandIndices(Buffer const * buf, bool listof = false);
361 void expandIndicesContext(Buffer const * buf, bool listof = false);
362 void expandCiteStyles(BufferView const *);
363 void expandGraphicsGroups(BufferView const *);
364 void expandSpellingSuggestions(BufferView const *);
365 void expandLanguageSelector(Buffer const * buf);
366 void expandArguments(BufferView const *, bool switcharg = false);
367 void expandCaptions(Buffer const * buf, bool switchcap = false);
368 void expandEnvironmentSeparators(BufferView const *);
369 void expandQuotes(BufferView const *);
377 /// Helper for std::find_if
381 MenuNamesEqual(QString const & name) : name_(name) {}
382 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
389 typedef std::vector<MenuDefinition> MenuList;
391 typedef MenuList::const_iterator const_iterator;
393 typedef MenuList::iterator iterator;
395 /////////////////////////////////////////////////////////////////////
396 // MenuDefinition implementation
397 /////////////////////////////////////////////////////////////////////
399 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
403 case MenuItem::Command: {
404 FuncStatus status = lyx::getStatus(*i.func());
405 if (status.unknown() || (!status.enabled() && i.optional()))
408 items_.back().status(status);
412 case MenuItem::Submenu: {
413 bool enabled = false;
414 if (i.hasSubmenu()) {
415 for (const_iterator cit = i.submenu().begin();
416 cit != i.submenu().end(); ++cit) {
417 // Only these kind of items affect the status of the submenu
418 if ((cit->kind() == MenuItem::Command
419 || cit->kind() == MenuItem::Submenu
420 || cit->kind() == MenuItem::Help)
421 && cit->status().enabled()) {
427 if (enabled || !i.optional()) {
429 items_.back().status().setEnabled(enabled);
434 case MenuItem::Separator:
435 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
445 void MenuDefinition::read(Lexer & lex)
462 md_indiceslistscontext,
476 md_spellingsuggestions,
486 LexerKeyword menutags[] = {
487 { "arguments", md_arguments },
488 { "bookmarks", md_bookmarks },
489 { "branches", md_branches },
490 { "captions", md_captions },
491 { "charstyles", md_charstyles },
492 { "citestyles", md_citestyles },
493 { "custom", md_custom },
494 { "documents", md_documents },
495 { "elements", md_elements },
496 { "end", md_endmenu },
497 { "environmentseparators", md_env_separators },
498 { "exportformats", md_exportformats },
499 { "floatinsert", md_floatinsert },
500 { "floatlistinsert", md_floatlistinsert },
501 { "graphicsgroups", md_graphicsgroups },
502 { "importformats", md_importformats },
503 { "indices", md_indices },
504 { "indicescontext", md_indicescontext },
505 { "indiceslists", md_indiceslists },
506 { "indiceslistscontext", md_indiceslistscontext },
508 { "languageselector", md_languageselector },
509 { "lastfiles", md_lastfiles },
510 { "optitem", md_optitem },
511 { "optsubmenu", md_optsubmenu },
512 { "pasterecent", md_pasterecent },
513 { "separator", md_separator },
514 { "spellingsuggestions", md_spellingsuggestions },
515 { "submenu", md_submenu },
516 { "switcharguments", md_switcharguments },
517 { "switchcaptions", md_switchcaptions },
518 { "switchquotes", md_switchquotes },
520 { "toolbars", md_toolbars },
521 { "updateformats", md_updateformats },
522 { "viewformats", md_viewformats }
525 lex.pushTable(menutags);
526 lex.setContext("MenuDefinition::read: ");
529 while (lex.isOK() && md_type != md_endmenu) {
530 switch (md_type = lex.lex()) {
534 docstring const name = translateIfPossible(lex.getDocString());
536 string const command = lex.getString();
537 FuncRequest func = lyxaction.lookupFunc(command);
538 FuncRequest::Origin origin = FuncRequest::MENU;
539 if (name_.startsWith("context-toc-"))
540 origin = FuncRequest::TOC;
541 bool const optional = (md_type == md_optitem);
542 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
547 add(MenuItem(MenuItem::Separator));
551 add(MenuItem(MenuItem::Lastfiles));
555 add(MenuItem(MenuItem::CharStyles));
559 add(MenuItem(MenuItem::Custom));
563 add(MenuItem(MenuItem::Elements));
567 add(MenuItem(MenuItem::Documents));
571 add(MenuItem(MenuItem::Bookmarks));
575 add(MenuItem(MenuItem::Toc));
579 add(MenuItem(MenuItem::ViewFormats));
582 case md_updateformats:
583 add(MenuItem(MenuItem::UpdateFormats));
586 case md_exportformats:
587 add(MenuItem(MenuItem::ExportFormats));
590 case md_importformats:
591 add(MenuItem(MenuItem::ImportFormats));
594 case md_floatlistinsert:
595 add(MenuItem(MenuItem::FloatListInsert));
599 add(MenuItem(MenuItem::FloatInsert));
603 add(MenuItem(MenuItem::PasteRecent));
607 add(MenuItem(MenuItem::Toolbars));
611 add(MenuItem(MenuItem::Branches));
615 add(MenuItem(MenuItem::CiteStyles));
618 case md_graphicsgroups:
619 add(MenuItem(MenuItem::GraphicsGroups));
622 case md_spellingsuggestions:
623 add(MenuItem(MenuItem::SpellingSuggestions));
626 case md_languageselector:
627 add(MenuItem(MenuItem::LanguageSelector));
631 add(MenuItem(MenuItem::Indices));
634 case md_indicescontext:
635 add(MenuItem(MenuItem::IndicesContext));
638 case md_indiceslists:
639 add(MenuItem(MenuItem::IndicesLists));
642 case md_indiceslistscontext:
643 add(MenuItem(MenuItem::IndicesListsContext));
647 add(MenuItem(MenuItem::Arguments));
650 case md_switcharguments:
651 add(MenuItem(MenuItem::SwitchArguments));
655 add(MenuItem(MenuItem::Captions));
658 case md_switchcaptions:
659 add(MenuItem(MenuItem::SwitchCaptions));
662 case md_env_separators:
663 add(MenuItem(MenuItem::EnvironmentSeparators));
666 case md_switchquotes:
667 add(MenuItem(MenuItem::SwitchQuotes));
673 docstring const mlabel = translateIfPossible(lex.getDocString());
675 docstring const mname = lex.getDocString();
676 bool const optional = (md_type == md_optsubmenu);
677 add(MenuItem(MenuItem::Submenu,
678 toqstr(mlabel), toqstr(mname), QString(), optional));
686 lex.printError("Unknown menu tag");
694 bool MenuDefinition::hasFunc(FuncRequest const & func) const
696 for (const_iterator it = begin(), et = end(); it != et; ++it)
697 if (*it->func() == func)
703 void MenuDefinition::catSub(docstring const & name)
705 add(MenuItem(MenuItem::Submenu,
706 qt_("More...|M"), toqstr(name), QString(), false));
709 void MenuDefinition::cat(MenuDefinition const & other)
711 const_iterator et = other.end();
712 for (const_iterator it = other.begin(); it != et; ++it)
717 void MenuDefinition::checkShortcuts() const
719 // This is a quadratic algorithm, but we do not care because
720 // menus are short enough
721 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
722 QString shortcut = it1->shortcut();
723 if (shortcut.isEmpty())
725 if (!it1->label().contains(shortcut))
726 LYXERR0("Menu warning: menu entry \""
728 << "\" does not contain shortcut `"
729 << shortcut << "'.");
730 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
731 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
732 LYXERR0("Menu warning: menu entries "
733 << '"' << it1->fulllabel()
734 << "\" and \"" << it2->fulllabel()
735 << "\" share the same shortcut.");
742 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
744 const_iterator m = begin();
745 const_iterator m_end = end();
746 for (; m != m_end; ++m) {
747 if (m->kind() == MenuItem::Command && *m->func() == func) {
748 names.push_back(qstring_to_ucs4(m->label()));
751 if (m->kind() == MenuItem::Submenu) {
752 names.push_back(qstring_to_ucs4(m->label()));
753 if (!m->hasSubmenu()) {
754 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
755 << m->label() << " name=" << m->submenuname());
759 if (m->submenu().searchMenu(func, names))
768 QString limitStringLength(docstring const & str)
770 size_t const max_item_length = 45;
771 docstring ret = str.substr(0, max_item_length + 1);
772 support::truncateWithEllipsis(ret, max_item_length);
777 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
782 graphics::getGraphicsGroups(bv->buffer(), grp);
786 set<string>::const_iterator it = grp.begin();
787 set<string>::const_iterator end = grp.end();
788 add(MenuItem(MenuItem::Command, qt_("No Group"),
789 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
790 for (; it != end; ++it) {
791 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
792 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
797 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
801 Cursor const & cur = bv->cursor();
805 docstring_list suggestions;
806 Paragraph const & par = cur.paragraph();
807 pos_type from = cur.pos();
809 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
811 case SpellChecker::UNKNOWN_WORD:
812 if (lyxrc.spellcheck_continuously) {
813 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
814 docstring const & selection = cur.selectionAsString(false);
815 if (!cur.selection() || selection == wl.word()) {
817 size_t m = 10; // first submenu index
818 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
819 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
820 for (; i != suggestions.size(); ++i) {
821 docstring const & suggestion = suggestions[i];
822 LYXERR(Debug::GUI, suggestion);
823 MenuItem w(MenuItem::Command, toqstr(suggestion),
824 FuncRequest(LFUN_WORD_REPLACE,
825 replace2string(suggestion, selection,
826 true, // case sensitive
830 false))); // find next
834 item.submenu().add(w);
839 add(MenuItem(MenuItem::Separator));
840 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
841 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
842 FuncRequest(LFUN_SPELLING_ADD, arg)));
843 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
844 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
848 case SpellChecker::LEARNED_WORD: {
849 LYXERR(Debug::GUI, "Learned Word.");
850 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
851 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
852 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
855 case SpellChecker::NO_DICTIONARY:
856 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
858 case SpellChecker::WORD_OK:
859 case SpellChecker::COMPOUND_WORD:
860 case SpellChecker::ROOT_FOUND:
861 case SpellChecker::IGNORED_WORD:
866 struct sortLanguageByName {
867 bool operator()(const Language * a, const Language * b) const {
868 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
872 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
877 std::set<Language const *> languages_buffer =
878 buf->masterBuffer()->getLanguages();
880 if (languages_buffer.size() < 2)
883 std::set<Language const *, sortLanguageByName> languages;
885 std::set<Language const *>::const_iterator const beg =
886 languages_buffer.begin();
887 for (std::set<Language const *>::const_iterator cit = beg;
888 cit != languages_buffer.end(); ++cit) {
889 languages.insert(*cit);
892 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
893 item.setSubmenu(MenuDefinition(qt_("Language")));
894 QString morelangs = qt_("More Languages ...|M");
895 QStringList accelerators;
896 if (morelangs.contains('|'))
897 accelerators.append(morelangs.section('|', -1));
898 std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
899 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
900 cit != languages.end(); ++cit) {
901 QString label = qt_((*cit)->display());
902 // try to add an accelerator
903 bool success = false;
904 // try capitals first
905 for (int i = 0; i < label.size(); ++i) {
906 QChar const ch = label[i];
909 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
910 label = label + toqstr("|") + ch;
911 accelerators.append(ch);
916 // if all capitals are taken, try the rest
918 for (int i = 0; i < label.size(); ++i) {
919 if (label[i].isSpace())
921 QString const ch = QString(label[i]);
922 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
923 label = label + toqstr("|") + ch;
924 accelerators.append(ch);
929 MenuItem w(MenuItem::Command, label,
930 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
931 item.submenu().addWithStatusCheck(w);
933 item.submenu().add(MenuItem(MenuItem::Separator));
934 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
935 FuncRequest(LFUN_DIALOG_SHOW, "character")));
940 void MenuDefinition::expandLastfiles()
942 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
943 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
947 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
948 string const file = lfit->absFileName();
949 QString const short_path = toqstr(makeDisplayPath(file, 30));
950 QString const long_path = toqstr(makeDisplayPath(file));
953 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
955 label = QString("%1. %2").arg(ii).arg(short_path);
956 add(MenuItem(MenuItem::Command, label,
957 FuncRequest(LFUN_FILE_OPEN, file), long_path));
962 void MenuDefinition::expandDocuments()
964 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
965 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
967 Buffer * first = theBufferList().first();
969 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
975 if (!guiApp->currentView())
977 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
980 Buffer const & b = wa->bufferView().buffer();
981 QString label = toqstr(b.fileName().displayName(20));
985 label = QString::number(i) + ". " + label + '|' + QString::number(i);
986 add(MenuItem(MenuItem::Command, label,
987 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
994 // We cannot use a for loop as the buffer list cycles.
996 if (!(guiApp->currentView()
997 && guiApp->currentView()->workArea(*b))) {
998 QString label = toqstr(b->fileName().displayName(20));
1002 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1003 item.submenu().add(MenuItem(MenuItem::Command, label,
1004 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1007 b = theBufferList().next(b);
1008 } while (b != first);
1010 if (!item.submenu().empty())
1015 void MenuDefinition::expandBookmarks()
1017 lyx::BookmarksSection const & bm = theSession().bookmarks();
1020 for (size_t i = 1; i <= bm.size(); ++i) {
1021 if (bm.isValid(i)) {
1022 string const file = bm.bookmark(i).filename.absFileName();
1023 QString const label = QString("%1. %2|%3").arg(i)
1024 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1025 add(MenuItem(MenuItem::Command, label,
1026 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1031 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1035 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1037 if (!buf && kind != MenuItem::ImportFormats)
1041 FuncCode action = LFUN_NOACTION;
1044 case MenuItem::ImportFormats:
1045 formats = theConverters().importableFormats();
1046 action = LFUN_BUFFER_IMPORT;
1048 case MenuItem::ViewFormats:
1049 formats = buf->params().exportableFormats(true);
1050 action = LFUN_BUFFER_VIEW;
1052 case MenuItem::UpdateFormats:
1053 formats = buf->params().exportableFormats(true);
1054 action = LFUN_BUFFER_UPDATE;
1056 case MenuItem::ExportFormats:
1057 formats = buf->params().exportableFormats(false);
1058 action = LFUN_BUFFER_EXPORT;
1065 bool const view_update = (kind == MenuItem::ViewFormats
1066 || kind == MenuItem::UpdateFormats);
1070 smenue = (kind == MenuItem::ViewFormats
1071 ? qt_("View (Other Formats)|F")
1072 : qt_("Update (Other Formats)|p"));
1073 MenuItem item(MenuItem::Submenu, smenue);
1074 item.setSubmenu(MenuDefinition(smenue));
1076 for (Format const * f : formats) {
1080 docstring lab = f->prettyname();
1081 docstring const scut = from_utf8(f->shortcut());
1082 docstring const tmplab = lab;
1085 lab += char_type('|') + scut;
1086 docstring const lab_i18n = translateIfPossible(lab);
1087 docstring const shortcut = split(lab_i18n, lab, '|');
1089 bool const untranslated = (lab == lab_i18n);
1090 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1093 case MenuItem::ImportFormats:
1094 label += from_ascii("...");
1096 case MenuItem::ViewFormats:
1097 case MenuItem::UpdateFormats:
1098 if (f->name() == buf->params().getDefaultOutputFormat()) {
1099 docstring lbl = (kind == MenuItem::ViewFormats
1100 ? bformat(_("View [%1$s]|V"), label)
1101 : bformat(_("Update [%1$s]|U"), label));
1102 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1106 case MenuItem::ExportFormats:
1107 if (!f->inExportMenu())
1111 // we already asserted earlier in this case
1115 if (!shortcut.empty())
1116 label += '|' + shortcut;
1119 // note that at this point, we know that buf is not null
1121 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1122 toqstr(label), FuncRequest(action, f->name())));
1125 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1126 FuncRequest(action, f->name())));
1128 add(MenuItem(MenuItem::Command, toqstr(label),
1129 FuncRequest(action, f->name())));
1137 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1142 FloatList const & floats = buf->params().documentClass().floats();
1143 FloatList::const_iterator cit = floats.begin();
1144 FloatList::const_iterator end = floats.end();
1146 for (; cit != end; ++cit) {
1147 if (!cit->second.usesFloatPkg()) {
1148 // Different floats could declare the same ListCommand. We only
1149 // want it on the list once, though.
1150 string const & list_cmd = cit->second.listCommand();
1151 if (list_cmd.empty())
1152 // we do not know how to generate such a list
1154 // This form of insert returns an iterator pointing to the newly
1155 // inserted element OR the existing element with that value, and
1156 // a bool indicating whether we inserted a new element. So we can
1157 // see if one is there and insert it if not all at once.
1158 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1162 string const & list_name = cit->second.listName();
1163 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1164 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1169 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1174 FloatList const & floats = buf->params().documentClass().floats();
1175 FloatList::const_iterator cit = floats.begin();
1176 FloatList::const_iterator end = floats.end();
1177 for (; cit != end; ++cit) {
1179 QString const label = qt_(cit->second.name());
1180 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1181 FuncRequest(LFUN_FLOAT_INSERT,
1182 cit->second.floattype())));
1187 void MenuDefinition::expandFlexInsert(
1188 Buffer const * buf, InsetLayout::InsetLyXType type)
1193 TextClass::InsetLayouts const & insetLayouts =
1194 buf->params().documentClass().insetLayouts();
1195 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1196 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1197 for (; cit != end; ++cit) {
1198 if (cit->second.lyxtype() == type) {
1199 if (!cit->second.obsoleted_by().empty())
1201 docstring label = cit->first;
1202 // we remove the "Flex:" prefix, if it is present
1203 if (prefixIs(label, from_ascii("Flex:")))
1204 label = label.substr(5);
1205 addWithStatusCheck(MenuItem(MenuItem::Command,
1206 toqstr(translateIfPossible(label)),
1207 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1210 // FIXME This is a little clunky.
1211 if (items_.empty() && type == InsetLayout::CUSTOM && !buf->isReadonly())
1212 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1216 // Threshold before we stop displaying sub-items alongside items
1217 // (for display purposes). Ideally this should fit on a screen.
1218 size_t const max_number_of_items = 30;
1219 // Size limit for the menu. This is for performance purposes,
1220 // because qt already displays a scrollable menu when necessary.
1221 // Ideally this should be the menu size from which scrollable
1222 // menus become unpractical.
1223 size_t const menu_size_limit = 80;
1225 void MenuDefinition::expandToc2(Toc const & toc_list,
1226 size_t from, size_t to, int depth,
1229 int shortcut_count = 0;
1231 // check whether depth is smaller than the smallest depth in toc.
1232 int min_depth = 1000;
1233 for (size_t i = from; i < to; ++i)
1234 min_depth = min(min_depth, toc_list[i].depth());
1235 if (min_depth > depth)
1238 if (to - from <= max_number_of_items) {
1239 for (size_t i = from; i < to; ++i) {
1240 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1241 label += limitStringLength(toc_list[i].asString());
1242 if (toc_list[i].depth() == depth) {
1244 if (shortcut_count < 9) {
1245 if (label.contains(QString::number(shortcut_count + 1)))
1246 label += QString::number(++shortcut_count);
1249 add(MenuItem(MenuItem::Command, label,
1250 FuncRequest(toc_list[i].action())));
1251 // separator after the menu heading
1252 if (toc_list[i].depth() < depth)
1253 add(MenuItem(MenuItem::Separator));
1259 size_t new_pos = pos + 1;
1260 while (new_pos < to && toc_list[new_pos].depth() > depth)
1263 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1264 label += limitStringLength(toc_list[pos].asString());
1265 if (toc_list[pos].depth() == depth) {
1267 if (shortcut_count < 9) {
1268 if (label.contains(QString::number(shortcut_count + 1)))
1269 label += QString::number(++shortcut_count);
1272 if (size >= menu_size_limit) {
1273 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1274 add(MenuItem(MenuItem::Command, "...", f));
1277 if (new_pos == pos + 1) {
1278 add(MenuItem(MenuItem::Command,
1279 label, FuncRequest(toc_list[pos].action())));
1282 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1283 MenuItem item(MenuItem::Submenu, label);
1284 item.setSubmenu(sub);
1294 void MenuDefinition::expandToc(Buffer const * buf)
1296 // To make things very cleanly, we would have to pass buf to
1297 // all MenuItem constructors and to expandToc2. However, we
1298 // know that all the entries in a TOC will be have status_ ==
1299 // OK, so we avoid this unnecessary overhead (JMarc)
1301 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1304 // Add an entry for the master doc if this is a child doc
1305 Buffer const * const master = buf->masterBuffer();
1306 if (buf != master) {
1307 ParIterator const pit = par_iterator_begin(master->inset());
1308 string const arg = convert<string>(pit->id());
1309 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1310 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1313 MenuDefinition other_lists;
1314 // In the navigation menu, only add tocs from this document
1315 TocBackend const & backend = buf->tocBackend();
1316 TocList const & toc_list = backend.tocs();
1317 for (pair<string, shared_ptr<Toc>> const & toc : toc_list) {
1318 // Handle table of contents later
1319 if (toc.first == "tableofcontents" || toc.second->empty())
1321 MenuDefinition submenu;
1322 submenu.expandTocSubmenu(toc.first, *toc.second);
1323 docstring const toc_name = backend.outlinerName(toc.first);
1324 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1325 item.setSubmenu(submenu);
1326 // deserves to be in the main menu?
1327 if (!TocBackend::isOther(toc.first))
1330 other_lists.add(item);
1332 if (!other_lists.empty()) {
1333 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1334 item.setSubmenu(other_lists);
1337 // Handle normal TOC
1338 add(MenuItem(MenuItem::Separator));
1339 TocList::const_iterator cit = toc_list.find("tableofcontents");
1340 if (cit == toc_list.end())
1341 LYXERR(Debug::GUI, "No table of contents.");
1343 if (!cit->second->empty())
1344 expandToc2(*cit->second, 0, cit->second->size(), 0,
1347 add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1352 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1354 // "Open outliner..." entry
1355 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1356 add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1357 add(MenuItem(MenuItem::Separator));
1359 expandToc2(toc, 0, toc.size(), 0, type);
1363 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1365 docstring_list const sel = cap::availableSelections(buf);
1367 docstring_list::const_iterator cit = sel.begin();
1368 docstring_list::const_iterator end = sel.end();
1370 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1371 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1372 FuncRequest(LFUN_PASTE, convert<string>(index))));
1377 void MenuDefinition::expandToolbars()
1379 MenuDefinition other_lists;
1380 // extracts the toolbars from the backend
1381 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1382 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1383 for (; cit != end; ++cit) {
1384 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1385 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1386 if (guiApp->toolbars().isMainToolbar(cit->name))
1389 other_lists.add(item);
1392 if (!other_lists.empty()) {
1393 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1394 item.setSubmenu(other_lists);
1400 void MenuDefinition::expandBranches(Buffer const * buf)
1402 if (!buf || buf->isReadonly())
1405 BufferParams const & master_params = buf->masterBuffer()->params();
1406 BufferParams const & params = buf->params();
1407 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1408 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1412 BranchList::const_iterator cit = master_params.branchlist().begin();
1413 BranchList::const_iterator end = master_params.branchlist().end();
1415 for (int ii = 1; cit != end; ++cit, ++ii) {
1416 docstring label = cit->branch();
1418 label = convert<docstring>(ii) + ". " + label
1419 + char_type('|') + convert<docstring>(ii);
1421 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1422 FuncRequest(LFUN_BRANCH_INSERT,
1426 if (buf == buf->masterBuffer())
1429 MenuDefinition child_branches;
1431 BranchList::const_iterator ccit = params.branchlist().begin();
1432 BranchList::const_iterator cend = params.branchlist().end();
1434 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1435 docstring label = ccit->branch();
1437 label = convert<docstring>(ii) + ". " + label
1438 + char_type('|') + convert<docstring>(ii);
1440 label += char_type('|');
1441 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1443 FuncRequest(LFUN_BRANCH_INSERT,
1447 if (!child_branches.empty()) {
1448 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1449 item.setSubmenu(child_branches);
1455 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1460 BufferParams const & params = buf->masterBuffer()->params();
1461 if (!params.use_indices) {
1463 addWithStatusCheck(MenuItem(MenuItem::Command,
1464 qt_("Index List|I"),
1465 FuncRequest(LFUN_INDEX_PRINT,
1466 from_ascii("idx"))));
1468 addWithStatusCheck(MenuItem(MenuItem::Command,
1469 qt_("Index Entry|d"),
1470 FuncRequest(LFUN_INDEX_INSERT,
1471 from_ascii("idx"))));
1475 if (params.indiceslist().empty())
1478 IndicesList::const_iterator cit = params.indiceslist().begin();
1479 IndicesList::const_iterator end = params.indiceslist().end();
1481 for (int ii = 1; cit != end; ++cit, ++ii) {
1483 docstring const label =
1484 bformat(_("Index: %1$s"), cit->index());
1485 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1486 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1488 docstring const label =
1489 bformat(_("Index Entry (%1$s)"), cit->index());
1490 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1491 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1497 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1502 BufferParams const & params = buf->masterBuffer()->params();
1503 if (!params.use_indices || params.indiceslist().empty())
1506 IndicesList::const_iterator cit = params.indiceslist().begin();
1507 IndicesList::const_iterator end = params.indiceslist().end();
1509 for (int ii = 1; cit != end; ++cit, ++ii) {
1511 InsetCommandParams p(INDEX_PRINT_CODE);
1512 p["type"] = cit->shortcut();
1513 string const data = InsetCommand::params2string(p);
1514 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1515 FuncRequest(LFUN_INSET_MODIFY, data)));
1517 docstring const label =
1518 bformat(_("Index Entry (%1$s)"), cit->index());
1519 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1520 FuncRequest(LFUN_INSET_MODIFY,
1521 from_ascii("changetype ") + cit->shortcut())));
1527 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1532 Inset const * inset = bv->cursor().nextInset();
1533 if (!inset || inset->lyxCode() != CITE_CODE) {
1534 add(MenuItem(MenuItem::Command,
1535 qt_("No Citation in Scope!"),
1536 FuncRequest(LFUN_NOACTION)));
1539 InsetCitation const * citinset =
1540 static_cast<InsetCitation const *>(inset);
1542 Buffer const * buf = &bv->buffer();
1543 BufferParams const & bp = buf->masterParams();
1544 string const cmd = citinset->params().getCmdName();
1546 docstring const & key = citinset->getParam("key");
1548 add(MenuItem(MenuItem::Command,
1549 qt_("No citations selected!"),
1550 FuncRequest(LFUN_NOACTION)));
1554 size_t const n = cmd.size();
1555 bool const force = isUpperCase(cmd[0]);
1556 bool const star = cmd[n] == '*';
1558 vector<docstring> const keys = getVectorFromString(key);
1560 vector<CitationStyle> const citeStyleList = bp.citeStyles();
1562 CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1563 bool const qualified = cs.hasQualifiedList
1565 || !citinset->getParam("pretextlist").empty()
1566 || !citinset->getParam("posttextlist").empty());
1567 std::map<docstring, docstring> pres =
1568 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1569 std::map<docstring, docstring> posts =
1570 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1573 ci.textBefore = citinset->getParam("before");
1574 ci.textAfter = citinset->getParam("after");
1575 ci.forceUpperCase = force;
1577 ci.context = CiteItem::Dialog;
1579 ci.isQualified = qualified;
1581 ci.posttexts = posts;
1582 vector<docstring> citeStrings =
1583 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1585 vector<docstring>::const_iterator cit = citeStrings.begin();
1586 vector<docstring>::const_iterator end = citeStrings.end();
1588 for (int ii = 1; cit != end; ++cit, ++ii) {
1589 docstring label = *cit;
1590 CitationStyle cs = citeStyleList[ii - 1];
1591 cs.forceUpperCase &= force;
1592 cs.hasStarredVersion &= star;
1593 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1594 FuncRequest(LFUN_INSET_MODIFY,
1595 "changetype " + from_utf8(citationStyleToString(cs)))));
1598 if (cs.hasStarredVersion) {
1599 docstring starred = _("All authors|h");
1600 // Check if we have a custom string/tooltip for the starred version
1601 if (!cs.stardesc.empty()) {
1603 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1605 starred = translateIfPossible(from_utf8(val));
1606 // Transform qt-style accelerators to menu-style
1607 int const amps = count_char(starred, '&');
1610 starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1611 size_t n = starred.find('&');
1612 char_type accel = char_type();
1613 if (n != docstring::npos && n < starred.size() - 1)
1614 accel = starred[n + 1];
1615 starred = subst(starred, from_ascii("&"), from_ascii(""));
1617 starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1618 if (accel != char_type())
1619 starred = starred + '|' + accel;
1622 add(MenuItem(MenuItem::Separator));
1623 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1624 FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1627 if (cs.forceUpperCase) {
1628 if (!cs.hasStarredVersion)
1629 add(MenuItem(MenuItem::Separator));
1630 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1631 FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1636 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1641 if (!bv->cursor().inTexted())
1644 Inset const * inset = &bv->cursor().inset();
1645 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1646 if (inset && args.empty())
1647 args = inset->getLayout().args();
1648 if (args.empty() || (switcharg && args.size() == 1))
1650 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1651 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1652 for (; lait != laend; ++lait) {
1653 Layout::latexarg arg = (*lait).second;
1654 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1655 QString item = toqstr(translateIfPossible(str));
1657 add(MenuItem(MenuItem::Command, item,
1658 FuncRequest(LFUN_INSET_MODIFY,
1659 from_ascii("changetype ")
1660 + from_ascii((*lait).first))));
1662 add(MenuItem(MenuItem::Command, item,
1663 FuncRequest(LFUN_ARGUMENT_INSERT,
1664 from_ascii((*lait).first))));
1669 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1674 DocumentClass const & dc = buf->params().documentClass();
1675 vector< pair<docstring, FuncRequest> > caps;
1676 for (pair<docstring, InsetLayout> const & il : dc.insetLayouts()) {
1678 docstring const type = split(il.first, instype, ':');
1679 if (instype == from_ascii("Caption")) {
1680 // skip forbidden caption types
1681 FuncRequest const cmd = switchcap
1682 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1683 : FuncRequest(LFUN_CAPTION_INSERT, type);
1684 if (getStatus(cmd).enabled())
1685 caps.push_back(make_pair(type, cmd));
1689 if (caps.empty() || (switchcap && caps.size() == 1))
1691 if (caps.size() == 1) {
1692 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1696 MenuDefinition captions;
1697 for (pair<docstring, FuncRequest> const & cap : caps) {
1698 docstring const type = cap.first;
1699 docstring const trtype = translateIfPossible(type);
1700 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1702 add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1704 captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1706 if (!captions.empty()) {
1707 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1708 item.setSubmenu(captions);
1714 void MenuDefinition::expandQuotes(BufferView const * bv)
1719 if (!bv->cursor().inTexted())
1722 Inset const * inset = bv->cursor().nextInset();
1723 if (!inset || inset->lyxCode() != QUOTE_CODE) {
1724 add(MenuItem(MenuItem::Command,
1725 qt_("No Quote in Scope!"),
1726 FuncRequest(LFUN_NOACTION)));
1729 InsetQuotes const * qinset =
1730 static_cast<InsetQuotes const *>(inset);
1732 map<string, docstring> styles = quoteparams.getTypes();
1733 string const qtype = qinset->getType();
1735 map<string, docstring>::const_iterator qq = styles.begin();
1736 map<string, docstring>::const_iterator end = styles.end();
1740 BufferParams const & bp = bv->buffer().masterBuffer()->params();
1742 // The global setting
1743 InsetQuotesParams::QuoteStyle globalqs = bp.quotes_style;
1744 char const globalqsc = quoteparams.getStyleChar(globalqs);
1746 // The current language's default
1747 InsetQuotesParams::QuoteStyle langdefqs =
1748 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1749 char const langqs = quoteparams.getStyleChar(langdefqs);
1751 bool main_global_qs = false;
1752 bool main_langdef_qs = false;
1753 bool main_dynamic_qs = false;
1754 docstring const subcmd = from_ascii("changetype ");
1755 docstring const wildcards = from_ascii("..");
1757 // First the top level menu (all glyphs of the current style) ...
1758 // Begin with dynamic (if they are current style),
1759 if (qtype[0] == 'x') {
1760 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1761 docstring desc = bformat(_("%1$s (dynamic)"),
1762 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1763 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1764 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1765 desc = bformat(_("%1$s (dynamic)"),
1766 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1767 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1768 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1769 desc = bformat(_("%1$s (dynamic)"),
1770 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1771 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1772 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1773 desc = bformat(_("%1$s (dynamic)"),
1774 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1775 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1776 main_dynamic_qs = true;
1778 // now traverse through the static styles ...
1779 for (; qq != end; ++qq) {
1780 docstring const style = from_ascii(qq->first);
1781 bool langdef = (style[0] == langqs);
1782 bool globaldef = (style[0] == globalqsc);
1784 if (prefixIs(style, qtype[0])) {
1785 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1786 docstring const desc = quoteparams.getShortGuiLabel(style);
1787 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1788 main_global_qs = globaldef;
1789 main_langdef_qs = langdef;
1791 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1792 docstring const desc =
1793 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1794 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1795 aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1799 add(MenuItem(MenuItem::Separator));
1801 bool display_static = false;
1802 // ... then potentially items to reset to the defaults and to dynamic style ...
1803 if (!main_dynamic_qs && globalqsc != 'x') {
1804 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1805 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1806 quoteparams.getGuiLabel(globalqs));
1807 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1808 display_static = true;
1810 if (!main_global_qs && langdefqs != globalqs) {
1811 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1812 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1813 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1814 quoteparams.getGuiLabel(globalqs), variant);
1815 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1817 if (!main_langdef_qs) {
1818 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1819 docstring const desc = (main_dynamic_qs || display_static)
1820 ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1821 quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1822 : bformat(_("Reset to language default (%1$s)|l"),
1823 quoteparams.getGuiLabel(langdefqs));
1824 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1827 add(MenuItem(MenuItem::Separator));
1829 // ... and a subitem with the rest
1830 MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1831 item.setSubmenu(aqs);
1836 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv)
1840 Text const * text = bv->cursor().text();
1841 // no paragraphs and no separators exist in math
1845 pit_type pit = bv->cursor().selBegin().pit();
1846 Paragraph const & par = text->getPar(pit);
1847 docstring const curlayout = par.layout().name();
1848 docstring outerlayout;
1849 depth_type current_depth = par.params().depth();
1850 // check if we have an environment in our nesting hierarchy
1851 Paragraph cpar = par;
1853 if (pit == 0 || cpar.params().depth() == 0)
1856 cpar = text->getPar(pit);
1857 if (cpar.params().depth() < current_depth
1858 && cpar.layout().isEnvironment()) {
1859 outerlayout = cpar.layout().name();
1860 current_depth = cpar.params().depth();
1863 if (par.layout().isEnvironment()) {
1864 docstring const label =
1865 bformat(_("Start New Environment (%1$s)"),
1866 translateIfPossible(curlayout));
1867 add(MenuItem(MenuItem::Command, toqstr(label),
1868 FuncRequest(LFUN_ENVIRONMENT_SPLIT)));
1870 if (!outerlayout.empty()) {
1871 docstring const label =
1872 bformat(_("Start New Parent Environment (%1$s)"),
1873 translateIfPossible(outerlayout));
1874 add(MenuItem(MenuItem::Command, toqstr(label),
1875 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1876 from_ascii("outer"))));
1883 /////////////////////////////////////////////////////////////////////
1884 // Menu::Impl definition and implementation
1885 /////////////////////////////////////////////////////////////////////
1889 /// populates the menu or one of its submenu
1890 /// This is used as a recursive function
1891 void populate(QMenu * qMenu, MenuDefinition const & menu);
1893 /// Only needed for top level menus.
1894 MenuDefinition * top_level_menu;
1897 /// the name of this menu
1903 /// Get a MenuDefinition item label from the menu backend
1904 static QString label(MenuItem const & mi)
1906 QString label = mi.label();
1907 label.replace("&", "&&");
1909 QString shortcut = mi.shortcut();
1910 if (!shortcut.isEmpty()) {
1911 int pos = label.indexOf(shortcut);
1913 //label.insert(pos, 1, char_type('&'));
1914 label.replace(pos, 0, "&");
1917 QString const binding = mi.binding();
1918 if (!binding.isEmpty())
1919 label += '\t' + binding;
1924 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
1926 LYXERR(Debug::GUI, "populating menu " << menu.name());
1928 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1931 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1932 for (MenuItem const & m : menu)
1934 case MenuItem::Separator:
1935 qMenu->addSeparator();
1937 case MenuItem::Submenu: {
1938 QMenu * subMenu = qMenu->addMenu(label(m));
1939 populate(subMenu, m.submenu());
1940 subMenu->setEnabled(!subMenu->isEmpty());
1943 case MenuItem::Command:
1945 // FIXME: A previous comment assured that MenuItem::Command was the
1946 // only possible case in practice, but this is wrong. It would be
1947 // good to document which cases are actually treated here.
1948 qMenu->addAction(new Action(m.func(), QIcon(), label(m),
1949 m.tooltip(), qMenu));
1954 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
1955 class AlwaysMnemonicStyle : public QProxyStyle {
1957 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1958 QStyleHintReturn *returnData = 0) const
1960 if (hint == QStyle::SH_UnderlineShortcut)
1962 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1967 /////////////////////////////////////////////////////////////////////
1968 // Menu implementation
1969 /////////////////////////////////////////////////////////////////////
1971 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1972 : QMenu(gv), d(new Menu::Impl)
1974 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
1976 setStyle(new AlwaysMnemonicStyle);
1980 d->top_level_menu = top_level? new MenuDefinition : 0;
1984 if (d->top_level_menu)
1985 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1991 delete d->top_level_menu;
1996 void Menu::updateView()
1998 guiApp->menus().updateMenu(this);
2004 QList<QAction *> items = actions();
2005 for (int i = 0; i != items.size(); ++i) {
2006 // QAction::menu() returns 0 if there's no submenu.
2007 delete items.at(i)->menu();
2013 /////////////////////////////////////////////////////////////////////
2014 // Menus::Impl definition and implementation
2015 /////////////////////////////////////////////////////////////////////
2017 struct Menus::Impl {
2019 bool hasMenu(QString const &) const;
2021 MenuDefinition & getMenu(QString const &);
2023 MenuDefinition const & getMenu(QString const &) const;
2025 /// Expands some special entries of the menu
2026 /** The entries with the following kind are expanded to a
2027 sequence of Command MenuItems: Lastfiles, Documents,
2028 ViewFormats, ExportFormats, UpdateFormats, Branches,
2029 Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2030 EnvironmentSeparators
2032 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2033 BufferView const *) const;
2035 /// Initialize specific MACOS X menubar
2036 void macxMenuBarInit(QMenuBar * qmb);
2038 /// Mac special menu.
2039 /** This defines a menu whose entries list the FuncRequests
2040 that will be removed by expand() in other menus. This is
2041 used by the Qt/Mac code.
2043 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2044 such that the items will keep accessing the FuncRequests in
2045 the MenuDefinition. While Menus::Impl might be recreated,
2046 we keep mac_special_menu_ in memory by making it static.
2048 static MenuDefinition mac_special_menu_;
2053 MenuDefinition menubar_;
2055 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2057 /// name to menu for \c menu() method.
2062 MenuDefinition Menus::Impl::mac_special_menu_;
2066 Here is what the Qt documentation says about how a menubar is chosen:
2068 1) If the window has a QMenuBar then it is used. 2) If the window
2069 is a modal then its menubar is used. If no menubar is specified
2070 then a default menubar is used (as documented below) 3) If the
2071 window has no parent then the default menubar is used (as
2074 The above 3 steps are applied all the way up the parent window
2075 chain until one of the above are satisifed. If all else fails a
2076 default menubar will be created, the default menubar on Qt/Mac is
2077 an empty menubar, however you can create a different default
2078 menubar by creating a parentless QMenuBar, the first one created
2079 will thus be designated the default menubar, and will be used
2080 whenever a default menubar is needed.
2082 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2083 that this menubar will be used also when one of LyX' dialogs has
2086 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2088 /* Since Qt 4.2, the qt/mac menu code has special code for
2089 specifying the role of a menu entry. However, it does not
2090 work very well with our scheme of creating menus on demand,
2091 and therefore we need to put these entries in a special
2092 invisible menu. (JMarc)
2095 /* The entries of our special mac menu. If we add support for
2096 * special entries in Menus, we could imagine something
2098 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
2099 * and therefore avoid hardcoding. I am not sure it is worth
2100 * the hassle, though. (JMarc)
2102 struct MacMenuEntry {
2106 QAction::MenuRole role;
2109 static const MacMenuEntry entries[] = {
2110 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2111 QAction::AboutRole},
2112 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2113 QAction::PreferencesRole},
2114 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2115 /* This doesn't work with Cocoa. */
2116 {LFUN_RECONFIGURE, "", "Reconfigure",
2117 QAction::ApplicationSpecificRole},
2119 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2121 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2122 const bool first_call = mac_special_menu_.empty();
2124 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2125 // the special menu for Menus. Fill it up only once.
2127 for (size_t i = 0 ; i < num_entries ; ++i) {
2128 FuncRequest const func(entries[i].action,
2129 from_utf8(entries[i].arg));
2130 mac_special_menu_.add(MenuItem(MenuItem::Command,
2131 entries[i].label, func));
2135 // add the entries to a QMenu that will eventually be empty
2136 // and therefore invisible.
2137 QMenu * qMenu = qmb->addMenu("special");
2139 for (MenuItem const & m : mac_special_menu_) {
2140 Action * action = new Action(m.func(), QIcon(), m.label(),
2142 action->setMenuRole(entries[i].role);
2143 qMenu->addAction(action);
2149 void Menus::Impl::expand(MenuDefinition const & frommenu,
2150 MenuDefinition & tomenu, BufferView const * bv) const
2152 if (!tomenu.empty())
2155 for (MenuDefinition::const_iterator cit = frommenu.begin();
2156 cit != frommenu.end() ; ++cit) {
2157 Buffer const * buf = bv ? &bv->buffer() : 0;
2158 switch (cit->kind()) {
2159 case MenuItem::Lastfiles:
2160 tomenu.expandLastfiles();
2163 case MenuItem::Documents:
2164 tomenu.expandDocuments();
2167 case MenuItem::Bookmarks:
2168 tomenu.expandBookmarks();
2171 case MenuItem::ImportFormats:
2172 case MenuItem::ViewFormats:
2173 case MenuItem::UpdateFormats:
2174 case MenuItem::ExportFormats:
2175 tomenu.expandFormats(cit->kind(), buf);
2178 case MenuItem::CharStyles:
2179 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2182 case MenuItem::Custom:
2183 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2186 case MenuItem::Elements:
2187 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
2190 case MenuItem::FloatListInsert:
2191 tomenu.expandFloatListInsert(buf);
2194 case MenuItem::FloatInsert:
2195 tomenu.expandFloatInsert(buf);
2198 case MenuItem::PasteRecent:
2199 tomenu.expandPasteRecent(buf);
2202 case MenuItem::Toolbars:
2203 tomenu.expandToolbars();
2206 case MenuItem::Branches:
2207 tomenu.expandBranches(buf);
2210 case MenuItem::Indices:
2211 tomenu.expandIndices(buf);
2214 case MenuItem::IndicesContext:
2215 tomenu.expandIndicesContext(buf);
2218 case MenuItem::IndicesLists:
2219 tomenu.expandIndices(buf, true);
2222 case MenuItem::IndicesListsContext:
2223 tomenu.expandIndicesContext(buf, true);
2226 case MenuItem::CiteStyles:
2227 tomenu.expandCiteStyles(bv);
2231 tomenu.expandToc(buf);
2234 case MenuItem::GraphicsGroups:
2235 tomenu.expandGraphicsGroups(bv);
2238 case MenuItem::SpellingSuggestions:
2239 tomenu.expandSpellingSuggestions(bv);
2242 case MenuItem::LanguageSelector:
2243 tomenu.expandLanguageSelector(buf);
2246 case MenuItem::Arguments:
2247 tomenu.expandArguments(bv, false);
2250 case MenuItem::SwitchArguments:
2251 tomenu.expandArguments(bv, true);
2254 case MenuItem::Captions:
2255 tomenu.expandCaptions(buf, false);
2258 case MenuItem::SwitchCaptions:
2259 tomenu.expandCaptions(buf, true);
2262 case MenuItem::EnvironmentSeparators:
2263 tomenu.expandEnvironmentSeparators(bv);
2266 case MenuItem::SwitchQuotes:
2267 tomenu.expandQuotes(bv);
2270 case MenuItem::Submenu: {
2271 MenuItem item(*cit);
2272 item.setSubmenu(MenuDefinition(cit->submenuname()));
2273 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2274 tomenu.addWithStatusCheck(item);
2278 case MenuItem::Info:
2279 case MenuItem::Help:
2280 case MenuItem::Separator:
2281 tomenu.addWithStatusCheck(*cit);
2284 case MenuItem::Command:
2285 if (!mac_special_menu_.hasFunc(*cit->func()))
2286 tomenu.addWithStatusCheck(*cit);
2290 // we do not want the menu to end with a separator
2291 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2292 tomenu.items_.pop_back();
2294 // Check whether the shortcuts are unique
2295 tomenu.checkShortcuts();
2299 bool Menus::Impl::hasMenu(QString const & name) const
2301 return find_if(menulist_.begin(), menulist_.end(),
2302 MenuNamesEqual(name)) != menulist_.end();
2306 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2308 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2309 MenuNamesEqual(name));
2310 if (cit == menulist_.end()) {
2311 LYXERR0("No submenu named " << name);
2312 LASSERT(false, { static const MenuDefinition m; return m; });
2318 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2320 iterator it = find_if(menulist_.begin(), menulist_.end(),
2321 MenuNamesEqual(name));
2322 if (it == menulist_.end()) {
2323 LYXERR0("No submenu named " << name);
2324 LASSERT(false, { static MenuDefinition m; return m; });
2330 /////////////////////////////////////////////////////////////////////
2334 /////////////////////////////////////////////////////////////////////
2336 Menus::Menus() : d(new Impl) {}
2352 void Menus::read(Lexer & lex)
2360 LexerKeyword menutags[] = {
2361 { "end", md_endmenuset },
2362 { "menu", md_menu },
2363 { "menubar", md_menubar }
2366 // consistency check
2367 if (compare_ascii_no_case(lex.getString(), "menuset"))
2368 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2370 lex.pushTable(menutags);
2371 lex.setContext("Menus::read");
2375 while (lex.isOK() && !quit) {
2376 switch (lex.lex()) {
2378 d->menubar_.read(lex);
2382 QString const name = toqstr(lex.getDocString());
2383 if (d->hasMenu(name))
2384 d->getMenu(name).read(lex);
2386 MenuDefinition menu(name);
2388 d->menulist_.push_back(menu);
2396 lex.printError("Unknown menu tag");
2404 bool Menus::searchMenu(FuncRequest const & func,
2405 docstring_list & names) const
2407 MenuDefinition menu;
2408 d->expand(d->menubar_, menu, 0);
2409 return menu.searchMenu(func, names);
2413 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2417 // setup special mac specific menu items, but only do this
2418 // the first time a QMenuBar is created. Otherwise Qt will
2419 // create duplicate items in the application menu. It seems
2420 // that Qt does not remove them when the QMenubar is cleared.
2421 d->macxMenuBarInit(qmb);
2424 // Clear all menubar contents before filling it.
2426 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2427 d->macxMenuBarInit(qmb);
2431 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2433 if (d->menubar_.empty()) {
2434 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2435 << d->menubar_.name());
2438 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2440 MenuDefinition menu;
2441 BufferView * bv = 0;
2443 bv = view->currentBufferView();
2444 d->expand(d->menubar_, menu, bv);
2446 MenuDefinition::const_iterator m = menu.begin();
2447 MenuDefinition::const_iterator end = menu.end();
2449 for (; m != end; ++m) {
2451 if (m->kind() != MenuItem::Submenu) {
2452 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2456 LYXERR(Debug::GUI, "menu bar item " << m->label()
2457 << " is a submenu named " << m->submenuname());
2459 QString name = m->submenuname();
2460 if (!d->hasMenu(name)) {
2461 LYXERR(Debug::GUI, "\tERROR: " << name
2462 << " submenu has no menu!");
2466 Menu * menu = new Menu(view, m->submenuname(), true);
2467 menu->setTitle(label(*m));
2469 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2470 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2471 // so we create a temporary one here
2472 QAction * action = new QAction(menu);
2473 menu->addAction(action);
2478 d->name_map_[view][name] = menu;
2483 void Menus::updateMenu(Menu * qmenu)
2485 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2488 if (qmenu->d->name.isEmpty())
2491 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2492 MenuDefinition fromLyxMenu(qmenu->d->name);
2493 while (!identifier.empty()) {
2494 docstring menu_name;
2495 identifier = split(identifier, menu_name, ';');
2497 if (!d->hasMenu(toqstr(menu_name))) {
2498 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2503 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2504 //FIXME: 50 is a wild guess. We should take into account here
2505 //the expansion of menu items, disabled optional items etc.
2506 bool const in_sub_menu = !fromLyxMenu.empty()
2507 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2509 fromLyxMenu.catSub(menu_name);
2511 fromLyxMenu.cat(cat_menu);
2512 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2515 if (fromLyxMenu.empty()) {
2516 qmenu->addAction(qt_("No Action Defined!"));
2520 BufferView * bv = 0;
2522 bv = qmenu->d->view->currentBufferView();
2523 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2524 qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2528 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2530 LYXERR(Debug::GUI, "Context menu requested: " << name);
2531 Menu * menu = d->name_map_[&view].value(name, 0);
2532 if (!menu && !name.startsWith("context-")) {
2533 LYXERR0("requested context menu not found: " << name);
2537 menu = new Menu(&view, name, true, keyboard);
2538 d->name_map_[&view][name] = menu;
2542 } // namespace frontend
2545 #include "moc_Menus.cpp"