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