3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
14 * \author Martin Vermeer
15 * \author Jürgen Vigna
17 * Full author contact details are available in file CREDITS.
24 #include "BranchList.h"
26 #include "buffer_funcs.h"
27 #include "bufferlist.h"
28 #include "bufferparams.h"
29 #include "BufferView.h"
32 #include "dispatchresult.h"
36 #include "funcrequest.h"
40 #include "iterators.h"
44 #include "LyXAction.h"
48 #include "lyxserver.h"
50 #include "paragraph.h"
51 #include "ParagraphParameters.h"
54 #include "insets/insetbox.h"
55 #include "insets/insetbranch.h"
56 #include "insets/insetcommand.h"
57 #include "insets/insetert.h"
58 #include "insets/insetexternal.h"
59 #include "insets/insetfloat.h"
60 #include "insets/insetgraphics.h"
61 #include "insets/insetnote.h"
62 #include "insets/insettabular.h"
63 #include "insets/insetvspace.h"
64 #include "insets/insetwrap.h"
66 #include "frontends/Alert.h"
67 #include "frontends/Dialogs.h"
68 #include "frontends/FileDialog.h"
69 #include "frontends/lyx_gui.h"
70 #include "frontends/LyXKeySym.h"
71 #include "frontends/LyXView.h"
72 #include "frontends/Menubar.h"
73 #include "frontends/Toolbar.h"
75 #include "support/FileInfo.h"
76 #include "support/filetools.h"
77 #include "support/forkedcontr.h"
78 #include "support/globbing.h"
79 #include "support/lstrings.h"
80 #include "support/path.h"
81 #include "support/path_defines.h"
82 #include "support/systemcall.h"
83 #include "support/tostr.h"
84 #include "support/std_sstream.h"
85 #include "support/os.h"
87 using bv_funcs::freefont2string;
89 using lyx::support::AddName;
90 using lyx::support::AddPath;
91 using lyx::support::bformat;
92 using lyx::support::ChangeExtension;
93 using lyx::support::contains;
94 using lyx::support::FileFilterList;
95 using lyx::support::FileInfo;
96 using lyx::support::FileSearch;
97 using lyx::support::ForkedcallsController;
98 using lyx::support::i18nLibFileSearch;
99 using lyx::support::IsDirWriteable;
100 using lyx::support::IsFileReadable;
101 using lyx::support::isStrInt;
102 using lyx::support::MakeAbsPath;
103 using lyx::support::MakeDisplayPath;
104 using lyx::support::Path;
105 using lyx::support::QuoteName;
106 using lyx::support::rtrim;
107 using lyx::support::split;
108 using lyx::support::strToInt;
109 using lyx::support::strToUnsignedInt;
110 using lyx::support::subst;
111 using lyx::support::system_lyxdir;
112 using lyx::support::Systemcall;
113 using lyx::support::token;
114 using lyx::support::trim;
115 using lyx::support::user_lyxdir;
116 using lyx::support::prefixIs;
117 using lyx::support::os::getTmpDir;
120 using std::make_pair;
123 using std::istringstream;
126 extern BufferList bufferlist;
127 extern LyXServer * lyxserver;
128 extern bool selection_possible;
130 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
133 extern tex_accent_struct get_accent(kb_action action);
136 LyXFunc::LyXFunc(LyXView * lv)
139 keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
140 cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
141 meta_fake_bit(key_modifier::none)
146 void LyXFunc::handleKeyFunc(kb_action action)
148 char c = encoded_last_key;
150 if (keyseq.length()) {
154 owner->getIntl().getTransManager()
155 .deadkey(c, get_accent(action).accent, view()->getLyXText());
156 // Need to clear, in case the minibuffer calls these
159 // copied verbatim from do_accent_char
160 view()->cursor().resetAnchor();
165 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
167 lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
169 // Do nothing if we have nothing (JMarc)
170 if (!keysym->isOK()) {
171 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
176 if (keysym->isModifier()) {
177 lyxerr[Debug::KEY] << "isModifier true" << endl;
181 Encoding const * encoding = view()->cursor().getEncoding();
183 encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
185 // Do a one-deep top-level lookup for
186 // cancel and meta-fake keys. RVDK_PATCH_5
187 cancel_meta_seq.reset();
189 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
190 lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
192 // When not cancel or meta-fake, do the normal lookup.
193 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
194 // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
195 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
196 // remove Caps Lock and Mod2 as a modifiers
197 func = keyseq.addkey(keysym, (state | meta_fake_bit));
198 lyxerr[Debug::KEY] << "action now set to ["
199 << func.action << ']' << endl;
202 // Dont remove this unless you know what you are doing.
203 meta_fake_bit = key_modifier::none;
205 // can this happen now ?
206 if (func.action == LFUN_NOACTION) {
207 func = FuncRequest(LFUN_PREFIX);
210 if (lyxerr.debugging(Debug::KEY)) {
211 lyxerr << "Key [action="
212 << func.action << "]["
213 << keyseq.print() << ']'
217 // already here we know if it any point in going further
218 // why not return already here if action == -1 and
219 // num_bytes == 0? (Lgb)
221 if (keyseq.length() > 1) {
222 owner->message(keyseq.print());
226 // Maybe user can only reach the key via holding down shift.
227 // Let's see. But only if shift is the only modifier
228 if (func.action == LFUN_UNKNOWN_ACTION &&
229 state == key_modifier::shift) {
230 lyxerr[Debug::KEY] << "Trying without shift" << endl;
231 func = keyseq.addkey(keysym, key_modifier::none);
232 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
235 if (func.action == LFUN_UNKNOWN_ACTION) {
236 // Hmm, we didn't match any of the keysequences. See
237 // if it's normal insertable text not already covered
239 if (keysym->isText() && keyseq.length() == 1) {
240 lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
241 func = FuncRequest(LFUN_SELFINSERT);
243 lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
244 owner->message(_("Unknown function."));
249 if (func.action == LFUN_SELFINSERT) {
250 if (encoded_last_key != 0) {
251 string arg(1, encoded_last_key);
252 dispatch(FuncRequest(LFUN_SELFINSERT, arg));
254 << "SelfInsert arg[`" << arg << "']" << endl;
262 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
264 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
266 Buffer * buf = owner->buffer();
267 LCursor & cur = view()->cursor();
269 if (cmd.action == LFUN_NOACTION) {
270 setStatusMessage(N_("Nothing to do"));
275 switch (cmd.action) {
276 case LFUN_UNKNOWN_ACTION:
277 #ifndef HAVE_LIBAIKSAURUS
278 case LFUN_THESAURUS_ENTRY:
284 flag |= lyx_gui::getStatus(cmd);
287 if (flag.unknown()) {
288 setStatusMessage(N_("Unknown action"));
292 // the default error message if we disable the command
293 setStatusMessage(N_("Command disabled"));
295 // Check whether we need a buffer
296 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
298 setStatusMessage(N_("Command not allowed with"
299 "out any document open"));
304 // I would really like to avoid having this switch and rather try to
305 // encode this in the function itself.
306 // -- And I'd rather let an inset decide which LFUNs it is willing
307 // to handle (Andre')
309 switch (cmd.action) {
310 case LFUN_TOOLTIPS_TOGGLE:
311 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
314 case LFUN_READ_ONLY_TOGGLE:
315 flag.setOnOff(buf->isReadonly());
318 case LFUN_SWITCHBUFFER:
319 // toggle on the current buffer, but do not toggle off
320 // the other ones (is that a good idea?)
321 if (cmd.argument == buf->fileName())
325 case LFUN_TRACK_CHANGES:
326 flag.setOnOff(buf->params().tracking_changes);
330 enable = cmd.argument == "custom"
331 || Exporter::IsExportable(*buf, cmd.argument);
334 enable = !buf->undostack().empty();
337 enable = !buf->redostack().empty();
341 enable = cur.selection();
345 enable = buf->isLatex() && lyxrc.chktex_command != "none";
349 enable = Exporter::IsExportable(*buf, "program");
352 case LFUN_LAYOUT_TABULAR:
353 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
357 case LFUN_LAYOUT_PARAGRAPH:
358 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
361 case LFUN_VC_REGISTER:
362 enable = !buf->lyxvc().inUse();
364 case LFUN_VC_CHECKIN:
365 enable = buf->lyxvc().inUse() && !buf->isReadonly();
367 case LFUN_VC_CHECKOUT:
368 enable = buf->lyxvc().inUse() && buf->isReadonly();
372 enable = buf->lyxvc().inUse();
374 case LFUN_MENURELOAD:
375 enable = !buf->isUnnamed() && !buf->isClean();
377 case LFUN_BOOKMARK_GOTO:
378 enable = view()->isSavedPosition(strToUnsignedInt(cmd.argument));
381 case LFUN_MERGE_CHANGES:
382 case LFUN_ACCEPT_CHANGE:
383 case LFUN_REJECT_CHANGE:
384 case LFUN_ACCEPT_ALL_CHANGES:
385 case LFUN_REJECT_ALL_CHANGES:
386 enable = buf && buf->params().tracking_changes;
389 case LFUN_INSET_SETTINGS: {
393 UpdatableInset * inset = cur.inset().asUpdatableInset();
394 lyxerr << "inset: " << inset << endl;
398 InsetOld::Code code = inset->lyxCode();
400 case InsetOld::TABULAR_CODE:
401 enable = cmd.argument == "tabular";
403 case InsetOld::ERT_CODE:
404 enable = cmd.argument == "ert";
406 case InsetOld::FLOAT_CODE:
407 enable = cmd.argument == "float";
409 case InsetOld::WRAP_CODE:
410 enable = cmd.argument == "wrap";
412 case InsetOld::NOTE_CODE:
413 enable = cmd.argument == "note";
415 case InsetOld::BRANCH_CODE:
416 enable = cmd.argument == "branch";
418 case InsetOld::BOX_CODE:
419 enable = cmd.argument == "box";
427 case LFUN_DIALOG_SHOW: {
428 string const name = cmd.getArg(0);
430 enable = name == "aboutlyx"
433 || name == "preferences"
434 || name == "texinfo";
435 else if (name == "print")
436 enable = Exporter::IsExportable(*buf, "dvi")
437 && lyxrc.print_command != "none";
438 else if (name == "character")
439 enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
440 else if (name == "vclog")
441 enable = buf->lyxvc().inUse();
442 else if (name == "latexlog")
443 enable = IsFileReadable(buf->getLogName().second);
448 case LFUN_MENUNEWTMPLT:
449 case LFUN_WORDFINDFORWARD:
450 case LFUN_WORDFINDBACKWARD:
452 case LFUN_EXEC_COMMAND:
455 case LFUN_CLOSEBUFFER:
464 case LFUN_RECONFIGURE:
468 case LFUN_DROP_LAYOUTS_CHOICE:
469 case LFUN_MENU_OPEN_BY_NAME:
472 case LFUN_GOTOFILEROW:
473 case LFUN_GOTO_PARAGRAPH:
474 case LFUN_DIALOG_SHOW_NEW_INSET:
475 case LFUN_DIALOG_SHOW_NEXT_INSET:
476 case LFUN_DIALOG_UPDATE:
477 case LFUN_DIALOG_HIDE:
478 case LFUN_DIALOG_DISCONNECT_INSET:
480 case LFUN_TOGGLECURSORFOLLOW:
484 case LFUN_KMAP_TOGGLE:
486 case LFUN_EXPORT_CUSTOM:
489 case LFUN_SAVEPREFERENCES:
490 case LFUN_SCREEN_FONT_UPDATE:
493 case LFUN_EXTERNAL_EDIT:
494 case LFUN_FILE_INSERT:
495 case LFUN_FILE_INSERT_ASCII:
496 case LFUN_FILE_INSERT_ASCII_PARA:
497 // these are handled in our dispatch()
501 cur.getStatus(cmd, flag);
507 // Can we use a readonly buffer?
508 if (buf && buf->isReadonly()
509 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
510 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
511 setStatusMessage(N_("Document is read-only"));
521 bool ensureBufferClean(BufferView * bv)
523 Buffer & buf = *bv->buffer();
527 string const file = MakeDisplayPath(buf.fileName(), 30);
528 string text = bformat(_("The document %1$s has unsaved "
529 "changes.\n\nDo you want to save "
530 "the document?"), file);
531 int const ret = Alert::prompt(_("Save changed document?"),
532 text, 0, 1, _("&Save"),
536 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
538 return buf.isClean();
541 void showPrintError(string const & name)
543 string str = bformat(_("Could not print the document %1$s.\n"
544 "Check that your printer is set up correctly."),
545 MakeDisplayPath(name, 50));
546 Alert::error(_("Print document failed"), str);
552 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
554 string const argument = cmd.argument;
555 kb_action const action = cmd.action;
557 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
558 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
560 // we have not done anything wrong yet.
562 dispatch_buffer.erase();
563 selection_possible = false;
565 // We cannot use this function here
566 if (!getStatus(cmd).enabled()) {
567 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
568 << lyxaction.getActionName(action)
569 << " [" << action << "] is disabled at this location"
571 setErrorMessage(getStatusMessage());
575 if (view()->available())
576 view()->hideCursor();
580 case LFUN_WORDFINDFORWARD:
581 case LFUN_WORDFINDBACKWARD: {
582 static string last_search;
583 string searched_string;
585 if (!argument.empty()) {
586 last_search = argument;
587 searched_string = argument;
589 searched_string = last_search;
592 if (searched_string.empty())
595 bool const fw = action == LFUN_WORDFINDFORWARD;
597 lyx::find::find2string(searched_string, true, false, fw);
598 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
603 owner->message(keyseq.printOptions());
606 case LFUN_EXEC_COMMAND:
607 owner->focus_command_buffer();
612 meta_fake_bit = key_modifier::none;
613 if (view()->available())
614 // cancel any selection
615 dispatch(FuncRequest(LFUN_MARK_OFF));
616 setMessage(N_("Cancel"));
620 meta_fake_bit = key_modifier::alt;
621 setMessage(keyseq.print());
624 case LFUN_READ_ONLY_TOGGLE:
625 if (owner->buffer()->lyxvc().inUse())
626 owner->buffer()->lyxvc().toggleReadOnly();
628 owner->buffer()->setReadonly(
629 !owner->buffer()->isReadonly());
632 // --- Menus -----------------------------------------------
634 menuNew(argument, false);
637 case LFUN_MENUNEWTMPLT:
638 menuNew(argument, true);
641 case LFUN_CLOSEBUFFER:
646 if (!owner->buffer()->isUnnamed()) {
647 string const str = bformat(_("Saving document %1$s..."),
648 MakeDisplayPath(owner->buffer()->fileName()));
650 MenuWrite(owner->buffer());
651 owner->message(str + _(" done."));
653 WriteAs(owner->buffer());
657 WriteAs(owner->buffer(), argument);
660 case LFUN_MENURELOAD: {
661 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
662 string text = bformat(_("Any changes will be lost. Are you sure "
663 "you want to revert to the saved version of the document %1$s?"), file);
664 int const ret = Alert::prompt(_("Revert to saved document?"),
665 text, 0, 1, _("&Revert"), _("&Cancel"));
673 Exporter::Export(owner->buffer(), argument, true);
674 view()->showErrorList(BufferFormat(*owner->buffer()));
678 Exporter::Preview(owner->buffer(), argument);
679 view()->showErrorList(BufferFormat(*owner->buffer()));
683 Exporter::Export(owner->buffer(), "program", true);
684 view()->showErrorList(_("Build"));
688 owner->buffer()->runChktex();
689 view()->showErrorList(_("ChkTeX"));
693 if (argument == "custom")
694 owner->getDialogs().show("sendto");
696 Exporter::Export(owner->buffer(), argument, false);
697 view()->showErrorList(BufferFormat(*owner->buffer()));
701 case LFUN_EXPORT_CUSTOM: {
703 string command = split(argument, format_name, ' ');
704 Format const * format = formats.getFormat(format_name);
706 lyxerr << "Format \"" << format_name
707 << "\" not recognized!"
712 Buffer * buffer = owner->buffer();
714 // The name of the file created by the conversion process
717 // Output to filename
718 if (format->name() == "lyx") {
719 string const latexname =
720 buffer->getLatexName(false);
721 filename = ChangeExtension(latexname,
722 format->extension());
723 filename = AddName(buffer->temppath(), filename);
725 if (!buffer->writeFile(filename))
729 Exporter::Export(buffer, format_name, true,
733 // Substitute $$FName for filename
734 if (!contains(command, "$$FName"))
735 command = "( " + command + " ) < $$FName";
736 command = subst(command, "$$FName", filename);
738 // Execute the command in the background
740 call.startscript(Systemcall::DontWait, command);
747 string command = split(split(argument, target, ' '),
751 || target_name.empty()
752 || command.empty()) {
753 lyxerr << "Unable to parse \""
754 << argument << '"' << std::endl;
757 if (target != "printer" && target != "file") {
758 lyxerr << "Unrecognized target \""
759 << target << '"' << std::endl;
763 Buffer * buffer = owner->buffer();
765 if (!Exporter::Export(buffer, "dvi", true)) {
766 showPrintError(buffer->fileName());
770 // Push directory path.
771 string const path = buffer->temppath();
774 // there are three cases here:
775 // 1. we print to a file
776 // 2. we print directly to a printer
777 // 3. we print using a spool command (print to file first)
780 string const dviname =
781 ChangeExtension(buffer->getLatexName(true),
784 if (target == "printer") {
785 if (!lyxrc.print_spool_command.empty()) {
786 // case 3: print using a spool
787 string const psname =
788 ChangeExtension(dviname,".ps");
789 command += lyxrc.print_to_file
792 + QuoteName(dviname);
795 lyxrc.print_spool_command +' ';
796 if (target_name != "default") {
797 command2 += lyxrc.print_spool_printerprefix
801 command2 += QuoteName(psname);
803 // If successful, then spool command
804 res = one.startscript(
809 res = one.startscript(
810 Systemcall::DontWait,
813 // case 2: print directly to a printer
814 res = one.startscript(
815 Systemcall::DontWait,
816 command + QuoteName(dviname));
820 // case 1: print to a file
821 command += lyxrc.print_to_file
822 + QuoteName(MakeAbsPath(target_name,
825 + QuoteName(dviname);
826 res = one.startscript(Systemcall::DontWait,
831 showPrintError(buffer->fileName());
844 InsetCommandParams p("tableofcontents");
845 string const data = InsetCommandMailer::params2string("toc", p);
846 owner->getDialogs().show("toc", data, 0);
854 case LFUN_RECONFIGURE:
858 case LFUN_HELP_OPEN: {
859 string const arg = argument;
861 setErrorMessage(N_("Missing argument"));
864 string const fname = i18nLibFileSearch("doc", arg, "lyx");
866 lyxerr << "LyX: unable to find documentation file `"
867 << arg << "'. Bad installation?" << endl;
870 owner->message(bformat(_("Opening help file %1$s..."),
871 MakeDisplayPath(fname)));
872 view()->loadLyXFile(fname, false);
876 // --- version control -------------------------------
877 case LFUN_VC_REGISTER:
878 if (!ensureBufferClean(view()))
880 if (!owner->buffer()->lyxvc().inUse()) {
881 owner->buffer()->lyxvc().registrer();
886 case LFUN_VC_CHECKIN:
887 if (!ensureBufferClean(view()))
889 if (owner->buffer()->lyxvc().inUse()
890 && !owner->buffer()->isReadonly()) {
891 owner->buffer()->lyxvc().checkIn();
896 case LFUN_VC_CHECKOUT:
897 if (!ensureBufferClean(view()))
899 if (owner->buffer()->lyxvc().inUse()
900 && owner->buffer()->isReadonly()) {
901 owner->buffer()->lyxvc().checkOut();
907 owner->buffer()->lyxvc().revert();
912 owner->buffer()->lyxvc().undoLast();
916 // --- buffers ----------------------------------------
917 case LFUN_SWITCHBUFFER:
918 view()->setBuffer(bufferlist.getBuffer(argument));
922 NewFile(view(), argument);
929 case LFUN_DROP_LAYOUTS_CHOICE:
930 owner->getToolbar().openLayoutList();
933 case LFUN_MENU_OPEN_BY_NAME:
934 owner->getMenubar().openByName(argument);
937 // --- lyxserver commands ----------------------------
939 setMessage(owner->buffer()->fileName());
940 lyxerr[Debug::INFO] << "FNAME["
941 << owner->buffer()->fileName()
946 dispatch_buffer = keyseq.print();
947 lyxserver->notifyClient(dispatch_buffer);
950 case LFUN_GOTOFILEROW: {
953 istringstream is(argument);
954 is >> file_name >> row;
955 if (prefixIs(file_name, getTmpDir())) {
956 // Needed by inverse dvi search. If it is a file
957 // in tmpdir, call the apropriated function
958 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
960 // Must replace extension of the file to be .lyx
962 string const s = ChangeExtension(file_name, ".lyx");
963 // Either change buffer or load the file
964 if (bufferlist.exists(s)) {
965 view()->setBuffer(bufferlist.getBuffer(s));
967 view()->loadLyXFile(s);
971 view()->setCursorFromRow(row);
974 // see BufferView_pimpl::center()
975 view()->updateScrollbar();
979 case LFUN_GOTO_PARAGRAPH: {
980 istringstream is(argument);
983 ParIterator par = owner->buffer()->getParFromID(id);
984 if (par == owner->buffer()->par_iterator_end()) {
985 lyxerr[Debug::INFO] << "No matching paragraph found! ["
986 << id << ']' << endl;
989 lyxerr[Debug::INFO] << "Paragraph " << par->id()
990 << " found." << endl;
994 view()->setCursor(par, 0);
996 view()->switchKeyMap();
997 owner->view_state_changed();
1000 // see BufferView_pimpl::center()
1001 view()->updateScrollbar();
1005 case LFUN_DIALOG_SHOW: {
1006 string const name = cmd.getArg(0);
1007 string data = trim(cmd.argument.substr(name.size()));
1009 if (name == "character") {
1010 data = freefont2string();
1012 owner->getDialogs().show("character", data);
1014 else if (name == "document")
1015 owner->getDialogs().showDocument();
1016 else if (name == "preamble")
1017 owner->getDialogs().showPreamble();
1018 else if (name == "preferences")
1019 owner->getDialogs().showPreferences();
1020 else if (name == "spellchecker")
1021 owner->getDialogs().showSpellchecker();
1023 else if (name == "latexlog") {
1024 pair<Buffer::LogType, string> const logfile =
1025 owner->buffer()->getLogName();
1026 switch (logfile.first) {
1027 case Buffer::latexlog:
1030 case Buffer::buildlog:
1034 data += logfile.second;
1035 owner->getDialogs().show("log", data);
1037 else if (name == "vclog") {
1038 string const data = "vc " +
1039 owner->buffer()->lyxvc().getLogFile();
1040 owner->getDialogs().show("log", data);
1043 owner->getDialogs().show(name, data);
1047 case LFUN_DIALOG_SHOW_NEW_INSET: {
1048 string const name = cmd.getArg(0);
1049 string data = trim(cmd.argument.substr(name.size()));
1050 if (name == "bibitem" ||
1052 name == "include" ||
1058 InsetCommandParams p(name);
1059 data = InsetCommandMailer::params2string(name, p);
1060 } else if (name == "box") {
1061 // \c data == "Boxed" || "Frameless" etc
1062 InsetBoxParams p(data);
1063 data = InsetBoxMailer::params2string(p);
1064 } else if (name == "branch") {
1065 InsetBranchParams p;
1066 data = InsetBranchMailer::params2string(p);
1067 } else if (name == "citation") {
1068 InsetCommandParams p("cite");
1069 data = InsetCommandMailer::params2string(name, p);
1070 } else if (name == "ert") {
1071 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1072 } else if (name == "external") {
1073 InsetExternalParams p;
1074 Buffer const & buffer = *owner->buffer();
1075 data = InsetExternalMailer::params2string(p, buffer);
1076 } else if (name == "float") {
1078 data = InsetFloatMailer::params2string(p);
1079 } else if (name == "graphics") {
1080 InsetGraphicsParams p;
1081 Buffer const & buffer = *owner->buffer();
1082 data = InsetGraphicsMailer::params2string(p, buffer);
1083 } else if (name == "note") {
1085 data = InsetNoteMailer::params2string(p);
1086 } else if (name == "vspace") {
1088 data = InsetVSpaceMailer::params2string(space);
1089 } else if (name == "wrap") {
1091 data = InsetWrapMailer::params2string(p);
1093 owner->getDialogs().show(name, data, 0);
1097 case LFUN_DIALOG_SHOW_NEXT_INSET:
1100 case LFUN_DIALOG_UPDATE: {
1101 string const & name = argument;
1102 // Can only update a dialog connected to an existing inset
1103 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1105 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1106 inset->dispatch(view()->cursor(), fr);
1107 } else if (name == "paragraph") {
1108 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1113 case LFUN_DIALOG_HIDE:
1114 Dialogs::hide(argument, 0);
1117 case LFUN_DIALOG_DISCONNECT_INSET:
1118 owner->getDialogs().disconnect(argument);
1121 case LFUN_CHILDOPEN: {
1122 string const filename =
1123 MakeAbsPath(argument, owner->buffer()->filePath());
1124 setMessage(N_("Opening child document ") +
1125 MakeDisplayPath(filename) + "...");
1126 view()->savePosition(0);
1127 string const parentfilename = owner->buffer()->fileName();
1128 if (bufferlist.exists(filename))
1129 view()->setBuffer(bufferlist.getBuffer(filename));
1131 view()->loadLyXFile(filename);
1132 // Set the parent name of the child document.
1133 // This makes insertion of citations and references in the child work,
1134 // when the target is in the parent or another child document.
1135 owner->buffer()->setParentName(parentfilename);
1139 case LFUN_TOGGLECURSORFOLLOW:
1140 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1144 owner->getIntl().KeyMapOn(false);
1147 case LFUN_KMAP_PRIM:
1148 owner->getIntl().KeyMapPrim();
1152 owner->getIntl().KeyMapSec();
1155 case LFUN_KMAP_TOGGLE:
1156 owner->getIntl().ToggleKeyMap();
1162 string rest = split(argument, countstr, ' ');
1163 istringstream is(countstr);
1166 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1167 for (int i = 0; i < count; ++i)
1168 dispatch(lyxaction.lookupFunc(rest));
1173 // argument contains ';'-terminated commands
1174 while (!argument.empty()) {
1176 string rest = split(argument, first, ';');
1177 dispatch(lyxaction.lookupFunc(rest));
1181 case LFUN_SAVEPREFERENCES: {
1182 Path p(user_lyxdir());
1183 lyxrc.write("preferences");
1187 case LFUN_SCREEN_FONT_UPDATE:
1188 // handle the screen font changes.
1189 lyxrc.set_font_norm_type();
1190 lyx_gui::update_fonts();
1191 // All visible buffers will need resize
1195 case LFUN_SET_COLOR: {
1197 string const x11_name = split(argument, lyx_name, ' ');
1198 if (lyx_name.empty() || x11_name.empty()) {
1199 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1204 bool const graphicsbg_changed =
1205 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1206 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1208 if (!lcolor.setColor(lyx_name, x11_name)) {
1210 bformat(_("Set-color \"%1$s\" failed "
1211 "- color is undefined or "
1212 "may not be redefined"), lyx_name));
1216 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1218 if (graphicsbg_changed) {
1219 #ifdef WITH_WARNINGS
1220 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1223 lyx::graphics::GCache::get().changeDisplay(true);
1230 owner->message(argument);
1233 case LFUN_TOOLTIPS_TOGGLE:
1234 owner->getDialogs().toggleTooltips();
1237 case LFUN_EXTERNAL_EDIT: {
1238 FuncRequest fr(action, argument);
1239 InsetExternal().dispatch(view()->cursor(), fr);
1243 case LFUN_BREAKLINE: {
1244 #warning swallow 'Return' if the minibuffer is focused. But how?
1248 DispatchResult res = view()->cursor().dispatch(cmd);
1249 if (!res.dispatched());
1250 view()->dispatch(cmd);
1255 if (view()->available()) {
1256 view()->fitCursor();
1258 view()->cursor().updatePos();
1259 // if we executed a mutating lfun, mark the buffer as dirty
1260 if (getStatus(cmd).enabled()
1261 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1262 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1263 view()->buffer()->markDirty();
1266 if (view()->cursor().inTexted()) {
1267 view()->owner()->updateLayoutChoice();
1268 sendDispatchMessage(getMessage(), cmd, verbose);
1274 void LyXFunc::sendDispatchMessage(string const & msg,
1275 FuncRequest const & cmd, bool verbose)
1277 owner->updateMenubar();
1278 owner->updateToolbar();
1280 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1281 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1283 owner->message(msg);
1287 string dispatch_msg = msg;
1288 if (!dispatch_msg.empty())
1289 dispatch_msg += ' ';
1291 string comname = lyxaction.getActionName(cmd.action);
1293 bool argsadded = false;
1295 if (!cmd.argument.empty()) {
1296 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1297 comname += ' ' + cmd.argument;
1302 string const shortcuts = toplevel_keymap->findbinding(cmd);
1304 if (!shortcuts.empty()) {
1305 comname += ": " + shortcuts;
1306 } else if (!argsadded && !cmd.argument.empty()) {
1307 comname += ' ' + cmd.argument;
1310 if (!comname.empty()) {
1311 comname = rtrim(comname);
1312 dispatch_msg += '(' + comname + ')';
1315 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1316 if (!dispatch_msg.empty())
1317 owner->message(dispatch_msg);
1321 void LyXFunc::setupLocalKeymap()
1323 keyseq.stdmap = toplevel_keymap.get();
1324 keyseq.curmap = toplevel_keymap.get();
1325 cancel_meta_seq.stdmap = toplevel_keymap.get();
1326 cancel_meta_seq.curmap = toplevel_keymap.get();
1330 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1332 string initpath = lyxrc.document_path;
1333 string filename(name);
1335 if (view()->available()) {
1336 string const trypath = owner->buffer()->filePath();
1337 // If directory is writeable, use this as default.
1338 if (IsDirWriteable(trypath))
1342 static int newfile_number;
1344 if (filename.empty()) {
1345 filename = AddName(lyxrc.document_path,
1346 "newfile" + tostr(++newfile_number) + ".lyx");
1347 FileInfo fi(filename);
1348 while (bufferlist.exists(filename) || fi.readable()) {
1350 filename = AddName(lyxrc.document_path,
1351 "newfile" + tostr(newfile_number) +
1353 fi.newFile(filename);
1357 // The template stuff
1360 FileDialog fileDlg(_("Select template file"),
1361 LFUN_SELECT_FILE_SYNC,
1362 make_pair(string(_("Documents|#o#O")),
1363 string(lyxrc.document_path)),
1364 make_pair(string(_("Templates|#T#t")),
1365 string(lyxrc.template_path)));
1367 FileDialog::Result result =
1368 fileDlg.open(lyxrc.template_path,
1369 FileFilterList(_("LyX Documents (*.lyx)")),
1372 if (result.first == FileDialog::Later)
1374 if (result.second.empty())
1376 templname = result.second;
1379 view()->newFile(filename, templname, !name.empty());
1383 void LyXFunc::open(string const & fname)
1385 string initpath = lyxrc.document_path;
1387 if (view()->available()) {
1388 string const trypath = owner->buffer()->filePath();
1389 // If directory is writeable, use this as default.
1390 if (IsDirWriteable(trypath))
1396 if (fname.empty()) {
1397 FileDialog fileDlg(_("Select document to open"),
1399 make_pair(string(_("Documents|#o#O")),
1400 string(lyxrc.document_path)),
1401 make_pair(string(_("Examples|#E#e")),
1402 string(AddPath(system_lyxdir(), "examples"))));
1404 FileDialog::Result result =
1405 fileDlg.open(initpath,
1406 FileFilterList(_("LyX Documents (*.lyx)")),
1409 if (result.first == FileDialog::Later)
1412 filename = result.second;
1414 // check selected filename
1415 if (filename.empty()) {
1416 owner->message(_("Canceled."));
1422 // get absolute path of file and add ".lyx" to the filename if
1424 string const fullpath = FileSearch(string(), filename, "lyx");
1425 if (!fullpath.empty()) {
1426 filename = fullpath;
1429 string const disp_fn(MakeDisplayPath(filename));
1431 // if the file doesn't exist, let the user create one
1432 FileInfo const f(filename, true);
1434 // the user specifically chose this name. Believe them.
1435 view()->newFile(filename, "", true);
1439 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1442 if (view()->loadLyXFile(filename)) {
1443 str2 = bformat(_("Document %1$s opened."), disp_fn);
1445 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1447 owner->message(str2);
1451 void LyXFunc::doImport(string const & argument)
1454 string filename = split(argument, format, ' ');
1456 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1457 << " file: " << filename << endl;
1459 // need user interaction
1460 if (filename.empty()) {
1461 string initpath = lyxrc.document_path;
1463 if (view()->available()) {
1464 string const trypath = owner->buffer()->filePath();
1465 // If directory is writeable, use this as default.
1466 if (IsDirWriteable(trypath))
1470 string const text = bformat(_("Select %1$s file to import"),
1471 formats.prettyName(format));
1473 FileDialog fileDlg(text,
1475 make_pair(string(_("Documents|#o#O")),
1476 string(lyxrc.document_path)),
1477 make_pair(string(_("Examples|#E#e")),
1478 string(AddPath(system_lyxdir(), "examples"))));
1480 string const filter = formats.prettyName(format)
1481 + " (*." + formats.extension(format) + ')';
1483 FileDialog::Result result =
1484 fileDlg.open(initpath,
1485 FileFilterList(filter),
1488 if (result.first == FileDialog::Later)
1491 filename = result.second;
1493 // check selected filename
1494 if (filename.empty())
1495 owner->message(_("Canceled."));
1498 if (filename.empty())
1501 // get absolute path of file
1502 filename = MakeAbsPath(filename);
1504 string const lyxfile = ChangeExtension(filename, ".lyx");
1506 // Check if the document already is open
1507 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1508 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1509 owner->message(_("Canceled."));
1514 // if the file exists already, and we didn't do
1515 // -i lyx thefile.lyx, warn
1516 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1517 string const file = MakeDisplayPath(lyxfile, 30);
1519 string text = bformat(_("The document %1$s already exists.\n\n"
1520 "Do you want to over-write that document?"), file);
1521 int const ret = Alert::prompt(_("Over-write document?"),
1522 text, 0, 1, _("&Over-write"), _("&Cancel"));
1525 owner->message(_("Canceled."));
1530 Importer::Import(owner, filename, format);
1534 void LyXFunc::closeBuffer()
1536 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1537 if (bufferlist.empty()) {
1538 // need this otherwise SEGV may occur while
1539 // trying to set variables that don't exist
1540 // since there's no current buffer
1541 owner->getDialogs().hideBufferDependent();
1543 view()->setBuffer(bufferlist.first());
1549 // Each "owner" should have it's own message method. lyxview and
1550 // the minibuffer would use the minibuffer, but lyxserver would
1551 // send an ERROR signal to its client. Alejandro 970603
1552 // This function is bit problematic when it comes to NLS, to make the
1553 // lyx servers client be language indepenent we must not translate
1554 // strings sent to this func.
1555 void LyXFunc::setErrorMessage(string const & m) const
1557 dispatch_buffer = m;
1562 void LyXFunc::setMessage(string const & m) const
1564 dispatch_buffer = m;
1568 void LyXFunc::setStatusMessage(string const & m) const
1574 string const LyXFunc::viewStatusMessage()
1576 // When meta-fake key is pressed, show the key sequence so far + "M-".
1578 return keyseq.print() + "M-";
1580 // Else, when a non-complete key sequence is pressed,
1581 // show the available options.
1582 if (keyseq.length() > 0 && !keyseq.deleted())
1583 return keyseq.printOptions();
1585 if (!view()->available())
1586 return _("Welcome to LyX!");
1588 return view()->cursor().currentState();
1592 BufferView * LyXFunc::view() const
1594 BOOST_ASSERT(owner);
1595 return owner->view().get();
1599 bool LyXFunc::wasMetaKey() const
1601 return (meta_fake_bit != key_modifier::none);