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