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