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