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