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