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