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