]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
Layout tweaks.
[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_GRAPHICS_EDIT:
487         case LFUN_ALL_INSETS_TOGGLE:
488         case LFUN_LANGUAGE_BUFFER:
489         case LFUN_TEXTCLASS_APPLY:
490         case LFUN_TEXTCLASS_LOAD:
491         case LFUN_SAVE_AS_DEFAULT:
492         case LFUN_BUFFERPARAMS_APPLY:
493         case LFUN_LYXRC_APPLY:
494                 // these are handled in our dispatch()
495                 break;
496
497         default:
498
499                 cur.getStatus(cmd, flag);
500                 if (!flag.enabled())
501                         flag = view()->getStatus(cmd);
502         }
503
504         if (!enable)
505                 flag.enabled(false);
506
507         // Can we use a readonly buffer?
508         if (buf && buf->isReadonly()
509             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
510             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
511                 setStatusMessage(N_("Document is read-only"));
512                 flag.enabled(false);
513         }
514
515         //lyxerr << "LyXFunc::getStatus: got: " << flag.enabled() << endl;
516         return flag;
517 }
518
519
520 namespace {
521
522 bool ensureBufferClean(BufferView * bv)
523 {
524         Buffer & buf = *bv->buffer();
525         if (buf.isClean())
526                 return true;
527
528         string const file = MakeDisplayPath(buf.fileName(), 30);
529         string text = bformat(_("The document %1$s has unsaved "
530                                 "changes.\n\nDo you want to save "
531                                 "the document?"), file);
532         int const ret = Alert::prompt(_("Save changed document?"),
533                                       text, 0, 1, _("&Save"),
534                                       _("&Cancel"));
535
536         if (ret == 0)
537                 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
538
539         return buf.isClean();
540 }
541
542
543 void showPrintError(string const & name)
544 {
545         string str = bformat(_("Could not print the document %1$s.\n"
546                                "Check that your printer is set up correctly."),
547                              MakeDisplayPath(name, 50));
548         Alert::error(_("Print document failed"), str);
549 }
550
551
552 void loadTextclass(string const & name)
553 {
554         std::pair<bool, lyx::textclass_type> const tc_pair =
555                 textclasslist.NumberOfClass(name);
556
557         if (!tc_pair.first) {
558                 lyxerr << "Document class \"" << name
559                        << "\" does not exist."
560                        << std::endl;
561                 return;
562         }
563
564         lyx::textclass_type const tc = tc_pair.second;
565
566         if (!textclasslist[tc].load()) {
567                 string s = bformat(_("The document could not be converted\n"
568                                      "into the document class %1$s."),
569                                    textclasslist[tc].name());
570                 Alert::error(_("Could not change class"), s);
571         }
572 }
573
574 } //namespace anon
575
576
577 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
578 {
579         string const argument = cmd.argument;
580         kb_action const action = cmd.action;
581
582         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
583         //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
584
585         // we have not done anything wrong yet.
586         errorstat = false;
587         dispatch_buffer.erase();
588         selection_possible = false;
589
590         bool update = true;
591         
592         // We cannot use this function here
593         if (!getStatus(cmd).enabled()) {
594                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
595                        << lyxaction.getActionName(action)
596                        << " [" << action << "] is disabled at this location"
597                        << endl;
598                 setErrorMessage(getStatusMessage());
599
600         } else {
601
602                 if (view()->available())
603                         view()->hideCursor();
604
605                 switch (action) {
606
607                 case LFUN_WORDFINDFORWARD:
608                 case LFUN_WORDFINDBACKWARD: {
609                         static string last_search;
610                         string searched_string;
611
612                         if (!argument.empty()) {
613                                 last_search = argument;
614                                 searched_string = argument;
615                         } else {
616                                 searched_string = last_search;
617                         }
618
619                         if (searched_string.empty())
620                                 break;
621
622                         bool const fw = action == LFUN_WORDFINDFORWARD;
623                         string const data =
624                                 lyx::find::find2string(searched_string, true, false, fw);
625                         lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
626                         break;
627                 }
628
629                 case LFUN_PREFIX:
630                         owner->message(keyseq.printOptions());
631                         break;
632
633                 case LFUN_EXEC_COMMAND:
634                         owner->focus_command_buffer();
635                         break;
636
637                 case LFUN_CANCEL:
638                         keyseq.reset();
639                         meta_fake_bit = key_modifier::none;
640                         if (view()->available())
641                                 // cancel any selection
642                                 dispatch(FuncRequest(LFUN_MARK_OFF));
643                         setMessage(N_("Cancel"));
644                         break;
645
646                 case LFUN_META_FAKE:
647                         meta_fake_bit = key_modifier::alt;
648                         setMessage(keyseq.print());
649                         break;
650
651                 case LFUN_READ_ONLY_TOGGLE:
652                         if (owner->buffer()->lyxvc().inUse())
653                                 owner->buffer()->lyxvc().toggleReadOnly();
654                         else
655                                 owner->buffer()->setReadonly(
656                                         !owner->buffer()->isReadonly());
657                         break;
658
659                 // --- Menus -----------------------------------------------
660                 case LFUN_MENUNEW:
661                         menuNew(argument, false);
662                         break;
663
664                 case LFUN_MENUNEWTMPLT:
665                         menuNew(argument, true);
666                         break;
667
668                 case LFUN_CLOSEBUFFER:
669                         closeBuffer();
670                         break;
671
672                 case LFUN_MENUWRITE:
673                         if (!owner->buffer()->isUnnamed()) {
674                                 string const str = bformat(_("Saving document %1$s..."),
675                                          MakeDisplayPath(owner->buffer()->fileName()));
676                                 owner->message(str);
677                                 MenuWrite(owner->buffer());
678                                 owner->message(str + _(" done."));
679                         } else
680                                 WriteAs(owner->buffer());
681                         break;
682
683                 case LFUN_WRITEAS:
684                         WriteAs(owner->buffer(), argument);
685                         break;
686
687                 case LFUN_MENURELOAD: {
688                         string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
689                         string text = bformat(_("Any changes will be lost. Are you sure "
690                                 "you want to revert to the saved version of the document %1$s?"), file);
691                         int const ret = Alert::prompt(_("Revert to saved document?"),
692                                 text, 0, 1, _("&Revert"), _("&Cancel"));
693
694                         if (ret == 0)
695                                 view()->reload();
696                         break;
697                 }
698
699                 case LFUN_UPDATE:
700                         Exporter::Export(owner->buffer(), argument, true);
701                         view()->showErrorList(BufferFormat(*owner->buffer()));
702                         break;
703
704                 case LFUN_PREVIEW:
705                         Exporter::Preview(owner->buffer(), argument);
706                         view()->showErrorList(BufferFormat(*owner->buffer()));
707                         break;
708
709                 case LFUN_BUILDPROG:
710                         Exporter::Export(owner->buffer(), "program", true);
711                         view()->showErrorList(_("Build"));
712                         break;
713
714                 case LFUN_RUNCHKTEX:
715                         owner->buffer()->runChktex();
716                         view()->showErrorList(_("ChkTeX"));
717                         break;
718
719                 case LFUN_EXPORT:
720                         if (argument == "custom")
721                                 owner->getDialogs().show("sendto");
722                         else {
723                                 Exporter::Export(owner->buffer(), argument, false);
724                                 view()->showErrorList(BufferFormat(*owner->buffer()));
725                         }
726                         break;
727
728                 case LFUN_EXPORT_CUSTOM: {
729                         string format_name;
730                         string command = split(argument, format_name, ' ');
731                         Format const * format = formats.getFormat(format_name);
732                         if (!format) {
733                                 lyxerr << "Format \"" << format_name
734                                        << "\" not recognized!"
735                                        << std::endl;
736                                 break;
737                         }
738
739                         Buffer * buffer = owner->buffer();
740
741                         // The name of the file created by the conversion process
742                         string filename;
743
744                         // Output to filename
745                         if (format->name() == "lyx") {
746                                 string const latexname =
747                                         buffer->getLatexName(false);
748                                 filename = ChangeExtension(latexname,
749                                                            format->extension());
750                                 filename = AddName(buffer->temppath(), filename);
751
752                                 if (!buffer->writeFile(filename))
753                                         break;
754
755                         } else {
756                                 Exporter::Export(buffer, format_name, true,
757                                                  filename);
758                         }
759
760                         // Substitute $$FName for filename
761                         if (!contains(command, "$$FName"))
762                                 command = "( " + command + " ) < $$FName";
763                         command = subst(command, "$$FName", filename);
764
765                         // Execute the command in the background
766                         Systemcall call;
767                         call.startscript(Systemcall::DontWait, command);
768                         break;
769                 }
770
771                 case LFUN_PRINT: {
772                         string target;
773                         string target_name;
774                         string command = split(split(argument, target, ' '),
775                                                target_name, ' ');
776
777                         if (target.empty()
778                             || target_name.empty()
779                             || command.empty()) {
780                                 lyxerr << "Unable to parse \""
781                                        << argument << '"' << std::endl;
782                                 break;
783                         }
784                         if (target != "printer" && target != "file") {
785                                 lyxerr << "Unrecognized target \""
786                                        << target << '"' << std::endl;
787                                 break;
788                         }
789
790                         Buffer * buffer = owner->buffer();
791
792                         if (!Exporter::Export(buffer, "dvi", true)) {
793                                 showPrintError(buffer->fileName());
794                                 break;
795                         }
796
797                         // Push directory path.
798                         string const path = buffer->temppath();
799                         Path p(path);
800
801                         // there are three cases here:
802                         // 1. we print to a file
803                         // 2. we print directly to a printer
804                         // 3. we print using a spool command (print to file first)
805                         Systemcall one;
806                         int res = 0;
807                         string const dviname =
808                                 ChangeExtension(buffer->getLatexName(true),
809                                                 "dvi");
810
811                         if (target == "printer") {
812                                 if (!lyxrc.print_spool_command.empty()) {
813                                         // case 3: print using a spool
814                                         string const psname =
815                                                 ChangeExtension(dviname,".ps");
816                                         command += lyxrc.print_to_file
817                                                 + QuoteName(psname)
818                                                 + ' '
819                                                 + QuoteName(dviname);
820
821                                         string command2 =
822                                                 lyxrc.print_spool_command +' ';
823                                         if (target_name != "default") {
824                                                 command2 += lyxrc.print_spool_printerprefix
825                                                         + target_name
826                                                         + ' ';
827                                         }
828                                         command2 += QuoteName(psname);
829                                         // First run dvips.
830                                         // If successful, then spool command
831                                         res = one.startscript(
832                                                 Systemcall::Wait,
833                                                 command);
834
835                                         if (res == 0)
836                                                 res = one.startscript(
837                                                         Systemcall::DontWait,
838                                                         command2);
839                                 } else {
840                                         // case 2: print directly to a printer
841                                         res = one.startscript(
842                                                 Systemcall::DontWait,
843                                                 command + QuoteName(dviname));
844                                 }
845
846                         } else {
847                                 // case 1: print to a file
848                                 command += lyxrc.print_to_file
849                                         + QuoteName(MakeAbsPath(target_name,
850                                                                 path))
851                                         + ' '
852                                         + QuoteName(dviname);
853                                 res = one.startscript(Systemcall::DontWait,
854                                                       command);
855                         }
856
857                         if (res != 0)
858                                 showPrintError(buffer->fileName());
859                         break;
860                 }
861
862                 case LFUN_IMPORT:
863                         doImport(argument);
864                         break;
865
866                 case LFUN_QUIT:
867                         QuitLyX();
868                         break;
869
870                 case LFUN_TOCVIEW: {
871                         InsetCommandParams p("tableofcontents");
872                         string const data = InsetCommandMailer::params2string("toc", p);
873                         owner->getDialogs().show("toc", data, 0);
874                         break;
875                 }
876
877                 case LFUN_AUTOSAVE:
878                         AutoSave(view());
879                         break;
880
881                 case LFUN_RECONFIGURE:
882                         Reconfigure(view());
883                         break;
884
885                 case LFUN_HELP_OPEN: {
886                         string const arg = argument;
887                         if (arg.empty()) {
888                                 setErrorMessage(N_("Missing argument"));
889                                 break;
890                         }
891                         string const fname = i18nLibFileSearch("doc", arg, "lyx");
892                         if (fname.empty()) {
893                                 lyxerr << "LyX: unable to find documentation file `"
894                                                          << arg << "'. Bad installation?" << endl;
895                                 break;
896                         }
897                         owner->message(bformat(_("Opening help file %1$s..."),
898                                 MakeDisplayPath(fname)));
899                         view()->loadLyXFile(fname, false);
900                         break;
901                 }
902
903                 // --- version control -------------------------------
904                 case LFUN_VC_REGISTER:
905                         if (!ensureBufferClean(view()))
906                                 break;
907                         if (!owner->buffer()->lyxvc().inUse()) {
908                                 owner->buffer()->lyxvc().registrer();
909                                 view()->reload();
910                         }
911                         break;
912
913                 case LFUN_VC_CHECKIN:
914                         if (!ensureBufferClean(view()))
915                                 break;
916                         if (owner->buffer()->lyxvc().inUse()
917                                         && !owner->buffer()->isReadonly()) {
918                                 owner->buffer()->lyxvc().checkIn();
919                                 view()->reload();
920                         }
921                         break;
922
923                 case LFUN_VC_CHECKOUT:
924                         if (!ensureBufferClean(view()))
925                                 break;
926                         if (owner->buffer()->lyxvc().inUse()
927                                         && owner->buffer()->isReadonly()) {
928                                 owner->buffer()->lyxvc().checkOut();
929                                 view()->reload();
930                         }
931                         break;
932
933                 case LFUN_VC_REVERT:
934                         owner->buffer()->lyxvc().revert();
935                         view()->reload();
936                         break;
937
938                 case LFUN_VC_UNDO:
939                         owner->buffer()->lyxvc().undoLast();
940                         view()->reload();
941                         break;
942
943                 // --- buffers ----------------------------------------
944                 case LFUN_SWITCHBUFFER:
945                         view()->setBuffer(bufferlist.getBuffer(argument));
946                         break;
947
948                 case LFUN_FILE_NEW:
949                         NewFile(view(), argument);
950                         break;
951
952                 case LFUN_FILE_OPEN:
953                         open(argument);
954                         break;
955
956                 case LFUN_DROP_LAYOUTS_CHOICE:
957                         owner->getToolbar().openLayoutList();
958                         break;
959
960                 case LFUN_MENU_OPEN_BY_NAME:
961                         owner->getMenubar().openByName(argument);
962                         break;
963
964                 // --- lyxserver commands ----------------------------
965                 case LFUN_GETNAME:
966                         setMessage(owner->buffer()->fileName());
967                         lyxerr[Debug::INFO] << "FNAME["
968                                                          << owner->buffer()->fileName()
969                                                          << "] " << endl;
970                         break;
971
972                 case LFUN_NOTIFY:
973                         dispatch_buffer = keyseq.print();
974                         lyxserver->notifyClient(dispatch_buffer);
975                         break;
976
977                 case LFUN_GOTOFILEROW: {
978                         string file_name;
979                         int row;
980                         istringstream is(argument);
981                         is >> file_name >> row;
982                         if (prefixIs(file_name, getTmpDir())) {
983                                 // Needed by inverse dvi search. If it is a file
984                                 // in tmpdir, call the apropriated function
985                                 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
986                         } else {
987                                 // Must replace extension of the file to be .lyx
988                                 // and get full path
989                                 string const s = ChangeExtension(file_name, ".lyx");
990                                 // Either change buffer or load the file
991                                 if (bufferlist.exists(s)) {
992                                         view()->setBuffer(bufferlist.getBuffer(s));
993                                 } else {
994                                         view()->loadLyXFile(s);
995                                 }
996                         }
997
998                         view()->setCursorFromRow(row);
999
1000                         view()->center();
1001                         // see BufferView_pimpl::center()
1002                         view()->updateScrollbar();
1003                         break;
1004                 }
1005
1006                 case LFUN_GOTO_PARAGRAPH: {
1007                         istringstream is(argument);
1008                         int id;
1009                         is >> id;
1010                         ParIterator par = owner->buffer()->getParFromID(id);
1011                         if (par == owner->buffer()->par_iterator_end()) {
1012                                 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1013                                                                 << id << ']' << endl;
1014                                 break;
1015                         } else {
1016                                 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1017                                                                 << " found." << endl;
1018                         }
1019
1020                         // Set the cursor
1021                         view()->setCursor(par, 0);
1022
1023                         view()->switchKeyMap();
1024                         owner->view_state_changed();
1025
1026                         view()->center();
1027                         // see BufferView_pimpl::center()
1028                         view()->updateScrollbar();
1029                         break;
1030                 }
1031
1032                 case LFUN_DIALOG_SHOW: {
1033                         string const name = cmd.getArg(0);
1034                         string data = trim(cmd.argument.substr(name.size()));
1035
1036                         if (name == "character") {
1037                                 data = freefont2string();
1038                                 if (!data.empty())
1039                                         owner->getDialogs().show("character", data);
1040                         }
1041
1042                         else if (name == "latexlog") {
1043                                 pair<Buffer::LogType, string> const logfile =
1044                                         owner->buffer()->getLogName();
1045                                 switch (logfile.first) {
1046                                 case Buffer::latexlog:
1047                                         data = "latex ";
1048                                         break;
1049                                 case Buffer::buildlog:
1050                                         data = "literate ";
1051                                         break;
1052                                 }
1053                                 data += logfile.second;
1054                                 owner->getDialogs().show("log", data);
1055                         }
1056                         else if (name == "vclog") {
1057                                 string const data = "vc " +
1058                                         owner->buffer()->lyxvc().getLogFile();
1059                                 owner->getDialogs().show("log", data);
1060                         }
1061                         else
1062                                 owner->getDialogs().show(name, data);
1063                         break;
1064                 }
1065
1066                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1067                         string const name = cmd.getArg(0);
1068                         string data = trim(cmd.argument.substr(name.size()));
1069                         if (name == "bibitem" ||
1070                             name == "bibtex" ||
1071                             name == "include" ||
1072                             name == "index" ||
1073                             name == "label" ||
1074                             name == "ref" ||
1075                             name == "toc" ||
1076                             name == "url") {
1077                                 InsetCommandParams p(name);
1078                                 data = InsetCommandMailer::params2string(name, p);
1079                         } else if (name == "box") {
1080                                 // \c data == "Boxed" || "Frameless" etc
1081                                 InsetBoxParams p(data);
1082                                 data = InsetBoxMailer::params2string(p);
1083                         } else if (name == "branch") {
1084                                 InsetBranchParams p;
1085                                 data = InsetBranchMailer::params2string(p);
1086                         } else if (name == "citation") {
1087                                 InsetCommandParams p("cite");
1088                                 data = InsetCommandMailer::params2string(name, p);
1089                         } else if (name == "ert") {
1090                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1091                         } else if (name == "external") {
1092                                 InsetExternalParams p;
1093                                 Buffer const & buffer = *owner->buffer();
1094                                 data = InsetExternalMailer::params2string(p, buffer);
1095                         } else if (name == "float") {
1096                                 InsetFloatParams p;
1097                                 data = InsetFloatMailer::params2string(p);
1098                         } else if (name == "graphics") {
1099                                 InsetGraphicsParams p;
1100                                 Buffer const & buffer = *owner->buffer();
1101                                 data = InsetGraphicsMailer::params2string(p, buffer);
1102                         } else if (name == "note") {
1103                                 InsetNoteParams p;
1104                                 data = InsetNoteMailer::params2string(p);
1105                         } else if (name == "vspace") {
1106                                 VSpace space;
1107                                 data = InsetVSpaceMailer::params2string(space);
1108                         } else if (name == "wrap") {
1109                                 InsetWrapParams p;
1110                                 data = InsetWrapMailer::params2string(p);
1111                         }
1112                         owner->getDialogs().show(name, data, 0);
1113                         break;
1114                 }
1115
1116                 case LFUN_DIALOG_SHOW_NEXT_INSET:
1117                         break;
1118
1119                 case LFUN_DIALOG_UPDATE: {
1120                         string const & name = argument;
1121                         // Can only update a dialog connected to an existing inset
1122                         InsetBase * inset = owner->getDialogs().getOpenInset(name);
1123                         if (inset) {
1124                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1125                                 inset->dispatch(view()->cursor(), fr);
1126                         } else if (name == "paragraph") {
1127                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1128                         } else if (name == "prefs") {
1129                                 owner->getDialogs().update(name, string());
1130                         }
1131                         break;
1132                 }
1133
1134                 case LFUN_DIALOG_HIDE:
1135                         Dialogs::hide(argument, 0);
1136                         break;
1137
1138                 case LFUN_DIALOG_DISCONNECT_INSET:
1139                         owner->getDialogs().disconnect(argument);
1140                         break;
1141
1142                 case LFUN_CHILDOPEN: {
1143                         string const filename =
1144                                 MakeAbsPath(argument, owner->buffer()->filePath());
1145                         setMessage(N_("Opening child document ") +
1146                                          MakeDisplayPath(filename) + "...");
1147                         view()->savePosition(0);
1148                         string const parentfilename = owner->buffer()->fileName();
1149                         if (bufferlist.exists(filename))
1150                                 view()->setBuffer(bufferlist.getBuffer(filename));
1151                         else
1152                                 view()->loadLyXFile(filename);
1153                         // Set the parent name of the child document.
1154                         // This makes insertion of citations and references in the child work,
1155                         // when the target is in the parent or another child document.
1156                         owner->buffer()->setParentName(parentfilename);
1157                         break;
1158                 }
1159
1160                 case LFUN_TOGGLECURSORFOLLOW:
1161                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1162                         break;
1163
1164                 case LFUN_KMAP_OFF:
1165                         owner->getIntl().KeyMapOn(false);
1166                         break;
1167
1168                 case LFUN_KMAP_PRIM:
1169                         owner->getIntl().KeyMapPrim();
1170                         break;
1171
1172                 case LFUN_KMAP_SEC:
1173                         owner->getIntl().KeyMapSec();
1174                         break;
1175
1176                 case LFUN_KMAP_TOGGLE:
1177                         owner->getIntl().ToggleKeyMap();
1178                         break;
1179
1180                 case LFUN_REPEAT: {
1181                         // repeat command
1182                         string countstr;
1183                         string rest = split(argument, countstr, ' ');
1184                         istringstream is(countstr);
1185                         int count = 0;
1186                         is >> count;
1187                         lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1188                         for (int i = 0; i < count; ++i)
1189                                 dispatch(lyxaction.lookupFunc(rest));
1190                         break;
1191                 }
1192
1193                 case LFUN_SEQUENCE:
1194                         // argument contains ';'-terminated commands
1195                         while (!argument.empty()) {
1196                                 string first;
1197                                 string rest = split(argument, first, ';');
1198                                 dispatch(lyxaction.lookupFunc(rest));
1199                         }
1200                         break;
1201
1202                 case LFUN_SAVEPREFERENCES: {
1203                         Path p(user_lyxdir());
1204                         lyxrc.write("preferences", false);
1205                         break;
1206                 }
1207
1208                 case LFUN_SCREEN_FONT_UPDATE:
1209                         // handle the screen font changes.
1210                         lyxrc.set_font_norm_type();
1211                         lyx_gui::update_fonts();
1212                         // All visible buffers will need resize
1213                         view()->resize();
1214                         break;
1215
1216                 case LFUN_SET_COLOR: {
1217                         string lyx_name;
1218                         string const x11_name = split(argument, lyx_name, ' ');
1219                         if (lyx_name.empty() || x11_name.empty()) {
1220                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1221                                                         " <x11_name>"));
1222                                 break;
1223                         }
1224
1225                         bool const graphicsbg_changed =
1226                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1227                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1228
1229                         if (!lcolor.setColor(lyx_name, x11_name)) {
1230                                 setErrorMessage(
1231                                         bformat(_("Set-color \"%1$s\" failed "
1232                                                                 "- color is undefined or "
1233                                                                 "may not be redefined"), lyx_name));
1234                                 break;
1235                         }
1236
1237                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1238
1239                         if (graphicsbg_changed) {
1240 #ifdef WITH_WARNINGS
1241 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1242 #endif
1243 #if 0
1244                                 lyx::graphics::GCache::get().changeDisplay(true);
1245 #endif
1246                         }
1247                         break;
1248                 }
1249
1250                 case LFUN_MESSAGE:
1251                         owner->message(argument);
1252                         break;
1253
1254                 case LFUN_TOOLTIPS_TOGGLE:
1255                         owner->getDialogs().toggleTooltips();
1256                         break;
1257
1258                 case LFUN_EXTERNAL_EDIT: {
1259                         FuncRequest fr(action, argument);
1260                         InsetExternal().dispatch(view()->cursor(), fr);
1261                         break;
1262                 }
1263
1264                 case LFUN_GRAPHICS_EDIT: {
1265                         FuncRequest fr(action, argument);
1266                         InsetGraphics().dispatch(view()->cursor(), fr);
1267                         break;
1268                 }
1269
1270                 case LFUN_ALL_INSETS_TOGGLE: {
1271                         string action;
1272                         string const name = split(argument, action, ' ');
1273                         InsetBase::Code const inset_code =
1274                                 InsetBase::translate(name);
1275
1276                         LCursor & cur = view()->cursor();
1277                         FuncRequest fr(LFUN_INSET_TOGGLE, action);
1278
1279                         InsetBase & inset = owner->buffer()->inset();
1280                         InsetIterator it  = inset_iterator_begin(inset);
1281                         InsetIterator const end = inset_iterator_end(inset);
1282                         for (; it != end; ++it) {
1283                                 if (inset_code == InsetBase::NO_CODE
1284                                     || inset_code == it->lyxCode())
1285                                         it->dispatch(cur, fr);
1286                         }
1287                         break;
1288                 }
1289
1290                 case LFUN_LANGUAGE_BUFFER: {
1291                         Buffer & buffer = *owner->buffer();
1292                         Language const * oldL = buffer.params().language;
1293                         Language const * newL = languages.getLanguage(argument);
1294                         if (!newL || oldL == newL)
1295                                 break;
1296
1297                         if (oldL->RightToLeft() == newL->RightToLeft()
1298                             && !buffer.isMultiLingual())
1299                                 buffer.changeLanguage(oldL, newL);
1300                         else
1301                                 buffer.updateDocLang(newL);
1302                         break;
1303                 }
1304
1305                 case LFUN_BUFFERPARAMS_APPLY: {
1306                         istringstream ss(argument);
1307                         LyXLex lex(0,0);
1308                         lex.setStream(ss);
1309                         int const unknown_tokens =
1310                                 owner->buffer()->readHeader(lex);
1311
1312                         if (unknown_tokens != 0) {
1313                                 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1314                                        << unknown_tokens << " unknown token"
1315                                        << (unknown_tokens == 1 ? "" : "s")
1316                                        << endl;
1317                         }
1318                         break;
1319                 }
1320
1321                 case LFUN_TEXTCLASS_APPLY: {
1322                         Buffer * buffer = owner->buffer();
1323
1324                         lyx::textclass_type const old_class =
1325                                 buffer->params().textclass;
1326
1327                         loadTextclass(argument);
1328
1329                         std::pair<bool, lyx::textclass_type> const tc_pair =
1330                                 textclasslist.NumberOfClass(argument);
1331
1332                         if (!tc_pair.first)
1333                                 break;
1334
1335                         lyx::textclass_type const new_class = tc_pair.second;
1336                         if (old_class == new_class)
1337                                 // nothing to do
1338                                 break;
1339
1340                         owner->message(_("Converting document to new document class..."));
1341                         ErrorList el;
1342                         lyx::cap::SwitchLayoutsBetweenClasses(
1343                                 old_class, new_class,
1344                                 buffer->paragraphs(), el);
1345
1346                         bufferErrors(*buffer, el);
1347                         view()->showErrorList(_("Class switch"));
1348                         break;
1349                 }
1350
1351                 case LFUN_TEXTCLASS_LOAD:
1352                         loadTextclass(argument);
1353                         break;
1354
1355                 case LFUN_LYXRC_APPLY: {
1356                         istringstream ss(argument);
1357                         bool const success = lyxrc.read(ss) == 0;
1358
1359                         if (!success) {
1360                                 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1361                                        << "Unable to read lyxrc data"
1362                                        << endl;
1363                         }
1364                         break;
1365                 }
1366
1367                 default: {
1368                         update = false;
1369                         DispatchResult res = view()->cursor().dispatch(cmd);
1370                         if (res.dispatched())
1371                                 update |= res.update();
1372                         else
1373                                 update |= view()->dispatch(cmd);
1374                         
1375                         break;
1376                 }
1377                 }
1378
1379                 if (view()->available()) {
1380                         if (view()->fitCursor() || update)
1381                                 view()->update();
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();
1387                 }
1388
1389                 if (view()->cursor().inTexted()) {
1390                         view()->owner()->updateLayoutChoice();
1391                         sendDispatchMessage(getMessage(), cmd, verbose);
1392                 }
1393         }
1394 }
1395
1396
1397 void LyXFunc::sendDispatchMessage(string const & msg,
1398                                   FuncRequest const & cmd, bool verbose)
1399 {
1400         owner->updateMenubar();
1401         owner->updateToolbar();
1402
1403         if (cmd.action == LFUN_SELFINSERT || !verbose) {
1404                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1405                 if (!msg.empty())
1406                         owner->message(msg);
1407                 return;
1408         }
1409
1410         string dispatch_msg = msg;
1411         if (!dispatch_msg.empty())
1412                 dispatch_msg += ' ';
1413
1414         string comname = lyxaction.getActionName(cmd.action);
1415
1416         bool argsadded = false;
1417
1418         if (!cmd.argument.empty()) {
1419                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1420                         comname += ' ' + cmd.argument;
1421                         argsadded = true;
1422                 }
1423         }
1424
1425         string const shortcuts = toplevel_keymap->findbinding(cmd);
1426
1427         if (!shortcuts.empty()) {
1428                 comname += ": " + shortcuts;
1429         } else if (!argsadded && !cmd.argument.empty()) {
1430                 comname += ' ' + cmd.argument;
1431         }
1432
1433         if (!comname.empty()) {
1434                 comname = rtrim(comname);
1435                 dispatch_msg += '(' + comname + ')';
1436         }
1437
1438         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1439         if (!dispatch_msg.empty())
1440                 owner->message(dispatch_msg);
1441 }
1442
1443
1444 void LyXFunc::setupLocalKeymap()
1445 {
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();
1450 }
1451
1452
1453 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1454 {
1455         string initpath = lyxrc.document_path;
1456         string filename(name);
1457
1458         if (view()->available()) {
1459                 string const trypath = owner->buffer()->filePath();
1460                 // If directory is writeable, use this as default.
1461                 if (IsDirWriteable(trypath))
1462                         initpath = trypath;
1463         }
1464
1465         static int newfile_number;
1466
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()) {
1472                         ++newfile_number;
1473                         filename = AddName(lyxrc.document_path,
1474                                     "newfile" + tostr(newfile_number) +
1475                                     ".lyx");
1476                         fi.newFile(filename);
1477                 }
1478         }
1479
1480         // The template stuff
1481         string templname;
1482         if (fromTemplate) {
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)));
1489
1490                 FileDialog::Result result =
1491                         fileDlg.open(lyxrc.template_path,
1492                                      FileFilterList(_("LyX Documents (*.lyx)")),
1493                                      string());
1494
1495                 if (result.first == FileDialog::Later)
1496                         return;
1497                 if (result.second.empty())
1498                         return;
1499                 templname = result.second;
1500         }
1501
1502         view()->newFile(filename, templname, !name.empty());
1503 }
1504
1505
1506 void LyXFunc::open(string const & fname)
1507 {
1508         string initpath = lyxrc.document_path;
1509
1510         if (view()->available()) {
1511                 string const trypath = owner->buffer()->filePath();
1512                 // If directory is writeable, use this as default.
1513                 if (IsDirWriteable(trypath))
1514                         initpath = trypath;
1515         }
1516
1517         string filename;
1518
1519         if (fname.empty()) {
1520                 FileDialog fileDlg(_("Select document to open"),
1521                         LFUN_FILE_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"))));
1526
1527                 FileDialog::Result result =
1528                         fileDlg.open(initpath,
1529                                      FileFilterList(_("LyX Documents (*.lyx)")),
1530                                      string());
1531
1532                 if (result.first == FileDialog::Later)
1533                         return;
1534
1535                 filename = result.second;
1536
1537                 // check selected filename
1538                 if (filename.empty()) {
1539                         owner->message(_("Canceled."));
1540                         return;
1541                 }
1542         } else
1543                 filename = fname;
1544
1545         // get absolute path of file and add ".lyx" to the filename if
1546         // necessary
1547         string const fullpath = FileSearch(string(), filename, "lyx");
1548         if (!fullpath.empty()) {
1549                 filename = fullpath;
1550         }
1551
1552         string const disp_fn(MakeDisplayPath(filename));
1553
1554         // if the file doesn't exist, let the user create one
1555         FileInfo const f(filename, true);
1556         if (!f.exist()) {
1557                 // the user specifically chose this name. Believe them.
1558                 view()->newFile(filename, "", true);
1559                 return;
1560         }
1561
1562         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1563
1564         string str2;
1565         if (view()->loadLyXFile(filename)) {
1566                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1567         } else {
1568                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1569         }
1570         owner->message(str2);
1571 }
1572
1573
1574 void LyXFunc::doImport(string const & argument)
1575 {
1576         string format;
1577         string filename = split(argument, format, ' ');
1578
1579         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1580                             << " file: " << filename << endl;
1581
1582         // need user interaction
1583         if (filename.empty()) {
1584                 string initpath = lyxrc.document_path;
1585
1586                 if (view()->available()) {
1587                         string const trypath = owner->buffer()->filePath();
1588                         // If directory is writeable, use this as default.
1589                         if (IsDirWriteable(trypath))
1590                                 initpath = trypath;
1591                 }
1592
1593                 string const text = bformat(_("Select %1$s file to import"),
1594                         formats.prettyName(format));
1595
1596                 FileDialog fileDlg(text,
1597                         LFUN_IMPORT,
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"))));
1602
1603                 string const filter = formats.prettyName(format)
1604                         + " (*." + formats.extension(format) + ')';
1605
1606                 FileDialog::Result result =
1607                         fileDlg.open(initpath,
1608                                      FileFilterList(filter),
1609                                      string());
1610
1611                 if (result.first == FileDialog::Later)
1612                         return;
1613
1614                 filename = result.second;
1615
1616                 // check selected filename
1617                 if (filename.empty())
1618                         owner->message(_("Canceled."));
1619         }
1620
1621         if (filename.empty())
1622                 return;
1623
1624         // get absolute path of file
1625         filename = MakeAbsPath(filename);
1626
1627         string const lyxfile = ChangeExtension(filename, ".lyx");
1628
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."));
1633                         return;
1634                 }
1635         }
1636
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);
1641
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"));
1646
1647                 if (ret == 1) {
1648                         owner->message(_("Canceled."));
1649                         return;
1650                 }
1651         }
1652
1653         Importer::Import(owner, filename, format);
1654 }
1655
1656
1657 void LyXFunc::closeBuffer()
1658 {
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();
1665                 } else {
1666                         view()->setBuffer(bufferlist.first());
1667                 }
1668         }
1669 }
1670
1671
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
1679 {
1680         dispatch_buffer = m;
1681         errorstat = true;
1682 }
1683
1684
1685 void LyXFunc::setMessage(string const & m) const
1686 {
1687         dispatch_buffer = m;
1688 }
1689
1690
1691 void LyXFunc::setStatusMessage(string const & m) const
1692 {
1693         status_buffer = m;
1694 }
1695
1696
1697 string const LyXFunc::viewStatusMessage()
1698 {
1699         // When meta-fake key is pressed, show the key sequence so far + "M-".
1700         if (wasMetaKey())
1701                 return keyseq.print() + "M-";
1702
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();
1707
1708         if (!view()->available())
1709                 return _("Welcome to LyX!");
1710
1711         return view()->cursor().currentState();
1712 }
1713
1714
1715 BufferView * LyXFunc::view() const
1716 {
1717         BOOST_ASSERT(owner);
1718         return owner->view().get();
1719 }
1720
1721
1722 bool LyXFunc::wasMetaKey() const
1723 {
1724         return (meta_fake_bit != key_modifier::none);
1725 }