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