]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
9e10195da245307695af908d3f3f23d418447307
[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 #ifndef HAVE_LIBAIKSAURUS
336         case LFUN_THESAURUS_ENTRY:
337                 disable = true;
338                 break;
339 #endif
340         case LFUN_RUNCHKTEX:
341                 disable = lyxrc.chktex_command == "none";
342                 break;
343         case LFUN_BUILDPROG:
344                 disable = !Exporter::IsExportable(buf, "program");
345                 break;
346
347         case LFUN_LAYOUT_CHARACTER:
348                 disable = tli && tli->lyxCode() == Inset::ERT_CODE;
349                 break;
350
351         case LFUN_LAYOUT_TABULAR:
352                 disable = !tli
353                         || (tli->lyxCode() != Inset::TABULAR_CODE
354                             && !tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
355                 break;
356
357         case LFUN_LAYOUT:
358         case LFUN_LAYOUT_PARAGRAPH: {
359                 Inset * inset = TEXT(false)->cursor.par()->inInset();
360                 disable = inset && inset->forceDefaultParagraphs(inset);
361                 break;
362         }
363
364         case LFUN_TABULAR_FEATURE:
365                 disable = true;
366                 if (tli) {
367                         FuncStatus ret;
368                         //ret.disabled(true);
369                         if (tli->lyxCode() == Inset::TABULAR_CODE) {
370                                 ret = static_cast<InsetTabular *>(tli)
371                                         ->getStatus(ev.argument);
372                         } else if (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE)) {
373                                 ret = static_cast<InsetTabular *>
374                                         (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE))
375                                         ->getStatus(ev.argument);
376                         }
377                         flag |= ret;
378                         disable = false;
379                 } else {
380                         static InsetTabular inset(*owner->buffer(), 1, 1);
381                         FuncStatus ret;
382
383                         disable = true;
384                         ret = inset.getStatus(ev.argument);
385                         if (ret.onoff(true) || ret.onoff(false))
386                                 flag.setOnOff(false);
387                 }
388                 break;
389
390         case LFUN_VC_REGISTER:
391                 disable = buf->lyxvc.inUse();
392                 break;
393         case LFUN_VC_CHECKIN:
394                 disable = !buf->lyxvc.inUse() || buf->isReadonly();
395                 break;
396         case LFUN_VC_CHECKOUT:
397                 disable = !buf->lyxvc.inUse() || !buf->isReadonly();
398                 break;
399         case LFUN_VC_REVERT:
400         case LFUN_VC_UNDO:
401         case LFUN_VC_HISTORY:
402                 disable = !buf->lyxvc.inUse();
403                 break;
404         case LFUN_BOOKMARK_GOTO:
405                 disable =  !view()->
406                         isSavedPosition(strToUnsignedInt(ev.argument));
407                 break;
408         case LFUN_INSET_TOGGLE: {
409                 LyXText * lt = view()->getLyXText();
410                 disable = !(isEditableInset(lt->getInset())
411                             || (lt->inset_owner
412                                 && lt->inset_owner->owner()
413                                 && lt->inset_owner->owner()->isOpen()));
414                 break;
415         }
416         case LFUN_LATEX_LOG:
417                 disable = !IsFileReadable(buf->getLogName().second);
418                 break;
419         case LFUN_MATH_VALIGN:
420                 if (mathcursor && mathcursor->formula()->hullType() != "simple") {
421                         char align = mathcursor->valign();
422                         if (align == '\0') {
423                                 disable = true;
424                                 break;
425                         }
426                         if (ev.argument.empty()) {
427                                 flag.clear();
428                                 break;
429                         }
430                         if (!contains("tcb", ev.argument[0])) {
431                                 disable = true;
432                                 break;
433                         }
434                         flag.setOnOff(ev.argument[0] == align);
435                 } else
436                         disable = true;
437                 break;
438
439         case LFUN_MATH_HALIGN:
440                 if (mathcursor && mathcursor->formula()->hullType() != "simple") {
441                         char align = mathcursor->halign();
442                         if (align == '\0') {
443                                 disable = true;
444                                 break;
445                         }
446                         if (ev.argument.empty()) {
447                                 flag.clear();
448                                 break;
449                         }
450                         if (!contains("lcr", ev.argument[0])) {
451                                 disable = true;
452                                 break;
453                         }
454                         flag.setOnOff(ev.argument[0] == align);
455                 } else
456                         disable = true;
457                 break;
458
459         case LFUN_MATH_MUTATE:
460                 if (tli && (tli->lyxCode() == Inset::MATH_CODE))
461                         flag.setOnOff(mathcursor->formula()->hullType() == ev.argument);
462                 else
463                         disable = true;
464                 break;
465
466         // we just need to be in math mode to enable that
467         case LFUN_MATH_SIZE:
468         case LFUN_MATH_SPACE:
469         case LFUN_MATH_LIMITS:
470         case LFUN_MATH_NONUMBER:
471         case LFUN_MATH_NUMBER:
472         case LFUN_MATH_EXTERN:
473                 disable = !mathcursor;
474                 break;
475
476         // we need to be math mode and a math array for that
477         // Hack: halign produces non-zero result iff we are in a math array
478         case LFUN_MATH_ROW_INSERT:
479         case LFUN_MATH_ROW_DELETE:
480         case LFUN_MATH_COLUMN_INSERT:
481         case LFUN_MATH_COLUMN_DELETE:
482                 disable = !mathcursor || !mathcursor->halign() ||
483                         mathcursor->formula()->hullType() == "simple";
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_REF_INSERT:
539                 code = Inset::REF_CODE;
540                 break;
541         case LFUN_CITATION_CREATE:
542         case LFUN_CITATION_INSERT:
543                 code = Inset::CITE_CODE;
544                 break;
545         case LFUN_INSERT_BIBTEX:
546                 code = Inset::BIBTEX_CODE;
547                 break;
548         case LFUN_INDEX_INSERT:
549                 code = Inset::INDEX_CODE;
550                 break;
551         case LFUN_INDEX_PRINT:
552                 code = Inset::INDEX_PRINT_CODE;
553                 break;
554         case LFUN_CHILD_INSERT:
555                 code = Inset::INCLUDE_CODE;
556                 break;
557         case LFUN_TOC_INSERT:
558                 code = Inset::TOC_CODE;
559                 break;
560         case LFUN_PARENTINSERT:
561                 code = Inset::PARENT_CODE;
562                 break;
563         case LFUN_HTMLURL:
564         case LFUN_URL:
565         case LFUN_INSERT_URL:
566                 code = Inset::URL_CODE;
567                 break;
568         case LFUN_QUOTE:
569                 // always allow this, since we will inset a raw quote
570                 // if an inset is not allowed.
571                 break;
572         case LFUN_HYPHENATION:
573         case LFUN_LIGATURE_BREAK:
574         case LFUN_HFILL:
575         case LFUN_MENU_SEPARATOR:
576         case LFUN_LDOTS:
577         case LFUN_END_OF_SENTENCE:
578                 code = Inset::SPECIALCHAR_CODE;
579                 break;
580         case LFUN_PROTECTEDSPACE:
581                 // slight hack: we know this is allowed in math mode
582                 if (!mathcursor)
583                         code = Inset::SPECIALCHAR_CODE;
584                 break;
585         default:
586                 break;
587         }
588         if (code != Inset::NO_CODE && tli && !tli->insetAllowed(code)) {
589                 disable = true;
590         }
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                 string const msg = string(_("Unknown function ("))
688                         + s + ")";
689                 owner->message(msg);
690                 return;
691         }
692
693         dispatch(action, verbose);
694 }
695
696
697 void LyXFunc::dispatch(int ac, bool verbose)
698 {
699         dispatch(lyxaction.retrieveActionArg(ac), verbose);
700 }
701
702
703
704 void LyXFunc::dispatch(FuncRequest const & ev, bool verbose)
705 {
706         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: action[" << ev.action
707                               <<"] arg[" << ev.argument << "]" << endl;
708
709         // we have not done anything wrong yet.
710         errorstat = false;
711         dispatch_buffer.erase();
712
713 #ifdef NEW_DISPATCHER
714         // We try do call the most specific dispatcher first:
715         //  1. the lockinginset's dispatch
716         //  2. the bufferview's dispatch
717         //  3. the lyxview's dispatch
718 #endif
719
720         selection_possible = false;
721
722         if (view()->available())
723                 view()->hideCursor();
724
725         string argument = ev.argument;
726         kb_action action = ev.action;
727
728         // We cannot use this function here
729         if (getStatus(ev).disabled()) {
730                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
731                        << lyxaction.getActionName(action)
732                        << " [" << action << "] is disabled at this location"
733                        << endl;
734                 setErrorMessage(getStatusMessage());
735                 goto exit_with_message;
736         }
737
738         if (view()->available() && view()->theLockingInset()) {
739                 UpdatableInset::RESULT result;
740                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
741                                      (!keyseq.deleted())))
742                 {
743                         UpdatableInset * inset = view()->theLockingInset();
744 #if 1
745                         int inset_x;
746                         int dummy_y;
747                         inset->getCursorPos(view(), inset_x, dummy_y);
748 #endif
749                         if ((action == LFUN_UNKNOWN_ACTION)
750                             && argument.empty()) {
751                                 argument = keyseq.getLastKeyEncoded();
752                         }
753                         // Undo/Redo is a bit tricky for insets.
754                         if (action == LFUN_UNDO) {
755                                 view()->menuUndo();
756                                 goto exit_with_message;
757                         } else if (action == LFUN_REDO) {
758                                 view()->menuRedo();
759                                 goto exit_with_message;
760                         } else if (((result=inset->
761                                      // Hand-over to inset's own dispatch:
762                                      localDispatch(FuncRequest(view(), action, argument))) ==
763                                     UpdatableInset::DISPATCHED) ||
764                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
765                                 goto exit_with_message;
766                                         // If UNDISPATCHED, just soldier on
767                         else if (result == UpdatableInset::FINISHED) {
768                                 goto exit_with_message;
769                                 // We do not need special RTL handling here:
770                                 // FINISHED means that the cursor should be
771                                 // one position after the inset.
772                         } else if (result == UpdatableInset::FINISHED_RIGHT) {
773                                 TEXT()->cursorRight(view());
774                                 moveCursorUpdate(true, false);
775                                 owner->view_state_changed();
776                                 goto exit_with_message;
777                         } else if (result == UpdatableInset::FINISHED_UP) {
778                                 if (TEXT()->cursor.irow()->previous()) {
779 #if 1
780                                         TEXT()->setCursorFromCoordinates(
781                                                 view(), TEXT()->cursor.ix() + inset_x,
782                                                 TEXT()->cursor.iy() -
783                                                 TEXT()->cursor.irow()->baseline() - 1);
784                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
785 #else
786                                         TEXT()->cursorUp(view());
787 #endif
788                                         moveCursorUpdate(true, false);
789                                         owner->view_state_changed();
790                                 } else {
791                                         view()->update(TEXT(), BufferView::SELECT|BufferView::FITCUR);
792                                 }
793                                 goto exit_with_message;
794                         } else if (result == UpdatableInset::FINISHED_DOWN) {
795                                 if (TEXT()->cursor.irow()->next()) {
796 #if 1
797                                         TEXT()->setCursorFromCoordinates(
798                                                 view(), TEXT()->cursor.ix() + inset_x,
799                                                 TEXT()->cursor.iy() -
800                                                 TEXT()->cursor.irow()->baseline() +
801                                                 TEXT()->cursor.irow()->height() + 1);
802                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
803 #else
804                                         TEXT()->cursorDown(view());
805 #endif
806                                 } else {
807                                         TEXT()->cursorRight(view());
808                                 }
809                                 moveCursorUpdate(true, false);
810                                 owner->view_state_changed();
811                                 goto exit_with_message;
812                         }
813 #warning I am not sure this is still right, please have a look! (Jug 20020417)
814                         else { // result == UNDISPATCHED
815                                 //setMessage(N_("Text mode"));
816                                 switch (action) {
817                                 case LFUN_UNKNOWN_ACTION:
818                                 case LFUN_BREAKPARAGRAPH:
819                                 case LFUN_BREAKLINE:
820                                         TEXT()->cursorRight(view());
821                                         view()->switchKeyMap();
822                                         owner->view_state_changed();
823                                         break;
824                                 case LFUN_RIGHT:
825                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
826                                                 TEXT()->cursorRight(view());
827                                                 moveCursorUpdate(true, false);
828                                                 owner->view_state_changed();
829                                         }
830                                         goto exit_with_message;
831                                 case LFUN_LEFT:
832                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
833                                                 TEXT()->cursorRight(view());
834                                                 moveCursorUpdate(true, false);
835                                                 owner->view_state_changed();
836                                         }
837                                         goto exit_with_message;
838                                 case LFUN_DOWN:
839                                         if (TEXT()->cursor.row()->next())
840                                                 TEXT()->cursorDown(view());
841                                         else
842                                                 TEXT()->cursorRight(view());
843                                         moveCursorUpdate(true, false);
844                                         owner->view_state_changed();
845                                         goto exit_with_message;
846                                 default:
847                                         break;
848                                 }
849                         }
850                 }
851         }
852
853         switch (action) {
854
855         case LFUN_ESCAPE:
856         {
857                 if (!view()->available()) break;
858                 // this function should be used always [asierra060396]
859                 UpdatableInset * tli =
860                         view()->theLockingInset();
861                 if (tli) {
862                         UpdatableInset * lock = tli->getLockingInset();
863
864                         if (tli == lock) {
865                                 view()->unlockInset(tli);
866                                 TEXT()->cursorRight(view());
867                                 moveCursorUpdate(true, false);
868                                 owner->view_state_changed();
869                         } else {
870                                 tli->unlockInsetInInset(view(),
871                                                         lock,
872                                                         true);
873                         }
874                         finishUndo();
875                         // Tell the paragraph dialog that we changed paragraph
876                         owner->getDialogs().updateParagraph();
877                 }
878         }
879         break;
880
881                 // --- Misc -------------------------------------------
882         case LFUN_WORDFINDFORWARD  :
883         case LFUN_WORDFINDBACKWARD : {
884                 static string last_search;
885                 string searched_string;
886
887                 if (!argument.empty()) {
888                         last_search = argument;
889                         searched_string = argument;
890                 } else {
891                         searched_string = last_search;
892                 }
893                 bool fw = (action == LFUN_WORDFINDBACKWARD);
894                 if (!searched_string.empty()) {
895                         lyxfind::LyXFind(view(), searched_string, fw);
896                 }
897 //              view()->showCursor();
898         }
899         break;
900
901         case LFUN_PREFIX:
902         {
903                 if (view()->available() && !view()->theLockingInset()) {
904                         view()->update(TEXT(),
905                                               BufferView::SELECT|BufferView::FITCUR);
906                 }
907                 owner->message(keyseq.printOptions());
908         }
909         break;
910
911         // --- Misc -------------------------------------------
912         case LFUN_EXEC_COMMAND:
913                 owner->focus_command_buffer();
914                 break;
915
916         case LFUN_CANCEL:                   // RVDK_PATCH_5
917                 keyseq.reset();
918                 meta_fake_bit = key_modifier::none;
919                 if (view()->available())
920                         // cancel any selection
921                         dispatch(LFUN_MARK_OFF);
922                 setMessage(N_("Cancel"));
923                 break;
924
925         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
926         {
927                 meta_fake_bit = key_modifier::alt;
928                 setMessage(keyseq.print());
929         }
930         break;
931
932         case LFUN_READ_ONLY_TOGGLE:
933                 if (owner->buffer()->lyxvc.inUse()) {
934                         owner->buffer()->lyxvc.toggleReadOnly();
935                 } else {
936                         owner->buffer()->setReadonly(
937                                 !owner->buffer()->isReadonly());
938                 }
939                 break;
940
941         case LFUN_CENTER: // this is center and redraw.
942                 view()->center();
943                 break;
944
945                 // --- Menus -----------------------------------------------
946         case LFUN_MENUNEW:
947                 menuNew(argument, false);
948                 break;
949
950         case LFUN_MENUNEWTMPLT:
951                 menuNew(argument, true);
952                 break;
953
954         case LFUN_CLOSEBUFFER:
955                 closeBuffer();
956                 break;
957
958         case LFUN_MENUWRITE:
959                 if (!owner->buffer()->isUnnamed()) {
960                         ostringstream s1;
961                         s1 << _("Saving document") << ' '
962                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
963                         owner->message(s1.str().c_str());
964                         MenuWrite(view(), owner->buffer());
965                         s1 << _(" done.");
966                         owner->message(s1.str().c_str());
967                 } else
968                         WriteAs(view(), owner->buffer());
969                 break;
970
971         case LFUN_WRITEAS:
972                 WriteAs(view(), owner->buffer(), argument);
973                 break;
974
975         case LFUN_MENURELOAD:
976                 reloadBuffer();
977                 break;
978
979         case LFUN_UPDATE:
980                 Exporter::Export(owner->buffer(), argument, true);
981                 break;
982
983         case LFUN_PREVIEW:
984                 Exporter::Preview(owner->buffer(), argument);
985                 break;
986
987         case LFUN_BUILDPROG:
988                 Exporter::Export(owner->buffer(), "program", true);
989                 break;
990
991         case LFUN_RUNCHKTEX:
992                 MenuRunChktex(owner->buffer());
993                 break;
994
995         case LFUN_MENUPRINT:
996                 owner->getDialogs().showPrint();
997                 break;
998
999         case LFUN_EXPORT:
1000                 if (argument == "custom")
1001                         owner->getDialogs().showSendto();
1002                 else
1003                         Exporter::Export(owner->buffer(), argument, false);
1004                 break;
1005
1006         case LFUN_IMPORT:
1007                 doImport(argument);
1008                 break;
1009
1010         case LFUN_QUIT:
1011                 QuitLyX();
1012                 break;
1013
1014         case LFUN_TOCVIEW:
1015 #if 0
1016         case LFUN_LOFVIEW:
1017         case LFUN_LOTVIEW:
1018         case LFUN_LOAVIEW:
1019 #endif
1020         {
1021                 InsetCommandParams p;
1022
1023 #if 0
1024                 if (action == LFUN_TOCVIEW)
1025 #endif
1026                         p.setCmdName("tableofcontents");
1027 #if 0
1028                 else if (action == LFUN_LOAVIEW)
1029                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1030                 else if (action == LFUN_LOFVIEW)
1031                         p.setCmdName("listoffigures");
1032                 else
1033                         p.setCmdName("listoftables");
1034 #endif
1035                 owner->getDialogs().createTOC(p.getAsString());
1036                 break;
1037         }
1038
1039         case LFUN_AUTOSAVE:
1040                 AutoSave(view());
1041                 break;
1042
1043         case LFUN_UNDO:
1044                 view()->menuUndo();
1045                 break;
1046
1047         case LFUN_REDO:
1048                 view()->menuRedo();
1049                 break;
1050
1051         case LFUN_MENUSEARCH:
1052                 owner->getDialogs().showSearch();
1053                 break;
1054
1055         case LFUN_REMOVEERRORS:
1056                 if (view()->removeAutoInsets()) {
1057 #warning repaint() or update() or nothing ?
1058                         view()->repaint();
1059                         view()->fitCursor();
1060                 }
1061                 break;
1062
1063         case LFUN_DEPTH_MIN:
1064                 changeDepth(view(), TEXT(false), -1);
1065                 break;
1066
1067         case LFUN_DEPTH_PLUS:
1068                 changeDepth(view(), TEXT(false), 1);
1069                 break;
1070
1071         case LFUN_FREE:
1072                 owner->getDialogs().setUserFreeFont();
1073                 break;
1074
1075         case LFUN_RECONFIGURE:
1076                 Reconfigure(view());
1077                 break;
1078
1079 #if 0
1080         case LFUN_FLOATSOPERATE:
1081                 if (argument == "openfoot")
1082                         view()->allFloats(1,0);
1083                 else if (argument == "closefoot")
1084                         view()->allFloats(0,0);
1085                 else if (argument == "openfig")
1086                         view()->allFloats(1,1);
1087                 else if (argument == "closefig")
1088                         view()->allFloats(0,1);
1089                 break;
1090 #else
1091 #ifdef WITH_WARNINGS
1092 //#warning Find another implementation here (or another lyxfunc)!
1093 #endif
1094 #endif
1095         case LFUN_HELP_ABOUTLYX:
1096                 owner->getDialogs().showAboutlyx();
1097                 break;
1098
1099         case LFUN_HELP_TEXINFO:
1100                 owner->getDialogs().showTexinfo();
1101                 break;
1102
1103         case LFUN_HELP_OPEN:
1104         {
1105                 string const arg = argument;
1106                 if (arg.empty()) {
1107                         setErrorMessage(N_("Missing argument"));
1108                         break;
1109                 }
1110                 owner->prohibitInput();
1111                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1112                 if (fname.empty()) {
1113                         lyxerr << "LyX: unable to find documentation file `"
1114                                << arg << "'. Bad installation?" << endl;
1115                         owner->allowInput();
1116                         break;
1117                 }
1118                 ostringstream str;
1119                 str << _("Opening help file") << ' '
1120                     << MakeDisplayPath(fname) << "...";
1121                 owner->message(str.str().c_str());
1122                 view()->buffer(bufferlist.loadLyXFile(fname, false));
1123                 owner->allowInput();
1124                 break;
1125         }
1126
1127                 // --- version control -------------------------------
1128         case LFUN_VC_REGISTER:
1129         {
1130                 if (!owner->buffer()->lyxvc.inUse())
1131                         owner->buffer()->lyxvc.registrer();
1132         }
1133         break;
1134
1135         case LFUN_VC_CHECKIN:
1136         {
1137                 if (owner->buffer()->lyxvc.inUse()
1138                     && !owner->buffer()->isReadonly())
1139                         owner->buffer()->lyxvc.checkIn();
1140         }
1141         break;
1142
1143         case LFUN_VC_CHECKOUT:
1144         {
1145                 if (owner->buffer()->lyxvc.inUse()
1146                     && owner->buffer()->isReadonly())
1147                         owner->buffer()->lyxvc.checkOut();
1148         }
1149         break;
1150
1151         case LFUN_VC_REVERT:
1152         {
1153                 owner->buffer()->lyxvc.revert();
1154         }
1155         break;
1156
1157         case LFUN_VC_UNDO:
1158         {
1159                 owner->buffer()->lyxvc.undoLast();
1160         }
1161         break;
1162
1163         case LFUN_VC_HISTORY:
1164         {
1165                 owner->getDialogs().showVCLogFile();
1166                 break;
1167         }
1168
1169         // --- buffers ----------------------------------------
1170
1171         case LFUN_SWITCHBUFFER:
1172                 view()->buffer(bufferlist.getBuffer(argument));
1173                 break;
1174
1175         case LFUN_FILE_NEW:
1176         {
1177                 // servercmd: argument must be <file>:<template>
1178                 Buffer * tmpbuf = NewFile(argument);
1179                 if (tmpbuf)
1180                         view()->buffer(tmpbuf);
1181         }
1182         break;
1183
1184         case LFUN_FILE_OPEN:
1185                 open(argument);
1186                 break;
1187
1188         case LFUN_LATEX_LOG:
1189                 owner->getDialogs().showLogFile();
1190                 break;
1191
1192         case LFUN_LAYOUT_DOCUMENT:
1193                 owner->getDialogs().showDocument();
1194                 break;
1195
1196         case LFUN_LAYOUT_PARAGRAPH:
1197                 owner->getDialogs().showParagraph();
1198                 break;
1199
1200         case LFUN_LAYOUT_CHARACTER:
1201                 owner->getDialogs().showCharacter();
1202                 break;
1203
1204         case LFUN_LAYOUT_TABULAR:
1205             if (view()->theLockingInset()) {
1206                 if (view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1207                     InsetTabular * inset = static_cast<InsetTabular *>
1208                         (view()->theLockingInset());
1209                     inset->openLayoutDialog(view());
1210                 } else if (view()->theLockingInset()->
1211                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1212                     InsetTabular * inset = static_cast<InsetTabular *>(
1213                         view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1214                     inset->openLayoutDialog(view());
1215                 }
1216             }
1217             break;
1218
1219         case LFUN_LAYOUT_PREAMBLE:
1220                 owner->getDialogs().showPreamble();
1221                 break;
1222
1223         case LFUN_DROP_LAYOUTS_CHOICE:
1224                 owner->getToolbar().openLayoutList();
1225                 break;
1226
1227         case LFUN_MENU_OPEN_BY_NAME:
1228                 owner->getMenubar().openByName(argument);
1229                 break; // RVDK_PATCH_5
1230
1231         case LFUN_SPELLCHECK:
1232                 owner->getDialogs().showSpellchecker();
1233                 break;
1234
1235         // --- lyxserver commands ----------------------------
1236
1237
1238         case LFUN_GETNAME:
1239                 setMessage(owner->buffer()->fileName());
1240                 lyxerr[Debug::INFO] << "FNAME["
1241                                << owner->buffer()->fileName()
1242                                << "] " << endl;
1243                 break;
1244
1245         case LFUN_NOTIFY:
1246         {
1247                 dispatch_buffer = keyseq.print();
1248                 lyxserver->notifyClient(dispatch_buffer);
1249         }
1250         break;
1251
1252         case LFUN_GOTOFILEROW:
1253         {
1254                 string file_name;
1255                 int row;
1256                 istringstream istr(argument.c_str());
1257                 istr >> file_name >> row;
1258                 // Must replace extension of the file to be .lyx and get full path
1259                 string const s(ChangeExtension(file_name, ".lyx"));
1260
1261                 // Either change buffer or load the file
1262                 if (bufferlist.exists(s)) {
1263                         view()->buffer(bufferlist.getBuffer(s));
1264                 } else {
1265                         view()->buffer(bufferlist.loadLyXFile(s));
1266                 }
1267
1268                 view()->setCursorFromRow(row);
1269
1270                 view()->center();
1271                 // see BufferView_pimpl::center()
1272                 view()->updateScrollbar();
1273         }
1274         break;
1275
1276         case LFUN_GOTO_PARAGRAPH:
1277         {
1278                 istringstream istr(argument.c_str());
1279
1280                 int id;
1281                 istr >> id;
1282                 Paragraph * par = owner->buffer()->getParFromID(id);
1283                 if (par == 0) {
1284                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1285                                             << id << "]" << endl;
1286                         break;
1287                 } else {
1288                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1289                                             << " found." << endl;
1290                 }
1291
1292                 if (view()->theLockingInset())
1293                         view()->unlockInset(view()->theLockingInset());
1294                 if (par->inInset()) {
1295                         par->inInset()->edit(view());
1296                 }
1297                 // Set the cursor
1298                 view()->getLyXText()->setCursor(view(), par, 0);
1299                 view()->switchKeyMap();
1300                 owner->view_state_changed();
1301
1302                 view()->center();
1303                 // see BufferView_pimpl::center()
1304                 view()->updateScrollbar();
1305         }
1306         break;
1307
1308         case LFUN_APROPOS:
1309         case LFUN_GETTIP:
1310         {
1311                 int const qa = lyxaction.LookupFunc(argument);
1312                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1313         }
1314         break;
1315
1316         // --- insert characters ----------------------------------------
1317
1318         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1319         case LFUN_MATH_EXTERN:
1320         case LFUN_MATH_NUMBER:
1321         case LFUN_MATH_NONUMBER:
1322         case LFUN_MATH_LIMITS:
1323         {
1324                 setErrorMessage(N_("This is only allowed in math mode!"));
1325         }
1326         break;
1327
1328         // passthrough hat and underscore outside mathed:
1329         case LFUN_SUBSCRIPT:
1330                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1331                 break;
1332         case LFUN_SUPERSCRIPT:
1333                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1334                 break;
1335
1336         case LFUN_MATH_PANEL:
1337                 owner->getDialogs().showMathPanel();
1338                 break;
1339
1340         case LFUN_CITATION_CREATE:
1341         {
1342                 InsetCommandParams p("cite");
1343
1344                 if (!argument.empty()) {
1345                         // This should be set at source, ie when typing
1346                         // "citation-insert foo" in the minibuffer.
1347                         // Question: would pybibliographer also need to be
1348                         // changed. Suspect so. Leave as-is therefore.
1349                         if (contains(argument, "|")) {
1350                                 p.setContents(token(argument, '|', 0));
1351                                 p.setOptions(token(argument, '|', 1));
1352                         } else {
1353                                 p.setContents(argument);
1354                         }
1355                         dispatch(FuncRequest(view(), LFUN_CITATION_INSERT, p.getAsString()));
1356                 } else
1357                         owner->getDialogs().createCitation(p.getAsString());
1358         }
1359         break;
1360
1361         case LFUN_CHILDOPEN:
1362         {
1363                 string const filename =
1364                         MakeAbsPath(argument,
1365                                     owner->buffer()->filePath());
1366                 setMessage(N_("Opening child document ") +
1367                            MakeDisplayPath(filename) + "...");
1368                 view()->savePosition(0);
1369                 if (bufferlist.exists(filename))
1370                         view()->buffer(bufferlist.getBuffer(filename));
1371                 else
1372                         view()->buffer(bufferlist.loadLyXFile(filename));
1373         }
1374         break;
1375
1376         case LFUN_TOGGLECURSORFOLLOW:
1377                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1378                 break;
1379
1380         case LFUN_KMAP_OFF:             // keymap off
1381                 owner->getIntl().KeyMapOn(false);
1382                 break;
1383
1384         case LFUN_KMAP_PRIM:    // primary keymap
1385                 owner->getIntl().KeyMapPrim();
1386                 break;
1387
1388         case LFUN_KMAP_SEC:             // secondary keymap
1389                 owner->getIntl().KeyMapSec();
1390                 break;
1391
1392         case LFUN_KMAP_TOGGLE:  // toggle keymap
1393                 owner->getIntl().ToggleKeyMap();
1394                 break;
1395
1396         case LFUN_SEQUENCE:
1397         {
1398                 // argument contains ';'-terminated commands
1399                 while (!argument.empty()) {
1400                         string first;
1401                         argument = split(argument, first, ';');
1402                         dispatch(first);
1403                 }
1404         }
1405         break;
1406
1407         case LFUN_DIALOG_PREFERENCES:
1408                 owner->getDialogs().showPreferences();
1409                 break;
1410
1411         case LFUN_SAVEPREFERENCES:
1412         {
1413                 Path p(user_lyxdir);
1414                 lyxrc.write("preferences");
1415         }
1416         break;
1417
1418         case LFUN_SCREEN_FONT_UPDATE:
1419         {
1420                 // handle the screen font changes.
1421                 lyxrc.set_font_norm_type();
1422                 lyx_gui::update_fonts();
1423                 // We also need to empty the textcache so that
1424                 // the buffer will be formatted correctly after
1425                 // a zoom change.
1426                 textcache.clear();
1427                 // Of course we should only do the resize and the textcache.clear
1428                 // if values really changed...but not very important right now. (Lgb)
1429                 // All visible buffers will need resize
1430                 view()->resize();
1431                 view()->repaint();
1432         }
1433         break;
1434
1435         case LFUN_SET_COLOR:
1436         {
1437                 string lyx_name;
1438                 string const x11_name = split(argument, lyx_name, ' ');
1439                 if (lyx_name.empty() || x11_name.empty()) {
1440                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1441                                                 " <x11_name>"));
1442                         break;
1443                         }
1444
1445                 bool const graphicsbg_changed =
1446                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1447                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1448
1449                 if (!lcolor.setColor(lyx_name, x11_name)) {
1450                         static string const err1 (N_("Set-color \""));
1451                         static string const err2 (
1452                                 N_("\" failed - color is undefined "
1453                                    "or may not be redefined"));
1454                         setErrorMessage(_(err1) + lyx_name + _(err2));
1455                         break;
1456                 }
1457
1458                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1459
1460                 if (graphicsbg_changed) {
1461 #ifdef WITH_WARNINGS
1462 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1463 #endif
1464 #if 0
1465                         grfx::GCache & gc = grfx::GCache::get();
1466                         gc.changeDisplay(true);
1467 #endif
1468                 }
1469
1470                 view()->repaint();
1471                 break;
1472         }
1473
1474         case LFUN_MESSAGE:
1475                 owner->message(argument);
1476                 break;
1477
1478         case LFUN_FORKS_SHOW:
1479                 owner->getDialogs().showForks();
1480                 break;
1481
1482         case LFUN_FORKS_KILL:
1483         {
1484                 if (!isStrInt(argument))
1485                         break;
1486
1487                 pid_t const pid = strToInt(argument);
1488                 ForkedcallsController & fcc = ForkedcallsController::get();
1489                 fcc.kill(pid);
1490                 break;
1491         }
1492
1493         case LFUN_TOOLTIPS_TOGGLE:
1494                 owner->getDialogs().toggleTooltips();
1495                 break;
1496
1497         default:
1498                 // Then if it was none of the above
1499                 // Trying the BufferView::pimpl dispatch:
1500                 if (!view()->dispatch(ev))
1501                         lyxerr << "A truly unknown func ["
1502                                << lyxaction.getActionName(ev.action) << "]!"
1503                                << endl;
1504                 break;
1505         } // end of switch
1506
1507 exit_with_message:
1508         sendDispatchMessage(getMessage(), ev, verbose);
1509 }
1510
1511
1512 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1513 {
1514         owner->updateMenubar();
1515         owner->updateToolbar();
1516
1517         if (ev.action == LFUN_SELFINSERT || !verbose) {
1518                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1519                 if (!msg.empty())
1520                         owner->message(msg);
1521                 return;
1522         }
1523
1524         string dispatch_msg = msg;
1525         if (!dispatch_msg.empty())
1526                 dispatch_msg += " ";
1527
1528         string comname = lyxaction.getActionName(ev.action);
1529
1530         int pseudoaction = ev.action;
1531         bool argsadded = false;
1532
1533         if (!ev.argument.empty()) {
1534                 // the pseudoaction is useful for the bindings
1535                 pseudoaction = lyxaction.searchActionArg(ev.action, ev.argument);
1536
1537                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
1538                         pseudoaction = ev.action;
1539                 } else {
1540                         comname += " " + ev.argument;
1541                         argsadded = true;
1542                 }
1543         }
1544
1545         string const shortcuts = toplevel_keymap->findbinding(pseudoaction);
1546
1547         if (!shortcuts.empty()) {
1548                 comname += ": " + shortcuts;
1549         } else if (!argsadded && !ev.argument.empty()) {
1550                 comname += " " + ev.argument;
1551         }
1552
1553         if (!comname.empty()) {
1554                 comname = rtrim(comname);
1555                 dispatch_msg += "(" + comname + ')';
1556         }
1557
1558         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1559         if (!dispatch_msg.empty())
1560                 owner->message(dispatch_msg);
1561 }
1562
1563
1564 void LyXFunc::setupLocalKeymap()
1565 {
1566         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1567         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1568 }
1569
1570
1571 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1572 {
1573         string initpath = lyxrc.document_path;
1574         string filename(name);
1575
1576         if (view()->available()) {
1577                 string const trypath = owner->buffer()->filePath();
1578                 // If directory is writeable, use this as default.
1579                 if (IsDirWriteable(trypath))
1580                         initpath = trypath;
1581         }
1582
1583         static int newfile_number;
1584
1585         if (filename.empty()) {
1586                 filename = AddName(lyxrc.document_path,
1587                             "newfile" + tostr(++newfile_number) + ".lyx");
1588                 FileInfo fi(filename);
1589                 while (bufferlist.exists(filename) || fi.readable()) {
1590                         ++newfile_number;
1591                         filename = AddName(lyxrc.document_path,
1592                                     "newfile" + tostr(newfile_number) +
1593                                     ".lyx");
1594                         fi.newFile(filename);
1595                 }
1596         }
1597
1598         // The template stuff
1599         string templname;
1600         if (fromTemplate) {
1601                 FileDialog fileDlg(owner, _("Select template file"),
1602                         LFUN_SELECT_FILE_SYNC,
1603                         make_pair(string(_("Documents|#o#O")),
1604                                   string(lyxrc.document_path)),
1605                         make_pair(string(_("Templates|#T#t")),
1606                                   string(lyxrc.template_path)));
1607
1608                 FileDialog::Result result =
1609                         fileDlg.Select(lyxrc.template_path,
1610                                        _("*.lyx|LyX Documents (*.lyx)"));
1611
1612                 if (result.first == FileDialog::Later)
1613                         return;
1614
1615                 string const fname = result.second;
1616
1617                 if (fname.empty())
1618                         return;
1619                 templname = fname;
1620         }
1621
1622         view()->buffer(bufferlist.newFile(filename, templname, !name.empty()));
1623 }
1624
1625
1626 void LyXFunc::open(string const & fname)
1627 {
1628         string initpath = lyxrc.document_path;
1629
1630         if (view()->available()) {
1631                 string const trypath = owner->buffer()->filePath();
1632                 // If directory is writeable, use this as default.
1633                 if (IsDirWriteable(trypath))
1634                         initpath = trypath;
1635         }
1636
1637         string filename;
1638
1639         if (fname.empty()) {
1640                 FileDialog fileDlg(owner, _("Select document to open"),
1641                         LFUN_FILE_OPEN,
1642                         make_pair(string(_("Documents|#o#O")),
1643                                   string(lyxrc.document_path)),
1644                         make_pair(string(_("Examples|#E#e")),
1645                                   string(AddPath(system_lyxdir, "examples"))));
1646
1647                 FileDialog::Result result =
1648                         fileDlg.Select(initpath,
1649                                        "*.lyx|LyX Documents (*.lyx)");
1650
1651                 if (result.first == FileDialog::Later)
1652                         return;
1653
1654                 filename = result.second;
1655
1656                 // check selected filename
1657                 if (filename.empty()) {
1658                         owner->message(_("Canceled."));
1659                         return;
1660                 }
1661         } else
1662                 filename = fname;
1663
1664         // get absolute path of file and add ".lyx" to the filename if
1665         // necessary
1666         string const fullpath = FileSearch(string(), filename, "lyx");
1667         if (!fullpath.empty()) {
1668                 filename = fullpath;
1669         }
1670
1671         string const disp_fn(MakeDisplayPath(filename));
1672
1673         // if the file doesn't exist, let the user create one
1674         FileInfo const f(filename, true);
1675         if (!f.exist()) {
1676                 if (!Alert::askQuestion(_("No such file"), disp_fn,
1677                         _("Start a new document with this filename ?"))) {
1678                         owner->message(_("Canceled"));
1679                         return;
1680                 }
1681                 // the user specifically chose this name. Believe them.
1682                 Buffer * buffer =  bufferlist.newFile(filename, "", true);
1683                 view()->buffer(buffer);
1684                 return;
1685         }
1686
1687         ostringstream str;
1688         str << _("Opening document") << ' ' << disp_fn << "...";
1689
1690         owner->message(str.str().c_str());
1691
1692         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1693         if (openbuf) {
1694                 view()->buffer(openbuf);
1695                 ostringstream str;
1696                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1697                 owner->message(str.str().c_str());
1698         } else {
1699                 ostringstream str;
1700                 str << _("Could not open document") << ' ' << disp_fn;
1701                 owner->message(str.str().c_str());
1702         }
1703 }
1704
1705
1706 void LyXFunc::doImport(string const & argument)
1707 {
1708         string format;
1709         string filename = split(argument, format, ' ');
1710
1711         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1712                             << " file: " << filename << endl;
1713
1714         // need user interaction
1715         if (filename.empty()) {
1716                 string initpath = lyxrc.document_path;
1717
1718                 if (view()->available()) {
1719                         string const trypath = owner->buffer()->filePath();
1720                         // If directory is writeable, use this as default.
1721                         if (IsDirWriteable(trypath))
1722                                 initpath = trypath;
1723                 }
1724
1725                 string const text = _("Select ") + formats.prettyName(format)
1726                         + _(" file to import");
1727
1728                 FileDialog fileDlg(owner, text,
1729                         LFUN_IMPORT,
1730                         make_pair(string(_("Documents|#o#O")),
1731                                   string(lyxrc.document_path)),
1732                         make_pair(string(_("Examples|#E#e")),
1733                                   string(AddPath(system_lyxdir, "examples"))));
1734
1735                 string const extension = "*." + formats.extension(format)
1736                         + "| " + formats.prettyName(format)
1737                         + " (*." + formats.extension(format) + ")";
1738
1739                 FileDialog::Result result = fileDlg.Select(initpath,
1740                                                            extension);
1741
1742                 if (result.first == FileDialog::Later)
1743                         return;
1744
1745                 filename = result.second;
1746
1747                 // check selected filename
1748                 if (filename.empty())
1749                         owner->message(_("Canceled."));
1750         }
1751
1752         if (filename.empty())
1753                 return;
1754
1755         // get absolute path of file
1756         filename = MakeAbsPath(filename);
1757
1758         string const lyxfile = ChangeExtension(filename, ".lyx");
1759
1760         // Check if the document already is open
1761         if (lyxrc.use_gui && bufferlist.exists(lyxfile)) {
1762                 switch (Alert::askConfirmation(_("Document is already open:"),
1763                                         MakeDisplayPath(lyxfile, 50),
1764                                         _("Do you want to close that document now?\n"
1765                                           "('No' will just switch to the open version)")))
1766                         {
1767                         case 1:
1768                                 // If close is canceled, we cancel here too.
1769                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1770                                         return;
1771                                 break;
1772                         case 2:
1773                                 view()->buffer(bufferlist.getBuffer(lyxfile));
1774                                 return;
1775                         case 3:
1776                                 owner->message(_("Canceled."));
1777                                 return;
1778                         }
1779         }
1780
1781         // if the file exists already, and we didn't do
1782         // -i lyx thefile.lyx, warn
1783         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1784                 if (!Alert::askQuestion(_("A document by the name"),
1785                         MakeDisplayPath(lyxfile), _("already exists. Overwrite?"))) {
1786                         owner->message(_("Canceled"));
1787                         return;
1788                 }
1789         }
1790
1791         Importer::Import(owner, filename, format);
1792 }
1793
1794
1795 void LyXFunc::reloadBuffer()
1796 {
1797         string const fn = owner->buffer()->fileName();
1798         if (bufferlist.close(owner->buffer()))
1799                 view()->buffer(bufferlist.loadLyXFile(fn));
1800 }
1801
1802
1803 void LyXFunc::closeBuffer()
1804 {
1805         if (bufferlist.close(owner->buffer()) && !quitting) {
1806                 if (bufferlist.empty()) {
1807                         // need this otherwise SEGV may occur while trying to
1808                         // set variables that don't exist
1809                         // since there's no current buffer
1810                         owner->getDialogs().hideBufferDependent();
1811                 } else {
1812                         view()->buffer(bufferlist.first());
1813                 }
1814         }
1815 }
1816
1817
1818 // Each "owner" should have it's own message method. lyxview and
1819 // the minibuffer would use the minibuffer, but lyxserver would
1820 // send an ERROR signal to its client.  Alejandro 970603
1821 // This func is bit problematic when it comes to NLS, to make the
1822 // lyx servers client be language indepenent we must not translate
1823 // strings sent to this func.
1824 void LyXFunc::setErrorMessage(string const & m) const
1825 {
1826         dispatch_buffer = m;
1827         errorstat = true;
1828 }
1829
1830
1831 void LyXFunc::setMessage(string const & m) const
1832 {
1833         dispatch_buffer = m;
1834 }
1835
1836
1837 void LyXFunc::setStatusMessage(string const & m) const
1838 {
1839         status_buffer = m;
1840 }
1841
1842
1843 string const LyXFunc::view_status_message()
1844 {
1845         // When meta-fake key is pressed, show the key sequence so far + "M-".
1846         if (wasMetaKey()) {
1847                 return keyseq.print() + "M-";
1848         }
1849
1850         // Else, when a non-complete key sequence is pressed,
1851         // show the available options.
1852         if (keyseq.length() > 0 && !keyseq.deleted()) {
1853                 return keyseq.printOptions();
1854         }
1855
1856         if (!view()->available())
1857                 return _("Welcome to LyX!");
1858
1859         return currentState(view());
1860 }
1861
1862
1863 BufferView * LyXFunc::view() const
1864 {
1865         lyx::Assert(owner);
1866         return owner->view().get();
1867 }