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