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