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())
331 case LFUN_TRACK_CHANGES:
332 flag.setOnOff(buf->params().tracking_changes);
336 enable = cmd.argument == "custom"
337 || Exporter::IsExportable(*buf, cmd.argument);
340 enable = !buf->undostack().empty();
343 enable = !buf->redostack().empty();
347 enable = cur.selection();
351 enable = buf->isLatex() && lyxrc.chktex_command != "none";
355 enable = Exporter::IsExportable(*buf, "program");
358 case LFUN_LAYOUT_TABULAR:
359 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
363 case LFUN_LAYOUT_PARAGRAPH:
364 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
367 case LFUN_VC_REGISTER:
368 enable = !buf->lyxvc().inUse();
370 case LFUN_VC_CHECKIN:
371 enable = buf->lyxvc().inUse() && !buf->isReadonly();
373 case LFUN_VC_CHECKOUT:
374 enable = buf->lyxvc().inUse() && buf->isReadonly();
378 enable = buf->lyxvc().inUse();
380 case LFUN_MENURELOAD:
381 enable = !buf->isUnnamed() && !buf->isClean();
383 case LFUN_BOOKMARK_GOTO:
384 enable = view()->isSavedPosition(strToUnsignedInt(cmd.argument));
387 case LFUN_MERGE_CHANGES:
388 case LFUN_ACCEPT_CHANGE:
389 case LFUN_REJECT_CHANGE:
390 case LFUN_ACCEPT_ALL_CHANGES:
391 case LFUN_REJECT_ALL_CHANGES:
392 enable = buf && buf->params().tracking_changes;
395 case LFUN_INSET_SETTINGS: {
399 UpdatableInset * inset = cur.inset().asUpdatableInset();
400 lyxerr << "inset: " << inset << endl;
404 InsetOld::Code code = inset->lyxCode();
406 case InsetOld::TABULAR_CODE:
407 enable = cmd.argument == "tabular";
409 case InsetOld::ERT_CODE:
410 enable = cmd.argument == "ert";
412 case InsetOld::FLOAT_CODE:
413 enable = cmd.argument == "float";
415 case InsetOld::WRAP_CODE:
416 enable = cmd.argument == "wrap";
418 case InsetOld::NOTE_CODE:
419 enable = cmd.argument == "note";
421 case InsetOld::BRANCH_CODE:
422 enable = cmd.argument == "branch";
424 case InsetOld::BOX_CODE:
425 enable = cmd.argument == "box";
433 case LFUN_DIALOG_SHOW: {
434 string const name = cmd.getArg(0);
436 enable = name == "aboutlyx"
439 || name == "preferences"
440 || name == "texinfo";
441 else if (name == "print")
442 enable = Exporter::IsExportable(*buf, "dvi")
443 && lyxrc.print_command != "none";
444 else if (name == "character")
445 enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
446 else if (name == "vclog")
447 enable = buf->lyxvc().inUse();
448 else if (name == "latexlog")
449 enable = IsFileReadable(buf->getLogName().second);
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_UPDATE:
483 case LFUN_DIALOG_HIDE:
484 case LFUN_DIALOG_DISCONNECT_INSET:
486 case LFUN_TOGGLECURSORFOLLOW:
490 case LFUN_KMAP_TOGGLE:
492 case LFUN_EXPORT_CUSTOM:
495 case LFUN_SAVEPREFERENCES:
496 case LFUN_SCREEN_FONT_UPDATE:
499 case LFUN_EXTERNAL_EDIT:
500 case LFUN_FILE_INSERT:
501 case LFUN_FILE_INSERT_ASCII:
502 case LFUN_FILE_INSERT_ASCII_PARA:
503 case LFUN_ALL_INSETS_TOGGLE:
504 case LFUN_LANGUAGE_BUFFER:
505 case LFUN_TEXTCLASS_APPLY:
506 case LFUN_TEXTCLASS_LOAD:
507 case LFUN_SAVE_AS_DEFAULT:
508 case LFUN_BUFFERPARAMS_APPLY:
510 // these are handled in our dispatch()
514 cur.getStatus(cmd, flag);
520 // Can we use a readonly buffer?
521 if (buf && buf->isReadonly()
522 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
523 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
524 setStatusMessage(N_("Document is read-only"));
534 bool ensureBufferClean(BufferView * bv)
536 Buffer & buf = *bv->buffer();
540 string const file = MakeDisplayPath(buf.fileName(), 30);
541 string text = bformat(_("The document %1$s has unsaved "
542 "changes.\n\nDo you want to save "
543 "the document?"), file);
544 int const ret = Alert::prompt(_("Save changed document?"),
545 text, 0, 1, _("&Save"),
549 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
551 return buf.isClean();
555 void showPrintError(string const & name)
557 string str = bformat(_("Could not print the document %1$s.\n"
558 "Check that your printer is set up correctly."),
559 MakeDisplayPath(name, 50));
560 Alert::error(_("Print document failed"), str);
564 void loadTextclass(string const & name)
566 std::pair<bool, lyx::textclass_type> const tc_pair =
567 textclasslist.NumberOfClass(name);
569 if (!tc_pair.first) {
570 lyxerr << "Document class \"" << name
571 << "\" does not exist."
576 lyx::textclass_type const tc = tc_pair.second;
578 if (!textclasslist[tc].load()) {
579 string s = bformat(_("The document could not be converted\n"
580 "into the document class %1$s."),
581 textclasslist[tc].name());
582 Alert::error(_("Could not change class"), s);
589 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
591 string const argument = cmd.argument;
592 kb_action const action = cmd.action;
594 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
595 //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
597 // we have not done anything wrong yet.
599 dispatch_buffer.erase();
600 selection_possible = false;
602 // We cannot use this function here
603 if (!getStatus(cmd).enabled()) {
604 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
605 << lyxaction.getActionName(action)
606 << " [" << action << "] is disabled at this location"
608 setErrorMessage(getStatusMessage());
612 if (view()->available())
613 view()->hideCursor();
617 case LFUN_WORDFINDFORWARD:
618 case LFUN_WORDFINDBACKWARD: {
619 static string last_search;
620 string searched_string;
622 if (!argument.empty()) {
623 last_search = argument;
624 searched_string = argument;
626 searched_string = last_search;
629 if (searched_string.empty())
632 bool const fw = action == LFUN_WORDFINDFORWARD;
634 lyx::find::find2string(searched_string, true, false, fw);
635 lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
640 owner->message(keyseq.printOptions());
643 case LFUN_EXEC_COMMAND:
644 owner->focus_command_buffer();
649 meta_fake_bit = key_modifier::none;
650 if (view()->available())
651 // cancel any selection
652 dispatch(FuncRequest(LFUN_MARK_OFF));
653 setMessage(N_("Cancel"));
657 meta_fake_bit = key_modifier::alt;
658 setMessage(keyseq.print());
661 case LFUN_READ_ONLY_TOGGLE:
662 if (owner->buffer()->lyxvc().inUse())
663 owner->buffer()->lyxvc().toggleReadOnly();
665 owner->buffer()->setReadonly(
666 !owner->buffer()->isReadonly());
669 // --- Menus -----------------------------------------------
671 menuNew(argument, false);
674 case LFUN_MENUNEWTMPLT:
675 menuNew(argument, true);
678 case LFUN_CLOSEBUFFER:
683 if (!owner->buffer()->isUnnamed()) {
684 string const str = bformat(_("Saving document %1$s..."),
685 MakeDisplayPath(owner->buffer()->fileName()));
687 MenuWrite(owner->buffer());
688 owner->message(str + _(" done."));
690 WriteAs(owner->buffer());
694 WriteAs(owner->buffer(), argument);
697 case LFUN_MENURELOAD: {
698 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
699 string text = bformat(_("Any changes will be lost. Are you sure "
700 "you want to revert to the saved version of the document %1$s?"), file);
701 int const ret = Alert::prompt(_("Revert to saved document?"),
702 text, 0, 1, _("&Revert"), _("&Cancel"));
710 Exporter::Export(owner->buffer(), argument, true);
711 view()->showErrorList(BufferFormat(*owner->buffer()));
715 Exporter::Preview(owner->buffer(), argument);
716 view()->showErrorList(BufferFormat(*owner->buffer()));
720 Exporter::Export(owner->buffer(), "program", true);
721 view()->showErrorList(_("Build"));
725 owner->buffer()->runChktex();
726 view()->showErrorList(_("ChkTeX"));
730 if (argument == "custom")
731 owner->getDialogs().show("sendto");
733 Exporter::Export(owner->buffer(), argument, false);
734 view()->showErrorList(BufferFormat(*owner->buffer()));
738 case LFUN_EXPORT_CUSTOM: {
740 string command = split(argument, format_name, ' ');
741 Format const * format = formats.getFormat(format_name);
743 lyxerr << "Format \"" << format_name
744 << "\" not recognized!"
749 Buffer * buffer = owner->buffer();
751 // The name of the file created by the conversion process
754 // Output to filename
755 if (format->name() == "lyx") {
756 string const latexname =
757 buffer->getLatexName(false);
758 filename = ChangeExtension(latexname,
759 format->extension());
760 filename = AddName(buffer->temppath(), filename);
762 if (!buffer->writeFile(filename))
766 Exporter::Export(buffer, format_name, true,
770 // Substitute $$FName for filename
771 if (!contains(command, "$$FName"))
772 command = "( " + command + " ) < $$FName";
773 command = subst(command, "$$FName", filename);
775 // Execute the command in the background
777 call.startscript(Systemcall::DontWait, command);
784 string command = split(split(argument, target, ' '),
788 || target_name.empty()
789 || command.empty()) {
790 lyxerr << "Unable to parse \""
791 << argument << '"' << std::endl;
794 if (target != "printer" && target != "file") {
795 lyxerr << "Unrecognized target \""
796 << target << '"' << std::endl;
800 Buffer * buffer = owner->buffer();
802 if (!Exporter::Export(buffer, "dvi", true)) {
803 showPrintError(buffer->fileName());
807 // Push directory path.
808 string const path = buffer->temppath();
811 // there are three cases here:
812 // 1. we print to a file
813 // 2. we print directly to a printer
814 // 3. we print using a spool command (print to file first)
817 string const dviname =
818 ChangeExtension(buffer->getLatexName(true),
821 if (target == "printer") {
822 if (!lyxrc.print_spool_command.empty()) {
823 // case 3: print using a spool
824 string const psname =
825 ChangeExtension(dviname,".ps");
826 command += lyxrc.print_to_file
829 + QuoteName(dviname);
832 lyxrc.print_spool_command +' ';
833 if (target_name != "default") {
834 command2 += lyxrc.print_spool_printerprefix
838 command2 += QuoteName(psname);
840 // If successful, then spool command
841 res = one.startscript(
846 res = one.startscript(
847 Systemcall::DontWait,
850 // case 2: print directly to a printer
851 res = one.startscript(
852 Systemcall::DontWait,
853 command + QuoteName(dviname));
857 // case 1: print to a file
858 command += lyxrc.print_to_file
859 + QuoteName(MakeAbsPath(target_name,
862 + QuoteName(dviname);
863 res = one.startscript(Systemcall::DontWait,
868 showPrintError(buffer->fileName());
881 InsetCommandParams p("tableofcontents");
882 string const data = InsetCommandMailer::params2string("toc", p);
883 owner->getDialogs().show("toc", data, 0);
891 case LFUN_RECONFIGURE:
895 case LFUN_HELP_OPEN: {
896 string const arg = argument;
898 setErrorMessage(N_("Missing argument"));
901 string const fname = i18nLibFileSearch("doc", arg, "lyx");
903 lyxerr << "LyX: unable to find documentation file `"
904 << arg << "'. Bad installation?" << endl;
907 owner->message(bformat(_("Opening help file %1$s..."),
908 MakeDisplayPath(fname)));
909 view()->loadLyXFile(fname, false);
913 // --- version control -------------------------------
914 case LFUN_VC_REGISTER:
915 if (!ensureBufferClean(view()))
917 if (!owner->buffer()->lyxvc().inUse()) {
918 owner->buffer()->lyxvc().registrer();
923 case LFUN_VC_CHECKIN:
924 if (!ensureBufferClean(view()))
926 if (owner->buffer()->lyxvc().inUse()
927 && !owner->buffer()->isReadonly()) {
928 owner->buffer()->lyxvc().checkIn();
933 case LFUN_VC_CHECKOUT:
934 if (!ensureBufferClean(view()))
936 if (owner->buffer()->lyxvc().inUse()
937 && owner->buffer()->isReadonly()) {
938 owner->buffer()->lyxvc().checkOut();
944 owner->buffer()->lyxvc().revert();
949 owner->buffer()->lyxvc().undoLast();
953 // --- buffers ----------------------------------------
954 case LFUN_SWITCHBUFFER:
955 view()->setBuffer(bufferlist.getBuffer(argument));
959 NewFile(view(), argument);
966 case LFUN_DROP_LAYOUTS_CHOICE:
967 owner->getToolbar().openLayoutList();
970 case LFUN_MENU_OPEN_BY_NAME:
971 owner->getMenubar().openByName(argument);
974 // --- lyxserver commands ----------------------------
976 setMessage(owner->buffer()->fileName());
977 lyxerr[Debug::INFO] << "FNAME["
978 << owner->buffer()->fileName()
983 dispatch_buffer = keyseq.print();
984 lyxserver->notifyClient(dispatch_buffer);
987 case LFUN_GOTOFILEROW: {
990 istringstream is(argument);
991 is >> file_name >> row;
992 if (prefixIs(file_name, getTmpDir())) {
993 // Needed by inverse dvi search. If it is a file
994 // in tmpdir, call the apropriated function
995 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
997 // Must replace extension of the file to be .lyx
999 string const s = ChangeExtension(file_name, ".lyx");
1000 // Either change buffer or load the file
1001 if (bufferlist.exists(s)) {
1002 view()->setBuffer(bufferlist.getBuffer(s));
1004 view()->loadLyXFile(s);
1008 view()->setCursorFromRow(row);
1011 // see BufferView_pimpl::center()
1012 view()->updateScrollbar();
1016 case LFUN_GOTO_PARAGRAPH: {
1017 istringstream is(argument);
1020 ParIterator par = owner->buffer()->getParFromID(id);
1021 if (par == owner->buffer()->par_iterator_end()) {
1022 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1023 << id << ']' << endl;
1026 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1027 << " found." << endl;
1031 view()->setCursor(par, 0);
1033 view()->switchKeyMap();
1034 owner->view_state_changed();
1037 // see BufferView_pimpl::center()
1038 view()->updateScrollbar();
1042 case LFUN_DIALOG_SHOW: {
1043 string const name = cmd.getArg(0);
1044 string data = trim(cmd.argument.substr(name.size()));
1046 if (name == "character") {
1047 data = freefont2string();
1049 owner->getDialogs().show("character", data);
1051 else if (name == "preamble")
1052 owner->getDialogs().showPreamble();
1053 else if (name == "preferences")
1054 owner->getDialogs().showPreferences();
1055 else if (name == "spellchecker")
1056 owner->getDialogs().showSpellchecker();
1058 else if (name == "latexlog") {
1059 pair<Buffer::LogType, string> const logfile =
1060 owner->buffer()->getLogName();
1061 switch (logfile.first) {
1062 case Buffer::latexlog:
1065 case Buffer::buildlog:
1069 data += logfile.second;
1070 owner->getDialogs().show("log", data);
1072 else if (name == "vclog") {
1073 string const data = "vc " +
1074 owner->buffer()->lyxvc().getLogFile();
1075 owner->getDialogs().show("log", data);
1078 owner->getDialogs().show(name, data);
1082 case LFUN_DIALOG_SHOW_NEW_INSET: {
1083 string const name = cmd.getArg(0);
1084 string data = trim(cmd.argument.substr(name.size()));
1085 if (name == "bibitem" ||
1087 name == "include" ||
1093 InsetCommandParams p(name);
1094 data = InsetCommandMailer::params2string(name, p);
1095 } else if (name == "box") {
1096 // \c data == "Boxed" || "Frameless" etc
1097 InsetBoxParams p(data);
1098 data = InsetBoxMailer::params2string(p);
1099 } else if (name == "branch") {
1100 InsetBranchParams p;
1101 data = InsetBranchMailer::params2string(p);
1102 } else if (name == "citation") {
1103 InsetCommandParams p("cite");
1104 data = InsetCommandMailer::params2string(name, p);
1105 } else if (name == "ert") {
1106 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1107 } else if (name == "external") {
1108 InsetExternalParams p;
1109 Buffer const & buffer = *owner->buffer();
1110 data = InsetExternalMailer::params2string(p, buffer);
1111 } else if (name == "float") {
1113 data = InsetFloatMailer::params2string(p);
1114 } else if (name == "graphics") {
1115 InsetGraphicsParams p;
1116 Buffer const & buffer = *owner->buffer();
1117 data = InsetGraphicsMailer::params2string(p, buffer);
1118 } else if (name == "note") {
1120 data = InsetNoteMailer::params2string(p);
1121 } else if (name == "vspace") {
1123 data = InsetVSpaceMailer::params2string(space);
1124 } else if (name == "wrap") {
1126 data = InsetWrapMailer::params2string(p);
1128 owner->getDialogs().show(name, data, 0);
1132 case LFUN_DIALOG_SHOW_NEXT_INSET:
1135 case LFUN_DIALOG_UPDATE: {
1136 string const & name = argument;
1137 // Can only update a dialog connected to an existing inset
1138 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1140 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1141 inset->dispatch(view()->cursor(), fr);
1142 } else if (name == "paragraph") {
1143 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1148 case LFUN_DIALOG_HIDE:
1149 Dialogs::hide(argument, 0);
1152 case LFUN_DIALOG_DISCONNECT_INSET:
1153 owner->getDialogs().disconnect(argument);
1156 case LFUN_CHILDOPEN: {
1157 string const filename =
1158 MakeAbsPath(argument, owner->buffer()->filePath());
1159 setMessage(N_("Opening child document ") +
1160 MakeDisplayPath(filename) + "...");
1161 view()->savePosition(0);
1162 string const parentfilename = owner->buffer()->fileName();
1163 if (bufferlist.exists(filename))
1164 view()->setBuffer(bufferlist.getBuffer(filename));
1166 view()->loadLyXFile(filename);
1167 // Set the parent name of the child document.
1168 // This makes insertion of citations and references in the child work,
1169 // when the target is in the parent or another child document.
1170 owner->buffer()->setParentName(parentfilename);
1174 case LFUN_TOGGLECURSORFOLLOW:
1175 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1179 owner->getIntl().KeyMapOn(false);
1182 case LFUN_KMAP_PRIM:
1183 owner->getIntl().KeyMapPrim();
1187 owner->getIntl().KeyMapSec();
1190 case LFUN_KMAP_TOGGLE:
1191 owner->getIntl().ToggleKeyMap();
1197 string rest = split(argument, countstr, ' ');
1198 istringstream is(countstr);
1201 lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1202 for (int i = 0; i < count; ++i)
1203 dispatch(lyxaction.lookupFunc(rest));
1208 // argument contains ';'-terminated commands
1209 while (!argument.empty()) {
1211 string rest = split(argument, first, ';');
1212 dispatch(lyxaction.lookupFunc(rest));
1216 case LFUN_SAVEPREFERENCES: {
1217 Path p(user_lyxdir());
1218 lyxrc.write("preferences");
1222 case LFUN_SCREEN_FONT_UPDATE:
1223 // handle the screen font changes.
1224 lyxrc.set_font_norm_type();
1225 lyx_gui::update_fonts();
1226 // All visible buffers will need resize
1230 case LFUN_SET_COLOR: {
1232 string const x11_name = split(argument, lyx_name, ' ');
1233 if (lyx_name.empty() || x11_name.empty()) {
1234 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1239 bool const graphicsbg_changed =
1240 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1241 x11_name != lcolor.getX11Name(LColor::graphicsbg));
1243 if (!lcolor.setColor(lyx_name, x11_name)) {
1245 bformat(_("Set-color \"%1$s\" failed "
1246 "- color is undefined or "
1247 "may not be redefined"), lyx_name));
1251 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1253 if (graphicsbg_changed) {
1254 #ifdef WITH_WARNINGS
1255 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1258 lyx::graphics::GCache::get().changeDisplay(true);
1265 owner->message(argument);
1268 case LFUN_TOOLTIPS_TOGGLE:
1269 owner->getDialogs().toggleTooltips();
1272 case LFUN_EXTERNAL_EDIT: {
1273 FuncRequest fr(action, argument);
1274 InsetExternal().dispatch(view()->cursor(), fr);
1278 case LFUN_BREAKLINE: {
1279 #warning swallow 'Return' if the minibuffer is focused. But how?
1283 case LFUN_ALL_INSETS_TOGGLE: {
1285 string const name = split(argument, action, ' ');
1286 InsetBase::Code const inset_code =
1287 InsetBase::translate(name);
1289 LCursor & cur = view()->cursor();
1290 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1292 InsetBase & inset = owner->buffer()->inset();
1293 InsetIterator it = inset_iterator_begin(inset);
1294 InsetIterator const end = inset_iterator_end(inset);
1295 for (; it != end; ++it) {
1296 if (inset_code == InsetBase::NO_CODE
1297 || inset_code == it->lyxCode())
1298 it->dispatch(cur, fr);
1303 case LFUN_LANGUAGE_BUFFER: {
1304 Buffer & buffer = *owner->buffer();
1305 Language const * oldL = buffer.params().language;
1306 Language const * newL = languages.getLanguage(argument);
1307 if (!newL || oldL == newL)
1310 if (oldL->RightToLeft() == newL->RightToLeft()
1311 && !buffer.isMultiLingual())
1312 buffer.changeLanguage(oldL, newL);
1314 buffer.updateDocLang(newL);
1318 case LFUN_BUFFERPARAMS_APPLY: {
1319 istringstream ss(argument);
1322 int const unknown_tokens =
1323 owner->buffer()->readHeader(lex);
1325 if (unknown_tokens != 0) {
1326 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1327 << unknown_tokens << " unknown token"
1328 << (unknown_tokens == 1 ? "" : "s")
1334 case LFUN_TEXTCLASS_APPLY: {
1335 Buffer * buffer = owner->buffer();
1337 lyx::textclass_type const old_class =
1338 buffer->params().textclass;
1340 loadTextclass(argument);
1342 std::pair<bool, lyx::textclass_type> const tc_pair =
1343 textclasslist.NumberOfClass(argument);
1348 lyx::textclass_type const new_class = tc_pair.second;
1349 if (old_class == new_class)
1354 _("Converting document to new document class..."));
1357 lyx::cap::SwitchLayoutsBetweenClasses(
1358 old_class, new_class,
1359 buffer->paragraphs(), el);
1361 bufferErrors(*buffer, el);
1362 view()->showErrorList(_("Class switch"));
1366 case LFUN_TEXTCLASS_LOAD:
1367 loadTextclass(argument);
1371 DispatchResult res = view()->cursor().dispatch(cmd);
1372 if (!res.dispatched());
1373 view()->dispatch(cmd);
1378 if (view()->available()) {
1379 view()->fitCursor();
1381 view()->cursor().updatePos();
1382 // if we executed a mutating lfun, mark the buffer as dirty
1383 if (getStatus(cmd).enabled()
1384 && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1385 && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1386 view()->buffer()->markDirty();
1389 if (view()->cursor().inTexted()) {
1390 view()->owner()->updateLayoutChoice();
1391 sendDispatchMessage(getMessage(), cmd, verbose);
1397 void LyXFunc::sendDispatchMessage(string const & msg,
1398 FuncRequest const & cmd, bool verbose)
1400 owner->updateMenubar();
1401 owner->updateToolbar();
1403 if (cmd.action == LFUN_SELFINSERT || !verbose) {
1404 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1406 owner->message(msg);
1410 string dispatch_msg = msg;
1411 if (!dispatch_msg.empty())
1412 dispatch_msg += ' ';
1414 string comname = lyxaction.getActionName(cmd.action);
1416 bool argsadded = false;
1418 if (!cmd.argument.empty()) {
1419 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1420 comname += ' ' + cmd.argument;
1425 string const shortcuts = toplevel_keymap->findbinding(cmd);
1427 if (!shortcuts.empty()) {
1428 comname += ": " + shortcuts;
1429 } else if (!argsadded && !cmd.argument.empty()) {
1430 comname += ' ' + cmd.argument;
1433 if (!comname.empty()) {
1434 comname = rtrim(comname);
1435 dispatch_msg += '(' + comname + ')';
1438 lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1439 if (!dispatch_msg.empty())
1440 owner->message(dispatch_msg);
1444 void LyXFunc::setupLocalKeymap()
1446 keyseq.stdmap = toplevel_keymap.get();
1447 keyseq.curmap = toplevel_keymap.get();
1448 cancel_meta_seq.stdmap = toplevel_keymap.get();
1449 cancel_meta_seq.curmap = toplevel_keymap.get();
1453 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1455 string initpath = lyxrc.document_path;
1456 string filename(name);
1458 if (view()->available()) {
1459 string const trypath = owner->buffer()->filePath();
1460 // If directory is writeable, use this as default.
1461 if (IsDirWriteable(trypath))
1465 static int newfile_number;
1467 if (filename.empty()) {
1468 filename = AddName(lyxrc.document_path,
1469 "newfile" + tostr(++newfile_number) + ".lyx");
1470 FileInfo fi(filename);
1471 while (bufferlist.exists(filename) || fi.readable()) {
1473 filename = AddName(lyxrc.document_path,
1474 "newfile" + tostr(newfile_number) +
1476 fi.newFile(filename);
1480 // The template stuff
1483 FileDialog fileDlg(_("Select template file"),
1484 LFUN_SELECT_FILE_SYNC,
1485 make_pair(string(_("Documents|#o#O")),
1486 string(lyxrc.document_path)),
1487 make_pair(string(_("Templates|#T#t")),
1488 string(lyxrc.template_path)));
1490 FileDialog::Result result =
1491 fileDlg.open(lyxrc.template_path,
1492 FileFilterList(_("LyX Documents (*.lyx)")),
1495 if (result.first == FileDialog::Later)
1497 if (result.second.empty())
1499 templname = result.second;
1502 view()->newFile(filename, templname, !name.empty());
1506 void LyXFunc::open(string const & fname)
1508 string initpath = lyxrc.document_path;
1510 if (view()->available()) {
1511 string const trypath = owner->buffer()->filePath();
1512 // If directory is writeable, use this as default.
1513 if (IsDirWriteable(trypath))
1519 if (fname.empty()) {
1520 FileDialog fileDlg(_("Select document to open"),
1522 make_pair(string(_("Documents|#o#O")),
1523 string(lyxrc.document_path)),
1524 make_pair(string(_("Examples|#E#e")),
1525 string(AddPath(system_lyxdir(), "examples"))));
1527 FileDialog::Result result =
1528 fileDlg.open(initpath,
1529 FileFilterList(_("LyX Documents (*.lyx)")),
1532 if (result.first == FileDialog::Later)
1535 filename = result.second;
1537 // check selected filename
1538 if (filename.empty()) {
1539 owner->message(_("Canceled."));
1545 // get absolute path of file and add ".lyx" to the filename if
1547 string const fullpath = FileSearch(string(), filename, "lyx");
1548 if (!fullpath.empty()) {
1549 filename = fullpath;
1552 string const disp_fn(MakeDisplayPath(filename));
1554 // if the file doesn't exist, let the user create one
1555 FileInfo const f(filename, true);
1557 // the user specifically chose this name. Believe them.
1558 view()->newFile(filename, "", true);
1562 owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1565 if (view()->loadLyXFile(filename)) {
1566 str2 = bformat(_("Document %1$s opened."), disp_fn);
1568 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1570 owner->message(str2);
1574 void LyXFunc::doImport(string const & argument)
1577 string filename = split(argument, format, ' ');
1579 lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1580 << " file: " << filename << endl;
1582 // need user interaction
1583 if (filename.empty()) {
1584 string initpath = lyxrc.document_path;
1586 if (view()->available()) {
1587 string const trypath = owner->buffer()->filePath();
1588 // If directory is writeable, use this as default.
1589 if (IsDirWriteable(trypath))
1593 string const text = bformat(_("Select %1$s file to import"),
1594 formats.prettyName(format));
1596 FileDialog fileDlg(text,
1598 make_pair(string(_("Documents|#o#O")),
1599 string(lyxrc.document_path)),
1600 make_pair(string(_("Examples|#E#e")),
1601 string(AddPath(system_lyxdir(), "examples"))));
1603 string const filter = formats.prettyName(format)
1604 + " (*." + formats.extension(format) + ')';
1606 FileDialog::Result result =
1607 fileDlg.open(initpath,
1608 FileFilterList(filter),
1611 if (result.first == FileDialog::Later)
1614 filename = result.second;
1616 // check selected filename
1617 if (filename.empty())
1618 owner->message(_("Canceled."));
1621 if (filename.empty())
1624 // get absolute path of file
1625 filename = MakeAbsPath(filename);
1627 string const lyxfile = ChangeExtension(filename, ".lyx");
1629 // Check if the document already is open
1630 if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1631 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1632 owner->message(_("Canceled."));
1637 // if the file exists already, and we didn't do
1638 // -i lyx thefile.lyx, warn
1639 if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1640 string const file = MakeDisplayPath(lyxfile, 30);
1642 string text = bformat(_("The document %1$s already exists.\n\n"
1643 "Do you want to over-write that document?"), file);
1644 int const ret = Alert::prompt(_("Over-write document?"),
1645 text, 0, 1, _("&Over-write"), _("&Cancel"));
1648 owner->message(_("Canceled."));
1653 Importer::Import(owner, filename, format);
1657 void LyXFunc::closeBuffer()
1659 if (bufferlist.close(owner->buffer(), true) && !quitting) {
1660 if (bufferlist.empty()) {
1661 // need this otherwise SEGV may occur while
1662 // trying to set variables that don't exist
1663 // since there's no current buffer
1664 owner->getDialogs().hideBufferDependent();
1666 view()->setBuffer(bufferlist.first());
1672 // Each "owner" should have it's own message method. lyxview and
1673 // the minibuffer would use the minibuffer, but lyxserver would
1674 // send an ERROR signal to its client. Alejandro 970603
1675 // This function is bit problematic when it comes to NLS, to make the
1676 // lyx servers client be language indepenent we must not translate
1677 // strings sent to this func.
1678 void LyXFunc::setErrorMessage(string const & m) const
1680 dispatch_buffer = m;
1685 void LyXFunc::setMessage(string const & m) const
1687 dispatch_buffer = m;
1691 void LyXFunc::setStatusMessage(string const & m) const
1697 string const LyXFunc::viewStatusMessage()
1699 // When meta-fake key is pressed, show the key sequence so far + "M-".
1701 return keyseq.print() + "M-";
1703 // Else, when a non-complete key sequence is pressed,
1704 // show the available options.
1705 if (keyseq.length() > 0 && !keyseq.deleted())
1706 return keyseq.printOptions();
1708 if (!view()->available())
1709 return _("Welcome to LyX!");
1711 return view()->cursor().currentState();
1715 BufferView * LyXFunc::view() const
1717 BOOST_ASSERT(owner);
1718 return owner->view().get();
1722 bool LyXFunc::wasMetaKey() const
1724 return (meta_fake_bit != key_modifier::none);