]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
Move the include dialog to the new scheme
[lyx.git] / src / lyxfunc.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *          Copyright 1995 Matthias Ettrich
7  *          Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxfunc.h"
14 #include "version.h"
15 #include "kbmap.h"
16 #include "lyxrow.h"
17 #include "bufferlist.h"
18 #include "BufferView.h"
19 #include "lyxserver.h"
20 #include "intl.h"
21 #include "lyx_main.h"
22 #include "lyx_cb.h"
23 #include "LyXAction.h"
24 #include "debug.h"
25 #include "lyxrc.h"
26 #include "lyxtext.h"
27 #include "gettext.h"
28 #include "Lsstream.h"
29 #include "trans_mgr.h"
30 #include "encoding.h"
31 #include "layout.h"
32 #include "bufferview_funcs.h"
33 #include "frontends/LyXView.h"
34 #include "frontends/lyx_gui.h"
35 #include "vspace.h"
36 #include "FloatList.h"
37 #include "format.h"
38 #include "exporter.h"
39 #include "importer.h"
40 #include "TextCache.h"
41 #include "lyxfind.h"
42 #include "undo_funcs.h"
43 #include "ParagraphParameters.h"
44
45 #include "insets/insetcommand.h"
46 #include "insets/inseterror.h"
47 #include "insets/insetert.h"
48 #include "insets/insettabular.h"
49
50 #include "mathed/formulamacro.h"
51 #include "mathed/math_cursor.h"
52 #include "mathed/math_inset.h"
53
54 #include "frontends/FileDialog.h"
55 #include "frontends/Dialogs.h"
56 #include "frontends/Toolbar.h"
57 #include "frontends/Menubar.h"
58 #include "frontends/Alert.h"
59
60 #include "graphics/GraphicsCache.h"
61
62 #include "support/lyxalgo.h"
63 #include "support/LAssert.h"
64 #include "support/filetools.h"
65 #include "support/FileInfo.h"
66 #include "support/forkedcontr.h"
67 #include "support/lstrings.h"
68 #include "support/path.h"
69 #include "support/lyxfunctional.h"
70
71 #include "BoostFormat.h"
72
73 #include <ctime>
74 #include <clocale>
75 #include <cstdlib>
76 #include <cctype>
77
78 #include <utility>
79 #include <algorithm>
80
81 using std::pair;
82 using std::make_pair;
83 using std::endl;
84 using std::find_if;
85 using std::vector;
86 using std::transform;
87 using std::back_inserter;
88
89 extern BufferList bufferlist;
90 extern LyXServer * lyxserver;
91 extern bool selection_possible;
92
93 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
94
95 // (alkis)
96 extern tex_accent_struct get_accent(kb_action action);
97
98 extern void ShowLatexLog();
99
100
101 LyXFunc::LyXFunc(LyXView * o)
102         : owner(o),
103         encoded_last_key(0),
104         keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
105         cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
106         meta_fake_bit(key_modifier::none)
107 {
108 }
109
110
111 inline
112 LyXText * LyXFunc::TEXT(bool flag = true) const
113 {
114         if (flag)
115                 return view()->text;
116         return view()->getLyXText();
117 }
118
119
120 inline
121 void LyXFunc::moveCursorUpdate(bool flag, bool selecting)
122 {
123         if (selecting || TEXT(flag)->selection.mark()) {
124                 TEXT(flag)->setSelection(view());
125                 if (TEXT(flag)->isTopLevel())
126                     view()->toggleToggle();
127         }
128         view()->update(TEXT(flag), BufferView::SELECT|BufferView::FITCUR);
129         view()->showCursor();
130
131         view()->switchKeyMap();
132 }
133
134
135 void LyXFunc::handleKeyFunc(kb_action action)
136 {
137         char c = encoded_last_key;
138
139         if (keyseq.length()) {
140                 c = 0;
141         }
142
143         owner->getIntl().getTransManager()
144                 .deadkey(c, get_accent(action).accent, TEXT(false));
145         // Need to clear, in case the minibuffer calls these
146         // actions
147         keyseq.clear();
148         // copied verbatim from do_accent_char
149         view()->update(TEXT(false),
150                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
151         TEXT(false)->selection.cursor = TEXT(false)->cursor;
152 }
153
154
155 void LyXFunc::processKeySym(LyXKeySymPtr keysym,
156                             key_modifier::state state)
157 {
158         string argument;
159
160         if (lyxerr.debugging(Debug::KEY)) {
161                 lyxerr << "KeySym is "
162                        << keysym->getSymbolName()
163                        << endl;
164         }
165
166         // Do nothing if we have nothing (JMarc)
167         if (!keysym->isOK()) {
168                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
169                                    << endl;
170                 return;
171         }
172
173         if (keysym->isModifier()) {
174                 lyxerr[Debug::KEY] << "isModifier true" << endl;
175                 return;
176         }
177
178         Encoding const * encoding = view()->getEncoding();
179
180         encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
181
182         // Do a one-deep top-level lookup for
183         // cancel and meta-fake keys. RVDK_PATCH_5
184         cancel_meta_seq.reset();
185
186         int action = cancel_meta_seq.addkey(keysym, state);
187         lyxerr[Debug::KEY] << "action first set to [" << action << ']' << endl;
188
189         // When not cancel or meta-fake, do the normal lookup.
190         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
191         // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
192         if ((action != LFUN_CANCEL) && (action != LFUN_META_FAKE)) {
193                 // remove Caps Lock and Mod2 as a modifiers
194                 action = keyseq.addkey(keysym, (state | meta_fake_bit));
195                 lyxerr[Debug::KEY] << "action now set to ["
196                         << action << ']' << endl;
197         }
198
199         // Dont remove this unless you know what you are doing.
200         meta_fake_bit = key_modifier::none;
201
202         // can this happen now ?
203         if (action == LFUN_NOACTION) {
204                 action = LFUN_PREFIX;
205         }
206
207         if (lyxerr.debugging(Debug::KEY)) {
208                 lyxerr << "Key [action="
209                        << action << "]["
210                        << keyseq.print() << ']'
211                        << endl;
212         }
213
214         // already here we know if it any point in going further
215         // why not return already here if action == -1 and
216         // num_bytes == 0? (Lgb)
217
218         if (keyseq.length() > 1) {
219                 owner->message(keyseq.print());
220         }
221
222
223         // Maybe user can only reach the key via holding down shift.
224         // Let's see. But only if shift is the only modifier
225         if (action == LFUN_UNKNOWN_ACTION && state == key_modifier::shift) {
226                 lyxerr[Debug::KEY] << "Trying without shift" << endl;
227                 action = keyseq.addkey(keysym, key_modifier::none);
228                 lyxerr[Debug::KEY] << "Action now " << action << endl;
229         }
230
231         if (action == LFUN_UNKNOWN_ACTION) {
232                 // Hmm, we didn't match any of the keysequences. See
233                 // if it's normal insertable text not already covered
234                 // by a binding
235                 if (keysym->isText() && keyseq.length() == 1) {
236                         lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
237                         action = LFUN_SELFINSERT;
238                 } else {
239                         lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
240                         owner->message(_("Unknown function."));
241                         return;
242                 }
243         }
244
245         if (action == LFUN_SELFINSERT) {
246                 if (encoded_last_key != 0) {
247                         string arg;
248                         arg += encoded_last_key;
249
250                         dispatch(FuncRequest(view(), LFUN_SELFINSERT, arg));
251
252                         lyxerr[Debug::KEY] << "SelfInsert arg[`"
253                                    << argument << "']" << endl;
254                 }
255         } else {
256                 dispatch(action);
257         }
258 }
259
260
261 FuncStatus LyXFunc::getStatus(int ac) const
262 {
263         return getStatus(lyxaction.retrieveActionArg(ac));
264 }
265
266
267 FuncStatus LyXFunc::getStatus(FuncRequest const & ev) const
268 {
269         FuncStatus flag;
270         Buffer * buf = owner->buffer();
271
272         if (ev.action == LFUN_NOACTION) {
273                 setStatusMessage(N_("Nothing to do"));
274                 return flag.disabled(true);
275         }
276
277         switch (ev.action) {
278         case LFUN_UNKNOWN_ACTION:
279 #ifndef HAVE_LIBAIKSAURUS
280         case LFUN_THESAURUS_ENTRY:
281 #endif
282                 flag.unknown(true);
283                 break;
284         default:
285                 flag |= lyx_gui::getStatus(ev);
286         }
287
288         if (flag.unknown()) {
289                 setStatusMessage(N_("Unknown action"));
290                 return flag;
291         }
292
293         // the default error message if we disable the command
294         setStatusMessage(N_("Command disabled"));
295
296         // Check whether we need a buffer
297         if (!lyxaction.funcHasFlag(ev.action, LyXAction::NoBuffer)) {
298                 // Yes we need a buffer, do we have one?
299                 if (buf) {
300                         // yes
301                         // Can we use a readonly buffer?
302                         if (buf->isReadonly() &&
303                             !lyxaction.funcHasFlag(ev.action,
304                                                    LyXAction::ReadOnly)) {
305                                 // no
306                                 setStatusMessage(N_("Document is read-only"));
307                                 flag.disabled(true);
308                         }
309                 } else {
310                         // no
311                         setStatusMessage(N_("Command not allowed with"
312                                            "out any document open"));
313                         return flag.disabled(true);
314                 }
315         }
316
317         UpdatableInset * tli = view()->theLockingInset();
318
319         // I would really like to avoid having this switch and rather try to
320         // encode this in the function itself.
321         bool disable = false;
322         switch (ev.action) {
323         case LFUN_MENUPRINT:
324                 disable = !Exporter::IsExportable(buf, "dvi")
325                         || lyxrc.print_command == "none";
326                 break;
327         case LFUN_EXPORT:
328                 disable = ev.argument != "custom"
329                         && !Exporter::IsExportable(buf, ev.argument);
330                 break;
331         case LFUN_UNDO:
332                 disable = buf->undostack.empty();
333                 break;
334         case LFUN_REDO:
335                 disable = buf->redostack.empty();
336                 break;
337         case LFUN_CUT:
338         case LFUN_COPY:
339                 if (tli) {
340                         UpdatableInset * in = tli;
341                         if (in->lyxCode() != Inset::TABULAR_CODE) {
342                                 in = tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE);
343                         }
344                         if (in && static_cast<InsetTabular*>(in)->hasSelection()) {
345                                 disable = false;
346                                 break;
347                         }
348                 }
349                 disable = !mathcursor && !view()->getLyXText()->selection.set();
350                 break;
351         case LFUN_RUNCHKTEX:
352                 disable = lyxrc.chktex_command == "none";
353                 break;
354         case LFUN_BUILDPROG:
355                 disable = !Exporter::IsExportable(buf, "program");
356                 break;
357
358         case LFUN_LAYOUT_CHARACTER:
359                 disable = tli && tli->lyxCode() == Inset::ERT_CODE;
360                 break;
361
362         case LFUN_LAYOUT_TABULAR:
363                 disable = !tli
364                         || (tli->lyxCode() != Inset::TABULAR_CODE
365                             && !tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
366                 break;
367
368         case LFUN_LAYOUT:
369         case LFUN_LAYOUT_PARAGRAPH: {
370                 Inset * inset = TEXT(false)->cursor.par()->inInset();
371                 disable = inset && inset->forceDefaultParagraphs(inset);
372                 break;
373         }
374
375         case LFUN_INSET_OPTARG:
376                 disable = (TEXT(false)->cursor.par()->layout()->optionalargs == 0);
377                 break;
378
379         case LFUN_TABULAR_FEATURE:
380                 if (mathcursor) {
381 #if 0
382                         // FIXME: check temporarily disabled
383                         // valign code
384                         char align = mathcursor->valign();
385                         if (align == '\0') {
386                                 disable = true;
387                                 break;
388                         }
389                         if (ev.argument.empty()) {
390                                 flag.clear();
391                                 break;
392                         }
393                         if (!contains("tcb", ev.argument[0])) {
394                                 disable = true;
395                                 break;
396                         }
397                         flag.setOnOff(ev.argument[0] == align);
398                 } else
399                         disable = true;
400
401                         char align = mathcursor->halign();
402                         if (align == '\0') {
403                                 disable = true;
404                                 break;
405                         }
406                         if (ev.argument.empty()) {
407                                 flag.clear();
408                                 break;
409                         }
410                         if (!contains("lcr", ev.argument[0])) {
411                                 disable = true;
412                                 break;
413                         }
414                         flag.setOnOff(ev.argument[0] == align);
415 #endif
416
417                         disable = !mathcursor->halign();
418                         break;
419                 }
420
421                 if (tli) {
422                         FuncStatus ret;
423                         //ret.disabled(true);
424                         if (tli->lyxCode() == Inset::TABULAR_CODE) {
425                                 ret = static_cast<InsetTabular *>(tli)
426                                         ->getStatus(ev.argument);
427                         } else if (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE)) {
428                                 ret = static_cast<InsetTabular *>
429                                         (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE))
430                                         ->getStatus(ev.argument);
431                         }
432                         flag |= ret;
433                         disable = false;
434                 } else {
435                         static InsetTabular inset(*owner->buffer(), 1, 1);
436                         FuncStatus ret;
437
438                         disable = true;
439                         ret = inset.getStatus(ev.argument);
440                         if (ret.onoff(true) || ret.onoff(false))
441                                 flag.setOnOff(false);
442                 }
443                 break;
444
445         case LFUN_VC_REGISTER:
446                 disable = buf->lyxvc.inUse();
447                 break;
448         case LFUN_VC_CHECKIN:
449                 disable = !buf->lyxvc.inUse() || buf->isReadonly();
450                 break;
451         case LFUN_VC_CHECKOUT:
452                 disable = !buf->lyxvc.inUse() || !buf->isReadonly();
453                 break;
454         case LFUN_VC_REVERT:
455         case LFUN_VC_UNDO:
456         case LFUN_VC_HISTORY:
457                 disable = !buf->lyxvc.inUse();
458                 break;
459         case LFUN_MENURELOAD:
460                 disable = buf->isUnnamed() || buf->isClean();
461                 break;
462         case LFUN_BOOKMARK_GOTO:
463                 disable =  !view()->
464                         isSavedPosition(strToUnsignedInt(ev.argument));
465                 break;
466         case LFUN_MERGE_CHANGES:
467         case LFUN_ACCEPT_CHANGE:
468         case LFUN_REJECT_CHANGE:
469         case LFUN_ACCEPT_ALL_CHANGES:
470         case LFUN_REJECT_ALL_CHANGES:
471                 disable = !buf->params.tracking_changes;
472                 break;
473         case LFUN_INSET_TOGGLE: {
474                 LyXText * lt = view()->getLyXText();
475                 disable = !(isEditableInset(lt->getInset())
476                             || (lt->inset_owner
477                                 && lt->inset_owner->owner()
478                                 && lt->inset_owner->owner()->isOpen()));
479                 break;
480         }
481         case LFUN_LATEX_LOG:
482                 disable = !IsFileReadable(buf->getLogName().second);
483                 break;
484
485         case LFUN_MATH_MUTATE:
486                 if (mathcursor)
487                         //flag.setOnOff(mathcursor->formula()->hullType() == ev.argument);
488                         flag.setOnOff(false);
489                 else
490                         disable = true;
491                 break;
492
493         // we just need to be in math mode to enable that
494         case LFUN_MATH_SIZE:
495         case LFUN_MATH_SPACE:
496         case LFUN_MATH_LIMITS:
497         case LFUN_MATH_NONUMBER:
498         case LFUN_MATH_NUMBER:
499         case LFUN_MATH_EXTERN:
500                 disable = !mathcursor;
501                 break;
502
503         default:
504                 break;
505         }
506
507         // the functions which insert insets
508         Inset::Code code = Inset::NO_CODE;
509         switch (ev.action) {
510         case LFUN_INSET_ERT:
511                 code = Inset::ERT_CODE;
512                 break;
513         case LFUN_INSET_GRAPHICS:
514                 code = Inset::GRAPHICS_CODE;
515                 break;
516         case LFUN_INSET_FOOTNOTE:
517                 code = Inset::FOOT_CODE;
518                 break;
519         case LFUN_TABULAR_INSERT:
520                 code = Inset::TABULAR_CODE;
521                 break;
522         case LFUN_INSET_MARGINAL:
523                 code = Inset::MARGIN_CODE;
524                 break;
525         case LFUN_INSET_MINIPAGE:
526                 code = Inset::MINIPAGE_CODE;
527                 break;
528         case LFUN_INSET_FLOAT:
529         case LFUN_INSET_WIDE_FLOAT:
530                 code = Inset::FLOAT_CODE;
531                 break;
532         case LFUN_INSET_WRAP:
533                 code = Inset::WRAP_CODE;
534                 break;
535         case LFUN_FLOAT_LIST:
536                 code = Inset::FLOAT_LIST_CODE;
537                 break;
538 #if 0
539         case LFUN_INSET_LIST:
540                 code = Inset::LIST_CODE;
541                 break;
542         case LFUN_INSET_THEOREM:
543                 code = Inset::THEOREM_CODE;
544                 break;
545 #endif
546         case LFUN_INSET_CAPTION:
547                 code = Inset::CAPTION_CODE;
548                 break;
549         case LFUN_INSERT_NOTE:
550                 code = Inset::NOTE_CODE;
551                 break;
552         case LFUN_INSERT_LABEL:
553                 code = Inset::LABEL_CODE;
554                 break;
555         case LFUN_INSET_OPTARG:
556                 code = Inset::OPTARG_CODE;
557                 break;
558         case LFUN_REF_INSERT:
559                 code = Inset::REF_CODE;
560                 break;
561         case LFUN_INDEX_INSERT:
562                 code = Inset::INDEX_CODE;
563                 break;
564         case LFUN_INDEX_PRINT:
565                 code = Inset::INDEX_PRINT_CODE;
566                 break;
567         case LFUN_TOC_INSERT:
568                 code = Inset::TOC_CODE;
569                 break;
570         case LFUN_PARENTINSERT:
571                 code = Inset::PARENT_CODE;
572                 break;
573         case LFUN_HTMLURL:
574         case LFUN_URL:
575                 code = Inset::URL_CODE;
576                 break;
577         case LFUN_QUOTE:
578                 // always allow this, since we will inset a raw quote
579                 // if an inset is not allowed.
580                 break;
581         case LFUN_HYPHENATION:
582         case LFUN_LIGATURE_BREAK:
583         case LFUN_HFILL:
584         case LFUN_MENU_SEPARATOR:
585         case LFUN_LDOTS:
586         case LFUN_END_OF_SENTENCE:
587                 code = Inset::SPECIALCHAR_CODE;
588                 break;
589         case LFUN_PROTECTEDSPACE:
590                 // slight hack: we know this is allowed in math mode
591                 if (!mathcursor)
592                         code = Inset::SPECIALCHAR_CODE;
593                 break;
594         default:
595                 break;
596         }
597         if (code != Inset::NO_CODE && tli && !tli->insetAllowed(code))
598                 disable = true;
599
600         if (disable)
601                 flag.disabled(true);
602
603         // A few general toggles
604         switch (ev.action) {
605         case LFUN_TOOLTIPS_TOGGLE:
606                 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
607                 break;
608
609         case LFUN_READ_ONLY_TOGGLE:
610                 flag.setOnOff(buf->isReadonly());
611                 break;
612         case LFUN_APPENDIX:
613                 flag.setOnOff(TEXT(false)->cursor.par()->params().startOfAppendix());
614                 break;
615         case LFUN_SWITCHBUFFER:
616                 // toggle on the current buffer, but do not toggle off
617                 // the other ones (is that a good idea?)
618                 if (ev.argument == buf->fileName())
619                         flag.setOnOff(true);
620                 break;
621         case LFUN_TRACK_CHANGES:
622                 flag.setOnOff(buf->params.tracking_changes);
623                 break;
624         default:
625                 break;
626         }
627
628         // the font related toggles
629         if (!mathcursor) {
630                 LyXFont const & font = TEXT(false)->real_current_font;
631                 switch (ev.action) {
632                 case LFUN_EMPH:
633                         flag.setOnOff(font.emph() == LyXFont::ON);
634                         break;
635                 case LFUN_NOUN:
636                         flag.setOnOff(font.noun() == LyXFont::ON);
637                         break;
638                 case LFUN_BOLD:
639                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
640                         break;
641                 case LFUN_SANS:
642                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
643                         break;
644                 case LFUN_ROMAN:
645                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
646                         break;
647                 case LFUN_CODE:
648                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
649                         break;
650                 default:
651                         break;
652                 }
653         } else {
654                 string tc = mathcursor->getLastCode();
655                 switch (ev.action) {
656                 case LFUN_BOLD:
657                         flag.setOnOff(tc == "mathbf");
658                         break;
659                 case LFUN_SANS:
660                         flag.setOnOff(tc == "mathsf");
661                         break;
662                 case LFUN_EMPH:
663                         flag.setOnOff(tc == "mathcal");
664                         break;
665                 case LFUN_ROMAN:
666                         flag.setOnOff(tc == "mathrm");
667                         break;
668                 case LFUN_CODE:
669                         flag.setOnOff(tc == "mathtt");
670                         break;
671                 case LFUN_NOUN:
672                         flag.setOnOff(tc == "mathbb");
673                         break;
674                 case LFUN_DEFAULT:
675                         flag.setOnOff(tc == "mathnormal");
676                         break;
677                 default:
678                         break;
679                 }
680         }
681
682         // this one is difficult to get right. As a half-baked
683         // solution, we consider only the first action of the sequence
684         if (ev.action == LFUN_SEQUENCE) {
685                 // argument contains ';'-terminated commands
686                 flag = getStatus(lyxaction.LookupFunc(token(ev.argument, ';', 0)));
687         }
688
689         return flag;
690 }
691
692
693 void LyXFunc::dispatch(string const & s, bool verbose)
694 {
695         int const action = lyxaction.LookupFunc(s);
696
697         if (action == LFUN_UNKNOWN_ACTION) {
698 #if USE_BOOST_FORMAT
699 boost::format fmt(_("Unknown function (%1$s)"));
700 fmt % s;
701 owner->message(fmt.str());
702 #else
703                 string const msg = string(_("Unknown function ("))
704                         + s + ')';
705                 owner->message(msg);
706 #endif
707                 return;
708         }
709
710         dispatch(action, verbose);
711 }
712
713
714 void LyXFunc::dispatch(int ac, bool verbose)
715 {
716         dispatch(lyxaction.retrieveActionArg(ac), verbose);
717 }
718
719
720
721 void LyXFunc::dispatch(FuncRequest const & ev, bool verbose)
722 {
723         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: action[" << ev.action
724                               <<"] arg[" << ev.argument << ']' << endl;
725
726         // we have not done anything wrong yet.
727         errorstat = false;
728         dispatch_buffer.erase();
729
730 #ifdef NEW_DISPATCHER
731         // We try do call the most specific dispatcher first:
732         //  1. the lockinginset's dispatch
733         //  2. the bufferview's dispatch
734         //  3. the lyxview's dispatch
735 #endif
736
737         selection_possible = false;
738
739         if (view()->available())
740                 view()->hideCursor();
741
742         string argument = ev.argument;
743         kb_action action = ev.action;
744
745         // We cannot use this function here
746         if (getStatus(ev).disabled()) {
747                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
748                        << lyxaction.getActionName(action)
749                        << " [" << action << "] is disabled at this location"
750                        << endl;
751                 setErrorMessage(getStatusMessage());
752                 goto exit_with_message;
753         }
754
755         if (view()->available() && view()->theLockingInset()) {
756                 Inset::RESULT result;
757                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
758                                      (!keyseq.deleted())))
759                 {
760                         UpdatableInset * inset = view()->theLockingInset();
761 #if 1
762                         int inset_x;
763                         int dummy_y;
764                         inset->getCursorPos(view(), inset_x, dummy_y);
765 #endif
766                         if ((action == LFUN_UNKNOWN_ACTION)
767                             && argument.empty()) {
768                                 argument = encoded_last_key;
769                         }
770                         // Undo/Redo is a bit tricky for insets.
771                         if (action == LFUN_UNDO) {
772                                 view()->undo();
773                                 goto exit_with_message;
774                         } else if (action == LFUN_REDO) {
775                                 view()->redo();
776                                 goto exit_with_message;
777                         } else if (((result=inset->
778                                      // Hand-over to inset's own dispatch:
779                                      localDispatch(FuncRequest(view(), action, argument))) ==
780                                     DISPATCHED) ||
781                                    (result == DISPATCHED_NOUPDATE))
782                                 goto exit_with_message;
783                                         // If UNDISPATCHED, just soldier on
784                         else if (result == FINISHED) {
785                                 goto exit_with_message;
786                                 // We do not need special RTL handling here:
787                                 // FINISHED means that the cursor should be
788                                 // one position after the inset.
789                         } else if (result == FINISHED_RIGHT) {
790                                 TEXT()->cursorRight(view());
791                                 moveCursorUpdate(true, false);
792                                 owner->view_state_changed();
793                                 goto exit_with_message;
794                         } else if (result == FINISHED_UP) {
795                                 if (TEXT()->cursor.irow()->previous()) {
796 #if 1
797                                         TEXT()->setCursorFromCoordinates(
798                                                 view(), TEXT()->cursor.ix() + inset_x,
799                                                 TEXT()->cursor.iy() -
800                                                 TEXT()->cursor.irow()->baseline() - 1);
801                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
802 #else
803                                         TEXT()->cursorUp(view());
804 #endif
805                                         moveCursorUpdate(true, false);
806                                         owner->view_state_changed();
807                                 } else {
808                                         view()->update(TEXT(), BufferView::SELECT|BufferView::FITCUR);
809                                 }
810                                 goto exit_with_message;
811                         } else if (result == FINISHED_DOWN) {
812                                 if (TEXT()->cursor.irow()->next()) {
813 #if 1
814                                         TEXT()->setCursorFromCoordinates(
815                                                 view(), TEXT()->cursor.ix() + inset_x,
816                                                 TEXT()->cursor.iy() -
817                                                 TEXT()->cursor.irow()->baseline() +
818                                                 TEXT()->cursor.irow()->height() + 1);
819                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
820 #else
821                                         TEXT()->cursorDown(view());
822 #endif
823                                 } else {
824                                         TEXT()->cursorRight(view());
825                                 }
826                                 moveCursorUpdate(true, false);
827                                 owner->view_state_changed();
828                                 goto exit_with_message;
829                         }
830 #warning I am not sure this is still right, please have a look! (Jug 20020417)
831                         else { // result == UNDISPATCHED
832                                 //setMessage(N_("Text mode"));
833                                 switch (action) {
834                                 case LFUN_UNKNOWN_ACTION:
835                                 case LFUN_BREAKPARAGRAPH:
836                                 case LFUN_BREAKLINE:
837                                         TEXT()->cursorRight(view());
838                                         view()->switchKeyMap();
839                                         owner->view_state_changed();
840                                         break;
841                                 case LFUN_RIGHT:
842                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
843                                                 TEXT()->cursorRight(view());
844                                                 moveCursorUpdate(true, false);
845                                                 owner->view_state_changed();
846                                         }
847                                         goto exit_with_message;
848                                 case LFUN_LEFT:
849                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
850                                                 TEXT()->cursorRight(view());
851                                                 moveCursorUpdate(true, false);
852                                                 owner->view_state_changed();
853                                         }
854                                         goto exit_with_message;
855                                 case LFUN_DOWN:
856                                         if (TEXT()->cursor.row()->next())
857                                                 TEXT()->cursorDown(view());
858                                         else
859                                                 TEXT()->cursorRight(view());
860                                         moveCursorUpdate(true, false);
861                                         owner->view_state_changed();
862                                         goto exit_with_message;
863                                 default:
864                                         break;
865                                 }
866                         }
867                 }
868         }
869
870         switch (action) {
871
872         case LFUN_ESCAPE:
873         {
874                 if (!view()->available()) break;
875                 // this function should be used always [asierra060396]
876                 UpdatableInset * tli =
877                         view()->theLockingInset();
878                 if (tli) {
879                         UpdatableInset * lock = tli->getLockingInset();
880
881                         if (tli == lock) {
882                                 view()->unlockInset(tli);
883                                 TEXT()->cursorRight(view());
884                                 moveCursorUpdate(true, false);
885                                 owner->view_state_changed();
886                         } else {
887                                 tli->unlockInsetInInset(view(),
888                                                         lock,
889                                                         true);
890                         }
891                         finishUndo();
892                         // Tell the paragraph dialog that we changed paragraph
893                         owner->getDialogs().updateParagraph();
894                 }
895         }
896         break;
897
898                 // --- Misc -------------------------------------------
899         case LFUN_WORDFINDFORWARD  :
900         case LFUN_WORDFINDBACKWARD : {
901                 static string last_search;
902                 string searched_string;
903
904                 if (!argument.empty()) {
905                         last_search = argument;
906                         searched_string = argument;
907                 } else {
908                         searched_string = last_search;
909                 }
910                 bool fw = (action == LFUN_WORDFINDFORWARD);
911                 if (!searched_string.empty()) {
912                         lyxfind::LyXFind(view(), searched_string, fw);
913                 }
914 //              view()->showCursor();
915         }
916         break;
917
918         case LFUN_PREFIX:
919         {
920                 if (view()->available() && !view()->theLockingInset()) {
921                         view()->update(TEXT(),
922                                               BufferView::SELECT|BufferView::FITCUR);
923                 }
924                 owner->message(keyseq.printOptions());
925         }
926         break;
927
928         // --- Misc -------------------------------------------
929         case LFUN_EXEC_COMMAND:
930                 owner->focus_command_buffer();
931                 break;
932
933         case LFUN_CANCEL:                   // RVDK_PATCH_5
934                 keyseq.reset();
935                 meta_fake_bit = key_modifier::none;
936                 if (view()->available())
937                         // cancel any selection
938                         dispatch(LFUN_MARK_OFF);
939                 setMessage(N_("Cancel"));
940                 break;
941
942         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
943         {
944                 meta_fake_bit = key_modifier::alt;
945                 setMessage(keyseq.print());
946         }
947         break;
948
949         case LFUN_READ_ONLY_TOGGLE:
950                 if (owner->buffer()->lyxvc.inUse()) {
951                         owner->buffer()->lyxvc.toggleReadOnly();
952                 } else {
953                         owner->buffer()->setReadonly(
954                                 !owner->buffer()->isReadonly());
955                 }
956                 break;
957
958         case LFUN_CENTER: // this is center and redraw.
959                 view()->center();
960                 break;
961
962                 // --- Menus -----------------------------------------------
963         case LFUN_MENUNEW:
964                 menuNew(argument, false);
965                 break;
966
967         case LFUN_MENUNEWTMPLT:
968                 menuNew(argument, true);
969                 break;
970
971         case LFUN_CLOSEBUFFER:
972                 closeBuffer();
973                 break;
974
975         case LFUN_MENUWRITE:
976                 if (!owner->buffer()->isUnnamed()) {
977                         ostringstream s1;
978 #if USE_BOOST_FORMAT
979                         s1 << boost::format(_("Saving document %1$s..."))
980                            % MakeDisplayPath(owner->buffer()->fileName());
981 #else
982                         s1 << _("Saving document ")
983                            << MakeDisplayPath(owner->buffer()->fileName())
984                            << _("...");
985 #endif
986                         owner->message(STRCONV(s1.str()));
987                         MenuWrite(view(), owner->buffer());
988                         s1 << _(" done.");
989                         owner->message(STRCONV(s1.str()));
990                 } else
991                         WriteAs(view(), owner->buffer());
992                 break;
993
994         case LFUN_WRITEAS:
995                 WriteAs(view(), owner->buffer(), argument);
996                 break;
997
998         case LFUN_MENURELOAD:
999                 reloadBuffer();
1000                 break;
1001
1002         case LFUN_UPDATE:
1003                 Exporter::Export(owner->buffer(), argument, true);
1004                 break;
1005
1006         case LFUN_PREVIEW:
1007                 Exporter::Preview(owner->buffer(), argument);
1008                 break;
1009
1010         case LFUN_BUILDPROG:
1011                 Exporter::Export(owner->buffer(), "program", true);
1012                 break;
1013
1014         case LFUN_RUNCHKTEX:
1015                 MenuRunChktex(owner->buffer());
1016                 break;
1017
1018         case LFUN_MENUPRINT:
1019                 owner->getDialogs().showPrint();
1020                 break;
1021
1022         case LFUN_EXPORT:
1023                 if (argument == "custom")
1024                         owner->getDialogs().showSendto();
1025                 else
1026                         Exporter::Export(owner->buffer(), argument, false);
1027                 break;
1028
1029         case LFUN_IMPORT:
1030                 doImport(argument);
1031                 break;
1032
1033         case LFUN_QUIT:
1034                 QuitLyX();
1035                 break;
1036
1037         case LFUN_TOCVIEW:
1038         {
1039                 InsetCommandParams p("tableofcontents");
1040                 string const data = InsetCommandMailer::params2string("toc", p);
1041                 owner->getDialogs().show("toc", data, 0);
1042                 break;
1043         }
1044
1045         case LFUN_AUTOSAVE:
1046                 AutoSave(view());
1047                 break;
1048
1049         case LFUN_UNDO:
1050                 view()->undo();
1051                 break;
1052
1053         case LFUN_REDO:
1054                 view()->redo();
1055                 break;
1056
1057         case LFUN_MENUSEARCH:
1058                 owner->getDialogs().showSearch();
1059                 break;
1060
1061         case LFUN_REMOVEERRORS:
1062                 if (view()->removeAutoInsets()) {
1063 #warning repaint() or update() or nothing ?
1064                         view()->repaint();
1065                         view()->fitCursor();
1066                 }
1067                 break;
1068
1069         case LFUN_DEPTH_MIN:
1070                 changeDepth(view(), TEXT(false), -1);
1071                 break;
1072
1073         case LFUN_DEPTH_PLUS:
1074                 changeDepth(view(), TEXT(false), 1);
1075                 break;
1076
1077         case LFUN_FREE:
1078                 owner->getDialogs().setUserFreeFont();
1079                 break;
1080
1081         case LFUN_RECONFIGURE:
1082                 Reconfigure(view());
1083                 break;
1084
1085 #if 0
1086         case LFUN_FLOATSOPERATE:
1087                 if (argument == "openfoot")
1088                         view()->allFloats(1,0);
1089                 else if (argument == "closefoot")
1090                         view()->allFloats(0,0);
1091                 else if (argument == "openfig")
1092                         view()->allFloats(1,1);
1093                 else if (argument == "closefig")
1094                         view()->allFloats(0,1);
1095                 break;
1096 #else
1097 #ifdef WITH_WARNINGS
1098 //#warning Find another implementation here (or another lyxfunc)!
1099 #endif
1100 #endif
1101         case LFUN_HELP_ABOUTLYX:
1102                 owner->getDialogs().showAboutlyx();
1103                 break;
1104
1105         case LFUN_HELP_TEXINFO:
1106                 owner->getDialogs().showTexinfo();
1107                 break;
1108
1109         case LFUN_HELP_OPEN:
1110         {
1111                 string const arg = argument;
1112                 if (arg.empty()) {
1113                         setErrorMessage(N_("Missing argument"));
1114                         break;
1115                 }
1116                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1117                 if (fname.empty()) {
1118                         lyxerr << "LyX: unable to find documentation file `"
1119                                << arg << "'. Bad installation?" << endl;
1120                         break;
1121                 }
1122                 ostringstream str;
1123 #if USE_BOOST_FORMAT
1124                 str << boost::format(_("Opening help file %1$s..."))
1125                     % MakeDisplayPath(fname);
1126 #else
1127                 str << _("Opening help file ")
1128                     << MakeDisplayPath(fname) << _("...");
1129 #endif
1130                 owner->message(STRCONV(str.str()));
1131                 view()->buffer(bufferlist.loadLyXFile(fname, false));
1132                 break;
1133         }
1134
1135                 // --- version control -------------------------------
1136         case LFUN_VC_REGISTER:
1137         {
1138                 if (!owner->buffer()->lyxvc.inUse())
1139                         owner->buffer()->lyxvc.registrer();
1140         }
1141         break;
1142
1143         case LFUN_VC_CHECKIN:
1144         {
1145                 if (owner->buffer()->lyxvc.inUse()
1146                     && !owner->buffer()->isReadonly())
1147                         owner->buffer()->lyxvc.checkIn();
1148         }
1149         break;
1150
1151         case LFUN_VC_CHECKOUT:
1152         {
1153                 if (owner->buffer()->lyxvc.inUse()
1154                     && owner->buffer()->isReadonly())
1155                         owner->buffer()->lyxvc.checkOut();
1156         }
1157         break;
1158
1159         case LFUN_VC_REVERT:
1160         {
1161                 owner->buffer()->lyxvc.revert();
1162         }
1163         break;
1164
1165         case LFUN_VC_UNDO:
1166         {
1167                 owner->buffer()->lyxvc.undoLast();
1168         }
1169         break;
1170
1171         case LFUN_VC_HISTORY:
1172         {
1173                 owner->getDialogs().showVCLogFile();
1174                 break;
1175         }
1176
1177         // --- buffers ----------------------------------------
1178
1179         case LFUN_SWITCHBUFFER:
1180                 view()->buffer(bufferlist.getBuffer(argument));
1181                 break;
1182
1183         case LFUN_FILE_NEW:
1184         {
1185                 // servercmd: argument must be <file>:<template>
1186                 Buffer * tmpbuf = NewFile(argument);
1187                 if (tmpbuf)
1188                         view()->buffer(tmpbuf);
1189         }
1190         break;
1191
1192         case LFUN_FILE_OPEN:
1193                 open(argument);
1194                 break;
1195
1196         case LFUN_LATEX_LOG:
1197                 owner->getDialogs().showLogFile();
1198                 break;
1199
1200         case LFUN_LAYOUT_DOCUMENT:
1201                 owner->getDialogs().showDocument();
1202                 break;
1203
1204         case LFUN_LAYOUT_PARAGRAPH:
1205                 owner->getDialogs().showParagraph();
1206                 break;
1207
1208         case LFUN_LAYOUT_CHARACTER:
1209                 owner->getDialogs().showCharacter();
1210                 break;
1211
1212         case LFUN_LAYOUT_TABULAR:
1213             if (view()->theLockingInset()) {
1214                 if (view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1215                     InsetTabular * inset = static_cast<InsetTabular *>
1216                         (view()->theLockingInset());
1217                     inset->openLayoutDialog(view());
1218                 } else if (view()->theLockingInset()->
1219                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1220                     InsetTabular * inset = static_cast<InsetTabular *>(
1221                         view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1222                     inset->openLayoutDialog(view());
1223                 }
1224             }
1225             break;
1226
1227         case LFUN_LAYOUT_PREAMBLE:
1228                 owner->getDialogs().showPreamble();
1229                 break;
1230
1231         case LFUN_DROP_LAYOUTS_CHOICE:
1232                 owner->getToolbar().openLayoutList();
1233                 break;
1234
1235         case LFUN_MENU_OPEN_BY_NAME:
1236                 owner->getMenubar().openByName(argument);
1237                 break; // RVDK_PATCH_5
1238
1239         case LFUN_SPELLCHECK:
1240                 owner->getDialogs().showSpellchecker();
1241                 break;
1242
1243         // --- lyxserver commands ----------------------------
1244
1245
1246         case LFUN_GETNAME:
1247                 setMessage(owner->buffer()->fileName());
1248                 lyxerr[Debug::INFO] << "FNAME["
1249                                << owner->buffer()->fileName()
1250                                << "] " << endl;
1251                 break;
1252
1253         case LFUN_NOTIFY:
1254         {
1255                 dispatch_buffer = keyseq.print();
1256                 lyxserver->notifyClient(dispatch_buffer);
1257         }
1258         break;
1259
1260         case LFUN_GOTOFILEROW:
1261         {
1262                 string file_name;
1263                 int row;
1264                 istringstream istr(argument.c_str());
1265                 istr >> file_name >> row;
1266                 // Must replace extension of the file to be .lyx and get full path
1267                 string const s(ChangeExtension(file_name, ".lyx"));
1268
1269                 // Either change buffer or load the file
1270                 if (bufferlist.exists(s)) {
1271                         view()->buffer(bufferlist.getBuffer(s));
1272                 } else {
1273                         view()->buffer(bufferlist.loadLyXFile(s));
1274                 }
1275
1276                 view()->setCursorFromRow(row);
1277
1278                 view()->center();
1279                 // see BufferView_pimpl::center()
1280                 view()->updateScrollbar();
1281         }
1282         break;
1283
1284         case LFUN_GOTO_PARAGRAPH:
1285         {
1286                 istringstream istr(argument.c_str());
1287
1288                 int id;
1289                 istr >> id;
1290                 Paragraph * par = owner->buffer()->getParFromID(id);
1291                 if (par == 0) {
1292                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1293                                             << id << ']' << endl;
1294                         break;
1295                 } else {
1296                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1297                                             << " found." << endl;
1298                 }
1299
1300                 if (view()->theLockingInset())
1301                         view()->unlockInset(view()->theLockingInset());
1302                 if (par->inInset()) {
1303                         par->inInset()->edit(view());
1304                 }
1305                 // Set the cursor
1306                 view()->getLyXText()->setCursor(view(), par, 0);
1307                 view()->switchKeyMap();
1308                 owner->view_state_changed();
1309
1310                 view()->center();
1311                 // see BufferView_pimpl::center()
1312                 view()->updateScrollbar();
1313         }
1314         break;
1315
1316         case LFUN_APROPOS:
1317         case LFUN_GETTIP:
1318         {
1319                 int const qa = lyxaction.LookupFunc(argument);
1320                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1321         }
1322         break;
1323
1324         // --- insert characters ----------------------------------------
1325
1326         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1327         case LFUN_MATH_EXTERN:
1328         case LFUN_MATH_NUMBER:
1329         case LFUN_MATH_NONUMBER:
1330         case LFUN_MATH_LIMITS:
1331         {
1332                 setErrorMessage(N_("This is only allowed in math mode!"));
1333         }
1334         break;
1335
1336         // passthrough hat and underscore outside mathed:
1337         case LFUN_SUBSCRIPT:
1338                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1339                 break;
1340         case LFUN_SUPERSCRIPT:
1341                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1342                 break;
1343
1344         case LFUN_MATH_PANEL:
1345                 owner->getDialogs().showMathPanel();
1346                 break;
1347
1348         case LFUN_DIALOG_SHOW_NEW_INSET: {
1349                 string const & name = argument;
1350                 string data;
1351                 if (name == "bibitem" ||
1352                     name == "bibtex" ||
1353                     name == "index" ||
1354                     name == "ref" ||
1355                     name == "toc" ||
1356                     name == "url") {
1357                         InsetCommandParams p(name);
1358                         data = InsetCommandMailer::params2string(name, p);
1359                 } else if (name == "citation") {
1360                         InsetCommandParams p("cite");
1361                         data = InsetCommandMailer::params2string(name, p);
1362                 } else if (name == "ert") {
1363                         data = InsetERTMailer::params2string(name,
1364                                                              InsetERT::Open);
1365                 }
1366                 owner->getDialogs().show(name, data, 0);
1367         }
1368         break;
1369
1370         case LFUN_DIALOG_SHOW_NEXT_INSET: {
1371         }
1372         break;
1373
1374         case LFUN_DIALOG_UPDATE: {
1375                 string const & name = argument;
1376                 // Can only update a dialog connected to an existing inset
1377                 InsetBase * i = owner->getDialogs().getOpenInset(name);
1378                 if (!i)
1379                         break;
1380
1381                 if (name == "bibitem" ||
1382                     name == "bibtex" ||
1383                     name == "citation" ||
1384                     name == "index" ||
1385                     name == "ref" ||
1386                     name == "toc" ||
1387                     name == "url") {
1388                         InsetCommand * inset = dynamic_cast<InsetCommand *>(i);
1389                         if (!inset)
1390                                 break;
1391
1392                         InsetCommandMailer mailer(name, *inset);
1393                         mailer.updateDialog();
1394
1395                 } else if (name == "error") {
1396                         InsetError * inset = dynamic_cast<InsetError *>(i);
1397                         if (!inset)
1398                                 break;
1399
1400                         owner->getDialogs().update("error",
1401                                                    inset->getContents());
1402
1403                 } else if (name == "ert") {
1404                         InsetERT * inset = dynamic_cast<InsetERT *>(i);
1405                         if (!inset)
1406                                 break;
1407
1408                         InsetERTMailer mailer(*inset);
1409                         mailer.updateDialog();
1410                 }
1411         }
1412         break;
1413
1414         case LFUN_DIALOG_HIDE:
1415                 owner ->getDialogs().hide(argument);
1416                 break;
1417
1418         case LFUN_DIALOG_DISCONNECT_INSET:
1419                 owner->getDialogs().disconnect(argument);
1420                 break;
1421
1422         case LFUN_CHILDOPEN:
1423         {
1424                 string const filename =
1425                         MakeAbsPath(argument,
1426                                     owner->buffer()->filePath());
1427                 setMessage(N_("Opening child document ") +
1428                            MakeDisplayPath(filename) + "...");
1429                 view()->savePosition(0);
1430                 if (bufferlist.exists(filename))
1431                         view()->buffer(bufferlist.getBuffer(filename));
1432                 else
1433                         view()->buffer(bufferlist.loadLyXFile(filename));
1434         }
1435         break;
1436
1437         case LFUN_TOGGLECURSORFOLLOW:
1438                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1439                 break;
1440
1441         case LFUN_KMAP_OFF:
1442                 owner->getIntl().KeyMapOn(false);
1443                 break;
1444
1445         case LFUN_KMAP_PRIM:
1446                 owner->getIntl().KeyMapPrim();
1447                 break;
1448
1449         case LFUN_KMAP_SEC:
1450                 owner->getIntl().KeyMapSec();
1451                 break;
1452
1453         case LFUN_KMAP_TOGGLE:
1454                 owner->getIntl().ToggleKeyMap();
1455                 break;
1456
1457         case LFUN_SEQUENCE:
1458         {
1459                 // argument contains ';'-terminated commands
1460                 while (!argument.empty()) {
1461                         string first;
1462                         argument = split(argument, first, ';');
1463                         dispatch(first);
1464                 }
1465         }
1466         break;
1467
1468         case LFUN_DIALOG_PREFERENCES:
1469                 owner->getDialogs().showPreferences();
1470                 break;
1471
1472         case LFUN_SAVEPREFERENCES:
1473         {
1474                 Path p(user_lyxdir);
1475                 lyxrc.write("preferences");
1476         }
1477         break;
1478
1479         case LFUN_SCREEN_FONT_UPDATE:
1480         {
1481                 // handle the screen font changes.
1482                 lyxrc.set_font_norm_type();
1483                 lyx_gui::update_fonts();
1484                 // We also need to empty the textcache so that
1485                 // the buffer will be formatted correctly after
1486                 // a zoom change.
1487                 textcache.clear();
1488                 // Of course we should only do the resize and the textcache.clear
1489                 // if values really changed...but not very important right now. (Lgb)
1490                 // All visible buffers will need resize
1491                 view()->resize();
1492                 view()->repaint();
1493         }
1494         break;
1495
1496         case LFUN_SET_COLOR:
1497         {
1498                 string lyx_name;
1499                 string const x11_name = split(argument, lyx_name, ' ');
1500                 if (lyx_name.empty() || x11_name.empty()) {
1501                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1502                                                 " <x11_name>"));
1503                         break;
1504                         }
1505
1506                 bool const graphicsbg_changed =
1507                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1508                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1509
1510                 if (!lcolor.setColor(lyx_name, x11_name)) {
1511 #if USE_BOOST_FORMAT
1512                         setErrorMessage(
1513                                 boost::io::str(
1514                                         boost::format(
1515                                                 _("Set-color \"%1$s\" failed "
1516                                                   "- color is undefined or "
1517                                                   "may not be redefined"))
1518                                         % lyx_name));
1519 #else
1520                         setErrorMessage(_("Set-color ") + lyx_name
1521                                         + _(" failed - color is undefined"
1522                                             " or may not be redefined"));
1523 #endif
1524
1525                         break;
1526                 }
1527
1528                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1529
1530                 if (graphicsbg_changed) {
1531 #ifdef WITH_WARNINGS
1532 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1533 #endif
1534 #if 0
1535                         grfx::GCache & gc = grfx::GCache::get();
1536                         gc.changeDisplay(true);
1537 #endif
1538                 }
1539
1540                 view()->repaint();
1541                 break;
1542         }
1543
1544         case LFUN_MESSAGE:
1545                 owner->message(argument);
1546                 break;
1547
1548         case LFUN_FORKS_SHOW:
1549                 owner->getDialogs().showForks();
1550                 break;
1551
1552         case LFUN_FORKS_KILL:
1553         {
1554                 if (!isStrInt(argument))
1555                         break;
1556
1557                 pid_t const pid = strToInt(argument);
1558                 ForkedcallsController & fcc = ForkedcallsController::get();
1559                 fcc.kill(pid);
1560                 break;
1561         }
1562
1563         case LFUN_TOOLTIPS_TOGGLE:
1564                 owner->getDialogs().toggleTooltips();
1565                 break;
1566
1567         default:
1568                 // Then if it was none of the above
1569                 // Trying the BufferView::pimpl dispatch:
1570                 if (!view()->dispatch(ev))
1571                         lyxerr << "A truly unknown func ["
1572                                << lyxaction.getActionName(ev.action) << "]!"
1573                                << endl;
1574                 break;
1575         } // end of switch
1576
1577 exit_with_message:
1578         sendDispatchMessage(getMessage(), ev, verbose);
1579 }
1580
1581
1582 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1583 {
1584         owner->updateMenubar();
1585         owner->updateToolbar();
1586
1587         if (ev.action == LFUN_SELFINSERT || !verbose) {
1588                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1589                 if (!msg.empty())
1590                         owner->message(msg);
1591                 return;
1592         }
1593
1594         string dispatch_msg = msg;
1595         if (!dispatch_msg.empty())
1596                 dispatch_msg += ' ';
1597
1598         string comname = lyxaction.getActionName(ev.action);
1599
1600         int pseudoaction = ev.action;
1601         bool argsadded = false;
1602
1603         if (!ev.argument.empty()) {
1604                 // the pseudoaction is useful for the bindings
1605                 pseudoaction = lyxaction.searchActionArg(ev.action, ev.argument);
1606
1607                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
1608                         pseudoaction = ev.action;
1609                 } else {
1610                         comname += ' ' + ev.argument;
1611                         argsadded = true;
1612                 }
1613         }
1614
1615         string const shortcuts = toplevel_keymap->findbinding(pseudoaction);
1616
1617         if (!shortcuts.empty()) {
1618                 comname += ": " + shortcuts;
1619         } else if (!argsadded && !ev.argument.empty()) {
1620                 comname += ' ' + ev.argument;
1621         }
1622
1623         if (!comname.empty()) {
1624                 comname = rtrim(comname);
1625                 dispatch_msg += '(' + comname + ')';
1626         }
1627
1628         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1629         if (!dispatch_msg.empty())
1630                 owner->message(dispatch_msg);
1631 }
1632
1633
1634 void LyXFunc::setupLocalKeymap()
1635 {
1636         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1637         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1638 }
1639
1640
1641 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1642 {
1643         string initpath = lyxrc.document_path;
1644         string filename(name);
1645
1646         if (view()->available()) {
1647                 string const trypath = owner->buffer()->filePath();
1648                 // If directory is writeable, use this as default.
1649                 if (IsDirWriteable(trypath))
1650                         initpath = trypath;
1651         }
1652
1653         static int newfile_number;
1654
1655         if (filename.empty()) {
1656                 filename = AddName(lyxrc.document_path,
1657                             "newfile" + tostr(++newfile_number) + ".lyx");
1658                 FileInfo fi(filename);
1659                 while (bufferlist.exists(filename) || fi.readable()) {
1660                         ++newfile_number;
1661                         filename = AddName(lyxrc.document_path,
1662                                     "newfile" + tostr(newfile_number) +
1663                                     ".lyx");
1664                         fi.newFile(filename);
1665                 }
1666         }
1667
1668         // The template stuff
1669         string templname;
1670         if (fromTemplate) {
1671                 FileDialog fileDlg(_("Select template file"),
1672                         LFUN_SELECT_FILE_SYNC,
1673                         make_pair(string(_("Documents|#o#O")),
1674                                   string(lyxrc.document_path)),
1675                         make_pair(string(_("Templates|#T#t")),
1676                                   string(lyxrc.template_path)));
1677
1678                 FileDialog::Result result =
1679                         fileDlg.open(lyxrc.template_path,
1680                                        _("*.lyx| LyX Documents (*.lyx)"));
1681
1682                 if (result.first == FileDialog::Later)
1683                         return;
1684
1685                 string const fname = result.second;
1686
1687                 if (fname.empty())
1688                         return;
1689                 templname = fname;
1690         }
1691
1692         view()->buffer(bufferlist.newFile(filename, templname, !name.empty()));
1693 }
1694
1695
1696 void LyXFunc::open(string const & fname)
1697 {
1698         string initpath = lyxrc.document_path;
1699
1700         if (view()->available()) {
1701                 string const trypath = owner->buffer()->filePath();
1702                 // If directory is writeable, use this as default.
1703                 if (IsDirWriteable(trypath))
1704                         initpath = trypath;
1705         }
1706
1707         string filename;
1708
1709         if (fname.empty()) {
1710                 FileDialog fileDlg(_("Select document to open"),
1711                         LFUN_FILE_OPEN,
1712                         make_pair(string(_("Documents|#o#O")),
1713                                   string(lyxrc.document_path)),
1714                         make_pair(string(_("Examples|#E#e")),
1715                                   string(AddPath(system_lyxdir, "examples"))));
1716
1717                 FileDialog::Result result =
1718                         fileDlg.open(initpath,
1719                                        _("*.lyx| LyX Documents (*.lyx)"));
1720
1721                 if (result.first == FileDialog::Later)
1722                         return;
1723
1724                 filename = result.second;
1725
1726                 // check selected filename
1727                 if (filename.empty()) {
1728                         owner->message(_("Canceled."));
1729                         return;
1730                 }
1731         } else
1732                 filename = fname;
1733
1734         // get absolute path of file and add ".lyx" to the filename if
1735         // necessary
1736         string const fullpath = FileSearch(string(), filename, "lyx");
1737         if (!fullpath.empty()) {
1738                 filename = fullpath;
1739         }
1740
1741         string const disp_fn(MakeDisplayPath(filename));
1742
1743         // if the file doesn't exist, let the user create one
1744         FileInfo const f(filename, true);
1745         if (!f.exist()) {
1746                 if (!Alert::askQuestion(_("No such file"), disp_fn,
1747                         _("Start a new document with this filename ?"))) {
1748                         owner->message(_("Canceled."));
1749                         return;
1750                 }
1751                 // the user specifically chose this name. Believe them.
1752                 Buffer * buffer =  bufferlist.newFile(filename, "", true);
1753                 view()->buffer(buffer);
1754                 return;
1755         }
1756
1757         ostringstream str;
1758 #if USE_BOOST_FORMAT
1759         str << boost::format(_("Opening document %1$s...")) % disp_fn;
1760 #else
1761         str << _("Opening document ") << disp_fn << _("...");
1762 #endif
1763
1764         owner->message(STRCONV(str.str()));
1765
1766         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1767         ostringstream str2;
1768         if (openbuf) {
1769                 view()->buffer(openbuf);
1770 #if USE_BOOST_FORMAT
1771                 str2 << boost::format(_("Document %1$s opened.")) % disp_fn;
1772 #else
1773                 str2 << _("Document ") << disp_fn << _(" opened.");
1774 #endif
1775         } else {
1776 #if USE_BOOST_FORMAT
1777                 str2 << boost::format(_("Could not open document %1$s"))
1778                         % disp_fn;
1779 #else
1780                 str2 << _("Could not open document ") << disp_fn;
1781 #endif
1782         }
1783         owner->message(STRCONV(str2.str()));
1784 }
1785
1786
1787 void LyXFunc::doImport(string const & argument)
1788 {
1789         string format;
1790         string filename = split(argument, format, ' ');
1791
1792         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1793                             << " file: " << filename << endl;
1794
1795         // need user interaction
1796         if (filename.empty()) {
1797                 string initpath = lyxrc.document_path;
1798
1799                 if (view()->available()) {
1800                         string const trypath = owner->buffer()->filePath();
1801                         // If directory is writeable, use this as default.
1802                         if (IsDirWriteable(trypath))
1803                                 initpath = trypath;
1804                 }
1805
1806 #if USE_BOOST_FORMAT
1807                 boost::format fmt(_("Select %1$s file to import"));
1808                 fmt % formats.prettyName(format);
1809                 string const text = fmt.str();
1810 #else
1811                 string const text = _("Select ") + formats.prettyName(format)
1812                         + _(" file to import");;
1813 #endif
1814
1815                 FileDialog fileDlg(text,
1816                         LFUN_IMPORT,
1817                         make_pair(string(_("Documents|#o#O")),
1818                                   string(lyxrc.document_path)),
1819                         make_pair(string(_("Examples|#E#e")),
1820                                   string(AddPath(system_lyxdir, "examples"))));
1821
1822                 string const extension = "*." + formats.extension(format)
1823                         + "| " + formats.prettyName(format)
1824                         + " (*." + formats.extension(format) + ')';
1825
1826                 FileDialog::Result result = fileDlg.open(initpath,
1827                                                            extension);
1828
1829                 if (result.first == FileDialog::Later)
1830                         return;
1831
1832                 filename = result.second;
1833
1834                 // check selected filename
1835                 if (filename.empty())
1836                         owner->message(_("Canceled."));
1837         }
1838
1839         if (filename.empty())
1840                 return;
1841
1842         // get absolute path of file
1843         filename = MakeAbsPath(filename);
1844
1845         string const lyxfile = ChangeExtension(filename, ".lyx");
1846
1847         // Check if the document already is open
1848         if (lyxrc.use_gui && bufferlist.exists(lyxfile)) {
1849                 switch (Alert::askConfirmation(_("Document is already open:"),
1850                                         MakeDisplayPath(lyxfile, 50),
1851                                         _("Do you want to close that document now?\n"
1852                                           "('No' will just switch to the open version)")))
1853                         {
1854                         case 1:
1855                                 // If close is canceled, we cancel here too.
1856                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1857                                         return;
1858                                 break;
1859                         case 2:
1860                                 view()->buffer(bufferlist.getBuffer(lyxfile));
1861                                 return;
1862                         case 3:
1863                                 owner->message(_("Canceled."));
1864                                 return;
1865                         }
1866         }
1867
1868         // if the file exists already, and we didn't do
1869         // -i lyx thefile.lyx, warn
1870         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1871                 if (!Alert::askQuestion(_("A document by the name"),
1872                         MakeDisplayPath(lyxfile), _("already exists. Overwrite?"))) {
1873                         owner->message(_("Canceled."));
1874                         return;
1875                 }
1876         }
1877
1878         Importer::Import(owner, filename, format);
1879 }
1880
1881
1882 void LyXFunc::reloadBuffer()
1883 {
1884         string const fn = owner->buffer()->fileName();
1885         if (bufferlist.close(owner->buffer()))
1886                 view()->buffer(bufferlist.loadLyXFile(fn));
1887 }
1888
1889
1890 void LyXFunc::closeBuffer()
1891 {
1892         if (bufferlist.close(owner->buffer()) && !quitting) {
1893                 if (bufferlist.empty()) {
1894                         // need this otherwise SEGV may occur while trying to
1895                         // set variables that don't exist
1896                         // since there's no current buffer
1897                         owner->getDialogs().hideBufferDependent();
1898                 } else {
1899                         view()->buffer(bufferlist.first());
1900                 }
1901         }
1902 }
1903
1904
1905 // Each "owner" should have it's own message method. lyxview and
1906 // the minibuffer would use the minibuffer, but lyxserver would
1907 // send an ERROR signal to its client.  Alejandro 970603
1908 // This func is bit problematic when it comes to NLS, to make the
1909 // lyx servers client be language indepenent we must not translate
1910 // strings sent to this func.
1911 void LyXFunc::setErrorMessage(string const & m) const
1912 {
1913         dispatch_buffer = m;
1914         errorstat = true;
1915 }
1916
1917
1918 void LyXFunc::setMessage(string const & m) const
1919 {
1920         dispatch_buffer = m;
1921 }
1922
1923
1924 void LyXFunc::setStatusMessage(string const & m) const
1925 {
1926         status_buffer = m;
1927 }
1928
1929
1930 string const LyXFunc::view_status_message()
1931 {
1932         // When meta-fake key is pressed, show the key sequence so far + "M-".
1933         if (wasMetaKey()) {
1934                 return keyseq.print() + "M-";
1935         }
1936
1937         // Else, when a non-complete key sequence is pressed,
1938         // show the available options.
1939         if (keyseq.length() > 0 && !keyseq.deleted()) {
1940                 return keyseq.printOptions();
1941         }
1942
1943         if (!view()->available())
1944                 return _("Welcome to LyX!");
1945
1946         return currentState(view());
1947 }
1948
1949
1950 BufferView * LyXFunc::view() const
1951 {
1952         lyx::Assert(owner);
1953         return owner->view().get();
1954 }