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"
39 #include "insetiterator.h"
44 #include "LyXAction.h"
48 #include "lyxserver.h"
50 #include "paragraph.h"
51 #include "pariterator.h"
52 #include "ParagraphParameters.h"
55 #include "insets/insetbox.h"
56 #include "insets/insetbranch.h"
57 #include "insets/insetcommand.h"
58 #include "insets/insetert.h"
59 #include "insets/insetexternal.h"
60 #include "insets/insetfloat.h"
61 #include "insets/insetgraphics.h"
62 #include "insets/insetnote.h"
63 #include "insets/insettabular.h"
64 #include "insets/insetvspace.h"
65 #include "insets/insetwrap.h"
67 #include "frontends/Alert.h"
68 #include "frontends/Dialogs.h"
69 #include "frontends/FileDialog.h"
70 #include "frontends/lyx_gui.h"
71 #include "frontends/LyXKeySym.h"
72 #include "frontends/LyXView.h"
73 #include "frontends/Menubar.h"
74 #include "frontends/Toolbar.h"
76 #include "support/FileInfo.h"
77 #include "support/filetools.h"
78 #include "support/forkedcontr.h"
79 #include "support/globbing.h"
80 #include "support/lstrings.h"
81 #include "support/path.h"
82 #include "support/path_defines.h"
83 #include "support/systemcall.h"
84 #include "support/tostr.h"
85 #include "support/std_sstream.h"
86 #include "support/os.h"
88 using bv_funcs::freefont2string;
90 using lyx::support::AddName;
91 using lyx::support::AddPath;
92 using lyx::support::bformat;
93 using lyx::support::ChangeExtension;
94 using lyx::support::contains;
95 using lyx::support::FileFilterList;
96 using lyx::support::FileInfo;
97 using lyx::support::FileSearch;
98 using lyx::support::ForkedcallsController;
99 using lyx::support::i18nLibFileSearch;
100 using lyx::support::IsDirWriteable;
101 using lyx::support::IsFileReadable;
102 using lyx::support::isStrInt;
103 using lyx::support::MakeAbsPath;
104 using lyx::support::MakeDisplayPath;
105 using lyx::support::Path;
106 using lyx::support::QuoteName;
107 using lyx::support::rtrim;
108 using lyx::support::split;
109 using lyx::support::strToInt;
110 using lyx::support::strToUnsignedInt;
111 using lyx::support::subst;
112 using lyx::support::system_lyxdir;
113 using lyx::support::Systemcall;
114 using lyx::support::token;
115 using lyx::support::trim;
116 using lyx::support::user_lyxdir;
117 using lyx::support::prefixIs;
118 using lyx::support::os::getTmpDir;
121 using std::make_pair;
124 using std::istringstream;
127 extern BufferList bufferlist;
128 extern LyXServer * lyxserver;
129 extern bool selection_possible;
131 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
134 extern tex_accent_struct get_accent(kb_action action);
137 LyXFunc::LyXFunc(LyXView * lv)
140 keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
141 cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
142 meta_fake_bit(key_modifier::none)
147 void LyXFunc::handleKeyFunc(kb_action action)
149 char c = encoded_last_key;
151 if (keyseq.length()) {
155 owner->getIntl().getTransManager()
156 .deadkey(c, get_accent(action).accent, view()->getLyXText());
157 // Need to clear, in case the minibuffer calls these
160 // copied verbatim from do_accent_char
161 view()->cursor().resetAnchor();
166 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
168 lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
170 // Do nothing if we have nothing (JMarc)
171 if (!keysym->isOK()) {
172 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
177 if (keysym->isModifier()) {
178 lyxerr[Debug::KEY] << "isModifier true" << endl;
182 Encoding const * encoding = view()->cursor().getEncoding();
184 encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
186 // Do a one-deep top-level lookup for
187 // cancel and meta-fake keys. RVDK_PATCH_5
188 cancel_meta_seq.reset();
190 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
191 lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
193 // When not cancel or meta-fake, do the normal lookup.
194 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
195 // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
196 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
197 // remove Caps Lock and Mod2 as a modifiers
198 func = keyseq.addkey(keysym, (state | meta_fake_bit));
199 lyxerr[Debug::KEY] << "action now set to ["
200 << func.action << ']' << endl;
203 // Dont remove this unless you know what you are doing.
204 meta_fake_bit = key_modifier::none;
206 // can this happen now ?
207 if (func.action == LFUN_NOACTION) {
208 func = FuncRequest(LFUN_PREFIX);
211 if (lyxerr.debugging(Debug::KEY)) {
212 lyxerr << "Key [action="
213 << func.action << "]["
214 << keyseq.print() << ']'
218 // already here we know if it any point in going further
219 // why not return already here if action == -1 and
220 // num_bytes == 0? (Lgb)
222 if (keyseq.length() > 1) {
223 owner->message(keyseq.print());
227 // Maybe user can only reach the key via holding down shift.
228 // Let's see. But only if shift is the only modifier
229 if (func.action == LFUN_UNKNOWN_ACTION &&
230 state == key_modifier::shift) {
231 lyxerr[Debug::KEY] << "Trying without shift" << endl;
232 func = keyseq.addkey(keysym, key_modifier::none);
233 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
236 if (func.action == LFUN_UNKNOWN_ACTION) {
237 // Hmm, we didn't match any of the keysequences. See
238 // if it's normal insertable text not already covered
240 if (keysym->isText() && keyseq.length() == 1) {
241 lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
242 func = FuncRequest(LFUN_SELFINSERT);
244 lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
245 owner->message(_("Unknown function."));
250 if (func.action == LFUN_SELFINSERT) {
251 if (encoded_last_key != 0) {
252 string arg(1, encoded_last_key);
253 dispatch(FuncRequest(LFUN_SELFINSERT, arg));
255 << "SelfInsert arg[`" << arg << "']" << endl;
263 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
265 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
267 Buffer * buf = owner->buffer();
268 LCursor & cur = view()->cursor();
270 if (cmd.action == LFUN_NOACTION) {
271 setStatusMessage(N_("Nothing to do"));
276 switch (cmd.action) {
277 case LFUN_UNKNOWN_ACTION:
278 #ifndef HAVE_LIBAIKSAURUS
279 case LFUN_THESAURUS_ENTRY:
285 flag |= lyx_gui::getStatus(cmd);
288 if (flag.unknown()) {
289 setStatusMessage(N_("Unknown action"));
293 // the default error message if we disable the command
294 setStatusMessage(N_("Command disabled"));
296 // Check whether we need a buffer
297 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
299 setStatusMessage(N_("Command not allowed with"
300 "out any document open"));
305 // I would really like to avoid having this switch and rather try to
306 // encode this in the function itself.
307 // -- And I'd rather let an inset decide which LFUNs it is willing
308 // to handle (Andre')
310 switch (cmd.action) {
311 case LFUN_TOOLTIPS_TOGGLE:
312 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
315 case LFUN_READ_ONLY_TOGGLE:
316 flag.setOnOff(buf->isReadonly());
319 case LFUN_SWITCHBUFFER:
320 // toggle on the current buffer, but do not toggle off
321 // the other ones (is that a good idea?)
322 if (cmd.argument == buf->fileName())
326 case LFUN_TRACK_CHANGES:
327 flag.setOnOff(buf->params().tracking_changes);
331 enable = cmd.argument == "custom"
332 || Exporter::IsExportable(*buf, cmd.argument);
335 enable = !buf->undostack().empty();
338 enable = !buf->redostack().empty();
342 enable = cur.selection();
346 enable = buf->isLatex() && lyxrc.chktex_command != "none";
350 enable = Exporter::IsExportable(*buf, "program");
353 case LFUN_LAYOUT_TABULAR:
354 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
358 case LFUN_LAYOUT_PARAGRAPH:
359 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
362 case LFUN_VC_REGISTER:
363 enable = !buf->lyxvc().inUse();
365 case LFUN_VC_CHECKIN:
366 enable = buf->lyxvc().inUse() && !buf->isReadonly();
368 case LFUN_VC_CHECKOUT:
369 enable = buf->lyxvc().inUse() && buf->isReadonly();
373 enable = buf->lyxvc().inUse();
375 case LFUN_MENURELOAD:
376 enable = !buf->isUnnamed() && !buf->isClean();
378 case LFUN_BOOKMARK_GOTO:
379 enable = view()->isSavedPosition(strToUnsignedInt(cmd.argument));
382 case LFUN_MERGE_CHANGES:
383 case LFUN_ACCEPT_CHANGE:
384 case LFUN_REJECT_CHANGE:
385 case LFUN_ACCEPT_ALL_CHANGES:
386 case LFUN_REJECT_ALL_CHANGES:
387 enable = buf && buf->params().tracking_changes;
390 case LFUN_INSET_SETTINGS: {
394 UpdatableInset * inset = cur.inset().asUpdatableInset();
395 lyxerr << "inset: " << inset << endl;
399 InsetOld::Code code = inset->lyxCode();
401 case InsetOld::TABULAR_CODE:
402 enable = cmd.argument == "tabular";
404 case InsetOld::ERT_CODE:
405 enable = cmd.argument == "ert";
407 case InsetOld::FLOAT_CODE:
408 enable = cmd.argument == "float";
410 case InsetOld::WRAP_CODE:
411 enable = cmd.argument == "wrap";
413 case InsetOld::NOTE_CODE:
414 enable = cmd.argument == "note";
416 case InsetOld::BRANCH_CODE:
417 enable = cmd.argument == "branch";
419 case InsetOld::BOX_CODE:
420 enable = cmd.argument == "box";
428 case LFUN_DIALOG_SHOW: {
429 string const name = cmd.getArg(0);
431 enable = name == "aboutlyx"
434 || name == "preferences"
435 || name == "texinfo";
436 else if (name == "print")
437 enable = Exporter::IsExportable(*buf, "dvi")
438 && lyxrc.print_command != "none";
439 else if (name == "character")
440 enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
441 else if (name == "vclog")
442 enable = buf->lyxvc().inUse();
443 else if (name == "latexlog")
444 enable = IsFileReadable(buf->getLogName().second);
449 case LFUN_MENUNEWTMPLT:
450 case LFUN_WORDFINDFORWARD:
451 case LFUN_WORDFINDBACKWARD:
453 case LFUN_EXEC_COMMAND:
456 case LFUN_CLOSEBUFFER:
465 case LFUN_RECONFIGURE:
469 case LFUN_DROP_LAYOUTS_CHOICE:
470 case LFUN_MENU_OPEN_BY_NAME:
473 case LFUN_GOTOFILEROW:
474 case LFUN_GOTO_PARAGRAPH:
475 case LFUN_DIALOG_SHOW_NEW_INSET:
476 case LFUN_DIALOG_SHOW_NEXT_INSET:
477 case LFUN_DIALOG_UPDATE:
478 case LFUN_DIALOG_HIDE:
479 case LFUN_DIALOG_DISCONNECT_INSET:
481 case LFUN_TOGGLECURSORFOLLOW:
485 case LFUN_KMAP_TOGGLE:
487 case LFUN_EXPORT_CUSTOM:
490 case LFUN_SAVEPREFERENCES:
491 case LFUN_SCREEN_FONT_UPDATE:
494 case LFUN_EXTERNAL_EDIT:
495 case LFUN_FILE_INSERT:
496 case LFUN_FILE_INSERT_ASCII:
497 case LFUN_FILE_INSERT_ASCII_PARA:
498 case LFUN_ALL_INSETS_TOGGLE:
499 // these are handled in our dispatch()
503 cur.getStatus(cmd, flag);
509 // Can we use a readonly buffer?
510 if (buf && buf->isReadonly()
511 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
512 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
513 setStatusMessage(N_("Document is read-only"));
523 bool ensureBufferClean(BufferView * bv)
525 Buffer & buf = *bv->buffer();
529 string const file = MakeDisplayPath(buf.fileName(), 30);
530 string text = bformat(_("The document %1$s has unsaved "
531 "changes.\n\nDo you want to save "
532 "the document?"), file);
533 int const ret = Alert::prompt(_("Save changed document?"),
534 text, 0, 1, _("&Save"),
538 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
540 return buf.isClean();
543 void showPrintError(string const & name)
545 string str = bformat(_("Could not print the document %1$s.\n"
546 "Check that your printer is set up correctly."),
547 MakeDisplayPath(name, 50));
548 Alert::error(_("Print document failed"), str);
554 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
556 string const argument = cmd.argument;
557 kb_action const action = cmd.action;
559 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
560 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
562 // we have not done anything wrong yet.
564 dispatch_buffer.erase();
565 selection_possible = false;
567 // We cannot use this function here
568 if (!getStatus(cmd).enabled()) {
569 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
570 << lyxaction.getActionName(action)
571 << " [" << action << "] is disabled at this location"
573 setErrorMessage(getStatusMessage());
577 if (view()->available())
578 view()->hideCursor();
582 case LFUN_WORDFINDFORWARD:
583 case LFUN_WORDFINDBACKWARD: {
584 static string last_search;
585 string searched_string;
587 if (!argument.empty()) {
588 last_search = argument;
589 searched_string = argument;
591 searched_string = last_search;
594 if (searched_string.empty())
597 bool const fw = action == LFUN_WORDFINDFORWARD;
599 lyx::find::find2string(searched_string, true, false, fw);
600 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
605 owner->message(keyseq.printOptions());
608 case LFUN_EXEC_COMMAND:
609 owner->focus_command_buffer();
614 meta_fake_bit = key_modifier::none;
615 if (view()->available())
616 // cancel any selection
617 dispatch(FuncRequest(LFUN_MARK_OFF));
618 setMessage(N_("Cancel"));
622 meta_fake_bit = key_modifier::alt;
623 setMessage(keyseq.print());
626 case LFUN_READ_ONLY_TOGGLE:
627 if (owner->buffer()->lyxvc().inUse())
628 owner->buffer()->lyxvc().toggleReadOnly();
630 owner->buffer()->setReadonly(
631 !owner->buffer()->isReadonly());
634 // --- Menus -----------------------------------------------
636 menuNew(argument, false);
639 case LFUN_MENUNEWTMPLT:
640 menuNew(argument, true);
643 case LFUN_CLOSEBUFFER:
648 if (!owner->buffer()->isUnnamed()) {
649 string const str = bformat(_("Saving document %1$s..."),
650 MakeDisplayPath(owner->buffer()->fileName()));
652 MenuWrite(owner->buffer());
653 owner->message(str + _(" done."));
655 WriteAs(owner->buffer());
659 WriteAs(owner->buffer(), argument);
662 case LFUN_MENURELOAD: {
663 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
664 string text = bformat(_("Any changes will be lost. Are you sure "
665 "you want to revert to the saved version of the document %1$s?"), file);
666 int const ret = Alert::prompt(_("Revert to saved document?"),
667 text, 0, 1, _("&Revert"), _("&Cancel"));
675 Exporter::Export(owner->buffer(), argument, true);
676 view()->showErrorList(BufferFormat(*owner->buffer()));
680 Exporter::Preview(owner->buffer(), argument);
681 view()->showErrorList(BufferFormat(*owner->buffer()));
685 Exporter::Export(owner->buffer(), "program", true);
686 view()->showErrorList(_("Build"));
690 owner->buffer()->runChktex();
691 view()->showErrorList(_("ChkTeX"));
695 if (argument == "custom")
696 owner->getDialogs().show("sendto");
698 Exporter::Export(owner->buffer(), argument, false);
699 view()->showErrorList(BufferFormat(*owner->buffer()));
703 case LFUN_EXPORT_CUSTOM: {
705 string command = split(argument, format_name, ' ');
706 Format const * format = formats.getFormat(format_name);
708 lyxerr << "Format \"" << format_name
709 << "\" not recognized!"
714 Buffer * buffer = owner->buffer();
716 // The name of the file created by the conversion process
719 // Output to filename
720 if (format->name() == "lyx") {
721 string const latexname =
722 buffer->getLatexName(false);
723 filename = ChangeExtension(latexname,
724 format->extension());
725 filename = AddName(buffer->temppath(), filename);
727 if (!buffer->writeFile(filename))
731 Exporter::Export(buffer, format_name, true,
735 // Substitute $$FName for filename
736 if (!contains(command, "$$FName"))
737 command = "( " + command + " ) < $$FName";
738 command = subst(command, "$$FName", filename);
740 // Execute the command in the background
742 call.startscript(Systemcall::DontWait, command);
749 string command = split(split(argument, target, ' '),
753 || target_name.empty()
754 || command.empty()) {
755 lyxerr << "Unable to parse \""
756 << argument << '"' << std::endl;
759 if (target != "printer" && target != "file") {
760 lyxerr << "Unrecognized target \""
761 << target << '"' << std::endl;
765 Buffer * buffer = owner->buffer();
767 if (!Exporter::Export(buffer, "dvi", true)) {
768 showPrintError(buffer->fileName());
772 // Push directory path.
773 string const path = buffer->temppath();
776 // there are three cases here:
777 // 1. we print to a file
778 // 2. we print directly to a printer
779 // 3. we print using a spool command (print to file first)
782 string const dviname =
783 ChangeExtension(buffer->getLatexName(true),
786 if (target == "printer") {
787 if (!lyxrc.print_spool_command.empty()) {
788 // case 3: print using a spool
789 string const psname =
790 ChangeExtension(dviname,".ps");
791 command += lyxrc.print_to_file
794 + QuoteName(dviname);
797 lyxrc.print_spool_command +' ';
798 if (target_name != "default") {
799 command2 += lyxrc.print_spool_printerprefix
803 command2 += QuoteName(psname);
805 // If successful, then spool command
806 res = one.startscript(
811 res = one.startscript(
812 Systemcall::DontWait,
815 // case 2: print directly to a printer
816 res = one.startscript(
817 Systemcall::DontWait,
818 command + QuoteName(dviname));
822 // case 1: print to a file
823 command += lyxrc.print_to_file
824 + QuoteName(MakeAbsPath(target_name,
827 + QuoteName(dviname);
828 res = one.startscript(Systemcall::DontWait,
833 showPrintError(buffer->fileName());
846 InsetCommandParams p("tableofcontents");
847 string const data = InsetCommandMailer::params2string("toc", p);
848 owner->getDialogs().show("toc", data, 0);
856 case LFUN_RECONFIGURE:
860 case LFUN_HELP_OPEN: {
861 string const arg = argument;
863 setErrorMessage(N_("Missing argument"));
866 string const fname = i18nLibFileSearch("doc", arg, "lyx");
868 lyxerr << "LyX: unable to find documentation file `"
869 << arg << "'. Bad installation?" << endl;
872 owner->message(bformat(_("Opening help file %1$s..."),
873 MakeDisplayPath(fname)));
874 view()->loadLyXFile(fname, false);
878 // --- version control -------------------------------
879 case LFUN_VC_REGISTER:
880 if (!ensureBufferClean(view()))
882 if (!owner->buffer()->lyxvc().inUse()) {
883 owner->buffer()->lyxvc().registrer();
888 case LFUN_VC_CHECKIN:
889 if (!ensureBufferClean(view()))
891 if (owner->buffer()->lyxvc().inUse()
892 && !owner->buffer()->isReadonly()) {
893 owner->buffer()->lyxvc().checkIn();
898 case LFUN_VC_CHECKOUT:
899 if (!ensureBufferClean(view()))
901 if (owner->buffer()->lyxvc().inUse()
902 && owner->buffer()->isReadonly()) {
903 owner->buffer()->lyxvc().checkOut();
909 owner->buffer()->lyxvc().revert();
914 owner->buffer()->lyxvc().undoLast();
918 // --- buffers ----------------------------------------
919 case LFUN_SWITCHBUFFER:
920 view()->setBuffer(bufferlist.getBuffer(argument));
924 NewFile(view(), argument);
931 case LFUN_DROP_LAYOUTS_CHOICE:
932 owner->getToolbar().openLayoutList();
935 case LFUN_MENU_OPEN_BY_NAME:
936 owner->getMenubar().openByName(argument);
939 // --- lyxserver commands ----------------------------
941 setMessage(owner->buffer()->fileName());
942 lyxerr[Debug::INFO] << "FNAME["
943 << owner->buffer()->fileName()
948 dispatch_buffer = keyseq.print();
949 lyxserver->notifyClient(dispatch_buffer);
952 case LFUN_GOTOFILEROW: {
955 istringstream is(argument);
956 is >> file_name >> row;
957 if (prefixIs(file_name, getTmpDir())) {
958 // Needed by inverse dvi search. If it is a file
959 // in tmpdir, call the apropriated function
960 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
962 // Must replace extension of the file to be .lyx
964 string const s = ChangeExtension(file_name, ".lyx");
965 // Either change buffer or load the file
966 if (bufferlist.exists(s)) {
967 view()->setBuffer(bufferlist.getBuffer(s));
969 view()->loadLyXFile(s);
973 view()->setCursorFromRow(row);
976 // see BufferView_pimpl::center()
977 view()->updateScrollbar();
981 case LFUN_GOTO_PARAGRAPH: {
982 istringstream is(argument);
985 ParIterator par = owner->buffer()->getParFromID(id);
986 if (par == owner->buffer()->par_iterator_end()) {
987 lyxerr[Debug::INFO] << "No matching paragraph found! ["
988 << id << ']' << endl;
991 lyxerr[Debug::INFO] << "Paragraph " << par->id()
992 << " found." << endl;
996 view()->setCursor(par, 0);
998 view()->switchKeyMap();
999 owner->view_state_changed();
1002 // see BufferView_pimpl::center()
1003 view()->updateScrollbar();
1007 case LFUN_DIALOG_SHOW: {
1008 string const name = cmd.getArg(0);
1009 string data = trim(cmd.argument.substr(name.size()));
1011 if (name == "character") {
1012 data = freefont2string();
1014 owner->getDialogs().show("character", data);
1016 else if (name == "document")
1017 owner->getDialogs().showDocument();
1018 else if (name == "preamble")
1019 owner->getDialogs().showPreamble();
1020 else if (name == "preferences")
1021 owner->getDialogs().showPreferences();
1022 else if (name == "spellchecker")
1023 owner->getDialogs().showSpellchecker();
1025 else if (name == "latexlog") {
1026 pair<Buffer::LogType, string> const logfile =
1027 owner->buffer()->getLogName();
1028 switch (logfile.first) {
1029 case Buffer::latexlog:
1032 case Buffer::buildlog:
1036 data += logfile.second;
1037 owner->getDialogs().show("log", data);
1039 else if (name == "vclog") {
1040 string const data = "vc " +
1041 owner->buffer()->lyxvc().getLogFile();
1042 owner->getDialogs().show("log", data);
1045 owner->getDialogs().show(name, data);
1049 case LFUN_DIALOG_SHOW_NEW_INSET: {
1050 string const name = cmd.getArg(0);
1051 string data = trim(cmd.argument.substr(name.size()));
1052 if (name == "bibitem" ||
1054 name == "include" ||
1060 InsetCommandParams p(name);
1061 data = InsetCommandMailer::params2string(name, p);
1062 } else if (name == "box") {
1063 // \c data == "Boxed" || "Frameless" etc
1064 InsetBoxParams p(data);
1065 data = InsetBoxMailer::params2string(p);
1066 } else if (name == "branch") {
1067 InsetBranchParams p;
1068 data = InsetBranchMailer::params2string(p);
1069 } else if (name == "citation") {
1070 InsetCommandParams p("cite");
1071 data = InsetCommandMailer::params2string(name, p);
1072 } else if (name == "ert") {
1073 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1074 } else if (name == "external") {
1075 InsetExternalParams p;
1076 Buffer const & buffer = *owner->buffer();
1077 data = InsetExternalMailer::params2string(p, buffer);
1078 } else if (name == "float") {
1080 data = InsetFloatMailer::params2string(p);
1081 } else if (name == "graphics") {
1082 InsetGraphicsParams p;
1083 Buffer const & buffer = *owner->buffer();
1084 data = InsetGraphicsMailer::params2string(p, buffer);
1085 } else if (name == "note") {
1087 data = InsetNoteMailer::params2string(p);
1088 } else if (name == "vspace") {
1090 data = InsetVSpaceMailer::params2string(space);
1091 } else if (name == "wrap") {
1093 data = InsetWrapMailer::params2string(p);
1095 owner->getDialogs().show(name, data, 0);
1099 case LFUN_DIALOG_SHOW_NEXT_INSET:
1102 case LFUN_DIALOG_UPDATE: {
1103 string const & name = argument;
1104 // Can only update a dialog connected to an existing inset
1105 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1107 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1108 inset->dispatch(view()->cursor(), fr);
1109 } else if (name == "paragraph") {
1110 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1115 case LFUN_DIALOG_HIDE:
1116 Dialogs::hide(argument, 0);
1119 case LFUN_DIALOG_DISCONNECT_INSET:
1120 owner->getDialogs().disconnect(argument);
1123 case LFUN_CHILDOPEN: {
1124 string const filename =
1125 MakeAbsPath(argument, owner->buffer()->filePath());
1126 setMessage(N_("Opening child document ") +
1127 MakeDisplayPath(filename) + "...");
1128 view()->savePosition(0);
1129 string const parentfilename = owner->buffer()->fileName();
1130 if (bufferlist.exists(filename))
1131 view()->setBuffer(bufferlist.getBuffer(filename));
1133 view()->loadLyXFile(filename);
1134 // Set the parent name of the child document.
1135 // This makes insertion of citations and references in the child work,
1136 // when the target is in the parent or another child document.
1137 owner->buffer()->setParentName(parentfilename);
1141 case LFUN_TOGGLECURSORFOLLOW:
1142 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1146 owner->getIntl().KeyMapOn(false);
1149 case LFUN_KMAP_PRIM:
1150 owner->getIntl().KeyMapPrim();
1154 owner->getIntl().KeyMapSec();
1157 case LFUN_KMAP_TOGGLE:
1158 owner->getIntl().ToggleKeyMap();
1164 string rest = split(argument, countstr, ' ');
1165 istringstream is(countstr);
1168 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1169 for (int i = 0; i < count; ++i)
1170 dispatch(lyxaction.lookupFunc(rest));
1175 // argument contains ';'-terminated commands
1176 while (!argument.empty()) {
1178 string rest = split(argument, first, ';');
1179 dispatch(lyxaction.lookupFunc(rest));
1183 case LFUN_SAVEPREFERENCES: {
1184 Path p(user_lyxdir());
1185 lyxrc.write("preferences");
1189 case LFUN_SCREEN_FONT_UPDATE:
1190 // handle the screen font changes.
1191 lyxrc.set_font_norm_type();
1192 lyx_gui::update_fonts();
1193 // All visible buffers will need resize
1197 case LFUN_SET_COLOR: {
1199 string const x11_name = split(argument, lyx_name, ' ');
1200 if (lyx_name.empty() || x11_name.empty()) {
1201 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1206 bool const graphicsbg_changed =
1207 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1208 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1210 if (!lcolor.setColor(lyx_name, x11_name)) {
1212 bformat(_("Set-color \"%1$s\" failed "
1213 "- color is undefined or "
1214 "may not be redefined"), lyx_name));
1218 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1220 if (graphicsbg_changed) {
1221 #ifdef WITH_WARNINGS
1222 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1225 lyx::graphics::GCache::get().changeDisplay(true);
1232 owner->message(argument);
1235 case LFUN_TOOLTIPS_TOGGLE:
1236 owner->getDialogs().toggleTooltips();
1239 case LFUN_EXTERNAL_EDIT: {
1240 FuncRequest fr(action, argument);
1241 InsetExternal().dispatch(view()->cursor(), fr);
1245 case LFUN_BREAKLINE: {
1246 #warning swallow 'Return' if the minibuffer is focused. But how?
1250 case LFUN_ALL_INSETS_TOGGLE: {
1252 string const name = split(argument, action, ' ');
1253 InsetBase::Code const inset_code =
1254 InsetBase::translate(name);
1256 LCursor & cur = view()->cursor();
1257 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1259 InsetBase & inset = owner->buffer()->inset();
1260 InsetIterator it = inset_iterator_begin(inset);
1261 InsetIterator const end = inset_iterator_end(inset);
1262 for (; it != end; ++it) {
1263 if (inset_code == InsetBase::NO_CODE
1264 || inset_code == it->lyxCode()) {
1265 it->dispatch(cur, fr);
1266 if (&cur.inset() == &*it
1267 && cur.disp_.dispatched())
1275 DispatchResult res = view()->cursor().dispatch(cmd);
1276 if (!res.dispatched());
1277 view()->dispatch(cmd);
1282 if (view()->available()) {
1283 view()->fitCursor();
1285 view()->cursor().updatePos();
1286 // if we executed a mutating lfun, mark the buffer as dirty
1287 if (getStatus(cmd).enabled()
1288 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1289 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1290 view()->buffer()->markDirty();
1293 if (view()->cursor().inTexted()) {
1294 view()->owner()->updateLayoutChoice();
1295 sendDispatchMessage(getMessage(), cmd, verbose);
1301 void LyXFunc::sendDispatchMessage(string const & msg,
1302 FuncRequest const & cmd, bool verbose)
1304 owner->updateMenubar();
1305 owner->updateToolbar();
1307 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1308 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1310 owner->message(msg);
1314 string dispatch_msg = msg;
1315 if (!dispatch_msg.empty())
1316 dispatch_msg += ' ';
1318 string comname = lyxaction.getActionName(cmd.action);
1320 bool argsadded = false;
1322 if (!cmd.argument.empty()) {
1323 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1324 comname += ' ' + cmd.argument;
1329 string const shortcuts = toplevel_keymap->findbinding(cmd);
1331 if (!shortcuts.empty()) {
1332 comname += ": " + shortcuts;
1333 } else if (!argsadded && !cmd.argument.empty()) {
1334 comname += ' ' + cmd.argument;
1337 if (!comname.empty()) {
1338 comname = rtrim(comname);
1339 dispatch_msg += '(' + comname + ')';
1342 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1343 if (!dispatch_msg.empty())
1344 owner->message(dispatch_msg);
1348 void LyXFunc::setupLocalKeymap()
1350 keyseq.stdmap = toplevel_keymap.get();
1351 keyseq.curmap = toplevel_keymap.get();
1352 cancel_meta_seq.stdmap = toplevel_keymap.get();
1353 cancel_meta_seq.curmap = toplevel_keymap.get();
1357 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1359 string initpath = lyxrc.document_path;
1360 string filename(name);
1362 if (view()->available()) {
1363 string const trypath = owner->buffer()->filePath();
1364 // If directory is writeable, use this as default.
1365 if (IsDirWriteable(trypath))
1369 static int newfile_number;
1371 if (filename.empty()) {
1372 filename = AddName(lyxrc.document_path,
1373 "newfile" + tostr(++newfile_number) + ".lyx");
1374 FileInfo fi(filename);
1375 while (bufferlist.exists(filename) || fi.readable()) {
1377 filename = AddName(lyxrc.document_path,
1378 "newfile" + tostr(newfile_number) +
1380 fi.newFile(filename);
1384 // The template stuff
1387 FileDialog fileDlg(_("Select template file"),
1388 LFUN_SELECT_FILE_SYNC,
1389 make_pair(string(_("Documents|#o#O")),
1390 string(lyxrc.document_path)),
1391 make_pair(string(_("Templates|#T#t")),
1392 string(lyxrc.template_path)));
1394 FileDialog::Result result =
1395 fileDlg.open(lyxrc.template_path,
1396 FileFilterList(_("LyX Documents (*.lyx)")),
1399 if (result.first == FileDialog::Later)
1401 if (result.second.empty())
1403 templname = result.second;
1406 view()->newFile(filename, templname, !name.empty());
1410 void LyXFunc::open(string const & fname)
1412 string initpath = lyxrc.document_path;
1414 if (view()->available()) {
1415 string const trypath = owner->buffer()->filePath();
1416 // If directory is writeable, use this as default.
1417 if (IsDirWriteable(trypath))
1423 if (fname.empty()) {
1424 FileDialog fileDlg(_("Select document to open"),
1426 make_pair(string(_("Documents|#o#O")),
1427 string(lyxrc.document_path)),
1428 make_pair(string(_("Examples|#E#e")),
1429 string(AddPath(system_lyxdir(), "examples"))));
1431 FileDialog::Result result =
1432 fileDlg.open(initpath,
1433 FileFilterList(_("LyX Documents (*.lyx)")),
1436 if (result.first == FileDialog::Later)
1439 filename = result.second;
1441 // check selected filename
1442 if (filename.empty()) {
1443 owner->message(_("Canceled."));
1449 // get absolute path of file and add ".lyx" to the filename if
1451 string const fullpath = FileSearch(string(), filename, "lyx");
1452 if (!fullpath.empty()) {
1453 filename = fullpath;
1456 string const disp_fn(MakeDisplayPath(filename));
1458 // if the file doesn't exist, let the user create one
1459 FileInfo const f(filename, true);
1461 // the user specifically chose this name. Believe them.
1462 view()->newFile(filename, "", true);
1466 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1469 if (view()->loadLyXFile(filename)) {
1470 str2 = bformat(_("Document %1$s opened."), disp_fn);
1472 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1474 owner->message(str2);
1478 void LyXFunc::doImport(string const & argument)
1481 string filename = split(argument, format, ' ');
1483 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1484 << " file: " << filename << endl;
1486 // need user interaction
1487 if (filename.empty()) {
1488 string initpath = lyxrc.document_path;
1490 if (view()->available()) {
1491 string const trypath = owner->buffer()->filePath();
1492 // If directory is writeable, use this as default.
1493 if (IsDirWriteable(trypath))
1497 string const text = bformat(_("Select %1$s file to import"),
1498 formats.prettyName(format));
1500 FileDialog fileDlg(text,
1502 make_pair(string(_("Documents|#o#O")),
1503 string(lyxrc.document_path)),
1504 make_pair(string(_("Examples|#E#e")),
1505 string(AddPath(system_lyxdir(), "examples"))));
1507 string const filter = formats.prettyName(format)
1508 + " (*." + formats.extension(format) + ')';
1510 FileDialog::Result result =
1511 fileDlg.open(initpath,
1512 FileFilterList(filter),
1515 if (result.first == FileDialog::Later)
1518 filename = result.second;
1520 // check selected filename
1521 if (filename.empty())
1522 owner->message(_("Canceled."));
1525 if (filename.empty())
1528 // get absolute path of file
1529 filename = MakeAbsPath(filename);
1531 string const lyxfile = ChangeExtension(filename, ".lyx");
1533 // Check if the document already is open
1534 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1535 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1536 owner->message(_("Canceled."));
1541 // if the file exists already, and we didn't do
1542 // -i lyx thefile.lyx, warn
1543 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1544 string const file = MakeDisplayPath(lyxfile, 30);
1546 string text = bformat(_("The document %1$s already exists.\n\n"
1547 "Do you want to over-write that document?"), file);
1548 int const ret = Alert::prompt(_("Over-write document?"),
1549 text, 0, 1, _("&Over-write"), _("&Cancel"));
1552 owner->message(_("Canceled."));
1557 Importer::Import(owner, filename, format);
1561 void LyXFunc::closeBuffer()
1563 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1564 if (bufferlist.empty()) {
1565 // need this otherwise SEGV may occur while
1566 // trying to set variables that don't exist
1567 // since there's no current buffer
1568 owner->getDialogs().hideBufferDependent();
1570 view()->setBuffer(bufferlist.first());
1576 // Each "owner" should have it's own message method. lyxview and
1577 // the minibuffer would use the minibuffer, but lyxserver would
1578 // send an ERROR signal to its client. Alejandro 970603
1579 // This function is bit problematic when it comes to NLS, to make the
1580 // lyx servers client be language indepenent we must not translate
1581 // strings sent to this func.
1582 void LyXFunc::setErrorMessage(string const & m) const
1584 dispatch_buffer = m;
1589 void LyXFunc::setMessage(string const & m) const
1591 dispatch_buffer = m;
1595 void LyXFunc::setStatusMessage(string const & m) const
1601 string const LyXFunc::viewStatusMessage()
1603 // When meta-fake key is pressed, show the key sequence so far + "M-".
1605 return keyseq.print() + "M-";
1607 // Else, when a non-complete key sequence is pressed,
1608 // show the available options.
1609 if (keyseq.length() > 0 && !keyseq.deleted())
1610 return keyseq.printOptions();
1612 if (!view()->available())
1613 return _("Welcome to LyX!");
1615 return view()->cursor().currentState();
1619 BufferView * LyXFunc::view() const
1621 BOOST_ASSERT(owner);
1622 return owner->view().get();
1626 bool LyXFunc::wasMetaKey() const
1628 return (meta_fake_bit != key_modifier::none);