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