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