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