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"
31 #include "CutAndPaste.h"
33 #include "dispatchresult.h"
35 #include "errorlist.h"
38 #include "funcrequest.h"
41 #include "insetiterator.h"
47 #include "LyXAction.h"
52 #include "lyxserver.h"
53 #include "lyxtextclasslist.h"
55 #include "paragraph.h"
56 #include "pariterator.h"
57 #include "ParagraphParameters.h"
60 #include "insets/insetbox.h"
61 #include "insets/insetbranch.h"
62 #include "insets/insetcommand.h"
63 #include "insets/insetert.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetfloat.h"
66 #include "insets/insetgraphics.h"
67 #include "insets/insetnote.h"
68 #include "insets/insettabular.h"
69 #include "insets/insetvspace.h"
70 #include "insets/insetwrap.h"
72 #include "frontends/Alert.h"
73 #include "frontends/Dialogs.h"
74 #include "frontends/FileDialog.h"
75 #include "frontends/lyx_gui.h"
76 #include "frontends/LyXKeySym.h"
77 #include "frontends/LyXView.h"
78 #include "frontends/Menubar.h"
79 #include "frontends/Toolbar.h"
81 #include "support/FileInfo.h"
82 #include "support/filetools.h"
83 #include "support/forkedcontr.h"
84 #include "support/globbing.h"
85 #include "support/lstrings.h"
86 #include "support/path.h"
87 #include "support/path_defines.h"
88 #include "support/systemcall.h"
89 #include "support/tostr.h"
90 #include "support/std_sstream.h"
91 #include "support/os.h"
93 using bv_funcs::freefont2string;
95 using lyx::support::AddName;
96 using lyx::support::AddPath;
97 using lyx::support::bformat;
98 using lyx::support::ChangeExtension;
99 using lyx::support::contains;
100 using lyx::support::FileFilterList;
101 using lyx::support::FileInfo;
102 using lyx::support::FileSearch;
103 using lyx::support::ForkedcallsController;
104 using lyx::support::i18nLibFileSearch;
105 using lyx::support::IsDirWriteable;
106 using lyx::support::IsFileReadable;
107 using lyx::support::isStrInt;
108 using lyx::support::MakeAbsPath;
109 using lyx::support::MakeDisplayPath;
110 using lyx::support::Path;
111 using lyx::support::QuoteName;
112 using lyx::support::rtrim;
113 using lyx::support::split;
114 using lyx::support::strToInt;
115 using lyx::support::strToUnsignedInt;
116 using lyx::support::subst;
117 using lyx::support::system_lyxdir;
118 using lyx::support::Systemcall;
119 using lyx::support::token;
120 using lyx::support::trim;
121 using lyx::support::user_lyxdir;
122 using lyx::support::prefixIs;
123 using lyx::support::os::getTmpDir;
126 using std::make_pair;
129 using std::istringstream;
132 extern BufferList bufferlist;
133 extern LyXServer * lyxserver;
134 extern bool selection_possible;
136 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
139 extern tex_accent_struct get_accent(kb_action action);
142 LyXFunc::LyXFunc(LyXView * lv)
145 keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
146 cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
147 meta_fake_bit(key_modifier::none)
152 void LyXFunc::handleKeyFunc(kb_action action)
154 char c = encoded_last_key;
156 if (keyseq.length()) {
160 owner->getIntl().getTransManager()
161 .deadkey(c, get_accent(action).accent, view()->getLyXText());
162 // Need to clear, in case the minibuffer calls these
165 // copied verbatim from do_accent_char
166 view()->cursor().resetAnchor();
171 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
173 lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
175 // Do nothing if we have nothing (JMarc)
176 if (!keysym->isOK()) {
177 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
182 if (keysym->isModifier()) {
183 lyxerr[Debug::KEY] << "isModifier true" << endl;
187 Encoding const * encoding = view()->cursor().getEncoding();
189 encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
191 // Do a one-deep top-level lookup for
192 // cancel and meta-fake keys. RVDK_PATCH_5
193 cancel_meta_seq.reset();
195 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
196 lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
198 // When not cancel or meta-fake, do the normal lookup.
199 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
200 // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
201 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
202 // remove Caps Lock and Mod2 as a modifiers
203 func = keyseq.addkey(keysym, (state | meta_fake_bit));
204 lyxerr[Debug::KEY] << "action now set to ["
205 << func.action << ']' << endl;
208 // Dont remove this unless you know what you are doing.
209 meta_fake_bit = key_modifier::none;
211 // can this happen now ?
212 if (func.action == LFUN_NOACTION) {
213 func = FuncRequest(LFUN_PREFIX);
216 if (lyxerr.debugging(Debug::KEY)) {
217 lyxerr << "Key [action="
218 << func.action << "]["
219 << keyseq.print() << ']'
223 // already here we know if it any point in going further
224 // why not return already here if action == -1 and
225 // num_bytes == 0? (Lgb)
227 if (keyseq.length() > 1) {
228 owner->message(keyseq.print());
232 // Maybe user can only reach the key via holding down shift.
233 // Let's see. But only if shift is the only modifier
234 if (func.action == LFUN_UNKNOWN_ACTION &&
235 state == key_modifier::shift) {
236 lyxerr[Debug::KEY] << "Trying without shift" << endl;
237 func = keyseq.addkey(keysym, key_modifier::none);
238 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
241 if (func.action == LFUN_UNKNOWN_ACTION) {
242 // Hmm, we didn't match any of the keysequences. See
243 // if it's normal insertable text not already covered
245 if (keysym->isText() && keyseq.length() == 1) {
246 lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
247 func = FuncRequest(LFUN_SELFINSERT);
249 lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
250 owner->message(_("Unknown function."));
255 if (func.action == LFUN_SELFINSERT) {
256 if (encoded_last_key != 0) {
257 string arg(1, encoded_last_key);
258 dispatch(FuncRequest(LFUN_SELFINSERT, arg));
260 << "SelfInsert arg[`" << arg << "']" << endl;
268 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
270 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
272 Buffer * buf = owner->buffer();
273 LCursor & cur = view()->cursor();
275 if (cmd.action == LFUN_NOACTION) {
276 setStatusMessage(N_("Nothing to do"));
281 switch (cmd.action) {
282 case LFUN_UNKNOWN_ACTION:
283 #ifndef HAVE_LIBAIKSAURUS
284 case LFUN_THESAURUS_ENTRY:
290 flag |= lyx_gui::getStatus(cmd);
293 if (flag.unknown()) {
294 setStatusMessage(N_("Unknown action"));
298 // the default error message if we disable the command
299 setStatusMessage(N_("Command disabled"));
301 // Check whether we need a buffer
302 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
304 setStatusMessage(N_("Command not allowed with"
305 "out any document open"));
310 // I would really like to avoid having this switch and rather try to
311 // encode this in the function itself.
312 // -- And I'd rather let an inset decide which LFUNs it is willing
313 // to handle (Andre')
315 switch (cmd.action) {
316 case LFUN_TOOLTIPS_TOGGLE:
317 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
320 case LFUN_READ_ONLY_TOGGLE:
321 flag.setOnOff(buf->isReadonly());
324 case LFUN_SWITCHBUFFER:
325 // toggle on the current buffer, but do not toggle off
326 // the other ones (is that a good idea?)
327 if (cmd.argument == buf->fileName())
332 enable = cmd.argument == "custom"
333 || Exporter::IsExportable(*buf, cmd.argument);
337 enable = cur.selection();
341 enable = buf->isLatex() && lyxrc.chktex_command != "none";
345 enable = Exporter::IsExportable(*buf, "program");
348 case LFUN_LAYOUT_TABULAR:
349 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
353 case LFUN_LAYOUT_PARAGRAPH:
354 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
357 case LFUN_VC_REGISTER:
358 enable = !buf->lyxvc().inUse();
360 case LFUN_VC_CHECKIN:
361 enable = buf->lyxvc().inUse() && !buf->isReadonly();
363 case LFUN_VC_CHECKOUT:
364 enable = buf->lyxvc().inUse() && buf->isReadonly();
368 enable = buf->lyxvc().inUse();
370 case LFUN_MENURELOAD:
371 enable = !buf->isUnnamed() && !buf->isClean();
375 case LFUN_INSET_SETTINGS: {
379 UpdatableInset * inset = cur.inset().asUpdatableInset();
380 lyxerr << "inset: " << inset << endl;
384 InsetOld::Code code = inset->lyxCode();
386 case InsetOld::TABULAR_CODE:
387 enable = cmd.argument == "tabular";
389 case InsetOld::ERT_CODE:
390 enable = cmd.argument == "ert";
392 case InsetOld::FLOAT_CODE:
393 enable = cmd.argument == "float";
395 case InsetOld::WRAP_CODE:
396 enable = cmd.argument == "wrap";
398 case InsetOld::NOTE_CODE:
399 enable = cmd.argument == "note";
401 case InsetOld::BRANCH_CODE:
402 enable = cmd.argument == "branch";
404 case InsetOld::BOX_CODE:
405 enable = cmd.argument == "box";
413 case LFUN_DIALOG_SHOW: {
414 string const name = cmd.getArg(0);
416 enable = name == "aboutlyx"
420 || name == "texinfo";
421 else if (name == "print")
422 enable = Exporter::IsExportable(*buf, "dvi")
423 && lyxrc.print_command != "none";
424 else if (name == "character")
425 enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
426 else if (name == "vclog")
427 enable = buf->lyxvc().inUse();
428 else if (name == "latexlog")
429 enable = IsFileReadable(buf->getLogName().second);
433 case LFUN_DIALOG_UPDATE: {
434 string const name = cmd.getArg(0);
436 enable = name == "prefs";
441 case LFUN_MENUNEWTMPLT:
442 case LFUN_WORDFINDFORWARD:
443 case LFUN_WORDFINDBACKWARD:
445 case LFUN_EXEC_COMMAND:
448 case LFUN_CLOSEBUFFER:
457 case LFUN_RECONFIGURE:
461 case LFUN_DROP_LAYOUTS_CHOICE:
462 case LFUN_MENU_OPEN_BY_NAME:
465 case LFUN_GOTOFILEROW:
466 case LFUN_GOTO_PARAGRAPH:
467 case LFUN_DIALOG_SHOW_NEW_INSET:
468 case LFUN_DIALOG_SHOW_NEXT_INSET:
469 case LFUN_DIALOG_HIDE:
470 case LFUN_DIALOG_DISCONNECT_INSET:
472 case LFUN_TOGGLECURSORFOLLOW:
476 case LFUN_KMAP_TOGGLE:
478 case LFUN_EXPORT_CUSTOM:
481 case LFUN_SAVEPREFERENCES:
482 case LFUN_SCREEN_FONT_UPDATE:
485 case LFUN_EXTERNAL_EDIT:
486 case LFUN_GRAPHICS_EDIT:
487 case LFUN_ALL_INSETS_TOGGLE:
488 case LFUN_LANGUAGE_BUFFER:
489 case LFUN_TEXTCLASS_APPLY:
490 case LFUN_TEXTCLASS_LOAD:
491 case LFUN_SAVE_AS_DEFAULT:
492 case LFUN_BUFFERPARAMS_APPLY:
493 case LFUN_LYXRC_APPLY:
494 // these are handled in our dispatch()
499 cur.getStatus(cmd, flag);
501 flag = view()->getStatus(cmd);
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"));
515 //lyxerr << "LyXFunc::getStatus: got: " << flag.enabled() << endl;
522 bool ensureBufferClean(BufferView * bv)
524 Buffer & buf = *bv->buffer();
528 string const file = MakeDisplayPath(buf.fileName(), 30);
529 string text = bformat(_("The document %1$s has unsaved "
530 "changes.\n\nDo you want to save "
531 "the document?"), file);
532 int const ret = Alert::prompt(_("Save changed document?"),
533 text, 0, 1, _("&Save"),
537 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
539 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);
552 void loadTextclass(string const & name)
554 std::pair<bool, lyx::textclass_type> const tc_pair =
555 textclasslist.NumberOfClass(name);
557 if (!tc_pair.first) {
558 lyxerr << "Document class \"" << name
559 << "\" does not exist."
564 lyx::textclass_type const tc = tc_pair.second;
566 if (!textclasslist[tc].load()) {
567 string s = bformat(_("The document could not be converted\n"
568 "into the document class %1$s."),
569 textclasslist[tc].name());
570 Alert::error(_("Could not change class"), s);
577 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
579 string const argument = cmd.argument;
580 kb_action const action = cmd.action;
582 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
583 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
585 // we have not done anything wrong yet.
587 dispatch_buffer.erase();
588 selection_possible = false;
592 // We cannot use this function here
593 if (!getStatus(cmd).enabled()) {
594 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
595 << lyxaction.getActionName(action)
596 << " [" << action << "] is disabled at this location"
598 setErrorMessage(getStatusMessage());
602 if (view()->available())
603 view()->hideCursor();
607 case LFUN_WORDFINDFORWARD:
608 case LFUN_WORDFINDBACKWARD: {
609 static string last_search;
610 string searched_string;
612 if (!argument.empty()) {
613 last_search = argument;
614 searched_string = argument;
616 searched_string = last_search;
619 if (searched_string.empty())
622 bool const fw = action == LFUN_WORDFINDFORWARD;
624 lyx::find::find2string(searched_string, true, false, fw);
625 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
630 owner->message(keyseq.printOptions());
633 case LFUN_EXEC_COMMAND:
634 owner->getToolbar().display("minibuffer", true);
635 owner->focus_command_buffer();
640 meta_fake_bit = key_modifier::none;
641 if (view()->available())
642 // cancel any selection
643 dispatch(FuncRequest(LFUN_MARK_OFF));
644 setMessage(N_("Cancel"));
648 meta_fake_bit = key_modifier::alt;
649 setMessage(keyseq.print());
652 case LFUN_READ_ONLY_TOGGLE:
653 if (owner->buffer()->lyxvc().inUse())
654 owner->buffer()->lyxvc().toggleReadOnly();
656 owner->buffer()->setReadonly(
657 !owner->buffer()->isReadonly());
660 // --- Menus -----------------------------------------------
662 menuNew(argument, false);
665 case LFUN_MENUNEWTMPLT:
666 menuNew(argument, true);
669 case LFUN_CLOSEBUFFER:
674 if (!owner->buffer()->isUnnamed()) {
675 string const str = bformat(_("Saving document %1$s..."),
676 MakeDisplayPath(owner->buffer()->fileName()));
678 MenuWrite(owner->buffer());
679 owner->message(str + _(" done."));
681 WriteAs(owner->buffer());
685 WriteAs(owner->buffer(), argument);
688 case LFUN_MENURELOAD: {
689 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
690 string text = bformat(_("Any changes will be lost. Are you sure "
691 "you want to revert to the saved version of the document %1$s?"), file);
692 int const ret = Alert::prompt(_("Revert to saved document?"),
693 text, 0, 1, _("&Revert"), _("&Cancel"));
701 Exporter::Export(owner->buffer(), argument, true);
702 view()->showErrorList(BufferFormat(*owner->buffer()));
706 Exporter::Preview(owner->buffer(), argument);
707 view()->showErrorList(BufferFormat(*owner->buffer()));
711 Exporter::Export(owner->buffer(), "program", true);
712 view()->showErrorList(_("Build"));
716 owner->buffer()->runChktex();
717 view()->showErrorList(_("ChkTeX"));
721 if (argument == "custom")
722 owner->getDialogs().show("sendto");
724 Exporter::Export(owner->buffer(), argument, false);
725 view()->showErrorList(BufferFormat(*owner->buffer()));
729 case LFUN_EXPORT_CUSTOM: {
731 string command = split(argument, format_name, ' ');
732 Format const * format = formats.getFormat(format_name);
734 lyxerr << "Format \"" << format_name
735 << "\" not recognized!"
740 Buffer * buffer = owner->buffer();
742 // The name of the file created by the conversion process
745 // Output to filename
746 if (format->name() == "lyx") {
747 string const latexname =
748 buffer->getLatexName(false);
749 filename = ChangeExtension(latexname,
750 format->extension());
751 filename = AddName(buffer->temppath(), filename);
753 if (!buffer->writeFile(filename))
757 Exporter::Export(buffer, format_name, true,
761 // Substitute $$FName for filename
762 if (!contains(command, "$$FName"))
763 command = "( " + command + " ) < $$FName";
764 command = subst(command, "$$FName", filename);
766 // Execute the command in the background
768 call.startscript(Systemcall::DontWait, command);
775 string command = split(split(argument, target, ' '),
779 || target_name.empty()
780 || command.empty()) {
781 lyxerr << "Unable to parse \""
782 << argument << '"' << std::endl;
785 if (target != "printer" && target != "file") {
786 lyxerr << "Unrecognized target \""
787 << target << '"' << std::endl;
791 Buffer * buffer = owner->buffer();
793 if (!Exporter::Export(buffer, "dvi", true)) {
794 showPrintError(buffer->fileName());
798 // Push directory path.
799 string const path = buffer->temppath();
802 // there are three cases here:
803 // 1. we print to a file
804 // 2. we print directly to a printer
805 // 3. we print using a spool command (print to file first)
808 string const dviname =
809 ChangeExtension(buffer->getLatexName(true),
812 if (target == "printer") {
813 if (!lyxrc.print_spool_command.empty()) {
814 // case 3: print using a spool
815 string const psname =
816 ChangeExtension(dviname,".ps");
817 command += lyxrc.print_to_file
820 + QuoteName(dviname);
823 lyxrc.print_spool_command +' ';
824 if (target_name != "default") {
825 command2 += lyxrc.print_spool_printerprefix
829 command2 += QuoteName(psname);
831 // If successful, then spool command
832 res = one.startscript(
837 res = one.startscript(
838 Systemcall::DontWait,
841 // case 2: print directly to a printer
842 res = one.startscript(
843 Systemcall::DontWait,
844 command + QuoteName(dviname));
848 // case 1: print to a file
849 command += lyxrc.print_to_file
850 + QuoteName(MakeAbsPath(target_name,
853 + QuoteName(dviname);
854 res = one.startscript(Systemcall::DontWait,
859 showPrintError(buffer->fileName());
872 InsetCommandParams p("tableofcontents");
873 string const data = InsetCommandMailer::params2string("toc", p);
874 owner->getDialogs().show("toc", data, 0);
882 case LFUN_RECONFIGURE:
886 case LFUN_HELP_OPEN: {
887 string const arg = argument;
889 setErrorMessage(N_("Missing argument"));
892 string const fname = i18nLibFileSearch("doc", arg, "lyx");
894 lyxerr << "LyX: unable to find documentation file `"
895 << arg << "'. Bad installation?" << endl;
898 owner->message(bformat(_("Opening help file %1$s..."),
899 MakeDisplayPath(fname)));
900 view()->loadLyXFile(fname, false);
904 // --- version control -------------------------------
905 case LFUN_VC_REGISTER:
906 if (!ensureBufferClean(view()))
908 if (!owner->buffer()->lyxvc().inUse()) {
909 owner->buffer()->lyxvc().registrer();
914 case LFUN_VC_CHECKIN:
915 if (!ensureBufferClean(view()))
917 if (owner->buffer()->lyxvc().inUse()
918 && !owner->buffer()->isReadonly()) {
919 owner->buffer()->lyxvc().checkIn();
924 case LFUN_VC_CHECKOUT:
925 if (!ensureBufferClean(view()))
927 if (owner->buffer()->lyxvc().inUse()
928 && owner->buffer()->isReadonly()) {
929 owner->buffer()->lyxvc().checkOut();
935 owner->buffer()->lyxvc().revert();
940 owner->buffer()->lyxvc().undoLast();
944 // --- buffers ----------------------------------------
945 case LFUN_SWITCHBUFFER:
946 view()->setBuffer(bufferlist.getBuffer(argument));
950 NewFile(view(), argument);
957 case LFUN_DROP_LAYOUTS_CHOICE:
958 owner->getToolbar().openLayoutList();
961 case LFUN_MENU_OPEN_BY_NAME:
962 owner->getMenubar().openByName(argument);
965 // --- lyxserver commands ----------------------------
967 setMessage(owner->buffer()->fileName());
968 lyxerr[Debug::INFO] << "FNAME["
969 << owner->buffer()->fileName()
974 dispatch_buffer = keyseq.print();
975 lyxserver->notifyClient(dispatch_buffer);
978 case LFUN_GOTOFILEROW: {
981 istringstream is(argument);
982 is >> file_name >> row;
983 if (prefixIs(file_name, getTmpDir())) {
984 // Needed by inverse dvi search. If it is a file
985 // in tmpdir, call the apropriated function
986 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
988 // Must replace extension of the file to be .lyx
990 string const s = ChangeExtension(file_name, ".lyx");
991 // Either change buffer or load the file
992 if (bufferlist.exists(s)) {
993 view()->setBuffer(bufferlist.getBuffer(s));
995 view()->loadLyXFile(s);
999 view()->setCursorFromRow(row);
1002 // see BufferView_pimpl::center()
1003 view()->updateScrollbar();
1007 case LFUN_GOTO_PARAGRAPH: {
1008 istringstream is(argument);
1011 ParIterator par = owner->buffer()->getParFromID(id);
1012 if (par == owner->buffer()->par_iterator_end()) {
1013 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1014 << id << ']' << endl;
1017 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1018 << " found." << endl;
1022 view()->setCursor(par, 0);
1024 view()->switchKeyMap();
1025 owner->view_state_changed();
1028 // see BufferView_pimpl::center()
1029 view()->updateScrollbar();
1033 case LFUN_DIALOG_SHOW: {
1034 string const name = cmd.getArg(0);
1035 string data = trim(cmd.argument.substr(name.size()));
1037 if (name == "character") {
1038 data = freefont2string();
1040 owner->getDialogs().show("character", data);
1043 else if (name == "latexlog") {
1044 pair<Buffer::LogType, string> const logfile =
1045 owner->buffer()->getLogName();
1046 switch (logfile.first) {
1047 case Buffer::latexlog:
1050 case Buffer::buildlog:
1054 data += logfile.second;
1055 owner->getDialogs().show("log", data);
1057 else if (name == "vclog") {
1058 string const data = "vc " +
1059 owner->buffer()->lyxvc().getLogFile();
1060 owner->getDialogs().show("log", data);
1063 owner->getDialogs().show(name, data);
1067 case LFUN_DIALOG_SHOW_NEW_INSET: {
1068 string const name = cmd.getArg(0);
1069 string data = trim(cmd.argument.substr(name.size()));
1070 if (name == "bibitem" ||
1072 name == "include" ||
1078 InsetCommandParams p(name);
1079 data = InsetCommandMailer::params2string(name, p);
1080 } else if (name == "box") {
1081 // \c data == "Boxed" || "Frameless" etc
1082 InsetBoxParams p(data);
1083 data = InsetBoxMailer::params2string(p);
1084 } else if (name == "branch") {
1085 InsetBranchParams p;
1086 data = InsetBranchMailer::params2string(p);
1087 } else if (name == "citation") {
1088 InsetCommandParams p("cite");
1089 data = InsetCommandMailer::params2string(name, p);
1090 } else if (name == "ert") {
1091 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1092 } else if (name == "external") {
1093 InsetExternalParams p;
1094 Buffer const & buffer = *owner->buffer();
1095 data = InsetExternalMailer::params2string(p, buffer);
1096 } else if (name == "float") {
1098 data = InsetFloatMailer::params2string(p);
1099 } else if (name == "graphics") {
1100 InsetGraphicsParams p;
1101 Buffer const & buffer = *owner->buffer();
1102 data = InsetGraphicsMailer::params2string(p, buffer);
1103 } else if (name == "note") {
1105 data = InsetNoteMailer::params2string(p);
1106 } else if (name == "vspace") {
1108 data = InsetVSpaceMailer::params2string(space);
1109 } else if (name == "wrap") {
1111 data = InsetWrapMailer::params2string(p);
1113 owner->getDialogs().show(name, data, 0);
1117 case LFUN_DIALOG_SHOW_NEXT_INSET:
1120 case LFUN_DIALOG_UPDATE: {
1121 string const & name = argument;
1122 // Can only update a dialog connected to an existing inset
1123 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1125 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1126 inset->dispatch(view()->cursor(), fr);
1127 } else if (name == "paragraph") {
1128 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1129 } else if (name == "prefs") {
1130 owner->getDialogs().update(name, string());
1135 case LFUN_DIALOG_HIDE:
1136 Dialogs::hide(argument, 0);
1139 case LFUN_DIALOG_DISCONNECT_INSET:
1140 owner->getDialogs().disconnect(argument);
1143 case LFUN_CHILDOPEN: {
1144 string const filename =
1145 MakeAbsPath(argument, owner->buffer()->filePath());
1146 setMessage(N_("Opening child document ") +
1147 MakeDisplayPath(filename) + "...");
1148 view()->savePosition(0);
1149 string const parentfilename = owner->buffer()->fileName();
1150 if (bufferlist.exists(filename))
1151 view()->setBuffer(bufferlist.getBuffer(filename));
1153 view()->loadLyXFile(filename);
1154 // Set the parent name of the child document.
1155 // This makes insertion of citations and references in the child work,
1156 // when the target is in the parent or another child document.
1157 owner->buffer()->setParentName(parentfilename);
1161 case LFUN_TOGGLECURSORFOLLOW:
1162 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1166 owner->getIntl().KeyMapOn(false);
1169 case LFUN_KMAP_PRIM:
1170 owner->getIntl().KeyMapPrim();
1174 owner->getIntl().KeyMapSec();
1177 case LFUN_KMAP_TOGGLE:
1178 owner->getIntl().ToggleKeyMap();
1184 string rest = split(argument, countstr, ' ');
1185 istringstream is(countstr);
1188 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1189 for (int i = 0; i < count; ++i)
1190 dispatch(lyxaction.lookupFunc(rest));
1195 // argument contains ';'-terminated commands
1196 while (!argument.empty()) {
1198 string rest = split(argument, first, ';');
1199 dispatch(lyxaction.lookupFunc(rest));
1203 case LFUN_SAVEPREFERENCES: {
1204 Path p(user_lyxdir());
1205 lyxrc.write("preferences", false);
1209 case LFUN_SCREEN_FONT_UPDATE:
1210 // handle the screen font changes.
1211 lyxrc.set_font_norm_type();
1212 lyx_gui::update_fonts();
1213 // All visible buffers will need resize
1217 case LFUN_SET_COLOR: {
1219 string const x11_name = split(argument, lyx_name, ' ');
1220 if (lyx_name.empty() || x11_name.empty()) {
1221 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1226 bool const graphicsbg_changed =
1227 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1228 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1230 if (!lcolor.setColor(lyx_name, x11_name)) {
1232 bformat(_("Set-color \"%1$s\" failed "
1233 "- color is undefined or "
1234 "may not be redefined"), lyx_name));
1238 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1240 if (graphicsbg_changed) {
1241 #ifdef WITH_WARNINGS
1242 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1245 lyx::graphics::GCache::get().changeDisplay(true);
1252 owner->message(argument);
1255 case LFUN_TOOLTIPS_TOGGLE:
1256 owner->getDialogs().toggleTooltips();
1259 case LFUN_EXTERNAL_EDIT: {
1260 FuncRequest fr(action, argument);
1261 InsetExternal().dispatch(view()->cursor(), fr);
1265 case LFUN_GRAPHICS_EDIT: {
1266 FuncRequest fr(action, argument);
1267 InsetGraphics().dispatch(view()->cursor(), fr);
1271 case LFUN_ALL_INSETS_TOGGLE: {
1273 string const name = split(argument, action, ' ');
1274 InsetBase::Code const inset_code =
1275 InsetBase::translate(name);
1277 LCursor & cur = view()->cursor();
1278 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1280 InsetBase & inset = owner->buffer()->inset();
1281 InsetIterator it = inset_iterator_begin(inset);
1282 InsetIterator const end = inset_iterator_end(inset);
1283 for (; it != end; ++it) {
1284 if (inset_code == InsetBase::NO_CODE
1285 || inset_code == it->lyxCode())
1286 it->dispatch(cur, fr);
1291 case LFUN_LANGUAGE_BUFFER: {
1292 Buffer & buffer = *owner->buffer();
1293 Language const * oldL = buffer.params().language;
1294 Language const * newL = languages.getLanguage(argument);
1295 if (!newL || oldL == newL)
1298 if (oldL->RightToLeft() == newL->RightToLeft()
1299 && !buffer.isMultiLingual())
1300 buffer.changeLanguage(oldL, newL);
1302 buffer.updateDocLang(newL);
1306 case LFUN_BUFFERPARAMS_APPLY: {
1307 istringstream ss(argument);
1310 int const unknown_tokens =
1311 owner->buffer()->readHeader(lex);
1313 if (unknown_tokens != 0) {
1314 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1315 << unknown_tokens << " unknown token"
1316 << (unknown_tokens == 1 ? "" : "s")
1322 case LFUN_TEXTCLASS_APPLY: {
1323 Buffer * buffer = owner->buffer();
1325 lyx::textclass_type const old_class =
1326 buffer->params().textclass;
1328 loadTextclass(argument);
1330 std::pair<bool, lyx::textclass_type> const tc_pair =
1331 textclasslist.NumberOfClass(argument);
1336 lyx::textclass_type const new_class = tc_pair.second;
1337 if (old_class == new_class)
1341 owner->message(_("Converting document to new document class..."));
1343 lyx::cap::SwitchLayoutsBetweenClasses(
1344 old_class, new_class,
1345 buffer->paragraphs(), el);
1347 bufferErrors(*buffer, el);
1348 view()->showErrorList(_("Class switch"));
1352 case LFUN_TEXTCLASS_LOAD:
1353 loadTextclass(argument);
1356 case LFUN_LYXRC_APPLY: {
1357 istringstream ss(argument);
1358 bool const success = lyxrc.read(ss) == 0;
1361 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1362 << "Unable to read lyxrc data"
1370 DispatchResult res = view()->cursor().dispatch(cmd);
1371 if (res.dispatched())
1372 update |= res.update();
1374 update |= view()->dispatch(cmd);
1380 if (view()->available()) {
1381 if (view()->fitCursor() || update)
1383 // if we executed a mutating lfun, mark the buffer as dirty
1384 if (getStatus(cmd).enabled()
1385 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1386 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1387 view()->buffer()->markDirty();
1390 if (view()->cursor().inTexted()) {
1391 view()->owner()->updateLayoutChoice();
1392 sendDispatchMessage(getMessage(), cmd, verbose);
1398 void LyXFunc::sendDispatchMessage(string const & msg,
1399 FuncRequest const & cmd, bool verbose)
1401 owner->updateMenubar();
1402 owner->updateToolbar();
1404 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1405 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1407 owner->message(msg);
1411 string dispatch_msg = msg;
1412 if (!dispatch_msg.empty())
1413 dispatch_msg += ' ';
1415 string comname = lyxaction.getActionName(cmd.action);
1417 bool argsadded = false;
1419 if (!cmd.argument.empty()) {
1420 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1421 comname += ' ' + cmd.argument;
1426 string const shortcuts = toplevel_keymap->findbinding(cmd);
1428 if (!shortcuts.empty()) {
1429 comname += ": " + shortcuts;
1430 } else if (!argsadded && !cmd.argument.empty()) {
1431 comname += ' ' + cmd.argument;
1434 if (!comname.empty()) {
1435 comname = rtrim(comname);
1436 dispatch_msg += '(' + comname + ')';
1439 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1440 if (!dispatch_msg.empty())
1441 owner->message(dispatch_msg);
1445 void LyXFunc::setupLocalKeymap()
1447 keyseq.stdmap = toplevel_keymap.get();
1448 keyseq.curmap = toplevel_keymap.get();
1449 cancel_meta_seq.stdmap = toplevel_keymap.get();
1450 cancel_meta_seq.curmap = toplevel_keymap.get();
1454 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1456 string initpath = lyxrc.document_path;
1457 string filename(name);
1459 if (view()->available()) {
1460 string const trypath = owner->buffer()->filePath();
1461 // If directory is writeable, use this as default.
1462 if (IsDirWriteable(trypath))
1466 static int newfile_number;
1468 if (filename.empty()) {
1469 filename = AddName(lyxrc.document_path,
1470 "newfile" + tostr(++newfile_number) + ".lyx");
1471 FileInfo fi(filename);
1472 while (bufferlist.exists(filename) || fi.readable()) {
1474 filename = AddName(lyxrc.document_path,
1475 "newfile" + tostr(newfile_number) +
1477 fi.newFile(filename);
1481 // The template stuff
1484 FileDialog fileDlg(_("Select template file"),
1485 LFUN_SELECT_FILE_SYNC,
1486 make_pair(string(_("Documents|#o#O")),
1487 string(lyxrc.document_path)),
1488 make_pair(string(_("Templates|#T#t")),
1489 string(lyxrc.template_path)));
1491 FileDialog::Result result =
1492 fileDlg.open(lyxrc.template_path,
1493 FileFilterList(_("LyX Documents (*.lyx)")),
1496 if (result.first == FileDialog::Later)
1498 if (result.second.empty())
1500 templname = result.second;
1503 view()->newFile(filename, templname, !name.empty());
1507 void LyXFunc::open(string const & fname)
1509 string initpath = lyxrc.document_path;
1511 if (view()->available()) {
1512 string const trypath = owner->buffer()->filePath();
1513 // If directory is writeable, use this as default.
1514 if (IsDirWriteable(trypath))
1520 if (fname.empty()) {
1521 FileDialog fileDlg(_("Select document to open"),
1523 make_pair(string(_("Documents|#o#O")),
1524 string(lyxrc.document_path)),
1525 make_pair(string(_("Examples|#E#e")),
1526 string(AddPath(system_lyxdir(), "examples"))));
1528 FileDialog::Result result =
1529 fileDlg.open(initpath,
1530 FileFilterList(_("LyX Documents (*.lyx)")),
1533 if (result.first == FileDialog::Later)
1536 filename = result.second;
1538 // check selected filename
1539 if (filename.empty()) {
1540 owner->message(_("Canceled."));
1546 // get absolute path of file and add ".lyx" to the filename if
1548 string const fullpath = FileSearch(string(), filename, "lyx");
1549 if (!fullpath.empty()) {
1550 filename = fullpath;
1553 string const disp_fn(MakeDisplayPath(filename));
1555 // if the file doesn't exist, let the user create one
1556 FileInfo const f(filename, true);
1558 // the user specifically chose this name. Believe them.
1559 view()->newFile(filename, "", true);
1563 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1566 if (view()->loadLyXFile(filename)) {
1567 str2 = bformat(_("Document %1$s opened."), disp_fn);
1569 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1571 owner->message(str2);
1575 void LyXFunc::doImport(string const & argument)
1578 string filename = split(argument, format, ' ');
1580 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1581 << " file: " << filename << endl;
1583 // need user interaction
1584 if (filename.empty()) {
1585 string initpath = lyxrc.document_path;
1587 if (view()->available()) {
1588 string const trypath = owner->buffer()->filePath();
1589 // If directory is writeable, use this as default.
1590 if (IsDirWriteable(trypath))
1594 string const text = bformat(_("Select %1$s file to import"),
1595 formats.prettyName(format));
1597 FileDialog fileDlg(text,
1599 make_pair(string(_("Documents|#o#O")),
1600 string(lyxrc.document_path)),
1601 make_pair(string(_("Examples|#E#e")),
1602 string(AddPath(system_lyxdir(), "examples"))));
1604 string const filter = formats.prettyName(format)
1605 + " (*." + formats.extension(format) + ')';
1607 FileDialog::Result result =
1608 fileDlg.open(initpath,
1609 FileFilterList(filter),
1612 if (result.first == FileDialog::Later)
1615 filename = result.second;
1617 // check selected filename
1618 if (filename.empty())
1619 owner->message(_("Canceled."));
1622 if (filename.empty())
1625 // get absolute path of file
1626 filename = MakeAbsPath(filename);
1628 string const lyxfile = ChangeExtension(filename, ".lyx");
1630 // Check if the document already is open
1631 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1632 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1633 owner->message(_("Canceled."));
1638 // if the file exists already, and we didn't do
1639 // -i lyx thefile.lyx, warn
1640 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1641 string const file = MakeDisplayPath(lyxfile, 30);
1643 string text = bformat(_("The document %1$s already exists.\n\n"
1644 "Do you want to over-write that document?"), file);
1645 int const ret = Alert::prompt(_("Over-write document?"),
1646 text, 0, 1, _("&Over-write"), _("&Cancel"));
1649 owner->message(_("Canceled."));
1654 Importer::Import(owner, filename, format);
1658 void LyXFunc::closeBuffer()
1660 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1661 if (bufferlist.empty()) {
1662 // need this otherwise SEGV may occur while
1663 // trying to set variables that don't exist
1664 // since there's no current buffer
1665 owner->getDialogs().hideBufferDependent();
1667 view()->setBuffer(bufferlist.first());
1673 // Each "owner" should have it's own message method. lyxview and
1674 // the minibuffer would use the minibuffer, but lyxserver would
1675 // send an ERROR signal to its client. Alejandro 970603
1676 // This function is bit problematic when it comes to NLS, to make the
1677 // lyx servers client be language indepenent we must not translate
1678 // strings sent to this func.
1679 void LyXFunc::setErrorMessage(string const & m) const
1681 dispatch_buffer = m;
1686 void LyXFunc::setMessage(string const & m) const
1688 dispatch_buffer = m;
1692 void LyXFunc::setStatusMessage(string const & m) const
1698 string const LyXFunc::viewStatusMessage()
1700 // When meta-fake key is pressed, show the key sequence so far + "M-".
1702 return keyseq.print() + "M-";
1704 // Else, when a non-complete key sequence is pressed,
1705 // show the available options.
1706 if (keyseq.length() > 0 && !keyseq.deleted())
1707 return keyseq.printOptions();
1709 if (!view()->available())
1710 return _("Welcome to LyX!");
1712 return view()->cursor().currentState();
1716 BufferView * LyXFunc::view() const
1718 BOOST_ASSERT(owner);
1719 return owner->view().get();
1723 bool LyXFunc::wasMetaKey() const
1725 return (meta_fake_bit != key_modifier::none);