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