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