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