]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
f40ed8c229857fef5ffba519fd2dbb2107597061
[lyx.git] / src / lyxfunc.C
1 /**
2  * \file lyxfunc.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Allan Rae
13  * \author Dekel Tsur
14  * \author Martin Vermeer
15  * \author Jürgen Vigna
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "lyxfunc.h"
23
24 #include "BranchList.h"
25 #include "buffer.h"
26 #include "buffer_funcs.h"
27 #include "bufferlist.h"
28 #include "bufferparams.h"
29 #include "BufferView.h"
30 #include "cursor.h"
31 #include "CutAndPaste.h"
32 #include "debug.h"
33 #include "dispatchresult.h"
34 #include "encoding.h"
35 #include "errorlist.h"
36 #include "exporter.h"
37 #include "format.h"
38 #include "funcrequest.h"
39 #include "gettext.h"
40 #include "importer.h"
41 #include "insetiterator.h"
42 #include "intl.h"
43 #include "kbmap.h"
44 #include "language.h"
45 #include "LColor.h"
46 #include "lyx_cb.h"
47 #include "LyXAction.h"
48 #include "lyxfind.h"
49 #include "lyxlex.h"
50 #include "lyxrc.h"
51 #include "lyxrow.h"
52 #include "lyxserver.h"
53 #include "lyxtextclasslist.h"
54 #include "lyxvc.h"
55 #include "paragraph.h"
56 #include "pariterator.h"
57 #include "ParagraphParameters.h"
58 #include "undo.h"
59
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"
71
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"
80
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"
92
93 using bv_funcs::freefont2string;
94
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;
124
125 using std::endl;
126 using std::make_pair;
127 using std::pair;
128 using std::string;
129 using std::istringstream;
130
131
132 extern BufferList bufferlist;
133 extern LyXServer * lyxserver;
134 extern bool selection_possible;
135
136 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
137
138 // (alkis)
139 extern tex_accent_struct get_accent(kb_action action);
140
141
142 LyXFunc::LyXFunc(LyXView * lv)
143         : owner(lv),
144         encoded_last_key(0),
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)
148 {
149 }
150
151
152 void LyXFunc::handleKeyFunc(kb_action action)
153 {
154         char c = encoded_last_key;
155
156         if (keyseq.length()) {
157                 c = 0;
158         }
159
160         owner->getIntl().getTransManager()
161                 .deadkey(c, get_accent(action).accent, view()->getLyXText());
162         // Need to clear, in case the minibuffer calls these
163         // actions
164         keyseq.clear();
165         // copied verbatim from do_accent_char
166         view()->cursor().resetAnchor();
167         view()->update();
168 }
169
170
171 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
172 {
173         lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
174
175         // Do nothing if we have nothing (JMarc)
176         if (!keysym->isOK()) {
177                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
178                                    << endl;
179                 return;
180         }
181
182         if (keysym->isModifier()) {
183                 lyxerr[Debug::KEY] << "isModifier true" << endl;
184                 return;
185         }
186
187         Encoding const * encoding = view()->cursor().getEncoding();
188
189         encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
190
191         // Do a one-deep top-level lookup for
192         // cancel and meta-fake keys. RVDK_PATCH_5
193         cancel_meta_seq.reset();
194
195         FuncRequest func = cancel_meta_seq.addkey(keysym, state);
196         lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
197
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;
206         }
207
208         // Dont remove this unless you know what you are doing.
209         meta_fake_bit = key_modifier::none;
210
211         // can this happen now ?
212         if (func.action == LFUN_NOACTION) {
213                 func = FuncRequest(LFUN_PREFIX);
214         }
215
216         if (lyxerr.debugging(Debug::KEY)) {
217                 lyxerr << "Key [action="
218                        << func.action << "]["
219                        << keyseq.print() << ']'
220                        << endl;
221         }
222
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)
226
227         if (keyseq.length() > 1) {
228                 owner->message(keyseq.print());
229         }
230
231
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;
239         }
240
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
244                 // by a binding
245                 if (keysym->isText() && keyseq.length() == 1) {
246                         lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
247                         func = FuncRequest(LFUN_SELFINSERT);
248                 } else {
249                         lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
250                         owner->message(_("Unknown function."));
251                         return;
252                 }
253         }
254
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));
259                         lyxerr[Debug::KEY]
260                                 << "SelfInsert arg[`" << arg << "']" << endl;
261                 }
262         } else {
263                 dispatch(func);
264         }
265 }
266
267
268 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
269 {
270         //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
271         FuncStatus flag;
272         Buffer * buf = owner->buffer();
273         LCursor & cur = view()->cursor();
274
275         if (cmd.action == LFUN_NOACTION) {
276                 setStatusMessage(N_("Nothing to do"));
277                 flag.enabled(false);
278                 return flag;
279         }
280
281         switch (cmd.action) {
282         case LFUN_UNKNOWN_ACTION:
283 #ifndef HAVE_LIBAIKSAURUS
284         case LFUN_THESAURUS_ENTRY:
285 #endif
286                 flag.unknown(true);
287                 flag.enabled(false);
288                 break;
289         default:
290                 flag |= lyx_gui::getStatus(cmd);
291         }
292
293         if (flag.unknown()) {
294                 setStatusMessage(N_("Unknown action"));
295                 return flag;
296         }
297
298         // the default error message if we disable the command
299         setStatusMessage(N_("Command disabled"));
300
301         // Check whether we need a buffer
302         if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
303                 // no, exit directly
304                 setStatusMessage(N_("Command not allowed with"
305                                     "out any document open"));
306                 flag.enabled(false);
307                 return flag;
308         }
309
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')
314         bool enable = true;
315         switch (cmd.action) {
316         case LFUN_TOOLTIPS_TOGGLE:
317                 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
318                 break;
319
320         case LFUN_READ_ONLY_TOGGLE:
321                 flag.setOnOff(buf->isReadonly());
322                 break;
323
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())
328                         flag.setOnOff(true);
329                 break;
330
331         case LFUN_EXPORT:
332                 enable = cmd.argument == "custom"
333                         || Exporter::IsExportable(*buf, cmd.argument);
334                 break;
335         case LFUN_CUT:
336         case LFUN_COPY:
337                 enable = cur.selection();
338                 break;
339
340         case LFUN_RUNCHKTEX:
341                 enable = buf->isLatex() && lyxrc.chktex_command != "none";
342                 break;
343
344         case LFUN_BUILDPROG:
345                 enable = Exporter::IsExportable(*buf, "program");
346                 break;
347
348         case LFUN_LAYOUT_TABULAR:
349                 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
350                 break;
351
352         case LFUN_LAYOUT:
353         case LFUN_LAYOUT_PARAGRAPH:
354                 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
355                 break;
356
357         case LFUN_VC_REGISTER:
358                 enable = !buf->lyxvc().inUse();
359                 break;
360         case LFUN_VC_CHECKIN:
361                 enable = buf->lyxvc().inUse() && !buf->isReadonly();
362                 break;
363         case LFUN_VC_CHECKOUT:
364                 enable = buf->lyxvc().inUse() && buf->isReadonly();
365                 break;
366         case LFUN_VC_REVERT:
367         case LFUN_VC_UNDO:
368                 enable = buf->lyxvc().inUse();
369                 break;
370         case LFUN_MENURELOAD:
371                 enable = !buf->isUnnamed() && !buf->isClean();
372                 break;
373
374
375         case LFUN_INSET_SETTINGS: {
376                 enable = false;
377                 if (!cur.size())
378                         break;
379                 UpdatableInset * inset = cur.inset().asUpdatableInset();
380                 lyxerr << "inset: " << inset << endl;
381                 if (!inset)
382                         break;
383
384                 InsetOld::Code code = inset->lyxCode();
385                 switch (code) {
386                         case InsetOld::TABULAR_CODE:
387                                 enable = cmd.argument == "tabular";
388                                 break;
389                         case InsetOld::ERT_CODE:
390                                 enable = cmd.argument == "ert";
391                                 break;
392                         case InsetOld::FLOAT_CODE:
393                                 enable = cmd.argument == "float";
394                                 break;
395                         case InsetOld::WRAP_CODE:
396                                 enable = cmd.argument == "wrap";
397                                 break;
398                         case InsetOld::NOTE_CODE:
399                                 enable = cmd.argument == "note";
400                                 break;
401                         case InsetOld::BRANCH_CODE:
402                                 enable = cmd.argument == "branch";
403                                 break;
404                         case InsetOld::BOX_CODE:
405                                 enable = cmd.argument == "box";
406                                 break;
407                         default:
408                                 break;
409                 }
410                 break;
411         }
412
413         case LFUN_DIALOG_SHOW: {
414                 string const name = cmd.getArg(0);
415                 if (!buf)
416                         enable = name == "aboutlyx"
417                                 || name == "file"
418                                 || name == "forks"
419                                 || name == "prefs"
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);
430                 break;
431         }
432
433         case LFUN_DIALOG_UPDATE: {
434                 string const name = cmd.getArg(0);
435                 if (!buf)
436                         enable = name == "prefs";
437                 break;
438         }
439
440         case LFUN_MENUNEW:
441         case LFUN_MENUNEWTMPLT:
442         case LFUN_WORDFINDFORWARD:
443         case LFUN_WORDFINDBACKWARD:
444         case LFUN_PREFIX:
445         case LFUN_EXEC_COMMAND:
446         case LFUN_CANCEL:
447         case LFUN_META_FAKE:
448         case LFUN_CLOSEBUFFER:
449         case LFUN_MENUWRITE:
450         case LFUN_WRITEAS:
451         case LFUN_UPDATE:
452         case LFUN_PREVIEW:
453         case LFUN_IMPORT:
454         case LFUN_QUIT:
455         case LFUN_TOCVIEW:
456         case LFUN_AUTOSAVE:
457         case LFUN_RECONFIGURE:
458         case LFUN_HELP_OPEN:
459         case LFUN_FILE_NEW:
460         case LFUN_FILE_OPEN:
461         case LFUN_DROP_LAYOUTS_CHOICE:
462         case LFUN_MENU_OPEN_BY_NAME:
463         case LFUN_GETNAME:
464         case LFUN_NOTIFY:
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:
471         case LFUN_CHILDOPEN:
472         case LFUN_TOGGLECURSORFOLLOW:
473         case LFUN_KMAP_OFF:
474         case LFUN_KMAP_PRIM:
475         case LFUN_KMAP_SEC:
476         case LFUN_KMAP_TOGGLE:
477         case LFUN_REPEAT:
478         case LFUN_EXPORT_CUSTOM:
479         case LFUN_PRINT:
480         case LFUN_SEQUENCE:
481         case LFUN_SAVEPREFERENCES:
482         case LFUN_SCREEN_FONT_UPDATE:
483         case LFUN_SET_COLOR:
484         case LFUN_MESSAGE:
485         case LFUN_EXTERNAL_EDIT:
486         case LFUN_ALL_INSETS_TOGGLE:
487         case LFUN_LANGUAGE_BUFFER:
488         case LFUN_TEXTCLASS_APPLY:
489         case LFUN_TEXTCLASS_LOAD:
490         case LFUN_SAVE_AS_DEFAULT:
491         case LFUN_BUFFERPARAMS_APPLY:
492         case LFUN_LYXRC_APPLY:
493                 // these are handled in our dispatch()
494                 break;
495
496         default:
497
498                 cur.getStatus(cmd, flag);
499                 if (!flag.enabled())
500                         flag = view()->getStatus(cmd);
501         }
502
503         if (!enable)
504                 flag.enabled(false);
505
506         // Can we use a readonly buffer?
507         if (buf && buf->isReadonly()
508             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
509             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
510                 setStatusMessage(N_("Document is read-only"));
511                 flag.enabled(false);
512         }
513
514         //lyxerr << "LyXFunc::getStatus: got: " << flag.enabled() << endl;
515         return flag;
516 }
517
518
519 namespace {
520
521 bool ensureBufferClean(BufferView * bv)
522 {
523         Buffer & buf = *bv->buffer();
524         if (buf.isClean())
525                 return true;
526
527         string const file = MakeDisplayPath(buf.fileName(), 30);
528         string text = bformat(_("The document %1$s has unsaved "
529                                 "changes.\n\nDo you want to save "
530                                 "the document?"), file);
531         int const ret = Alert::prompt(_("Save changed document?"),
532                                       text, 0, 1, _("&Save"),
533                                       _("&Cancel"));
534
535         if (ret == 0)
536                 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
537
538         return buf.isClean();
539 }
540
541
542 void showPrintError(string const & name)
543 {
544         string str = bformat(_("Could not print the document %1$s.\n"
545                                "Check that your printer is set up correctly."),
546                              MakeDisplayPath(name, 50));
547         Alert::error(_("Print document failed"), str);
548 }
549
550
551 void loadTextclass(string const & name)
552 {
553         std::pair<bool, lyx::textclass_type> const tc_pair =
554                 textclasslist.NumberOfClass(name);
555
556         if (!tc_pair.first) {
557                 lyxerr << "Document class \"" << name
558                        << "\" does not exist."
559                        << std::endl;
560                 return;
561         }
562
563         lyx::textclass_type const tc = tc_pair.second;
564
565         if (!textclasslist[tc].load()) {
566                 string s = bformat(_("The document could not be converted\n"
567                                      "into the document class %1$s."),
568                                    textclasslist[tc].name());
569                 Alert::error(_("Could not change class"), s);
570         }
571 }
572
573 } //namespace anon
574
575
576 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
577 {
578         string const argument = cmd.argument;
579         kb_action const action = cmd.action;
580
581         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
582         //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
583
584         // we have not done anything wrong yet.
585         errorstat = false;
586         dispatch_buffer.erase();
587         selection_possible = false;
588
589         bool update = true;
590         
591         // We cannot use this function here
592         if (!getStatus(cmd).enabled()) {
593                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
594                        << lyxaction.getActionName(action)
595                        << " [" << action << "] is disabled at this location"
596                        << endl;
597                 setErrorMessage(getStatusMessage());
598
599         } else {
600
601                 if (view()->available())
602                         view()->hideCursor();
603
604                 switch (action) {
605
606                 case LFUN_WORDFINDFORWARD:
607                 case LFUN_WORDFINDBACKWARD: {
608                         static string last_search;
609                         string searched_string;
610
611                         if (!argument.empty()) {
612                                 last_search = argument;
613                                 searched_string = argument;
614                         } else {
615                                 searched_string = last_search;
616                         }
617
618                         if (searched_string.empty())
619                                 break;
620
621                         bool const fw = action == LFUN_WORDFINDFORWARD;
622                         string const data =
623                                 lyx::find::find2string(searched_string, true, false, fw);
624                         lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
625                         break;
626                 }
627
628                 case LFUN_PREFIX:
629                         owner->message(keyseq.printOptions());
630                         break;
631
632                 case LFUN_EXEC_COMMAND:
633                         owner->focus_command_buffer();
634                         break;
635
636                 case LFUN_CANCEL:
637                         keyseq.reset();
638                         meta_fake_bit = key_modifier::none;
639                         if (view()->available())
640                                 // cancel any selection
641                                 dispatch(FuncRequest(LFUN_MARK_OFF));
642                         setMessage(N_("Cancel"));
643                         break;
644
645                 case LFUN_META_FAKE:
646                         meta_fake_bit = key_modifier::alt;
647                         setMessage(keyseq.print());
648                         break;
649
650                 case LFUN_READ_ONLY_TOGGLE:
651                         if (owner->buffer()->lyxvc().inUse())
652                                 owner->buffer()->lyxvc().toggleReadOnly();
653                         else
654                                 owner->buffer()->setReadonly(
655                                         !owner->buffer()->isReadonly());
656                         break;
657
658                 // --- Menus -----------------------------------------------
659                 case LFUN_MENUNEW:
660                         menuNew(argument, false);
661                         break;
662
663                 case LFUN_MENUNEWTMPLT:
664                         menuNew(argument, true);
665                         break;
666
667                 case LFUN_CLOSEBUFFER:
668                         closeBuffer();
669                         break;
670
671                 case LFUN_MENUWRITE:
672                         if (!owner->buffer()->isUnnamed()) {
673                                 string const str = bformat(_("Saving document %1$s..."),
674                                          MakeDisplayPath(owner->buffer()->fileName()));
675                                 owner->message(str);
676                                 MenuWrite(owner->buffer());
677                                 owner->message(str + _(" done."));
678                         } else
679                                 WriteAs(owner->buffer());
680                         break;
681
682                 case LFUN_WRITEAS:
683                         WriteAs(owner->buffer(), argument);
684                         break;
685
686                 case LFUN_MENURELOAD: {
687                         string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
688                         string text = bformat(_("Any changes will be lost. Are you sure "
689                                 "you want to revert to the saved version of the document %1$s?"), file);
690                         int const ret = Alert::prompt(_("Revert to saved document?"),
691                                 text, 0, 1, _("&Revert"), _("&Cancel"));
692
693                         if (ret == 0)
694                                 view()->reload();
695                         break;
696                 }
697
698                 case LFUN_UPDATE:
699                         Exporter::Export(owner->buffer(), argument, true);
700                         view()->showErrorList(BufferFormat(*owner->buffer()));
701                         break;
702
703                 case LFUN_PREVIEW:
704                         Exporter::Preview(owner->buffer(), argument);
705                         view()->showErrorList(BufferFormat(*owner->buffer()));
706                         break;
707
708                 case LFUN_BUILDPROG:
709                         Exporter::Export(owner->buffer(), "program", true);
710                         view()->showErrorList(_("Build"));
711                         break;
712
713                 case LFUN_RUNCHKTEX:
714                         owner->buffer()->runChktex();
715                         view()->showErrorList(_("ChkTeX"));
716                         break;
717
718                 case LFUN_EXPORT:
719                         if (argument == "custom")
720                                 owner->getDialogs().show("sendto");
721                         else {
722                                 Exporter::Export(owner->buffer(), argument, false);
723                                 view()->showErrorList(BufferFormat(*owner->buffer()));
724                         }
725                         break;
726
727                 case LFUN_EXPORT_CUSTOM: {
728                         string format_name;
729                         string command = split(argument, format_name, ' ');
730                         Format const * format = formats.getFormat(format_name);
731                         if (!format) {
732                                 lyxerr << "Format \"" << format_name
733                                        << "\" not recognized!"
734                                        << std::endl;
735                                 break;
736                         }
737
738                         Buffer * buffer = owner->buffer();
739
740                         // The name of the file created by the conversion process
741                         string filename;
742
743                         // Output to filename
744                         if (format->name() == "lyx") {
745                                 string const latexname =
746                                         buffer->getLatexName(false);
747                                 filename = ChangeExtension(latexname,
748                                                            format->extension());
749                                 filename = AddName(buffer->temppath(), filename);
750
751                                 if (!buffer->writeFile(filename))
752                                         break;
753
754                         } else {
755                                 Exporter::Export(buffer, format_name, true,
756                                                  filename);
757                         }
758
759                         // Substitute $$FName for filename
760                         if (!contains(command, "$$FName"))
761                                 command = "( " + command + " ) < $$FName";
762                         command = subst(command, "$$FName", filename);
763
764                         // Execute the command in the background
765                         Systemcall call;
766                         call.startscript(Systemcall::DontWait, command);
767                         break;
768                 }
769
770                 case LFUN_PRINT: {
771                         string target;
772                         string target_name;
773                         string command = split(split(argument, target, ' '),
774                                                target_name, ' ');
775
776                         if (target.empty()
777                             || target_name.empty()
778                             || command.empty()) {
779                                 lyxerr << "Unable to parse \""
780                                        << argument << '"' << std::endl;
781                                 break;
782                         }
783                         if (target != "printer" && target != "file") {
784                                 lyxerr << "Unrecognized target \""
785                                        << target << '"' << std::endl;
786                                 break;
787                         }
788
789                         Buffer * buffer = owner->buffer();
790
791                         if (!Exporter::Export(buffer, "dvi", true)) {
792                                 showPrintError(buffer->fileName());
793                                 break;
794                         }
795
796                         // Push directory path.
797                         string const path = buffer->temppath();
798                         Path p(path);
799
800                         // there are three cases here:
801                         // 1. we print to a file
802                         // 2. we print directly to a printer
803                         // 3. we print using a spool command (print to file first)
804                         Systemcall one;
805                         int res = 0;
806                         string const dviname =
807                                 ChangeExtension(buffer->getLatexName(true),
808                                                 "dvi");
809
810                         if (target == "printer") {
811                                 if (!lyxrc.print_spool_command.empty()) {
812                                         // case 3: print using a spool
813                                         string const psname =
814                                                 ChangeExtension(dviname,".ps");
815                                         command += lyxrc.print_to_file
816                                                 + QuoteName(psname)
817                                                 + ' '
818                                                 + QuoteName(dviname);
819
820                                         string command2 =
821                                                 lyxrc.print_spool_command +' ';
822                                         if (target_name != "default") {
823                                                 command2 += lyxrc.print_spool_printerprefix
824                                                         + target_name
825                                                         + ' ';
826                                         }
827                                         command2 += QuoteName(psname);
828                                         // First run dvips.
829                                         // If successful, then spool command
830                                         res = one.startscript(
831                                                 Systemcall::Wait,
832                                                 command);
833
834                                         if (res == 0)
835                                                 res = one.startscript(
836                                                         Systemcall::DontWait,
837                                                         command2);
838                                 } else {
839                                         // case 2: print directly to a printer
840                                         res = one.startscript(
841                                                 Systemcall::DontWait,
842                                                 command + QuoteName(dviname));
843                                 }
844
845                         } else {
846                                 // case 1: print to a file
847                                 command += lyxrc.print_to_file
848                                         + QuoteName(MakeAbsPath(target_name,
849                                                                 path))
850                                         + ' '
851                                         + QuoteName(dviname);
852                                 res = one.startscript(Systemcall::DontWait,
853                                                       command);
854                         }
855
856                         if (res != 0)
857                                 showPrintError(buffer->fileName());
858                         break;
859                 }
860
861                 case LFUN_IMPORT:
862                         doImport(argument);
863                         break;
864
865                 case LFUN_QUIT:
866                         QuitLyX();
867                         break;
868
869                 case LFUN_TOCVIEW: {
870                         InsetCommandParams p("tableofcontents");
871                         string const data = InsetCommandMailer::params2string("toc", p);
872                         owner->getDialogs().show("toc", data, 0);
873                         break;
874                 }
875
876                 case LFUN_AUTOSAVE:
877                         AutoSave(view());
878                         break;
879
880                 case LFUN_RECONFIGURE:
881                         Reconfigure(view());
882                         break;
883
884                 case LFUN_HELP_OPEN: {
885                         string const arg = argument;
886                         if (arg.empty()) {
887                                 setErrorMessage(N_("Missing argument"));
888                                 break;
889                         }
890                         string const fname = i18nLibFileSearch("doc", arg, "lyx");
891                         if (fname.empty()) {
892                                 lyxerr << "LyX: unable to find documentation file `"
893                                                          << arg << "'. Bad installation?" << endl;
894                                 break;
895                         }
896                         owner->message(bformat(_("Opening help file %1$s..."),
897                                 MakeDisplayPath(fname)));
898                         view()->loadLyXFile(fname, false);
899                         break;
900                 }
901
902                 // --- version control -------------------------------
903                 case LFUN_VC_REGISTER:
904                         if (!ensureBufferClean(view()))
905                                 break;
906                         if (!owner->buffer()->lyxvc().inUse()) {
907                                 owner->buffer()->lyxvc().registrer();
908                                 view()->reload();
909                         }
910                         break;
911
912                 case LFUN_VC_CHECKIN:
913                         if (!ensureBufferClean(view()))
914                                 break;
915                         if (owner->buffer()->lyxvc().inUse()
916                                         && !owner->buffer()->isReadonly()) {
917                                 owner->buffer()->lyxvc().checkIn();
918                                 view()->reload();
919                         }
920                         break;
921
922                 case LFUN_VC_CHECKOUT:
923                         if (!ensureBufferClean(view()))
924                                 break;
925                         if (owner->buffer()->lyxvc().inUse()
926                                         && owner->buffer()->isReadonly()) {
927                                 owner->buffer()->lyxvc().checkOut();
928                                 view()->reload();
929                         }
930                         break;
931
932                 case LFUN_VC_REVERT:
933                         owner->buffer()->lyxvc().revert();
934                         view()->reload();
935                         break;
936
937                 case LFUN_VC_UNDO:
938                         owner->buffer()->lyxvc().undoLast();
939                         view()->reload();
940                         break;
941
942                 // --- buffers ----------------------------------------
943                 case LFUN_SWITCHBUFFER:
944                         view()->setBuffer(bufferlist.getBuffer(argument));
945                         break;
946
947                 case LFUN_FILE_NEW:
948                         NewFile(view(), argument);
949                         break;
950
951                 case LFUN_FILE_OPEN:
952                         open(argument);
953                         break;
954
955                 case LFUN_DROP_LAYOUTS_CHOICE:
956                         owner->getToolbar().openLayoutList();
957                         break;
958
959                 case LFUN_MENU_OPEN_BY_NAME:
960                         owner->getMenubar().openByName(argument);
961                         break;
962
963                 // --- lyxserver commands ----------------------------
964                 case LFUN_GETNAME:
965                         setMessage(owner->buffer()->fileName());
966                         lyxerr[Debug::INFO] << "FNAME["
967                                                          << owner->buffer()->fileName()
968                                                          << "] " << endl;
969                         break;
970
971                 case LFUN_NOTIFY:
972                         dispatch_buffer = keyseq.print();
973                         lyxserver->notifyClient(dispatch_buffer);
974                         break;
975
976                 case LFUN_GOTOFILEROW: {
977                         string file_name;
978                         int row;
979                         istringstream is(argument);
980                         is >> file_name >> row;
981                         if (prefixIs(file_name, getTmpDir())) {
982                                 // Needed by inverse dvi search. If it is a file
983                                 // in tmpdir, call the apropriated function
984                                 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
985                         } else {
986                                 // Must replace extension of the file to be .lyx
987                                 // and get full path
988                                 string const s = ChangeExtension(file_name, ".lyx");
989                                 // Either change buffer or load the file
990                                 if (bufferlist.exists(s)) {
991                                         view()->setBuffer(bufferlist.getBuffer(s));
992                                 } else {
993                                         view()->loadLyXFile(s);
994                                 }
995                         }
996
997                         view()->setCursorFromRow(row);
998
999                         view()->center();
1000                         // see BufferView_pimpl::center()
1001                         view()->updateScrollbar();
1002                         break;
1003                 }
1004
1005                 case LFUN_GOTO_PARAGRAPH: {
1006                         istringstream is(argument);
1007                         int id;
1008                         is >> id;
1009                         ParIterator par = owner->buffer()->getParFromID(id);
1010                         if (par == owner->buffer()->par_iterator_end()) {
1011                                 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1012                                                                 << id << ']' << endl;
1013                                 break;
1014                         } else {
1015                                 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1016                                                                 << " found." << endl;
1017                         }
1018
1019                         // Set the cursor
1020                         view()->setCursor(par, 0);
1021
1022                         view()->switchKeyMap();
1023                         owner->view_state_changed();
1024
1025                         view()->center();
1026                         // see BufferView_pimpl::center()
1027                         view()->updateScrollbar();
1028                         break;
1029                 }
1030
1031                 case LFUN_DIALOG_SHOW: {
1032                         string const name = cmd.getArg(0);
1033                         string data = trim(cmd.argument.substr(name.size()));
1034
1035                         if (name == "character") {
1036                                 data = freefont2string();
1037                                 if (!data.empty())
1038                                         owner->getDialogs().show("character", data);
1039                         }
1040
1041                         else if (name == "latexlog") {
1042                                 pair<Buffer::LogType, string> const logfile =
1043                                         owner->buffer()->getLogName();
1044                                 switch (logfile.first) {
1045                                 case Buffer::latexlog:
1046                                         data = "latex ";
1047                                         break;
1048                                 case Buffer::buildlog:
1049                                         data = "literate ";
1050                                         break;
1051                                 }
1052                                 data += logfile.second;
1053                                 owner->getDialogs().show("log", data);
1054                         }
1055                         else if (name == "vclog") {
1056                                 string const data = "vc " +
1057                                         owner->buffer()->lyxvc().getLogFile();
1058                                 owner->getDialogs().show("log", data);
1059                         }
1060                         else
1061                                 owner->getDialogs().show(name, data);
1062                         break;
1063                 }
1064
1065                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1066                         string const name = cmd.getArg(0);
1067                         string data = trim(cmd.argument.substr(name.size()));
1068                         if (name == "bibitem" ||
1069                             name == "bibtex" ||
1070                             name == "include" ||
1071                             name == "index" ||
1072                             name == "label" ||
1073                             name == "ref" ||
1074                             name == "toc" ||
1075                             name == "url") {
1076                                 InsetCommandParams p(name);
1077                                 data = InsetCommandMailer::params2string(name, p);
1078                         } else if (name == "box") {
1079                                 // \c data == "Boxed" || "Frameless" etc
1080                                 InsetBoxParams p(data);
1081                                 data = InsetBoxMailer::params2string(p);
1082                         } else if (name == "branch") {
1083                                 InsetBranchParams p;
1084                                 data = InsetBranchMailer::params2string(p);
1085                         } else if (name == "citation") {
1086                                 InsetCommandParams p("cite");
1087                                 data = InsetCommandMailer::params2string(name, p);
1088                         } else if (name == "ert") {
1089                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1090                         } else if (name == "external") {
1091                                 InsetExternalParams p;
1092                                 Buffer const & buffer = *owner->buffer();
1093                                 data = InsetExternalMailer::params2string(p, buffer);
1094                         } else if (name == "float") {
1095                                 InsetFloatParams p;
1096                                 data = InsetFloatMailer::params2string(p);
1097                         } else if (name == "graphics") {
1098                                 InsetGraphicsParams p;
1099                                 Buffer const & buffer = *owner->buffer();
1100                                 data = InsetGraphicsMailer::params2string(p, buffer);
1101                         } else if (name == "note") {
1102                                 InsetNoteParams p;
1103                                 data = InsetNoteMailer::params2string(p);
1104                         } else if (name == "vspace") {
1105                                 VSpace space;
1106                                 data = InsetVSpaceMailer::params2string(space);
1107                         } else if (name == "wrap") {
1108                                 InsetWrapParams p;
1109                                 data = InsetWrapMailer::params2string(p);
1110                         }
1111                         owner->getDialogs().show(name, data, 0);
1112                         break;
1113                 }
1114
1115                 case LFUN_DIALOG_SHOW_NEXT_INSET:
1116                         break;
1117
1118                 case LFUN_DIALOG_UPDATE: {
1119                         string const & name = argument;
1120                         // Can only update a dialog connected to an existing inset
1121                         InsetBase * inset = owner->getDialogs().getOpenInset(name);
1122                         if (inset) {
1123                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1124                                 inset->dispatch(view()->cursor(), fr);
1125                         } else if (name == "paragraph") {
1126                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1127                         } else if (name == "prefs") {
1128                                 owner->getDialogs().update(name, string());
1129                         }
1130                         break;
1131                 }
1132
1133                 case LFUN_DIALOG_HIDE:
1134                         Dialogs::hide(argument, 0);
1135                         break;
1136
1137                 case LFUN_DIALOG_DISCONNECT_INSET:
1138                         owner->getDialogs().disconnect(argument);
1139                         break;
1140
1141                 case LFUN_CHILDOPEN: {
1142                         string const filename =
1143                                 MakeAbsPath(argument, owner->buffer()->filePath());
1144                         setMessage(N_("Opening child document ") +
1145                                          MakeDisplayPath(filename) + "...");
1146                         view()->savePosition(0);
1147                         string const parentfilename = owner->buffer()->fileName();
1148                         if (bufferlist.exists(filename))
1149                                 view()->setBuffer(bufferlist.getBuffer(filename));
1150                         else
1151                                 view()->loadLyXFile(filename);
1152                         // Set the parent name of the child document.
1153                         // This makes insertion of citations and references in the child work,
1154                         // when the target is in the parent or another child document.
1155                         owner->buffer()->setParentName(parentfilename);
1156                         break;
1157                 }
1158
1159                 case LFUN_TOGGLECURSORFOLLOW:
1160                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1161                         break;
1162
1163                 case LFUN_KMAP_OFF:
1164                         owner->getIntl().KeyMapOn(false);
1165                         break;
1166
1167                 case LFUN_KMAP_PRIM:
1168                         owner->getIntl().KeyMapPrim();
1169                         break;
1170
1171                 case LFUN_KMAP_SEC:
1172                         owner->getIntl().KeyMapSec();
1173                         break;
1174
1175                 case LFUN_KMAP_TOGGLE:
1176                         owner->getIntl().ToggleKeyMap();
1177                         break;
1178
1179                 case LFUN_REPEAT: {
1180                         // repeat command
1181                         string countstr;
1182                         string rest = split(argument, countstr, ' ');
1183                         istringstream is(countstr);
1184                         int count = 0;
1185                         is >> count;
1186                         lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1187                         for (int i = 0; i < count; ++i)
1188                                 dispatch(lyxaction.lookupFunc(rest));
1189                         break;
1190                 }
1191
1192                 case LFUN_SEQUENCE:
1193                         // argument contains ';'-terminated commands
1194                         while (!argument.empty()) {
1195                                 string first;
1196                                 string rest = split(argument, first, ';');
1197                                 dispatch(lyxaction.lookupFunc(rest));
1198                         }
1199                         break;
1200
1201                 case LFUN_SAVEPREFERENCES: {
1202                         Path p(user_lyxdir());
1203                         lyxrc.write("preferences", false);
1204                         break;
1205                 }
1206
1207                 case LFUN_SCREEN_FONT_UPDATE:
1208                         // handle the screen font changes.
1209                         lyxrc.set_font_norm_type();
1210                         lyx_gui::update_fonts();
1211                         // All visible buffers will need resize
1212                         view()->resize();
1213                         break;
1214
1215                 case LFUN_SET_COLOR: {
1216                         string lyx_name;
1217                         string const x11_name = split(argument, lyx_name, ' ');
1218                         if (lyx_name.empty() || x11_name.empty()) {
1219                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1220                                                         " <x11_name>"));
1221                                 break;
1222                         }
1223
1224                         bool const graphicsbg_changed =
1225                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1226                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1227
1228                         if (!lcolor.setColor(lyx_name, x11_name)) {
1229                                 setErrorMessage(
1230                                         bformat(_("Set-color \"%1$s\" failed "
1231                                                                 "- color is undefined or "
1232                                                                 "may not be redefined"), lyx_name));
1233                                 break;
1234                         }
1235
1236                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1237
1238                         if (graphicsbg_changed) {
1239 #ifdef WITH_WARNINGS
1240 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1241 #endif
1242 #if 0
1243                                 lyx::graphics::GCache::get().changeDisplay(true);
1244 #endif
1245                         }
1246                         break;
1247                 }
1248
1249                 case LFUN_MESSAGE:
1250                         owner->message(argument);
1251                         break;
1252
1253                 case LFUN_TOOLTIPS_TOGGLE:
1254                         owner->getDialogs().toggleTooltips();
1255                         break;
1256
1257                 case LFUN_EXTERNAL_EDIT: {
1258                         FuncRequest fr(action, argument);
1259                         InsetExternal().dispatch(view()->cursor(), fr);
1260                         break;
1261                 }
1262
1263                 case LFUN_ALL_INSETS_TOGGLE: {
1264                         string action;
1265                         string const name = split(argument, action, ' ');
1266                         InsetBase::Code const inset_code =
1267                                 InsetBase::translate(name);
1268
1269                         LCursor & cur = view()->cursor();
1270                         FuncRequest fr(LFUN_INSET_TOGGLE, action);
1271
1272                         InsetBase & inset = owner->buffer()->inset();
1273                         InsetIterator it  = inset_iterator_begin(inset);
1274                         InsetIterator const end = inset_iterator_end(inset);
1275                         for (; it != end; ++it) {
1276                                 if (inset_code == InsetBase::NO_CODE
1277                                     || inset_code == it->lyxCode())
1278                                         it->dispatch(cur, fr);
1279                         }
1280                         break;
1281                 }
1282
1283                 case LFUN_LANGUAGE_BUFFER: {
1284                         Buffer & buffer = *owner->buffer();
1285                         Language const * oldL = buffer.params().language;
1286                         Language const * newL = languages.getLanguage(argument);
1287                         if (!newL || oldL == newL)
1288                                 break;
1289
1290                         if (oldL->RightToLeft() == newL->RightToLeft()
1291                             && !buffer.isMultiLingual())
1292                                 buffer.changeLanguage(oldL, newL);
1293                         else
1294                                 buffer.updateDocLang(newL);
1295                         break;
1296                 }
1297
1298                 case LFUN_BUFFERPARAMS_APPLY: {
1299                         istringstream ss(argument);
1300                         LyXLex lex(0,0);
1301                         lex.setStream(ss);
1302                         int const unknown_tokens =
1303                                 owner->buffer()->readHeader(lex);
1304
1305                         if (unknown_tokens != 0) {
1306                                 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1307                                        << unknown_tokens << " unknown token"
1308                                        << (unknown_tokens == 1 ? "" : "s")
1309                                        << endl;
1310                         }
1311                         break;
1312                 }
1313
1314                 case LFUN_TEXTCLASS_APPLY: {
1315                         Buffer * buffer = owner->buffer();
1316
1317                         lyx::textclass_type const old_class =
1318                                 buffer->params().textclass;
1319
1320                         loadTextclass(argument);
1321
1322                         std::pair<bool, lyx::textclass_type> const tc_pair =
1323                                 textclasslist.NumberOfClass(argument);
1324
1325                         if (!tc_pair.first)
1326                                 break;
1327
1328                         lyx::textclass_type const new_class = tc_pair.second;
1329                         if (old_class == new_class)
1330                                 // nothing to do
1331                                 break;
1332
1333                         owner->message(_("Converting document to new document class..."));
1334                         ErrorList el;
1335                         lyx::cap::SwitchLayoutsBetweenClasses(
1336                                 old_class, new_class,
1337                                 buffer->paragraphs(), el);
1338
1339                         bufferErrors(*buffer, el);
1340                         view()->showErrorList(_("Class switch"));
1341                         break;
1342                 }
1343
1344                 case LFUN_TEXTCLASS_LOAD:
1345                         loadTextclass(argument);
1346                         break;
1347
1348                 case LFUN_LYXRC_APPLY: {
1349                         istringstream ss(argument);
1350                         bool const success = lyxrc.read(ss) == 0;
1351
1352                         if (!success) {
1353                                 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1354                                        << "Unable to read lyxrc data"
1355                                        << endl;
1356                         }
1357                         break;
1358                 }
1359
1360                 default: {
1361                         update = false;
1362                         DispatchResult res = view()->cursor().dispatch(cmd);
1363                         if (res.dispatched())
1364                                 update |= res.update();
1365                         else
1366                                 update |= view()->dispatch(cmd);
1367                         
1368                         break;
1369                 }
1370                 }
1371
1372                 if (view()->available()) {
1373                         if (view()->fitCursor() || update)
1374                                 view()->update();
1375                         // if we executed a mutating lfun, mark the buffer as dirty
1376                         if (getStatus(cmd).enabled()
1377                                         && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1378                                         && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1379                                 view()->buffer()->markDirty();
1380                 }
1381
1382                 if (view()->cursor().inTexted()) {
1383                         view()->owner()->updateLayoutChoice();
1384                         sendDispatchMessage(getMessage(), cmd, verbose);
1385                 }
1386         }
1387 }
1388
1389
1390 void LyXFunc::sendDispatchMessage(string const & msg,
1391                                   FuncRequest const & cmd, bool verbose)
1392 {
1393         owner->updateMenubar();
1394         owner->updateToolbar();
1395
1396         if (cmd.action == LFUN_SELFINSERT || !verbose) {
1397                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1398                 if (!msg.empty())
1399                         owner->message(msg);
1400                 return;
1401         }
1402
1403         string dispatch_msg = msg;
1404         if (!dispatch_msg.empty())
1405                 dispatch_msg += ' ';
1406
1407         string comname = lyxaction.getActionName(cmd.action);
1408
1409         bool argsadded = false;
1410
1411         if (!cmd.argument.empty()) {
1412                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1413                         comname += ' ' + cmd.argument;
1414                         argsadded = true;
1415                 }
1416         }
1417
1418         string const shortcuts = toplevel_keymap->findbinding(cmd);
1419
1420         if (!shortcuts.empty()) {
1421                 comname += ": " + shortcuts;
1422         } else if (!argsadded && !cmd.argument.empty()) {
1423                 comname += ' ' + cmd.argument;
1424         }
1425
1426         if (!comname.empty()) {
1427                 comname = rtrim(comname);
1428                 dispatch_msg += '(' + comname + ')';
1429         }
1430
1431         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1432         if (!dispatch_msg.empty())
1433                 owner->message(dispatch_msg);
1434 }
1435
1436
1437 void LyXFunc::setupLocalKeymap()
1438 {
1439         keyseq.stdmap = toplevel_keymap.get();
1440         keyseq.curmap = toplevel_keymap.get();
1441         cancel_meta_seq.stdmap = toplevel_keymap.get();
1442         cancel_meta_seq.curmap = toplevel_keymap.get();
1443 }
1444
1445
1446 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1447 {
1448         string initpath = lyxrc.document_path;
1449         string filename(name);
1450
1451         if (view()->available()) {
1452                 string const trypath = owner->buffer()->filePath();
1453                 // If directory is writeable, use this as default.
1454                 if (IsDirWriteable(trypath))
1455                         initpath = trypath;
1456         }
1457
1458         static int newfile_number;
1459
1460         if (filename.empty()) {
1461                 filename = AddName(lyxrc.document_path,
1462                             "newfile" + tostr(++newfile_number) + ".lyx");
1463                 FileInfo fi(filename);
1464                 while (bufferlist.exists(filename) || fi.readable()) {
1465                         ++newfile_number;
1466                         filename = AddName(lyxrc.document_path,
1467                                     "newfile" + tostr(newfile_number) +
1468                                     ".lyx");
1469                         fi.newFile(filename);
1470                 }
1471         }
1472
1473         // The template stuff
1474         string templname;
1475         if (fromTemplate) {
1476                 FileDialog fileDlg(_("Select template file"),
1477                         LFUN_SELECT_FILE_SYNC,
1478                         make_pair(string(_("Documents|#o#O")),
1479                                   string(lyxrc.document_path)),
1480                         make_pair(string(_("Templates|#T#t")),
1481                                   string(lyxrc.template_path)));
1482
1483                 FileDialog::Result result =
1484                         fileDlg.open(lyxrc.template_path,
1485                                      FileFilterList(_("LyX Documents (*.lyx)")),
1486                                      string());
1487
1488                 if (result.first == FileDialog::Later)
1489                         return;
1490                 if (result.second.empty())
1491                         return;
1492                 templname = result.second;
1493         }
1494
1495         view()->newFile(filename, templname, !name.empty());
1496 }
1497
1498
1499 void LyXFunc::open(string const & fname)
1500 {
1501         string initpath = lyxrc.document_path;
1502
1503         if (view()->available()) {
1504                 string const trypath = owner->buffer()->filePath();
1505                 // If directory is writeable, use this as default.
1506                 if (IsDirWriteable(trypath))
1507                         initpath = trypath;
1508         }
1509
1510         string filename;
1511
1512         if (fname.empty()) {
1513                 FileDialog fileDlg(_("Select document to open"),
1514                         LFUN_FILE_OPEN,
1515                         make_pair(string(_("Documents|#o#O")),
1516                                   string(lyxrc.document_path)),
1517                         make_pair(string(_("Examples|#E#e")),
1518                                   string(AddPath(system_lyxdir(), "examples"))));
1519
1520                 FileDialog::Result result =
1521                         fileDlg.open(initpath,
1522                                      FileFilterList(_("LyX Documents (*.lyx)")),
1523                                      string());
1524
1525                 if (result.first == FileDialog::Later)
1526                         return;
1527
1528                 filename = result.second;
1529
1530                 // check selected filename
1531                 if (filename.empty()) {
1532                         owner->message(_("Canceled."));
1533                         return;
1534                 }
1535         } else
1536                 filename = fname;
1537
1538         // get absolute path of file and add ".lyx" to the filename if
1539         // necessary
1540         string const fullpath = FileSearch(string(), filename, "lyx");
1541         if (!fullpath.empty()) {
1542                 filename = fullpath;
1543         }
1544
1545         string const disp_fn(MakeDisplayPath(filename));
1546
1547         // if the file doesn't exist, let the user create one
1548         FileInfo const f(filename, true);
1549         if (!f.exist()) {
1550                 // the user specifically chose this name. Believe them.
1551                 view()->newFile(filename, "", true);
1552                 return;
1553         }
1554
1555         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1556
1557         string str2;
1558         if (view()->loadLyXFile(filename)) {
1559                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1560         } else {
1561                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1562         }
1563         owner->message(str2);
1564 }
1565
1566
1567 void LyXFunc::doImport(string const & argument)
1568 {
1569         string format;
1570         string filename = split(argument, format, ' ');
1571
1572         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1573                             << " file: " << filename << endl;
1574
1575         // need user interaction
1576         if (filename.empty()) {
1577                 string initpath = lyxrc.document_path;
1578
1579                 if (view()->available()) {
1580                         string const trypath = owner->buffer()->filePath();
1581                         // If directory is writeable, use this as default.
1582                         if (IsDirWriteable(trypath))
1583                                 initpath = trypath;
1584                 }
1585
1586                 string const text = bformat(_("Select %1$s file to import"),
1587                         formats.prettyName(format));
1588
1589                 FileDialog fileDlg(text,
1590                         LFUN_IMPORT,
1591                         make_pair(string(_("Documents|#o#O")),
1592                                   string(lyxrc.document_path)),
1593                         make_pair(string(_("Examples|#E#e")),
1594                                   string(AddPath(system_lyxdir(), "examples"))));
1595
1596                 string const filter = formats.prettyName(format)
1597                         + " (*." + formats.extension(format) + ')';
1598
1599                 FileDialog::Result result =
1600                         fileDlg.open(initpath,
1601                                      FileFilterList(filter),
1602                                      string());
1603
1604                 if (result.first == FileDialog::Later)
1605                         return;
1606
1607                 filename = result.second;
1608
1609                 // check selected filename
1610                 if (filename.empty())
1611                         owner->message(_("Canceled."));
1612         }
1613
1614         if (filename.empty())
1615                 return;
1616
1617         // get absolute path of file
1618         filename = MakeAbsPath(filename);
1619
1620         string const lyxfile = ChangeExtension(filename, ".lyx");
1621
1622         // Check if the document already is open
1623         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1624                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1625                         owner->message(_("Canceled."));
1626                         return;
1627                 }
1628         }
1629
1630         // if the file exists already, and we didn't do
1631         // -i lyx thefile.lyx, warn
1632         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1633                 string const file = MakeDisplayPath(lyxfile, 30);
1634
1635                 string text = bformat(_("The document %1$s already exists.\n\n"
1636                         "Do you want to over-write that document?"), file);
1637                 int const ret = Alert::prompt(_("Over-write document?"),
1638                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1639
1640                 if (ret == 1) {
1641                         owner->message(_("Canceled."));
1642                         return;
1643                 }
1644         }
1645
1646         Importer::Import(owner, filename, format);
1647 }
1648
1649
1650 void LyXFunc::closeBuffer()
1651 {
1652         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1653                 if (bufferlist.empty()) {
1654                         // need this otherwise SEGV may occur while
1655                         // trying to set variables that don't exist
1656                         // since there's no current buffer
1657                         owner->getDialogs().hideBufferDependent();
1658                 } else {
1659                         view()->setBuffer(bufferlist.first());
1660                 }
1661         }
1662 }
1663
1664
1665 // Each "owner" should have it's own message method. lyxview and
1666 // the minibuffer would use the minibuffer, but lyxserver would
1667 // send an ERROR signal to its client.  Alejandro 970603
1668 // This function is bit problematic when it comes to NLS, to make the
1669 // lyx servers client be language indepenent we must not translate
1670 // strings sent to this func.
1671 void LyXFunc::setErrorMessage(string const & m) const
1672 {
1673         dispatch_buffer = m;
1674         errorstat = true;
1675 }
1676
1677
1678 void LyXFunc::setMessage(string const & m) const
1679 {
1680         dispatch_buffer = m;
1681 }
1682
1683
1684 void LyXFunc::setStatusMessage(string const & m) const
1685 {
1686         status_buffer = m;
1687 }
1688
1689
1690 string const LyXFunc::viewStatusMessage()
1691 {
1692         // When meta-fake key is pressed, show the key sequence so far + "M-".
1693         if (wasMetaKey())
1694                 return keyseq.print() + "M-";
1695
1696         // Else, when a non-complete key sequence is pressed,
1697         // show the available options.
1698         if (keyseq.length() > 0 && !keyseq.deleted())
1699                 return keyseq.printOptions();
1700
1701         if (!view()->available())
1702                 return _("Welcome to LyX!");
1703
1704         return view()->cursor().currentState();
1705 }
1706
1707
1708 BufferView * LyXFunc::view() const
1709 {
1710         BOOST_ASSERT(owner);
1711         return owner->view().get();
1712 }
1713
1714
1715 bool LyXFunc::wasMetaKey() const
1716 {
1717         return (meta_fake_bit != key_modifier::none);
1718 }