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