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