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/Toolbars.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/os.h"
94 using bv_funcs::freefont2string;
96 using lyx::support::AddName;
97 using lyx::support::AddPath;
98 using lyx::support::bformat;
99 using lyx::support::ChangeExtension;
100 using lyx::support::contains;
101 using lyx::support::FileFilterList;
102 using lyx::support::FileInfo;
103 using lyx::support::FileSearch;
104 using lyx::support::ForkedcallsController;
105 using lyx::support::i18nLibFileSearch;
106 using lyx::support::IsDirWriteable;
107 using lyx::support::IsFileReadable;
108 using lyx::support::isStrInt;
109 using lyx::support::MakeAbsPath;
110 using lyx::support::MakeDisplayPath;
111 using lyx::support::Path;
112 using lyx::support::QuoteName;
113 using lyx::support::rtrim;
114 using lyx::support::split;
115 using lyx::support::strToInt;
116 using lyx::support::strToUnsignedInt;
117 using lyx::support::subst;
118 using lyx::support::system_lyxdir;
119 using lyx::support::Systemcall;
120 using lyx::support::token;
121 using lyx::support::trim;
122 using lyx::support::user_lyxdir;
123 using lyx::support::prefixIs;
124 using lyx::support::os::getTmpDir;
127 using std::make_pair;
130 using std::istringstream;
132 namespace biblio = lyx::biblio;
135 extern BufferList bufferlist;
136 extern LyXServer * lyxserver;
137 extern bool selection_possible;
139 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
142 extern tex_accent_struct get_accent(kb_action action);
145 LyXFunc::LyXFunc(LyXView * lv)
148 keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
149 cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
150 meta_fake_bit(key_modifier::none)
155 void LyXFunc::handleKeyFunc(kb_action action)
157 char c = encoded_last_key;
159 if (keyseq.length()) {
163 owner->getIntl().getTransManager()
164 .deadkey(c, get_accent(action).accent, view()->getLyXText());
165 // Need to clear, in case the minibuffer calls these
168 // copied verbatim from do_accent_char
169 view()->cursor().resetAnchor();
174 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
176 lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
178 // Do nothing if we have nothing (JMarc)
179 if (!keysym->isOK()) {
180 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
185 if (keysym->isModifier()) {
186 lyxerr[Debug::KEY] << "isModifier true" << endl;
190 Encoding const * encoding = view()->cursor().getEncoding();
192 encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
194 // Do a one-deep top-level lookup for
195 // cancel and meta-fake keys. RVDK_PATCH_5
196 cancel_meta_seq.reset();
198 FuncRequest func = cancel_meta_seq.addkey(keysym, state);
199 lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
201 // When not cancel or meta-fake, do the normal lookup.
202 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
203 // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
204 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
205 // remove Caps Lock and Mod2 as a modifiers
206 func = keyseq.addkey(keysym, (state | meta_fake_bit));
207 lyxerr[Debug::KEY] << "action now set to ["
208 << func.action << ']' << endl;
211 // Dont remove this unless you know what you are doing.
212 meta_fake_bit = key_modifier::none;
214 // can this happen now ?
215 if (func.action == LFUN_NOACTION) {
216 func = FuncRequest(LFUN_PREFIX);
219 if (lyxerr.debugging(Debug::KEY)) {
220 lyxerr << "Key [action="
221 << func.action << "]["
222 << keyseq.print() << ']'
226 // already here we know if it any point in going further
227 // why not return already here if action == -1 and
228 // num_bytes == 0? (Lgb)
230 if (keyseq.length() > 1) {
231 owner->message(keyseq.print());
235 // Maybe user can only reach the key via holding down shift.
236 // Let's see. But only if shift is the only modifier
237 if (func.action == LFUN_UNKNOWN_ACTION &&
238 state == key_modifier::shift) {
239 lyxerr[Debug::KEY] << "Trying without shift" << endl;
240 func = keyseq.addkey(keysym, key_modifier::none);
241 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
244 if (func.action == LFUN_UNKNOWN_ACTION) {
245 // Hmm, we didn't match any of the keysequences. See
246 // if it's normal insertable text not already covered
248 if (keysym->isText() && keyseq.length() == 1) {
249 lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
250 func = FuncRequest(LFUN_SELFINSERT);
252 lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
253 owner->message(_("Unknown function."));
258 if (func.action == LFUN_SELFINSERT) {
259 if (encoded_last_key != 0) {
260 string arg(1, encoded_last_key);
261 dispatch(FuncRequest(LFUN_SELFINSERT, arg));
263 << "SelfInsert arg[`" << arg << "']" << endl;
271 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
273 //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
275 Buffer * buf = owner->buffer();
276 LCursor & cur = view()->cursor();
278 if (cmd.action == LFUN_NOACTION) {
279 setStatusMessage(N_("Nothing to do"));
284 switch (cmd.action) {
285 case LFUN_UNKNOWN_ACTION:
286 #ifndef HAVE_LIBAIKSAURUS
287 case LFUN_THESAURUS_ENTRY:
293 flag |= lyx_gui::getStatus(cmd);
296 if (flag.unknown()) {
297 setStatusMessage(N_("Unknown action"));
301 // the default error message if we disable the command
302 setStatusMessage(N_("Command disabled"));
306 // Check whether we need a buffer
307 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
309 setStatusMessage(N_("Command not allowed with"
310 "out any document open"));
315 // I would really like to avoid having this switch and rather try to
316 // encode this in the function itself.
317 // -- And I'd rather let an inset decide which LFUNs it is willing
318 // to handle (Andre')
320 switch (cmd.action) {
321 case LFUN_TOOLTIPS_TOGGLE:
322 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
325 case LFUN_READ_ONLY_TOGGLE:
326 flag.setOnOff(buf->isReadonly());
329 case LFUN_SWITCHBUFFER:
330 // toggle on the current buffer, but do not toggle off
331 // the other ones (is that a good idea?)
332 if (cmd.argument == buf->fileName())
337 enable = cmd.argument == "custom"
338 || Exporter::IsExportable(*buf, cmd.argument);
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();
380 case LFUN_INSET_SETTINGS: {
384 UpdatableInset * inset = cur.inset().asUpdatableInset();
385 lyxerr << "inset: " << inset << endl;
389 InsetOld::Code code = inset->lyxCode();
391 case InsetOld::TABULAR_CODE:
392 enable = cmd.argument == "tabular";
394 case InsetOld::ERT_CODE:
395 enable = cmd.argument == "ert";
397 case InsetOld::FLOAT_CODE:
398 enable = cmd.argument == "float";
400 case InsetOld::WRAP_CODE:
401 enable = cmd.argument == "wrap";
403 case InsetOld::NOTE_CODE:
404 enable = cmd.argument == "note";
406 case InsetOld::BRANCH_CODE:
407 enable = cmd.argument == "branch";
409 case InsetOld::BOX_CODE:
410 enable = cmd.argument == "box";
418 case LFUN_DIALOG_SHOW: {
419 string const name = cmd.getArg(0);
421 enable = name == "aboutlyx"
425 || name == "texinfo";
426 else if (name == "print")
427 enable = Exporter::IsExportable(*buf, "dvi")
428 && lyxrc.print_command != "none";
429 else if (name == "character")
430 enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
431 else if (name == "vclog")
432 enable = buf->lyxvc().inUse();
433 else if (name == "latexlog")
434 enable = IsFileReadable(buf->getLogName().second);
438 case LFUN_DIALOG_UPDATE: {
439 string const name = cmd.getArg(0);
441 enable = name == "prefs";
445 // this one is difficult to get right. As a half-baked
446 // solution, we consider only the first action of the sequence
447 case LFUN_SEQUENCE: {
448 // argument contains ';'-terminated commands
449 string const firstcmd = token(cmd.argument, ';', 0);
450 flag = getStatus(lyxaction.lookupFunc(firstcmd));
454 case LFUN_MENUNEWTMPLT:
455 case LFUN_WORDFINDFORWARD:
456 case LFUN_WORDFINDBACKWARD:
458 case LFUN_EXEC_COMMAND:
461 case LFUN_CLOSEBUFFER:
470 case LFUN_RECONFIGURE:
474 case LFUN_DROP_LAYOUTS_CHOICE:
475 case LFUN_MENU_OPEN_BY_NAME:
478 case LFUN_GOTOFILEROW:
479 case LFUN_GOTO_PARAGRAPH:
480 case LFUN_DIALOG_SHOW_NEW_INSET:
481 case LFUN_DIALOG_SHOW_NEXT_INSET:
482 case LFUN_DIALOG_HIDE:
483 case LFUN_DIALOG_DISCONNECT_INSET:
485 case LFUN_TOGGLECURSORFOLLOW:
489 case LFUN_KMAP_TOGGLE:
491 case LFUN_EXPORT_CUSTOM:
493 case LFUN_SAVEPREFERENCES:
494 case LFUN_SCREEN_FONT_UPDATE:
497 case LFUN_EXTERNAL_EDIT:
498 case LFUN_GRAPHICS_EDIT:
499 case LFUN_ALL_INSETS_TOGGLE:
500 case LFUN_LANGUAGE_BUFFER:
501 case LFUN_TEXTCLASS_APPLY:
502 case LFUN_TEXTCLASS_LOAD:
503 case LFUN_SAVE_AS_DEFAULT:
504 case LFUN_BUFFERPARAMS_APPLY:
505 case LFUN_LYXRC_APPLY:
506 case LFUN_NEXTBUFFER:
507 case LFUN_PREVIOUSBUFFER:
508 // these are handled in our dispatch()
513 cur.getStatus(cmd, flag);
515 flag = view()->getStatus(cmd);
521 // Can we use a readonly buffer?
522 if (buf && buf->isReadonly()
523 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
524 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
525 setStatusMessage(N_("Document is read-only"));
529 //lyxerr << "LyXFunc::getStatus: got: " << flag.enabled() << endl;
536 bool ensureBufferClean(BufferView * bv)
538 Buffer & buf = *bv->buffer();
542 string const file = MakeDisplayPath(buf.fileName(), 30);
543 string text = bformat(_("The document %1$s has unsaved "
544 "changes.\n\nDo you want to save "
545 "the document?"), file);
546 int const ret = Alert::prompt(_("Save changed document?"),
547 text, 0, 1, _("&Save"),
551 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
553 return buf.isClean();
557 void showPrintError(string const & name)
559 string str = bformat(_("Could not print the document %1$s.\n"
560 "Check that your printer is set up correctly."),
561 MakeDisplayPath(name, 50));
562 Alert::error(_("Print document failed"), str);
566 void loadTextclass(string const & name)
568 std::pair<bool, lyx::textclass_type> const tc_pair =
569 textclasslist.NumberOfClass(name);
571 if (!tc_pair.first) {
572 lyxerr << "Document class \"" << name
573 << "\" does not exist."
578 lyx::textclass_type const tc = tc_pair.second;
580 if (!textclasslist[tc].load()) {
581 string s = bformat(_("The document could not be converted\n"
582 "into the document class %1$s."),
583 textclasslist[tc].name());
584 Alert::error(_("Could not change class"), s);
591 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
593 string const argument = cmd.argument;
594 kb_action const action = cmd.action;
596 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
597 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
599 // we have not done anything wrong yet.
601 dispatch_buffer.erase();
602 selection_possible = false;
606 // We cannot use this function here
607 if (!getStatus(cmd).enabled()) {
608 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
609 << lyxaction.getActionName(action)
610 << " [" << action << "] is disabled at this location"
612 setErrorMessage(getStatusMessage());
616 if (view()->available())
617 view()->hideCursor();
621 case LFUN_WORDFINDFORWARD:
622 case LFUN_WORDFINDBACKWARD: {
623 static string last_search;
624 string searched_string;
626 if (!argument.empty()) {
627 last_search = argument;
628 searched_string = argument;
630 searched_string = last_search;
633 if (searched_string.empty())
636 bool const fw = action == LFUN_WORDFINDFORWARD;
638 lyx::find::find2string(searched_string, true, false, fw);
639 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
644 owner->message(keyseq.printOptions());
647 case LFUN_EXEC_COMMAND:
648 owner->getToolbars().display("minibuffer", true);
649 owner->focus_command_buffer();
654 meta_fake_bit = key_modifier::none;
655 if (view()->available())
656 // cancel any selection
657 dispatch(FuncRequest(LFUN_MARK_OFF));
658 setMessage(N_("Cancel"));
662 meta_fake_bit = key_modifier::alt;
663 setMessage(keyseq.print());
666 case LFUN_READ_ONLY_TOGGLE:
667 if (owner->buffer()->lyxvc().inUse())
668 owner->buffer()->lyxvc().toggleReadOnly();
670 owner->buffer()->setReadonly(
671 !owner->buffer()->isReadonly());
674 // --- Menus -----------------------------------------------
676 menuNew(argument, false);
679 case LFUN_MENUNEWTMPLT:
680 menuNew(argument, true);
683 case LFUN_CLOSEBUFFER:
688 if (!owner->buffer()->isUnnamed()) {
689 string const str = bformat(_("Saving document %1$s..."),
690 MakeDisplayPath(owner->buffer()->fileName()));
692 MenuWrite(owner->buffer());
693 owner->message(str + _(" done."));
695 WriteAs(owner->buffer());
699 WriteAs(owner->buffer(), argument);
702 case LFUN_MENURELOAD: {
703 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
704 string text = bformat(_("Any changes will be lost. Are you sure "
705 "you want to revert to the saved version of the document %1$s?"), file);
706 int const ret = Alert::prompt(_("Revert to saved document?"),
707 text, 0, 1, _("&Revert"), _("&Cancel"));
715 Exporter::Export(owner->buffer(), argument, true);
716 view()->showErrorList(BufferFormat(*owner->buffer()));
720 Exporter::Preview(owner->buffer(), argument);
721 view()->showErrorList(BufferFormat(*owner->buffer()));
725 Exporter::Export(owner->buffer(), "program", true);
726 view()->showErrorList(_("Build"));
730 owner->buffer()->runChktex();
731 view()->showErrorList(_("ChkTeX"));
735 if (argument == "custom")
736 owner->getDialogs().show("sendto");
738 Exporter::Export(owner->buffer(), argument, false);
739 view()->showErrorList(BufferFormat(*owner->buffer()));
743 case LFUN_EXPORT_CUSTOM: {
745 string command = split(argument, format_name, ' ');
746 Format const * format = formats.getFormat(format_name);
748 lyxerr << "Format \"" << format_name
749 << "\" not recognized!"
754 Buffer * buffer = owner->buffer();
756 // The name of the file created by the conversion process
759 // Output to filename
760 if (format->name() == "lyx") {
761 string const latexname =
762 buffer->getLatexName(false);
763 filename = ChangeExtension(latexname,
764 format->extension());
765 filename = AddName(buffer->temppath(), filename);
767 if (!buffer->writeFile(filename))
771 Exporter::Export(buffer, format_name, true,
775 // Substitute $$FName for filename
776 if (!contains(command, "$$FName"))
777 command = "( " + command + " ) < $$FName";
778 command = subst(command, "$$FName", filename);
780 // Execute the command in the background
782 call.startscript(Systemcall::DontWait, command);
789 string command = split(split(argument, target, ' '),
793 || target_name.empty()
794 || command.empty()) {
795 lyxerr << "Unable to parse \""
796 << argument << '"' << std::endl;
799 if (target != "printer" && target != "file") {
800 lyxerr << "Unrecognized target \""
801 << target << '"' << std::endl;
805 Buffer * buffer = owner->buffer();
807 if (!Exporter::Export(buffer, "dvi", true)) {
808 showPrintError(buffer->fileName());
812 // Push directory path.
813 string const path = buffer->temppath();
816 // there are three cases here:
817 // 1. we print to a file
818 // 2. we print directly to a printer
819 // 3. we print using a spool command (print to file first)
822 string const dviname =
823 ChangeExtension(buffer->getLatexName(true),
826 if (target == "printer") {
827 if (!lyxrc.print_spool_command.empty()) {
828 // case 3: print using a spool
829 string const psname =
830 ChangeExtension(dviname,".ps");
831 command += lyxrc.print_to_file
834 + QuoteName(dviname);
837 lyxrc.print_spool_command +' ';
838 if (target_name != "default") {
839 command2 += lyxrc.print_spool_printerprefix
843 command2 += QuoteName(psname);
845 // If successful, then spool command
846 res = one.startscript(
851 res = one.startscript(
852 Systemcall::DontWait,
855 // case 2: print directly to a printer
856 res = one.startscript(
857 Systemcall::DontWait,
858 command + QuoteName(dviname));
862 // case 1: print to a file
863 command += lyxrc.print_to_file
864 + QuoteName(MakeAbsPath(target_name,
867 + QuoteName(dviname);
868 res = one.startscript(Systemcall::DontWait,
873 showPrintError(buffer->fileName());
886 InsetCommandParams p("tableofcontents");
887 string const data = InsetCommandMailer::params2string("toc", p);
888 owner->getDialogs().show("toc", data, 0);
896 case LFUN_RECONFIGURE:
900 case LFUN_HELP_OPEN: {
901 string const arg = argument;
903 setErrorMessage(N_("Missing argument"));
906 string const fname = i18nLibFileSearch("doc", arg, "lyx");
908 lyxerr << "LyX: unable to find documentation file `"
909 << arg << "'. Bad installation?" << endl;
912 owner->message(bformat(_("Opening help file %1$s..."),
913 MakeDisplayPath(fname)));
914 view()->loadLyXFile(fname, false);
918 // --- version control -------------------------------
919 case LFUN_VC_REGISTER:
920 if (!ensureBufferClean(view()))
922 if (!owner->buffer()->lyxvc().inUse()) {
923 owner->buffer()->lyxvc().registrer();
928 case LFUN_VC_CHECKIN:
929 if (!ensureBufferClean(view()))
931 if (owner->buffer()->lyxvc().inUse()
932 && !owner->buffer()->isReadonly()) {
933 owner->buffer()->lyxvc().checkIn();
938 case LFUN_VC_CHECKOUT:
939 if (!ensureBufferClean(view()))
941 if (owner->buffer()->lyxvc().inUse()
942 && owner->buffer()->isReadonly()) {
943 owner->buffer()->lyxvc().checkOut();
949 owner->buffer()->lyxvc().revert();
954 owner->buffer()->lyxvc().undoLast();
958 // --- buffers ----------------------------------------
959 case LFUN_SWITCHBUFFER:
960 view()->setBuffer(bufferlist.getBuffer(argument));
963 case LFUN_NEXTBUFFER:
964 view()->setBuffer(bufferlist.next(view()->buffer()));
967 case LFUN_PREVIOUSBUFFER:
968 view()->setBuffer(bufferlist.previous(view()->buffer()));
972 NewFile(view(), argument);
979 case LFUN_DROP_LAYOUTS_CHOICE:
980 owner->getToolbars().openLayoutList();
983 case LFUN_MENU_OPEN_BY_NAME:
984 owner->getMenubar().openByName(argument);
987 // --- lyxserver commands ----------------------------
989 setMessage(owner->buffer()->fileName());
990 lyxerr[Debug::INFO] << "FNAME["
991 << owner->buffer()->fileName()
996 dispatch_buffer = keyseq.print();
997 lyxserver->notifyClient(dispatch_buffer);
1000 case LFUN_GOTOFILEROW: {
1003 istringstream is(argument);
1004 is >> file_name >> row;
1005 if (prefixIs(file_name, getTmpDir())) {
1006 // Needed by inverse dvi search. If it is a file
1007 // in tmpdir, call the apropriated function
1008 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
1010 // Must replace extension of the file to be .lyx
1011 // and get full path
1012 string const s = ChangeExtension(file_name, ".lyx");
1013 // Either change buffer or load the file
1014 if (bufferlist.exists(s)) {
1015 view()->setBuffer(bufferlist.getBuffer(s));
1017 view()->loadLyXFile(s);
1021 view()->setCursorFromRow(row);
1024 // see BufferView_pimpl::center()
1025 view()->updateScrollbar();
1029 case LFUN_GOTO_PARAGRAPH: {
1030 istringstream is(argument);
1033 ParIterator par = owner->buffer()->getParFromID(id);
1034 if (par == owner->buffer()->par_iterator_end()) {
1035 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1036 << id << ']' << endl;
1039 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1040 << " found." << endl;
1044 view()->setCursor(par, 0);
1046 view()->switchKeyMap();
1047 owner->view_state_changed();
1050 // see BufferView_pimpl::center()
1051 view()->updateScrollbar();
1055 case LFUN_DIALOG_SHOW: {
1056 string const name = cmd.getArg(0);
1057 string data = trim(cmd.argument.substr(name.size()));
1059 if (name == "character") {
1060 data = freefont2string();
1062 owner->getDialogs().show("character", data);
1065 else if (name == "latexlog") {
1066 pair<Buffer::LogType, string> const logfile =
1067 owner->buffer()->getLogName();
1068 switch (logfile.first) {
1069 case Buffer::latexlog:
1072 case Buffer::buildlog:
1076 data += logfile.second;
1077 owner->getDialogs().show("log", data);
1079 else if (name == "vclog") {
1080 string const data = "vc " +
1081 owner->buffer()->lyxvc().getLogFile();
1082 owner->getDialogs().show("log", data);
1085 owner->getDialogs().show(name, data);
1089 case LFUN_DIALOG_SHOW_NEW_INSET: {
1090 string const name = cmd.getArg(0);
1091 string data = trim(cmd.argument.substr(name.size()));
1092 if (name == "bibitem" ||
1094 name == "include" ||
1100 InsetCommandParams p(name);
1101 data = InsetCommandMailer::params2string(name, p);
1102 } else if (name == "box") {
1103 // \c data == "Boxed" || "Frameless" etc
1104 InsetBoxParams p(data);
1105 data = InsetBoxMailer::params2string(p);
1106 } else if (name == "branch") {
1107 InsetBranchParams p;
1108 data = InsetBranchMailer::params2string(p);
1109 } else if (name == "citation") {
1110 InsetCommandParams p("cite");
1111 data = InsetCommandMailer::params2string(name, p);
1112 } else if (name == "ert") {
1113 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1114 } else if (name == "external") {
1115 InsetExternalParams p;
1116 Buffer const & buffer = *owner->buffer();
1117 data = InsetExternalMailer::params2string(p, buffer);
1118 } else if (name == "float") {
1120 data = InsetFloatMailer::params2string(p);
1121 } else if (name == "graphics") {
1122 InsetGraphicsParams p;
1123 Buffer const & buffer = *owner->buffer();
1124 data = InsetGraphicsMailer::params2string(p, buffer);
1125 } else if (name == "note") {
1127 data = InsetNoteMailer::params2string(p);
1128 } else if (name == "vspace") {
1130 data = InsetVSpaceMailer::params2string(space);
1131 } else if (name == "wrap") {
1133 data = InsetWrapMailer::params2string(p);
1135 owner->getDialogs().show(name, data, 0);
1139 case LFUN_DIALOG_SHOW_NEXT_INSET:
1142 case LFUN_DIALOG_UPDATE: {
1143 string const & name = argument;
1144 // Can only update a dialog connected to an existing inset
1145 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1147 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1148 inset->dispatch(view()->cursor(), fr);
1149 } else if (name == "paragraph") {
1150 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1151 } else if (name == "prefs") {
1152 owner->getDialogs().update(name, string());
1157 case LFUN_DIALOG_HIDE:
1158 Dialogs::hide(argument, 0);
1161 case LFUN_DIALOG_DISCONNECT_INSET:
1162 owner->getDialogs().disconnect(argument);
1165 case LFUN_CHILDOPEN: {
1166 string const filename =
1167 MakeAbsPath(argument, owner->buffer()->filePath());
1168 setMessage(N_("Opening child document ") +
1169 MakeDisplayPath(filename) + "...");
1170 view()->savePosition(0);
1171 string const parentfilename = owner->buffer()->fileName();
1172 if (bufferlist.exists(filename))
1173 view()->setBuffer(bufferlist.getBuffer(filename));
1175 view()->loadLyXFile(filename);
1176 // Set the parent name of the child document.
1177 // This makes insertion of citations and references in the child work,
1178 // when the target is in the parent or another child document.
1179 owner->buffer()->setParentName(parentfilename);
1183 case LFUN_TOGGLECURSORFOLLOW:
1184 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1188 owner->getIntl().KeyMapOn(false);
1191 case LFUN_KMAP_PRIM:
1192 owner->getIntl().KeyMapPrim();
1196 owner->getIntl().KeyMapSec();
1199 case LFUN_KMAP_TOGGLE:
1200 owner->getIntl().ToggleKeyMap();
1206 string rest = split(argument, countstr, ' ');
1207 istringstream is(countstr);
1210 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1211 for (int i = 0; i < count; ++i)
1212 dispatch(lyxaction.lookupFunc(rest));
1216 case LFUN_SEQUENCE: {
1217 // argument contains ';'-terminated commands
1218 string arg = argument;
1219 while (!arg.empty()) {
1221 arg = split(arg, first, ';');
1222 dispatch(lyxaction.lookupFunc(first));
1227 case LFUN_SAVEPREFERENCES: {
1228 Path p(user_lyxdir());
1229 lyxrc.write("preferences", false);
1233 case LFUN_SCREEN_FONT_UPDATE:
1234 // handle the screen font changes.
1235 lyxrc.set_font_norm_type();
1236 lyx_gui::update_fonts();
1237 // All visible buffers will need resize
1241 case LFUN_SET_COLOR: {
1243 string const x11_name = split(argument, lyx_name, ' ');
1244 if (lyx_name.empty() || x11_name.empty()) {
1245 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1250 bool const graphicsbg_changed =
1251 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1252 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1254 if (!lcolor.setColor(lyx_name, x11_name)) {
1256 bformat(_("Set-color \"%1$s\" failed "
1257 "- color is undefined or "
1258 "may not be redefined"), lyx_name));
1262 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1264 if (graphicsbg_changed) {
1265 #ifdef WITH_WARNINGS
1266 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1269 lyx::graphics::GCache::get().changeDisplay(true);
1276 owner->message(argument);
1279 case LFUN_TOOLTIPS_TOGGLE:
1280 owner->getDialogs().toggleTooltips();
1283 case LFUN_EXTERNAL_EDIT: {
1284 FuncRequest fr(action, argument);
1285 InsetExternal().dispatch(view()->cursor(), fr);
1289 case LFUN_GRAPHICS_EDIT: {
1290 FuncRequest fr(action, argument);
1291 InsetGraphics().dispatch(view()->cursor(), fr);
1295 case LFUN_ALL_INSETS_TOGGLE: {
1297 string const name = split(argument, action, ' ');
1298 InsetBase::Code const inset_code =
1299 InsetBase::translate(name);
1301 LCursor & cur = view()->cursor();
1302 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1304 InsetBase & inset = owner->buffer()->inset();
1305 InsetIterator it = inset_iterator_begin(inset);
1306 InsetIterator const end = inset_iterator_end(inset);
1307 for (; it != end; ++it) {
1308 if (inset_code == InsetBase::NO_CODE
1309 || inset_code == it->lyxCode())
1310 it->dispatch(cur, fr);
1315 case LFUN_LANGUAGE_BUFFER: {
1316 Buffer & buffer = *owner->buffer();
1317 Language const * oldL = buffer.params().language;
1318 Language const * newL = languages.getLanguage(argument);
1319 if (!newL || oldL == newL)
1322 if (oldL->RightToLeft() == newL->RightToLeft()
1323 && !buffer.isMultiLingual())
1324 buffer.changeLanguage(oldL, newL);
1326 buffer.updateDocLang(newL);
1330 case LFUN_SAVE_AS_DEFAULT: {
1331 string const fname =
1332 AddName(AddPath(user_lyxdir(), "templates/"),
1334 Buffer defaults(fname);
1336 istringstream ss(argument);
1339 int const unknown_tokens = defaults.readHeader(lex);
1341 if (unknown_tokens != 0) {
1342 lyxerr << "Warning in LFUN_SAVE_AS_DEFAULT!\n"
1343 << unknown_tokens << " unknown token"
1344 << (unknown_tokens == 1 ? "" : "s")
1348 if (defaults.writeFile(defaults.fileName()))
1349 setMessage(_("Document defaults saved in ")
1350 + MakeDisplayPath(fname));
1352 setErrorMessage(_("Unable to save document defaults"));
1356 case LFUN_BUFFERPARAMS_APPLY: {
1357 biblio::CiteEngine const engine =
1358 owner->buffer()->params().cite_engine;
1360 istringstream ss(argument);
1363 int const unknown_tokens =
1364 owner->buffer()->readHeader(lex);
1366 if (unknown_tokens != 0) {
1367 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1368 << unknown_tokens << " unknown token"
1369 << (unknown_tokens == 1 ? "" : "s")
1372 if (engine == owner->buffer()->params().cite_engine)
1375 LCursor & cur = view()->cursor();
1376 FuncRequest fr(LFUN_INSET_REFRESH);
1378 InsetBase & inset = owner->buffer()->inset();
1379 InsetIterator it = inset_iterator_begin(inset);
1380 InsetIterator const end = inset_iterator_end(inset);
1381 for (; it != end; ++it)
1382 if (it->lyxCode() == InsetBase::CITE_CODE)
1383 it->dispatch(cur, fr);
1387 case LFUN_TEXTCLASS_APPLY: {
1388 Buffer * buffer = owner->buffer();
1390 lyx::textclass_type const old_class =
1391 buffer->params().textclass;
1393 loadTextclass(argument);
1395 std::pair<bool, lyx::textclass_type> const tc_pair =
1396 textclasslist.NumberOfClass(argument);
1401 lyx::textclass_type const new_class = tc_pair.second;
1402 if (old_class == new_class)
1406 owner->message(_("Converting document to new document class..."));
1408 lyx::cap::SwitchLayoutsBetweenClasses(
1409 old_class, new_class,
1410 buffer->paragraphs(), el);
1412 bufferErrors(*buffer, el);
1413 view()->showErrorList(_("Class switch"));
1417 case LFUN_TEXTCLASS_LOAD:
1418 loadTextclass(argument);
1421 case LFUN_LYXRC_APPLY: {
1422 istringstream ss(argument);
1423 bool const success = lyxrc.read(ss) == 0;
1426 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1427 << "Unable to read lyxrc data"
1435 view()->cursor().dispatch(cmd);
1436 if (view()->cursor().result().dispatched())
1437 update |= view()->cursor().result().update();
1439 update |= view()->dispatch(cmd);
1445 if (view()->available()) {
1446 // Redraw screen unless explicitly told otherwise.
1447 // This also initializes the position cache for all insets
1448 // in (at least partially) visible top-level paragraphs.
1452 // fitCursor() needs valid inset position. The previous call to
1453 // update() makes sure we have such even for freshly created
1455 if (view()->fitCursor())
1457 // if we executed a mutating lfun, mark the buffer as dirty
1458 if (getStatus(cmd).enabled()
1459 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1460 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1461 view()->buffer()->markDirty();
1464 if (view()->cursor().inTexted()) {
1465 view()->owner()->updateLayoutChoice();
1466 sendDispatchMessage(getMessage(), cmd, verbose);
1472 void LyXFunc::sendDispatchMessage(string const & msg,
1473 FuncRequest const & cmd, bool verbose)
1475 owner->updateMenubar();
1476 owner->updateToolbars();
1478 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1479 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1481 owner->message(msg);
1485 string dispatch_msg = msg;
1486 if (!dispatch_msg.empty())
1487 dispatch_msg += ' ';
1489 string comname = lyxaction.getActionName(cmd.action);
1491 bool argsadded = false;
1493 if (!cmd.argument.empty()) {
1494 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1495 comname += ' ' + cmd.argument;
1500 string const shortcuts = toplevel_keymap->printbindings(cmd);
1502 if (!shortcuts.empty()) {
1503 comname += ": " + shortcuts;
1504 } else if (!argsadded && !cmd.argument.empty()) {
1505 comname += ' ' + cmd.argument;
1508 if (!comname.empty()) {
1509 comname = rtrim(comname);
1510 dispatch_msg += '(' + comname + ')';
1513 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1514 if (!dispatch_msg.empty())
1515 owner->message(dispatch_msg);
1519 void LyXFunc::setupLocalKeymap()
1521 keyseq.stdmap = toplevel_keymap.get();
1522 keyseq.curmap = toplevel_keymap.get();
1523 cancel_meta_seq.stdmap = toplevel_keymap.get();
1524 cancel_meta_seq.curmap = toplevel_keymap.get();
1528 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1530 string initpath = lyxrc.document_path;
1531 string filename(name);
1533 if (view()->available()) {
1534 string const trypath = owner->buffer()->filePath();
1535 // If directory is writeable, use this as default.
1536 if (IsDirWriteable(trypath))
1540 static int newfile_number;
1542 if (filename.empty()) {
1543 filename = AddName(lyxrc.document_path,
1544 "newfile" + tostr(++newfile_number) + ".lyx");
1545 FileInfo fi(filename);
1546 while (bufferlist.exists(filename) || fi.readable()) {
1548 filename = AddName(lyxrc.document_path,
1549 "newfile" + tostr(newfile_number) +
1551 fi.newFile(filename);
1555 // The template stuff
1558 FileDialog fileDlg(_("Select template file"),
1559 LFUN_SELECT_FILE_SYNC,
1560 make_pair(string(_("Documents|#o#O")),
1561 string(lyxrc.document_path)),
1562 make_pair(string(_("Templates|#T#t")),
1563 string(lyxrc.template_path)));
1565 FileDialog::Result result =
1566 fileDlg.open(lyxrc.template_path,
1567 FileFilterList(_("LyX Documents (*.lyx)")),
1570 if (result.first == FileDialog::Later)
1572 if (result.second.empty())
1574 templname = result.second;
1577 view()->newFile(filename, templname, !name.empty());
1581 void LyXFunc::open(string const & fname)
1583 string initpath = lyxrc.document_path;
1585 if (view()->available()) {
1586 string const trypath = owner->buffer()->filePath();
1587 // If directory is writeable, use this as default.
1588 if (IsDirWriteable(trypath))
1594 if (fname.empty()) {
1595 FileDialog fileDlg(_("Select document to open"),
1597 make_pair(string(_("Documents|#o#O")),
1598 string(lyxrc.document_path)),
1599 make_pair(string(_("Examples|#E#e")),
1600 string(AddPath(system_lyxdir(), "examples"))));
1602 FileDialog::Result result =
1603 fileDlg.open(initpath,
1604 FileFilterList(_("LyX Documents (*.lyx)")),
1607 if (result.first == FileDialog::Later)
1610 filename = result.second;
1612 // check selected filename
1613 if (filename.empty()) {
1614 owner->message(_("Canceled."));
1620 // get absolute path of file and add ".lyx" to the filename if
1622 string const fullpath = FileSearch(string(), filename, "lyx");
1623 if (!fullpath.empty()) {
1624 filename = fullpath;
1627 string const disp_fn(MakeDisplayPath(filename));
1629 // if the file doesn't exist, let the user create one
1630 FileInfo const f(filename, true);
1632 // the user specifically chose this name. Believe them.
1633 view()->newFile(filename, "", true);
1637 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1640 if (view()->loadLyXFile(filename)) {
1641 str2 = bformat(_("Document %1$s opened."), disp_fn);
1643 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1645 owner->message(str2);
1649 void LyXFunc::doImport(string const & argument)
1652 string filename = split(argument, format, ' ');
1654 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1655 << " file: " << filename << endl;
1657 // need user interaction
1658 if (filename.empty()) {
1659 string initpath = lyxrc.document_path;
1661 if (view()->available()) {
1662 string const trypath = owner->buffer()->filePath();
1663 // If directory is writeable, use this as default.
1664 if (IsDirWriteable(trypath))
1668 string const text = bformat(_("Select %1$s file to import"),
1669 formats.prettyName(format));
1671 FileDialog fileDlg(text,
1673 make_pair(string(_("Documents|#o#O")),
1674 string(lyxrc.document_path)),
1675 make_pair(string(_("Examples|#E#e")),
1676 string(AddPath(system_lyxdir(), "examples"))));
1678 string const filter = formats.prettyName(format)
1679 + " (*." + formats.extension(format) + ')';
1681 FileDialog::Result result =
1682 fileDlg.open(initpath,
1683 FileFilterList(filter),
1686 if (result.first == FileDialog::Later)
1689 filename = result.second;
1691 // check selected filename
1692 if (filename.empty())
1693 owner->message(_("Canceled."));
1696 if (filename.empty())
1699 // get absolute path of file
1700 filename = MakeAbsPath(filename);
1702 string const lyxfile = ChangeExtension(filename, ".lyx");
1704 // Check if the document already is open
1705 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1706 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1707 owner->message(_("Canceled."));
1712 // if the file exists already, and we didn't do
1713 // -i lyx thefile.lyx, warn
1714 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1715 string const file = MakeDisplayPath(lyxfile, 30);
1717 string text = bformat(_("The document %1$s already exists.\n\n"
1718 "Do you want to over-write that document?"), file);
1719 int const ret = Alert::prompt(_("Over-write document?"),
1720 text, 0, 1, _("&Over-write"), _("&Cancel"));
1723 owner->message(_("Canceled."));
1728 Importer::Import(owner, filename, format);
1732 void LyXFunc::closeBuffer()
1734 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1735 if (bufferlist.empty()) {
1736 // need this otherwise SEGV may occur while
1737 // trying to set variables that don't exist
1738 // since there's no current buffer
1739 owner->getDialogs().hideBufferDependent();
1741 view()->setBuffer(bufferlist.first());
1747 // Each "owner" should have it's own message method. lyxview and
1748 // the minibuffer would use the minibuffer, but lyxserver would
1749 // send an ERROR signal to its client. Alejandro 970603
1750 // This function is bit problematic when it comes to NLS, to make the
1751 // lyx servers client be language indepenent we must not translate
1752 // strings sent to this func.
1753 void LyXFunc::setErrorMessage(string const & m) const
1755 dispatch_buffer = m;
1760 void LyXFunc::setMessage(string const & m) const
1762 dispatch_buffer = m;
1766 void LyXFunc::setStatusMessage(string const & m) const
1772 string const LyXFunc::viewStatusMessage()
1774 // When meta-fake key is pressed, show the key sequence so far + "M-".
1776 return keyseq.print() + "M-";
1778 // Else, when a non-complete key sequence is pressed,
1779 // show the available options.
1780 if (keyseq.length() > 0 && !keyseq.deleted())
1781 return keyseq.printOptions();
1783 if (!view()->available())
1784 return _("Welcome to LyX!");
1786 return view()->cursor().currentState();
1790 BufferView * LyXFunc::view() const
1792 BOOST_ASSERT(owner);
1793 return owner->view().get();
1797 bool LyXFunc::wasMetaKey() const
1799 return (meta_fake_bit != key_modifier::none);