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