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