]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
ws chanes only
[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_EXTERNAL:
523                 code = Inset::EXTERNAL_CODE;
524                 break;
525         case LFUN_INSET_MARGINAL:
526                 code = Inset::MARGIN_CODE;
527                 break;
528         case LFUN_INSET_MINIPAGE:
529                 code = Inset::MINIPAGE_CODE;
530                 break;
531         case LFUN_INSET_FLOAT:
532         case LFUN_INSET_WIDE_FLOAT:
533                 code = Inset::FLOAT_CODE;
534                 break;
535         case LFUN_INSET_WRAP:
536                 code = Inset::WRAP_CODE;
537                 break;
538         case LFUN_FLOAT_LIST:
539                 code = Inset::FLOAT_LIST_CODE;
540                 break;
541 #if 0
542         case LFUN_INSET_LIST:
543                 code = Inset::LIST_CODE;
544                 break;
545         case LFUN_INSET_THEOREM:
546                 code = Inset::THEOREM_CODE;
547                 break;
548 #endif
549         case LFUN_INSET_CAPTION:
550                 code = Inset::CAPTION_CODE;
551                 break;
552         case LFUN_INSERT_NOTE:
553                 code = Inset::NOTE_CODE;
554                 break;
555         case LFUN_INSERT_LABEL:
556                 code = Inset::LABEL_CODE;
557                 break;
558         case LFUN_INSET_OPTARG:
559                 code = Inset::OPTARG_CODE;
560                 break;
561         case LFUN_REF_INSERT:
562                 code = Inset::REF_CODE;
563                 break;
564         case LFUN_INDEX_INSERT:
565                 code = Inset::INDEX_CODE;
566                 break;
567         case LFUN_INDEX_PRINT:
568                 code = Inset::INDEX_PRINT_CODE;
569                 break;
570         case LFUN_CHILD_INSERT:
571                 code = Inset::INCLUDE_CODE;
572                 break;
573         case LFUN_TOC_INSERT:
574                 code = Inset::TOC_CODE;
575                 break;
576         case LFUN_PARENTINSERT:
577                 code = Inset::PARENT_CODE;
578                 break;
579         case LFUN_HTMLURL:
580         case LFUN_URL:
581         case LFUN_INSERT_URL:
582                 code = Inset::URL_CODE;
583                 break;
584         case LFUN_QUOTE:
585                 // always allow this, since we will inset a raw quote
586                 // if an inset is not allowed.
587                 break;
588         case LFUN_HYPHENATION:
589         case LFUN_LIGATURE_BREAK:
590         case LFUN_HFILL:
591         case LFUN_MENU_SEPARATOR:
592         case LFUN_LDOTS:
593         case LFUN_END_OF_SENTENCE:
594                 code = Inset::SPECIALCHAR_CODE;
595                 break;
596         case LFUN_PROTECTEDSPACE:
597                 // slight hack: we know this is allowed in math mode
598                 if (!mathcursor)
599                         code = Inset::SPECIALCHAR_CODE;
600                 break;
601         default:
602                 break;
603         }
604         if (code != Inset::NO_CODE && tli && !tli->insetAllowed(code))
605                 disable = true;
606
607         if (disable)
608                 flag.disabled(true);
609
610         // A few general toggles
611         switch (ev.action) {
612         case LFUN_TOOLTIPS_TOGGLE:
613                 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
614                 break;
615
616         case LFUN_READ_ONLY_TOGGLE:
617                 flag.setOnOff(buf->isReadonly());
618                 break;
619         case LFUN_APPENDIX:
620                 flag.setOnOff(TEXT(false)->cursor.par()->params().startOfAppendix());
621                 break;
622         case LFUN_SWITCHBUFFER:
623                 // toggle on the current buffer, but do not toggle off
624                 // the other ones (is that a good idea?)
625                 if (ev.argument == buf->fileName())
626                         flag.setOnOff(true);
627                 break;
628         case LFUN_TRACK_CHANGES:
629                 flag.setOnOff(buf->params.tracking_changes);
630                 break;
631         default:
632                 break;
633         }
634
635         // the font related toggles
636         if (!mathcursor) {
637                 LyXFont const & font = TEXT(false)->real_current_font;
638                 switch (ev.action) {
639                 case LFUN_EMPH:
640                         flag.setOnOff(font.emph() == LyXFont::ON);
641                         break;
642                 case LFUN_NOUN:
643                         flag.setOnOff(font.noun() == LyXFont::ON);
644                         break;
645                 case LFUN_BOLD:
646                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
647                         break;
648                 case LFUN_SANS:
649                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
650                         break;
651                 case LFUN_ROMAN:
652                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
653                         break;
654                 case LFUN_CODE:
655                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
656                         break;
657                 default:
658                         break;
659                 }
660         } else {
661                 string tc = mathcursor->getLastCode();
662                 switch (ev.action) {
663                 case LFUN_BOLD:
664                         flag.setOnOff(tc == "mathbf");
665                         break;
666                 case LFUN_SANS:
667                         flag.setOnOff(tc == "mathsf");
668                         break;
669                 case LFUN_EMPH:
670                         flag.setOnOff(tc == "mathcal");
671                         break;
672                 case LFUN_ROMAN:
673                         flag.setOnOff(tc == "mathrm");
674                         break;
675                 case LFUN_CODE:
676                         flag.setOnOff(tc == "mathtt");
677                         break;
678                 case LFUN_NOUN:
679                         flag.setOnOff(tc == "mathbb");
680                         break;
681                 case LFUN_DEFAULT:
682                         flag.setOnOff(tc == "mathnormal");
683                         break;
684                 default:
685                         break;
686                 }
687         }
688
689         // this one is difficult to get right. As a half-baked
690         // solution, we consider only the first action of the sequence
691         if (ev.action == LFUN_SEQUENCE) {
692                 // argument contains ';'-terminated commands
693                 flag = getStatus(lyxaction.LookupFunc(token(ev.argument, ';', 0)));
694         }
695
696         return flag;
697 }
698
699
700 void LyXFunc::dispatch(string const & s, bool verbose)
701 {
702         int const action = lyxaction.LookupFunc(s);
703
704         if (action == LFUN_UNKNOWN_ACTION) {
705 #if USE_BOOST_FORMAT
706 boost::format fmt(_("Unknown function (%1$s)"));
707 fmt % s;
708 owner->message(fmt.str());
709 #else
710                 string const msg = string(_("Unknown function ("))
711                         + s + ')';
712                 owner->message(msg);
713 #endif
714                 return;
715         }
716
717         dispatch(action, verbose);
718 }
719
720
721 void LyXFunc::dispatch(int ac, bool verbose)
722 {
723         dispatch(lyxaction.retrieveActionArg(ac), verbose);
724 }
725
726
727
728 void LyXFunc::dispatch(FuncRequest const & ev, bool verbose)
729 {
730         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: action[" << ev.action
731                               <<"] arg[" << ev.argument << ']' << endl;
732
733         // we have not done anything wrong yet.
734         errorstat = false;
735         dispatch_buffer.erase();
736
737 #ifdef NEW_DISPATCHER
738         // We try do call the most specific dispatcher first:
739         //  1. the lockinginset's dispatch
740         //  2. the bufferview's dispatch
741         //  3. the lyxview's dispatch
742 #endif
743
744         selection_possible = false;
745
746         if (view()->available())
747                 view()->hideCursor();
748
749         string argument = ev.argument;
750         kb_action action = ev.action;
751
752         // We cannot use this function here
753         if (getStatus(ev).disabled()) {
754                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
755                        << lyxaction.getActionName(action)
756                        << " [" << action << "] is disabled at this location"
757                        << endl;
758                 setErrorMessage(getStatusMessage());
759                 goto exit_with_message;
760         }
761
762         if (view()->available() && view()->theLockingInset()) {
763                 Inset::RESULT result;
764                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
765                                      (!keyseq.deleted())))
766                 {
767                         UpdatableInset * inset = view()->theLockingInset();
768 #if 1
769                         int inset_x;
770                         int dummy_y;
771                         inset->getCursorPos(view(), inset_x, dummy_y);
772 #endif
773                         if ((action == LFUN_UNKNOWN_ACTION)
774                             && argument.empty()) {
775                                 argument = encoded_last_key;
776                         }
777                         // Undo/Redo is a bit tricky for insets.
778                         if (action == LFUN_UNDO) {
779                                 view()->undo();
780                                 goto exit_with_message;
781                         } else if (action == LFUN_REDO) {
782                                 view()->redo();
783                                 goto exit_with_message;
784                         } else if (((result=inset->
785                                      // Hand-over to inset's own dispatch:
786                                      localDispatch(FuncRequest(view(), action, argument))) ==
787                                     DISPATCHED) ||
788                                    (result == DISPATCHED_NOUPDATE))
789                                 goto exit_with_message;
790                                         // If UNDISPATCHED, just soldier on
791                         else if (result == FINISHED) {
792                                 goto exit_with_message;
793                                 // We do not need special RTL handling here:
794                                 // FINISHED means that the cursor should be
795                                 // one position after the inset.
796                         } else if (result == FINISHED_RIGHT) {
797                                 TEXT()->cursorRight(view());
798                                 moveCursorUpdate(true, false);
799                                 owner->view_state_changed();
800                                 goto exit_with_message;
801                         } else if (result == FINISHED_UP) {
802                                 if (TEXT()->cursor.irow()->previous()) {
803 #if 1
804                                         TEXT()->setCursorFromCoordinates(
805                                                 view(), TEXT()->cursor.ix() + inset_x,
806                                                 TEXT()->cursor.iy() -
807                                                 TEXT()->cursor.irow()->baseline() - 1);
808                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
809 #else
810                                         TEXT()->cursorUp(view());
811 #endif
812                                         moveCursorUpdate(true, false);
813                                         owner->view_state_changed();
814                                 } else {
815                                         view()->update(TEXT(), BufferView::SELECT|BufferView::FITCUR);
816                                 }
817                                 goto exit_with_message;
818                         } else if (result == FINISHED_DOWN) {
819                                 if (TEXT()->cursor.irow()->next()) {
820 #if 1
821                                         TEXT()->setCursorFromCoordinates(
822                                                 view(), TEXT()->cursor.ix() + inset_x,
823                                                 TEXT()->cursor.iy() -
824                                                 TEXT()->cursor.irow()->baseline() +
825                                                 TEXT()->cursor.irow()->height() + 1);
826                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
827 #else
828                                         TEXT()->cursorDown(view());
829 #endif
830                                 } else {
831                                         TEXT()->cursorRight(view());
832                                 }
833                                 moveCursorUpdate(true, false);
834                                 owner->view_state_changed();
835                                 goto exit_with_message;
836                         }
837 #warning I am not sure this is still right, please have a look! (Jug 20020417)
838                         else { // result == UNDISPATCHED
839                                 //setMessage(N_("Text mode"));
840                                 switch (action) {
841                                 case LFUN_UNKNOWN_ACTION:
842                                 case LFUN_BREAKPARAGRAPH:
843                                 case LFUN_BREAKLINE:
844                                         TEXT()->cursorRight(view());
845                                         view()->switchKeyMap();
846                                         owner->view_state_changed();
847                                         break;
848                                 case LFUN_RIGHT:
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_LEFT:
856                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
857                                                 TEXT()->cursorRight(view());
858                                                 moveCursorUpdate(true, false);
859                                                 owner->view_state_changed();
860                                         }
861                                         goto exit_with_message;
862                                 case LFUN_DOWN:
863                                         if (TEXT()->cursor.row()->next())
864                                                 TEXT()->cursorDown(view());
865                                         else
866                                                 TEXT()->cursorRight(view());
867                                         moveCursorUpdate(true, false);
868                                         owner->view_state_changed();
869                                         goto exit_with_message;
870                                 default:
871                                         break;
872                                 }
873                         }
874                 }
875         }
876
877         switch (action) {
878
879         case LFUN_ESCAPE:
880         {
881                 if (!view()->available()) break;
882                 // this function should be used always [asierra060396]
883                 UpdatableInset * tli =
884                         view()->theLockingInset();
885                 if (tli) {
886                         UpdatableInset * lock = tli->getLockingInset();
887
888                         if (tli == lock) {
889                                 view()->unlockInset(tli);
890                                 TEXT()->cursorRight(view());
891                                 moveCursorUpdate(true, false);
892                                 owner->view_state_changed();
893                         } else {
894                                 tli->unlockInsetInInset(view(),
895                                                         lock,
896                                                         true);
897                         }
898                         finishUndo();
899                         // Tell the paragraph dialog that we changed paragraph
900                         owner->getDialogs().updateParagraph();
901                 }
902         }
903         break;
904
905                 // --- Misc -------------------------------------------
906         case LFUN_WORDFINDFORWARD  :
907         case LFUN_WORDFINDBACKWARD : {
908                 static string last_search;
909                 string searched_string;
910
911                 if (!argument.empty()) {
912                         last_search = argument;
913                         searched_string = argument;
914                 } else {
915                         searched_string = last_search;
916                 }
917                 bool fw = (action == LFUN_WORDFINDFORWARD);
918                 if (!searched_string.empty()) {
919                         lyxfind::LyXFind(view(), searched_string, fw);
920                 }
921 //              view()->showCursor();
922         }
923         break;
924
925         case LFUN_PREFIX:
926         {
927                 if (view()->available() && !view()->theLockingInset()) {
928                         view()->update(TEXT(),
929                                               BufferView::SELECT|BufferView::FITCUR);
930                 }
931                 owner->message(keyseq.printOptions());
932         }
933         break;
934
935         // --- Misc -------------------------------------------
936         case LFUN_EXEC_COMMAND:
937                 owner->focus_command_buffer();
938                 break;
939
940         case LFUN_CANCEL:                   // RVDK_PATCH_5
941                 keyseq.reset();
942                 meta_fake_bit = key_modifier::none;
943                 if (view()->available())
944                         // cancel any selection
945                         dispatch(LFUN_MARK_OFF);
946                 setMessage(N_("Cancel"));
947                 break;
948
949         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
950         {
951                 meta_fake_bit = key_modifier::alt;
952                 setMessage(keyseq.print());
953         }
954         break;
955
956         case LFUN_READ_ONLY_TOGGLE:
957                 if (owner->buffer()->lyxvc.inUse()) {
958                         owner->buffer()->lyxvc.toggleReadOnly();
959                 } else {
960                         owner->buffer()->setReadonly(
961                                 !owner->buffer()->isReadonly());
962                 }
963                 break;
964
965         case LFUN_CENTER: // this is center and redraw.
966                 view()->center();
967                 break;
968
969                 // --- Menus -----------------------------------------------
970         case LFUN_MENUNEW:
971                 menuNew(argument, false);
972                 break;
973
974         case LFUN_MENUNEWTMPLT:
975                 menuNew(argument, true);
976                 break;
977
978         case LFUN_CLOSEBUFFER:
979                 closeBuffer();
980                 break;
981
982         case LFUN_MENUWRITE:
983                 if (!owner->buffer()->isUnnamed()) {
984                         ostringstream s1;
985 #if USE_BOOST_FORMAT
986                         s1 << boost::format(_("Saving document %1$s..."))
987                            % MakeDisplayPath(owner->buffer()->fileName());
988 #else
989                         s1 << _("Saving document ")
990                            << MakeDisplayPath(owner->buffer()->fileName())
991                            << _("...");
992 #endif
993                         owner->message(STRCONV(s1.str()));
994                         MenuWrite(view(), owner->buffer());
995                         s1 << _(" done.");
996                         owner->message(STRCONV(s1.str()));
997                 } else
998                         WriteAs(view(), owner->buffer());
999                 break;
1000
1001         case LFUN_WRITEAS:
1002                 WriteAs(view(), owner->buffer(), argument);
1003                 break;
1004
1005         case LFUN_MENURELOAD:
1006                 reloadBuffer();
1007                 break;
1008
1009         case LFUN_UPDATE:
1010                 Exporter::Export(owner->buffer(), argument, true);
1011                 break;
1012
1013         case LFUN_PREVIEW:
1014                 Exporter::Preview(owner->buffer(), argument);
1015                 break;
1016
1017         case LFUN_BUILDPROG:
1018                 Exporter::Export(owner->buffer(), "program", true);
1019                 break;
1020
1021         case LFUN_RUNCHKTEX:
1022                 MenuRunChktex(owner->buffer());
1023                 break;
1024
1025         case LFUN_MENUPRINT:
1026                 owner->getDialogs().showPrint();
1027                 break;
1028
1029         case LFUN_EXPORT:
1030                 if (argument == "custom")
1031                         owner->getDialogs().showSendto();
1032                 else
1033                         Exporter::Export(owner->buffer(), argument, false);
1034                 break;
1035
1036         case LFUN_IMPORT:
1037                 doImport(argument);
1038                 break;
1039
1040         case LFUN_QUIT:
1041                 QuitLyX();
1042                 break;
1043
1044         case LFUN_TOCVIEW:
1045         {
1046                 InsetCommandParams p("tableofcontents");
1047                 string const data = InsetCommandMailer::params2string("toc", p);
1048                 owner->getDialogs().show("toc", data, 0);
1049                 break;
1050         }
1051
1052         case LFUN_AUTOSAVE:
1053                 AutoSave(view());
1054                 break;
1055
1056         case LFUN_UNDO:
1057                 view()->undo();
1058                 break;
1059
1060         case LFUN_REDO:
1061                 view()->redo();
1062                 break;
1063
1064         case LFUN_MENUSEARCH:
1065                 owner->getDialogs().showSearch();
1066                 break;
1067
1068         case LFUN_REMOVEERRORS:
1069                 if (view()->removeAutoInsets()) {
1070 #warning repaint() or update() or nothing ?
1071                         view()->repaint();
1072                         view()->fitCursor();
1073                 }
1074                 break;
1075
1076         case LFUN_DEPTH_MIN:
1077                 changeDepth(view(), TEXT(false), -1);
1078                 break;
1079
1080         case LFUN_DEPTH_PLUS:
1081                 changeDepth(view(), TEXT(false), 1);
1082                 break;
1083
1084         case LFUN_FREE:
1085                 owner->getDialogs().setUserFreeFont();
1086                 break;
1087
1088         case LFUN_RECONFIGURE:
1089                 Reconfigure(view());
1090                 break;
1091
1092 #if 0
1093         case LFUN_FLOATSOPERATE:
1094                 if (argument == "openfoot")
1095                         view()->allFloats(1,0);
1096                 else if (argument == "closefoot")
1097                         view()->allFloats(0,0);
1098                 else if (argument == "openfig")
1099                         view()->allFloats(1,1);
1100                 else if (argument == "closefig")
1101                         view()->allFloats(0,1);
1102                 break;
1103 #else
1104 #ifdef WITH_WARNINGS
1105 //#warning Find another implementation here (or another lyxfunc)!
1106 #endif
1107 #endif
1108         case LFUN_HELP_ABOUTLYX:
1109                 owner->getDialogs().showAboutlyx();
1110                 break;
1111
1112         case LFUN_HELP_TEXINFO:
1113                 owner->getDialogs().showTexinfo();
1114                 break;
1115
1116         case LFUN_HELP_OPEN:
1117         {
1118                 string const arg = argument;
1119                 if (arg.empty()) {
1120                         setErrorMessage(N_("Missing argument"));
1121                         break;
1122                 }
1123                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1124                 if (fname.empty()) {
1125                         lyxerr << "LyX: unable to find documentation file `"
1126                                << arg << "'. Bad installation?" << endl;
1127                         break;
1128                 }
1129                 ostringstream str;
1130 #if USE_BOOST_FORMAT
1131                 str << boost::format(_("Opening help file %1$s..."))
1132                     % MakeDisplayPath(fname);
1133 #else
1134                 str << _("Opening help file ")
1135                     << MakeDisplayPath(fname) << _("...");
1136 #endif
1137                 owner->message(STRCONV(str.str()));
1138                 view()->buffer(bufferlist.loadLyXFile(fname, false));
1139                 break;
1140         }
1141
1142                 // --- version control -------------------------------
1143         case LFUN_VC_REGISTER:
1144         {
1145                 if (!owner->buffer()->lyxvc.inUse())
1146                         owner->buffer()->lyxvc.registrer();
1147         }
1148         break;
1149
1150         case LFUN_VC_CHECKIN:
1151         {
1152                 if (owner->buffer()->lyxvc.inUse()
1153                     && !owner->buffer()->isReadonly())
1154                         owner->buffer()->lyxvc.checkIn();
1155         }
1156         break;
1157
1158         case LFUN_VC_CHECKOUT:
1159         {
1160                 if (owner->buffer()->lyxvc.inUse()
1161                     && owner->buffer()->isReadonly())
1162                         owner->buffer()->lyxvc.checkOut();
1163         }
1164         break;
1165
1166         case LFUN_VC_REVERT:
1167         {
1168                 owner->buffer()->lyxvc.revert();
1169         }
1170         break;
1171
1172         case LFUN_VC_UNDO:
1173         {
1174                 owner->buffer()->lyxvc.undoLast();
1175         }
1176         break;
1177
1178         case LFUN_VC_HISTORY:
1179         {
1180                 owner->getDialogs().showVCLogFile();
1181                 break;
1182         }
1183
1184         // --- buffers ----------------------------------------
1185
1186         case LFUN_SWITCHBUFFER:
1187                 view()->buffer(bufferlist.getBuffer(argument));
1188                 break;
1189
1190         case LFUN_FILE_NEW:
1191         {
1192                 // servercmd: argument must be <file>:<template>
1193                 Buffer * tmpbuf = NewFile(argument);
1194                 if (tmpbuf)
1195                         view()->buffer(tmpbuf);
1196         }
1197         break;
1198
1199         case LFUN_FILE_OPEN:
1200                 open(argument);
1201                 break;
1202
1203         case LFUN_LATEX_LOG:
1204                 owner->getDialogs().showLogFile();
1205                 break;
1206
1207         case LFUN_LAYOUT_DOCUMENT:
1208                 owner->getDialogs().showDocument();
1209                 break;
1210
1211         case LFUN_LAYOUT_PARAGRAPH:
1212                 owner->getDialogs().showParagraph();
1213                 break;
1214
1215         case LFUN_LAYOUT_CHARACTER:
1216                 owner->getDialogs().showCharacter();
1217                 break;
1218
1219         case LFUN_LAYOUT_TABULAR:
1220             if (view()->theLockingInset()) {
1221                 if (view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1222                     InsetTabular * inset = static_cast<InsetTabular *>
1223                         (view()->theLockingInset());
1224                     inset->openLayoutDialog(view());
1225                 } else if (view()->theLockingInset()->
1226                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1227                     InsetTabular * inset = static_cast<InsetTabular *>(
1228                         view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1229                     inset->openLayoutDialog(view());
1230                 }
1231             }
1232             break;
1233
1234         case LFUN_LAYOUT_PREAMBLE:
1235                 owner->getDialogs().showPreamble();
1236                 break;
1237
1238         case LFUN_DROP_LAYOUTS_CHOICE:
1239                 owner->getToolbar().openLayoutList();
1240                 break;
1241
1242         case LFUN_MENU_OPEN_BY_NAME:
1243                 owner->getMenubar().openByName(argument);
1244                 break; // RVDK_PATCH_5
1245
1246         case LFUN_SPELLCHECK:
1247                 owner->getDialogs().showSpellchecker();
1248                 break;
1249
1250         // --- lyxserver commands ----------------------------
1251
1252
1253         case LFUN_GETNAME:
1254                 setMessage(owner->buffer()->fileName());
1255                 lyxerr[Debug::INFO] << "FNAME["
1256                                << owner->buffer()->fileName()
1257                                << "] " << endl;
1258                 break;
1259
1260         case LFUN_NOTIFY:
1261         {
1262                 dispatch_buffer = keyseq.print();
1263                 lyxserver->notifyClient(dispatch_buffer);
1264         }
1265         break;
1266
1267         case LFUN_GOTOFILEROW:
1268         {
1269                 string file_name;
1270                 int row;
1271                 istringstream istr(argument.c_str());
1272                 istr >> file_name >> row;
1273                 // Must replace extension of the file to be .lyx and get full path
1274                 string const s(ChangeExtension(file_name, ".lyx"));
1275
1276                 // Either change buffer or load the file
1277                 if (bufferlist.exists(s)) {
1278                         view()->buffer(bufferlist.getBuffer(s));
1279                 } else {
1280                         view()->buffer(bufferlist.loadLyXFile(s));
1281                 }
1282
1283                 view()->setCursorFromRow(row);
1284
1285                 view()->center();
1286                 // see BufferView_pimpl::center()
1287                 view()->updateScrollbar();
1288         }
1289         break;
1290
1291         case LFUN_GOTO_PARAGRAPH:
1292         {
1293                 istringstream istr(argument.c_str());
1294
1295                 int id;
1296                 istr >> id;
1297                 Paragraph * par = owner->buffer()->getParFromID(id);
1298                 if (par == 0) {
1299                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1300                                             << id << ']' << endl;
1301                         break;
1302                 } else {
1303                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1304                                             << " found." << endl;
1305                 }
1306
1307                 if (view()->theLockingInset())
1308                         view()->unlockInset(view()->theLockingInset());
1309                 if (par->inInset()) {
1310                         par->inInset()->edit(view());
1311                 }
1312                 // Set the cursor
1313                 view()->getLyXText()->setCursor(view(), par, 0);
1314                 view()->switchKeyMap();
1315                 owner->view_state_changed();
1316
1317                 view()->center();
1318                 // see BufferView_pimpl::center()
1319                 view()->updateScrollbar();
1320         }
1321         break;
1322
1323         case LFUN_APROPOS:
1324         case LFUN_GETTIP:
1325         {
1326                 int const qa = lyxaction.LookupFunc(argument);
1327                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1328         }
1329         break;
1330
1331         // --- insert characters ----------------------------------------
1332
1333         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1334         case LFUN_MATH_EXTERN:
1335         case LFUN_MATH_NUMBER:
1336         case LFUN_MATH_NONUMBER:
1337         case LFUN_MATH_LIMITS:
1338         {
1339                 setErrorMessage(N_("This is only allowed in math mode!"));
1340         }
1341         break;
1342
1343         // passthrough hat and underscore outside mathed:
1344         case LFUN_SUBSCRIPT:
1345                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1346                 break;
1347         case LFUN_SUPERSCRIPT:
1348                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1349                 break;
1350
1351         case LFUN_MATH_PANEL:
1352                 owner->getDialogs().showMathPanel();
1353                 break;
1354
1355         case LFUN_DIALOG_SHOW_NEW_INSET: {
1356                 string const & name = argument;
1357                 string data;
1358                 if (name == "bibitem" ||
1359                     name == "bibtex" ||
1360                     name == "index" ||
1361                     name == "ref" ||
1362                     name == "toc" ||
1363                     name == "url") {
1364                         InsetCommandParams p(name);
1365                         data = InsetCommandMailer::params2string(name, p);
1366                 } else if (name == "citation") {
1367                         InsetCommandParams p("cite");
1368                         data = InsetCommandMailer::params2string(name, p);
1369                 } else if (name == "ert") {
1370                         data = InsetERTMailer::params2string(name,
1371                                                              InsetERT::Open);
1372                 }
1373                 owner->getDialogs().show(name, data, 0);
1374         }
1375         break;
1376
1377         case LFUN_DIALOG_SHOW_NEXT_INSET: {
1378         }
1379         break;
1380
1381         case LFUN_DIALOG_UPDATE: {
1382                 string const & name = argument;
1383                 // Can only update a dialog connected to an existing inset
1384                 InsetBase * i = owner->getDialogs().getOpenInset(name);
1385                 if (!i)
1386                         break;
1387
1388                 if (name == "bibitem" ||
1389                     name == "bibtex" ||
1390                     name == "citation" ||
1391                     name == "index" ||
1392                     name == "ref" ||
1393                     name == "toc" ||
1394                     name == "url") {
1395                         InsetCommand * inset = dynamic_cast<InsetCommand *>(i);
1396                         if (!inset)
1397                                 break;
1398
1399                         InsetCommandMailer mailer(name, *inset);
1400                         mailer.updateDialog();
1401
1402                 } else if (name == "error") {
1403                         InsetError * inset = dynamic_cast<InsetError *>(i);
1404                         if (!inset)
1405                                 break;
1406
1407                         owner->getDialogs().update("error",
1408                                                    inset->getContents());
1409
1410                 } else if (name == "ert") {
1411                         InsetERT * inset = dynamic_cast<InsetERT *>(i);
1412                         if (!inset)
1413                                 break;
1414
1415                         InsetERTMailer mailer(*inset);
1416                         mailer.updateDialog();
1417                 }
1418         }
1419         break;
1420
1421         case LFUN_DIALOG_HIDE:
1422                 owner ->getDialogs().hide(argument);
1423                 break;
1424
1425         case LFUN_DIALOG_DISCONNECT_INSET:
1426                 owner->getDialogs().disconnect(argument);
1427                 break;
1428
1429         case LFUN_CHILDOPEN:
1430         {
1431                 string const filename =
1432                         MakeAbsPath(argument,
1433                                     owner->buffer()->filePath());
1434                 setMessage(N_("Opening child document ") +
1435                            MakeDisplayPath(filename) + "...");
1436                 view()->savePosition(0);
1437                 if (bufferlist.exists(filename))
1438                         view()->buffer(bufferlist.getBuffer(filename));
1439                 else
1440                         view()->buffer(bufferlist.loadLyXFile(filename));
1441         }
1442         break;
1443
1444         case LFUN_TOGGLECURSORFOLLOW:
1445                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1446                 break;
1447
1448         case LFUN_KMAP_OFF:
1449                 owner->getIntl().KeyMapOn(false);
1450                 break;
1451
1452         case LFUN_KMAP_PRIM:
1453                 owner->getIntl().KeyMapPrim();
1454                 break;
1455
1456         case LFUN_KMAP_SEC:
1457                 owner->getIntl().KeyMapSec();
1458                 break;
1459
1460         case LFUN_KMAP_TOGGLE:
1461                 owner->getIntl().ToggleKeyMap();
1462                 break;
1463
1464         case LFUN_SEQUENCE:
1465         {
1466                 // argument contains ';'-terminated commands
1467                 while (!argument.empty()) {
1468                         string first;
1469                         argument = split(argument, first, ';');
1470                         dispatch(first);
1471                 }
1472         }
1473         break;
1474
1475         case LFUN_DIALOG_PREFERENCES:
1476                 owner->getDialogs().showPreferences();
1477                 break;
1478
1479         case LFUN_SAVEPREFERENCES:
1480         {
1481                 Path p(user_lyxdir);
1482                 lyxrc.write("preferences");
1483         }
1484         break;
1485
1486         case LFUN_SCREEN_FONT_UPDATE:
1487         {
1488                 // handle the screen font changes.
1489                 lyxrc.set_font_norm_type();
1490                 lyx_gui::update_fonts();
1491                 // We also need to empty the textcache so that
1492                 // the buffer will be formatted correctly after
1493                 // a zoom change.
1494                 textcache.clear();
1495                 // Of course we should only do the resize and the textcache.clear
1496                 // if values really changed...but not very important right now. (Lgb)
1497                 // All visible buffers will need resize
1498                 view()->resize();
1499                 view()->repaint();
1500         }
1501         break;
1502
1503         case LFUN_SET_COLOR:
1504         {
1505                 string lyx_name;
1506                 string const x11_name = split(argument, lyx_name, ' ');
1507                 if (lyx_name.empty() || x11_name.empty()) {
1508                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1509                                                 " <x11_name>"));
1510                         break;
1511                         }
1512
1513                 bool const graphicsbg_changed =
1514                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1515                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1516
1517                 if (!lcolor.setColor(lyx_name, x11_name)) {
1518 #if USE_BOOST_FORMAT
1519                         setErrorMessage(
1520                                 boost::io::str(
1521                                         boost::format(
1522                                                 _("Set-color \"%1$s\" failed "
1523                                                   "- color is undefined or "
1524                                                   "may not be redefined"))
1525                                         % lyx_name));
1526 #else
1527                         setErrorMessage(_("Set-color ") + lyx_name
1528                                         + _(" failed - color is undefined"
1529                                             " or may not be redefined"));
1530 #endif
1531
1532                         break;
1533                 }
1534
1535                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1536
1537                 if (graphicsbg_changed) {
1538 #ifdef WITH_WARNINGS
1539 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1540 #endif
1541 #if 0
1542                         grfx::GCache & gc = grfx::GCache::get();
1543                         gc.changeDisplay(true);
1544 #endif
1545                 }
1546
1547                 view()->repaint();
1548                 break;
1549         }
1550
1551         case LFUN_MESSAGE:
1552                 owner->message(argument);
1553                 break;
1554
1555         case LFUN_FORKS_SHOW:
1556                 owner->getDialogs().showForks();
1557                 break;
1558
1559         case LFUN_FORKS_KILL:
1560         {
1561                 if (!isStrInt(argument))
1562                         break;
1563
1564                 pid_t const pid = strToInt(argument);
1565                 ForkedcallsController & fcc = ForkedcallsController::get();
1566                 fcc.kill(pid);
1567                 break;
1568         }
1569
1570         case LFUN_TOOLTIPS_TOGGLE:
1571                 owner->getDialogs().toggleTooltips();
1572                 break;
1573
1574         default:
1575                 // Then if it was none of the above
1576                 // Trying the BufferView::pimpl dispatch:
1577                 if (!view()->dispatch(ev))
1578                         lyxerr << "A truly unknown func ["
1579                                << lyxaction.getActionName(ev.action) << "]!"
1580                                << endl;
1581                 break;
1582         } // end of switch
1583
1584 exit_with_message:
1585         sendDispatchMessage(getMessage(), ev, verbose);
1586 }
1587
1588
1589 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1590 {
1591         owner->updateMenubar();
1592         owner->updateToolbar();
1593
1594         if (ev.action == LFUN_SELFINSERT || !verbose) {
1595                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1596                 if (!msg.empty())
1597                         owner->message(msg);
1598                 return;
1599         }
1600
1601         string dispatch_msg = msg;
1602         if (!dispatch_msg.empty())
1603                 dispatch_msg += ' ';
1604
1605         string comname = lyxaction.getActionName(ev.action);
1606
1607         int pseudoaction = ev.action;
1608         bool argsadded = false;
1609
1610         if (!ev.argument.empty()) {
1611                 // the pseudoaction is useful for the bindings
1612                 pseudoaction = lyxaction.searchActionArg(ev.action, ev.argument);
1613
1614                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
1615                         pseudoaction = ev.action;
1616                 } else {
1617                         comname += ' ' + ev.argument;
1618                         argsadded = true;
1619                 }
1620         }
1621
1622         string const shortcuts = toplevel_keymap->findbinding(pseudoaction);
1623
1624         if (!shortcuts.empty()) {
1625                 comname += ": " + shortcuts;
1626         } else if (!argsadded && !ev.argument.empty()) {
1627                 comname += ' ' + ev.argument;
1628         }
1629
1630         if (!comname.empty()) {
1631                 comname = rtrim(comname);
1632                 dispatch_msg += '(' + comname + ')';
1633         }
1634
1635         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1636         if (!dispatch_msg.empty())
1637                 owner->message(dispatch_msg);
1638 }
1639
1640
1641 void LyXFunc::setupLocalKeymap()
1642 {
1643         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1644         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1645 }
1646
1647
1648 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1649 {
1650         string initpath = lyxrc.document_path;
1651         string filename(name);
1652
1653         if (view()->available()) {
1654                 string const trypath = owner->buffer()->filePath();
1655                 // If directory is writeable, use this as default.
1656                 if (IsDirWriteable(trypath))
1657                         initpath = trypath;
1658         }
1659
1660         static int newfile_number;
1661
1662         if (filename.empty()) {
1663                 filename = AddName(lyxrc.document_path,
1664                             "newfile" + tostr(++newfile_number) + ".lyx");
1665                 FileInfo fi(filename);
1666                 while (bufferlist.exists(filename) || fi.readable()) {
1667                         ++newfile_number;
1668                         filename = AddName(lyxrc.document_path,
1669                                     "newfile" + tostr(newfile_number) +
1670                                     ".lyx");
1671                         fi.newFile(filename);
1672                 }
1673         }
1674
1675         // The template stuff
1676         string templname;
1677         if (fromTemplate) {
1678                 FileDialog fileDlg(_("Select template file"),
1679                         LFUN_SELECT_FILE_SYNC,
1680                         make_pair(string(_("Documents|#o#O")),
1681                                   string(lyxrc.document_path)),
1682                         make_pair(string(_("Templates|#T#t")),
1683                                   string(lyxrc.template_path)));
1684
1685                 FileDialog::Result result =
1686                         fileDlg.open(lyxrc.template_path,
1687                                        _("*.lyx| LyX Documents (*.lyx)"));
1688
1689                 if (result.first == FileDialog::Later)
1690                         return;
1691
1692                 string const fname = result.second;
1693
1694                 if (fname.empty())
1695                         return;
1696                 templname = fname;
1697         }
1698
1699         view()->buffer(bufferlist.newFile(filename, templname, !name.empty()));
1700 }
1701
1702
1703 void LyXFunc::open(string const & fname)
1704 {
1705         string initpath = lyxrc.document_path;
1706
1707         if (view()->available()) {
1708                 string const trypath = owner->buffer()->filePath();
1709                 // If directory is writeable, use this as default.
1710                 if (IsDirWriteable(trypath))
1711                         initpath = trypath;
1712         }
1713
1714         string filename;
1715
1716         if (fname.empty()) {
1717                 FileDialog fileDlg(_("Select document to open"),
1718                         LFUN_FILE_OPEN,
1719                         make_pair(string(_("Documents|#o#O")),
1720                                   string(lyxrc.document_path)),
1721                         make_pair(string(_("Examples|#E#e")),
1722                                   string(AddPath(system_lyxdir, "examples"))));
1723
1724                 FileDialog::Result result =
1725                         fileDlg.open(initpath,
1726                                        _("*.lyx| LyX Documents (*.lyx)"));
1727
1728                 if (result.first == FileDialog::Later)
1729                         return;
1730
1731                 filename = result.second;
1732
1733                 // check selected filename
1734                 if (filename.empty()) {
1735                         owner->message(_("Canceled."));
1736                         return;
1737                 }
1738         } else
1739                 filename = fname;
1740
1741         // get absolute path of file and add ".lyx" to the filename if
1742         // necessary
1743         string const fullpath = FileSearch(string(), filename, "lyx");
1744         if (!fullpath.empty()) {
1745                 filename = fullpath;
1746         }
1747
1748         string const disp_fn(MakeDisplayPath(filename));
1749
1750         // if the file doesn't exist, let the user create one
1751         FileInfo const f(filename, true);
1752         if (!f.exist()) {
1753                 if (!Alert::askQuestion(_("No such file"), disp_fn,
1754                         _("Start a new document with this filename ?"))) {
1755                         owner->message(_("Canceled."));
1756                         return;
1757                 }
1758                 // the user specifically chose this name. Believe them.
1759                 Buffer * buffer =  bufferlist.newFile(filename, "", true);
1760                 view()->buffer(buffer);
1761                 return;
1762         }
1763
1764         ostringstream str;
1765 #if USE_BOOST_FORMAT
1766         str << boost::format(_("Opening document %1$s...")) % disp_fn;
1767 #else
1768         str << _("Opening document ") << disp_fn << _("...");
1769 #endif
1770
1771         owner->message(STRCONV(str.str()));
1772
1773         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1774         ostringstream str2;
1775         if (openbuf) {
1776                 view()->buffer(openbuf);
1777 #if USE_BOOST_FORMAT
1778                 str2 << boost::format(_("Document %1$s opened.")) % disp_fn;
1779 #else
1780                 str2 << _("Document ") << disp_fn << _(" opened.");
1781 #endif
1782         } else {
1783 #if USE_BOOST_FORMAT
1784                 str2 << boost::format(_("Could not open document %1$s"))
1785                         % disp_fn;
1786 #else
1787                 str2 << _("Could not open document ") << disp_fn;
1788 #endif
1789         }
1790         owner->message(STRCONV(str2.str()));
1791 }
1792
1793
1794 void LyXFunc::doImport(string const & argument)
1795 {
1796         string format;
1797         string filename = split(argument, format, ' ');
1798
1799         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1800                             << " file: " << filename << endl;
1801
1802         // need user interaction
1803         if (filename.empty()) {
1804                 string initpath = lyxrc.document_path;
1805
1806                 if (view()->available()) {
1807                         string const trypath = owner->buffer()->filePath();
1808                         // If directory is writeable, use this as default.
1809                         if (IsDirWriteable(trypath))
1810                                 initpath = trypath;
1811                 }
1812
1813 #if USE_BOOST_FORMAT
1814                 boost::format fmt(_("Select %1$s file to import"));
1815                 fmt % formats.prettyName(format);
1816                 string const text = fmt.str();
1817 #else
1818                 string const text = _("Select ") + formats.prettyName(format)
1819                         + _(" file to import");;
1820 #endif
1821
1822                 FileDialog fileDlg(text,
1823                         LFUN_IMPORT,
1824                         make_pair(string(_("Documents|#o#O")),
1825                                   string(lyxrc.document_path)),
1826                         make_pair(string(_("Examples|#E#e")),
1827                                   string(AddPath(system_lyxdir, "examples"))));
1828
1829                 string const extension = "*." + formats.extension(format)
1830                         + "| " + formats.prettyName(format)
1831                         + " (*." + formats.extension(format) + ')';
1832
1833                 FileDialog::Result result = fileDlg.open(initpath,
1834                                                            extension);
1835
1836                 if (result.first == FileDialog::Later)
1837                         return;
1838
1839                 filename = result.second;
1840
1841                 // check selected filename
1842                 if (filename.empty())
1843                         owner->message(_("Canceled."));
1844         }
1845
1846         if (filename.empty())
1847                 return;
1848
1849         // get absolute path of file
1850         filename = MakeAbsPath(filename);
1851
1852         string const lyxfile = ChangeExtension(filename, ".lyx");
1853
1854         // Check if the document already is open
1855         if (lyxrc.use_gui && bufferlist.exists(lyxfile)) {
1856                 switch (Alert::askConfirmation(_("Document is already open:"),
1857                                         MakeDisplayPath(lyxfile, 50),
1858                                         _("Do you want to close that document now?\n"
1859                                           "('No' will just switch to the open version)")))
1860                         {
1861                         case 1:
1862                                 // If close is canceled, we cancel here too.
1863                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1864                                         return;
1865                                 break;
1866                         case 2:
1867                                 view()->buffer(bufferlist.getBuffer(lyxfile));
1868                                 return;
1869                         case 3:
1870                                 owner->message(_("Canceled."));
1871                                 return;
1872                         }
1873         }
1874
1875         // if the file exists already, and we didn't do
1876         // -i lyx thefile.lyx, warn
1877         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1878                 if (!Alert::askQuestion(_("A document by the name"),
1879                         MakeDisplayPath(lyxfile), _("already exists. Overwrite?"))) {
1880                         owner->message(_("Canceled."));
1881                         return;
1882                 }
1883         }
1884
1885         Importer::Import(owner, filename, format);
1886 }
1887
1888
1889 void LyXFunc::reloadBuffer()
1890 {
1891         string const fn = owner->buffer()->fileName();
1892         if (bufferlist.close(owner->buffer()))
1893                 view()->buffer(bufferlist.loadLyXFile(fn));
1894 }
1895
1896
1897 void LyXFunc::closeBuffer()
1898 {
1899         if (bufferlist.close(owner->buffer()) && !quitting) {
1900                 if (bufferlist.empty()) {
1901                         // need this otherwise SEGV may occur while trying to
1902                         // set variables that don't exist
1903                         // since there's no current buffer
1904                         owner->getDialogs().hideBufferDependent();
1905                 } else {
1906                         view()->buffer(bufferlist.first());
1907                 }
1908         }
1909 }
1910
1911
1912 // Each "owner" should have it's own message method. lyxview and
1913 // the minibuffer would use the minibuffer, but lyxserver would
1914 // send an ERROR signal to its client.  Alejandro 970603
1915 // This func is bit problematic when it comes to NLS, to make the
1916 // lyx servers client be language indepenent we must not translate
1917 // strings sent to this func.
1918 void LyXFunc::setErrorMessage(string const & m) const
1919 {
1920         dispatch_buffer = m;
1921         errorstat = true;
1922 }
1923
1924
1925 void LyXFunc::setMessage(string const & m) const
1926 {
1927         dispatch_buffer = m;
1928 }
1929
1930
1931 void LyXFunc::setStatusMessage(string const & m) const
1932 {
1933         status_buffer = m;
1934 }
1935
1936
1937 string const LyXFunc::view_status_message()
1938 {
1939         // When meta-fake key is pressed, show the key sequence so far + "M-".
1940         if (wasMetaKey()) {
1941                 return keyseq.print() + "M-";
1942         }
1943
1944         // Else, when a non-complete key sequence is pressed,
1945         // show the available options.
1946         if (keyseq.length() > 0 && !keyseq.deleted()) {
1947                 return keyseq.printOptions();
1948         }
1949
1950         if (!view()->available())
1951                 return _("Welcome to LyX!");
1952
1953         return currentState(view());
1954 }
1955
1956
1957 BufferView * LyXFunc::view() const
1958 {
1959         lyx::Assert(owner);
1960         return owner->view().get();
1961 }