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