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