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