]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
534d64e73741eb2413992bc5d8acbe4505d406c6
[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         lyx::Assert(action != LFUN_SELECT_FILE_SYNC);
942
943         switch (action) {
944                 
945         case LFUN_ESCAPE:
946         {
947                 if (!owner->view()->available()) break;
948                 
949                 // this function should be used always [asierra060396]
950                 UpdatableInset * tli =
951                         owner->view()->theLockingInset();
952                 if (tli) {
953                         UpdatableInset * lock = tli->getLockingInset();
954                         
955                         if (tli == lock) {
956                                 owner->view()->unlockInset(tli);
957                                 TEXT()->cursorRight(owner->view());
958                                 moveCursorUpdate(true, false);
959                                 owner->showState();
960                         } else {
961                                 tli->unlockInsetInInset(owner->view(),
962                                                         lock,
963                                                         true);
964                         }
965                 }
966         }
967         break;
968                         
969                 // --- Misc -------------------------------------------
970         case LFUN_WORDFINDFORWARD  : 
971         case LFUN_WORDFINDBACKWARD : {
972                 static string last_search;
973                 string searched_string;
974             
975                 if (!argument.empty()) {
976                         last_search = argument;
977                         searched_string = argument;
978                 } else {
979                         searched_string = last_search;
980                 }
981                 bool fw = (action == LFUN_WORDFINDBACKWARD);
982                 if (!searched_string.empty()) {
983                         LyXFind(owner->view(), searched_string, fw);
984                 }
985 //              owner->view()->showCursor();
986         }
987         break;
988                 
989         case LFUN_PREFIX:
990         {
991                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
992                         owner->view()->update(TEXT(),
993                                               BufferView::SELECT|BufferView::FITCUR);
994                 }
995                 string buf;
996                 keyseq.print(buf, true);
997                 owner->message(buf);
998         }
999         break;
1000
1001         // --- Misc -------------------------------------------
1002         case LFUN_EXEC_COMMAND:
1003         {
1004                 std::vector<string> allCmds;
1005                 std::transform(lyxaction.func_begin(), lyxaction.func_end(),
1006                                std::back_inserter(allCmds), lyx::firster());
1007                 static std::vector<string> hist;
1008                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
1009                                                   allCmds, hist);
1010         }
1011         break;
1012                 
1013         case LFUN_CANCEL:                   // RVDK_PATCH_5
1014                 keyseq.reset();
1015                 meta_fake_bit = 0;
1016                 if (owner->view()->available())
1017                         // cancel any selection
1018                         dispatch(LFUN_MARK_OFF);
1019                 setMessage(N_("Cancel"));
1020                 break;
1021
1022         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1023         {
1024                 meta_fake_bit = Mod1Mask;
1025                 string buf;
1026                 keyseq.print(buf, true);
1027                 setMessage(buf); // RVDK_PATCH_5
1028         }
1029         break;  
1030
1031         case LFUN_READ_ONLY_TOGGLE:
1032                 if (owner->buffer()->lyxvc.inUse()) {
1033                         owner->buffer()->lyxvc.toggleReadOnly();
1034                 } else {
1035                         owner->buffer()->setReadonly(
1036                                 !owner->buffer()->isReadonly());
1037                 }
1038                 break;
1039                 
1040         case LFUN_CENTER: // this is center and redraw.
1041                 owner->view()->center();
1042                 break;
1043                 
1044                 // --- Menus -----------------------------------------------
1045         case LFUN_MENUNEW:
1046                 menuNew(false);
1047                 break;
1048                 
1049         case LFUN_MENUNEWTMPLT:
1050                 menuNew(true);
1051                 break;
1052                 
1053         case LFUN_CLOSEBUFFER:
1054                 closeBuffer();
1055                 break;
1056                 
1057         case LFUN_MENUWRITE:
1058                 if (!owner->buffer()->isUnnamed()) {
1059                         ostringstream s1;
1060                         s1 << _("Saving document") << ' '
1061                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1062                         owner->message(s1.str().c_str());
1063                         MenuWrite(owner->view(), owner->buffer());
1064                 } else
1065                         WriteAs(owner->view(), owner->buffer());
1066                 break;
1067                 
1068         case LFUN_WRITEAS:
1069                 WriteAs(owner->view(), owner->buffer(), argument);
1070                 break;
1071                 
1072         case LFUN_MENURELOAD:
1073                 reloadBuffer();
1074                 break;
1075                 
1076         case LFUN_UPDATE:
1077                 Exporter::Export(owner->buffer(), argument, true);
1078                 break;
1079
1080         case LFUN_PREVIEW:
1081                 Exporter::Preview(owner->buffer(), argument);
1082                 break;
1083                 
1084         case LFUN_BUILDPROG:
1085                 Exporter::Export(owner->buffer(), "program", true);
1086                 break;
1087                 
1088         case LFUN_RUNCHKTEX:
1089                 MenuRunChktex(owner->buffer());
1090                 break;
1091                                 
1092         case LFUN_MENUPRINT:
1093                 owner->getDialogs()->showPrint();
1094                 break;
1095
1096         case LFUN_EXPORT:
1097                 if (argument == "custom")
1098                         MenuSendto();
1099                 else
1100                         Exporter::Export(owner->buffer(), argument, false);
1101                 break;
1102
1103         case LFUN_IMPORT:
1104                 doImport(argument);
1105                 break;
1106                 
1107         case LFUN_QUIT:
1108                 QuitLyX();
1109                 break;
1110                 
1111         case LFUN_TOCVIEW:
1112 #if 0
1113         case LFUN_LOFVIEW:
1114         case LFUN_LOTVIEW:
1115         case LFUN_LOAVIEW:
1116 #endif
1117         {
1118                 InsetCommandParams p;
1119
1120 #if 0
1121                 if (action == LFUN_TOCVIEW)
1122 #endif
1123                         p.setCmdName("tableofcontents");
1124 #if 0
1125                 else if (action == LFUN_LOAVIEW )
1126                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1127                 else if (action == LFUN_LOFVIEW)
1128                         p.setCmdName("listoffigures");
1129                 else
1130                         p.setCmdName("listoftables");
1131 #endif
1132                 owner->getDialogs()->createTOC(p.getAsString());
1133                 break;
1134         }       
1135
1136         case LFUN_DIALOG_TABULAR_INSERT:
1137                 owner->getDialogs()->showTabularCreate();
1138                 break;
1139                 
1140         case LFUN_FIGURE:
1141                 Figure();
1142                 break;
1143
1144         case LFUN_AUTOSAVE:
1145                 AutoSave(owner->view());
1146                 break;
1147                 
1148         case LFUN_UNDO:
1149                 owner->view()->menuUndo();
1150                 break;
1151                 
1152         case LFUN_REDO:
1153                 owner->view()->menuRedo();
1154                 break;
1155                 
1156         case LFUN_MENUSEARCH:
1157                 owner->getDialogs()->showSearch();
1158                 break;
1159                 
1160         case LFUN_REMOVEERRORS:
1161                 if (owner->view()->removeAutoInsets()) {
1162                         owner->view()->redraw();
1163                         owner->view()->fitCursor();
1164                 }
1165                 break;
1166
1167         case LFUN_DEPTH:
1168                 changeDepth(owner->view(), TEXT(false), 0);
1169                 break;
1170                 
1171         case LFUN_DEPTH_MIN:
1172                 changeDepth(owner->view(), TEXT(false), -1);
1173                 break;
1174                 
1175         case LFUN_DEPTH_PLUS:
1176                 changeDepth(owner->view(), TEXT(false), 1);
1177                 break;
1178                 
1179         case LFUN_FREE:
1180                 owner->getDialogs()->setUserFreeFont();
1181                 break;
1182
1183         case LFUN_RECONFIGURE:
1184                 Reconfigure(owner->view());
1185                 break;
1186
1187 #if 0
1188         case LFUN_FLOATSOPERATE:
1189                 if (argument == "openfoot")
1190                         owner->view()->allFloats(1,0);
1191                 else if (argument == "closefoot")
1192                         owner->view()->allFloats(0,0);
1193                 else if (argument == "openfig")
1194                         owner->view()->allFloats(1,1);
1195                 else if (argument == "closefig")
1196                         owner->view()->allFloats(0,1);
1197                 break;
1198 #else
1199 #ifdef WITH_WARNINGS
1200 #warning Find another implementation here (or another lyxfunc)!
1201 #endif
1202 #endif
1203         case LFUN_HELP_ABOUTLYX:
1204                 owner->getDialogs()->showAboutlyx();
1205                 break;
1206
1207         case LFUN_HELP_COPYRIGHT:
1208         case LFUN_HELP_CREDITS:
1209                 
1210
1211         case LFUN_HELP_OPEN:
1212         {
1213                 string const arg = argument;
1214                 if (arg.empty()) {
1215                         setErrorMessage(N_("Missing argument"));
1216                         break;
1217                 }
1218                 owner->prohibitInput();
1219                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1220                 if (fname.empty()) {
1221                         lyxerr << "LyX: unable to find documentation file `"
1222                                << arg << "'. Bad installation?" << endl;
1223                         owner->allowInput();
1224                         break;
1225                 }
1226                 ostringstream str;
1227                 str << _("Opening help file") << ' '
1228                     << MakeDisplayPath(fname) << "...";
1229                 owner->message(str.str().c_str());
1230                 owner->view()->buffer(bufferlist.loadLyXFile(fname, false));
1231                 owner->allowInput();
1232                 break;
1233         }
1234
1235         case LFUN_HELP_VERSION:
1236         
1237                 // --- version control -------------------------------
1238         case LFUN_VC_REGISTER:
1239         {
1240                 if (!owner->buffer()->lyxvc.inUse())
1241                         owner->buffer()->lyxvc.registrer();
1242         }
1243         break;
1244                 
1245         case LFUN_VC_CHECKIN:
1246         {
1247                 if (owner->buffer()->lyxvc.inUse()
1248                     && !owner->buffer()->isReadonly())
1249                         owner->buffer()->lyxvc.checkIn();
1250         }
1251         break;
1252                 
1253         case LFUN_VC_CHECKOUT:
1254         {
1255                 if (owner->buffer()->lyxvc.inUse()
1256                     && owner->buffer()->isReadonly())
1257                         owner->buffer()->lyxvc.checkOut();
1258         }
1259         break;
1260         
1261         case LFUN_VC_REVERT:
1262         {
1263                 owner->buffer()->lyxvc.revert();
1264         }
1265         break;
1266                 
1267         case LFUN_VC_UNDO:
1268         {
1269                 owner->buffer()->lyxvc.undoLast();
1270         }
1271         break;
1272                 
1273         case LFUN_VC_HISTORY:
1274         {
1275                 owner->getDialogs()->showVCLogFile();
1276                 break;
1277         }
1278         
1279         // --- buffers ----------------------------------------
1280
1281         case LFUN_SWITCHBUFFER:
1282                 owner->view()->buffer(bufferlist.getBuffer(argument));
1283                 break;
1284
1285         case LFUN_FILE_NEW:
1286         {
1287                 // servercmd: argument must be <file>:<template>
1288                 Buffer * tmpbuf = NewLyxFile(argument);
1289                 if (tmpbuf)
1290                         owner->view()->buffer(tmpbuf);
1291         }
1292         break;
1293                         
1294         case LFUN_FILE_OPEN:
1295                 open(argument);
1296                 break;
1297
1298         case LFUN_LATEX_LOG:
1299                 owner->getDialogs()->showLogFile();
1300                 break;
1301                 
1302         case LFUN_LAYOUTNO:
1303         {
1304                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1305                 int sel = strToInt(argument);
1306                 lyxerr[Debug::INFO] << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1307                 
1308                 // Should this give a setMessage instead?
1309                 if (sel == 0) 
1310                         return string(); // illegal argument
1311
1312                 --sel; // sel 1..., but layout 0...
1313
1314                 // Pretend we got the name instead.
1315                 dispatch(int(LFUN_LAYOUT), 
1316                          textclasslist.NameOfLayout(owner->view()
1317                                                     ->buffer()->params.textclass,
1318                                                     sel));
1319                 return string();
1320         }
1321                 
1322         case LFUN_LAYOUT_DOCUMENT:
1323                 owner->getDialogs()->showDocument();
1324                 break;
1325                 
1326         case LFUN_LAYOUT_PARAGRAPH:
1327                 owner->getDialogs()->showParagraph();
1328                 break;
1329                 
1330         case LFUN_LAYOUT_CHARACTER:
1331                 owner->getDialogs()->showCharacter();
1332                 break;
1333
1334         case LFUN_LAYOUT_TABULAR:
1335             if (owner->view()->theLockingInset()) {
1336                 if (owner->view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1337                     InsetTabular * inset = static_cast<InsetTabular *>
1338                         (owner->view()->theLockingInset());
1339                     inset->openLayoutDialog(owner->view());
1340                 } else if (owner->view()->theLockingInset()->
1341                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1342                     InsetTabular * inset = static_cast<InsetTabular *>(
1343                         owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1344                     inset->openLayoutDialog(owner->view());
1345                 }
1346             }
1347             break;
1348
1349         case LFUN_LAYOUT_PREAMBLE:
1350                 owner->getDialogs()->showPreamble();
1351                 break;
1352                 
1353         case LFUN_LAYOUT_SAVE_DEFAULT:
1354                 MenuLayoutSave(owner->view());
1355                 break;
1356                 
1357         case LFUN_DROP_LAYOUTS_CHOICE:
1358                 owner->getToolbar()->openLayoutList();
1359                 break;
1360
1361         case LFUN_MENU_OPEN_BY_NAME:
1362                 owner->getMenubar()->openByName(argument);
1363                 break; // RVDK_PATCH_5
1364                 
1365         case LFUN_SPELLCHECK:
1366                 if (lyxrc.isp_command != "none")
1367                         owner->getDialogs()->showSpellchecker();
1368                 break;
1369                 
1370         // --- lyxserver commands ----------------------------
1371
1372
1373         case LFUN_GETNAME:
1374                 setMessage(owner->buffer()->fileName());
1375                 lyxerr[Debug::INFO] << "FNAME["
1376                                << owner->buffer()->fileName()
1377                                << "] " << endl;
1378                 break;
1379                 
1380         case LFUN_NOTIFY:
1381         {
1382                 string buf;
1383                 keyseq.print(buf);
1384                 dispatch_buffer = buf;
1385                 lyxserver->notifyClient(dispatch_buffer);
1386         }
1387         break;
1388
1389         case LFUN_GOTOFILEROW:
1390         {
1391                 string file_name;
1392                 int row;
1393                 istringstream istr(argument.c_str());
1394                 istr >> file_name >> row;
1395                 // Must replace extension of the file to be .lyx and get full path
1396                 string const s(ChangeExtension(file_name, ".lyx"));
1397
1398                 // Either change buffer or load the file
1399                 if (bufferlist.exists(s)) {
1400                         owner->view()->buffer(bufferlist.getBuffer(s));
1401                 } else {
1402                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1403                 }
1404                 
1405                 // Set the cursor  
1406                 owner->view()->setCursorFromRow(row);
1407
1408                 // Recenter screen
1409                 owner->view()->center();
1410         }
1411         break;
1412
1413         case LFUN_GOTO_PARAGRAPH:
1414         {
1415                 istringstream istr(argument.c_str());
1416
1417                 int id;
1418                 istr >> id;
1419                 Paragraph * par = owner->buffer()->getParFromID(id);
1420                 if (par == 0) {
1421                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1422                                             << id << "]" << std::endl;
1423                         break;
1424                 } else {
1425                         lyxerr << "Paragraph " << par->id()
1426                                << " found." << endl;
1427                 }
1428
1429                 // Set the cursor
1430                 owner->view()->text->setCursor(owner->view(), par, 0);
1431                 owner->view()->setState();
1432                 owner->showState();
1433
1434                 // Recenter screen
1435                 owner->view()->center();
1436         }
1437         break;
1438
1439         case LFUN_APROPOS:
1440         case LFUN_GETTIP:
1441         {
1442                 int const qa = lyxaction.LookupFunc(argument);
1443                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1444         }
1445         break;
1446
1447         // --- toolbar ----------------------------------
1448         case LFUN_PUSH_TOOLBAR:
1449         {
1450                 int nth = strToInt(argument);
1451                 if (nth <= 0) {
1452                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1453                 } else {
1454                         owner->getToolbar()->push(nth);
1455                 }
1456         }
1457         break;
1458         
1459         case LFUN_ADD_TO_TOOLBAR:
1460         {
1461                 if (lyxerr.debugging(Debug::GUI)) {
1462                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1463                                 "argument = `" << argument << '\'' << endl;
1464                 }
1465                 string tmp(argument);
1466                 //lyxerr <<string("Argument: ") + argument);
1467                 //lyxerr <<string("Tmp     : ") + tmp);
1468                 if (tmp.empty()) {
1469                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1470                 } else {
1471                         owner->getToolbar()->add(argument, false);
1472                         owner->getToolbar()->set();
1473                 }
1474         }
1475         break;
1476         
1477         // --- insert characters ----------------------------------------
1478
1479         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1480         case LFUN_MATH_EXTERN:
1481         case LFUN_MATH_NUMBER:
1482         case LFUN_MATH_NONUMBER:
1483         case LFUN_MATH_LIMITS:
1484         {
1485                 setErrorMessage(N_("This is only allowed in math mode!"));
1486         }
1487         break;
1488
1489         case LFUN_MATH_PANEL:
1490                 owner->getDialogs()->showMathPanel();
1491                 break;
1492         
1493         case LFUN_CITATION_CREATE:
1494         {
1495                 InsetCommandParams p( "cite" );
1496                 
1497                 if (!argument.empty()) {
1498                         // This should be set at source, ie when typing
1499                         // "citation-insert foo" in the minibuffer.
1500                         // Question: would pybibliographer also need to be
1501                         // changed. Suspect so. Leave as-is therefore.
1502                         if (contains(argument, "|")) {
1503                                 p.setContents( token(argument, '|', 0) );
1504                                 p.setOptions(  token(argument, '|', 1) );
1505                         } else {
1506                                 p.setContents( argument );
1507                         }
1508                         dispatch(LFUN_CITATION_INSERT, p.getAsString());
1509                 } else
1510                         owner->getDialogs()->createCitation( p.getAsString() );
1511         }
1512         break;
1513                     
1514         case LFUN_CHILDOPEN:
1515         {
1516                 string const filename =
1517                         MakeAbsPath(argument, 
1518                                     OnlyPath(owner->buffer()->fileName()));
1519                 setMessage(N_("Opening child document ") +
1520                            MakeDisplayPath(filename) + "...");
1521                 owner->view()->savePosition(0);
1522                 if (bufferlist.exists(filename))
1523                         owner->view()->buffer(bufferlist.getBuffer(filename));
1524                 else
1525                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1526         }
1527         break;
1528
1529         case LFUN_TOGGLECURSORFOLLOW:
1530                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1531                 break;
1532                 
1533         case LFUN_KMAP_OFF:             // keymap off
1534                 owner->getIntl()->KeyMapOn(false);
1535                 break;
1536                 
1537         case LFUN_KMAP_PRIM:    // primary keymap
1538                 owner->getIntl()->KeyMapPrim();
1539                 break;
1540                 
1541         case LFUN_KMAP_SEC:             // secondary keymap
1542                 owner->getIntl()->KeyMapSec();
1543                 break;
1544                 
1545         case LFUN_KMAP_TOGGLE:  // toggle keymap
1546                 owner->getIntl()->ToggleKeyMap();
1547                 break;
1548
1549         case LFUN_SEQUENCE: 
1550         {
1551                 // argument contains ';'-terminated commands
1552                 while (argument.find(';') != string::npos) {
1553                         string first;
1554                         argument = split(argument, first, ';');
1555                         dispatch(first);
1556                 }
1557         }
1558         break;
1559
1560         case LFUN_DIALOG_PREFERENCES:
1561                 owner->getDialogs()->showPreferences();
1562                 break;
1563                 
1564         case LFUN_SAVEPREFERENCES:
1565         {
1566                 Path p(user_lyxdir);
1567                 lyxrc.write("preferences");
1568         }
1569         break;
1570
1571         case LFUN_SCREEN_FONT_UPDATE:
1572         {
1573                 // handle the screen font changes.
1574                 // 
1575                 lyxrc.set_font_norm_type();
1576                 fontloader.update();
1577                 // Of course we should only do the resize and the textcache.clear
1578                 // if values really changed...but not very important right now. (Lgb)
1579                 // All visible buffers will need resize
1580                 owner->resize();
1581                 // We also need to empty the textcache so that
1582                 // the buffer will be formatted correctly after
1583                 // a zoom change.
1584                 textcache.clear();
1585         }
1586         break;
1587
1588         case LFUN_SET_COLOR:
1589         {
1590                 string lyx_name;
1591                 string const x11_name = split(argument, lyx_name, ' ');
1592                 if (lyx_name.empty() || x11_name.empty()) {
1593                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1594                                                 " <x11_name>"));
1595                         break;
1596                         }
1597
1598                 if (!lcolor.setColor(lyx_name, x11_name)) {
1599                         static string const err1 (N_("Set-color \""));
1600                         static string const err2 (
1601                                 N_("\" failed - color is undefined "
1602                                    "or may not be redefined"));
1603                         setErrorMessage(_(err1) + lyx_name + _(err2));
1604                         break;
1605                 }
1606                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1607                 owner->view()->redraw();
1608                 break;
1609         }
1610
1611         case LFUN_MESSAGE:
1612                 owner->message(argument);
1613                 break;
1614
1615         case LFUN_MESSAGE_PUSH:
1616                 owner->messagePush(argument);
1617                 break;
1618
1619         case LFUN_MESSAGE_POP:
1620                 owner->messagePop();
1621                 break;
1622
1623         default:
1624                 // Then if it was none of the above
1625                 if (!owner->view()->Dispatch(action, argument))
1626                         lyxerr << "A truly unknown func ["
1627                                << lyxaction.getActionName(action) << "]!"
1628                                << endl;
1629                 break;
1630         } // end of switch
1631
1632 exit_with_message:
1633
1634         commandshortcut.erase();
1635         
1636         if (lyxrc.display_shortcuts && show_sc) {
1637                 if (action != LFUN_SELFINSERT) {
1638                         // Put name of command and list of shortcuts
1639                         // for it in minibuffer
1640                         string comname = lyxaction.getActionName(action);
1641
1642                         int pseudoaction = action;
1643                         bool argsadded = false;
1644
1645                         if (!argument.empty()) {
1646                                 // If we have the command with argument, 
1647                                 // this is better
1648                                 pseudoaction = 
1649                                         lyxaction.searchActionArg(action,
1650                                                                   argument);
1651
1652                                 if (pseudoaction == -1) {
1653                                         pseudoaction = action;
1654                                 } else {
1655                                         comname += " " + argument;
1656                                         argsadded = true;
1657                                 }
1658                         }
1659
1660                         string const shortcuts =
1661                                 toplevel_keymap->findbinding(pseudoaction);
1662
1663                         if (!shortcuts.empty()) {
1664                                 comname += ": " + shortcuts;
1665                         } else if (!argsadded) {
1666                                 comname += " " + argument;
1667                         }
1668
1669                         if (!comname.empty()) {
1670                                 comname = strip(comname);
1671                                 commandshortcut = "(" + comname + ')';
1672
1673                                 // Here we could even add a small pause,
1674                                 // to annoy the user and make him learn
1675                                 // the shortcuts.
1676                                 // No! That will just annoy, not teach
1677                                 // anything. The user will read the messages
1678                                 // if they are interested. (Asger)
1679                         }
1680                 }
1681         }
1682
1683         string const res = getMessage();
1684
1685         if (res.empty()) {
1686                 if (!commandshortcut.empty()) {
1687                         owner->getMiniBuffer()->addSet(commandshortcut);
1688                 }
1689         } else {
1690                 string const msg(_(res) + ' ' + commandshortcut);
1691                 owner->message(msg);
1692         }
1693
1694         return res;
1695 }
1696
1697
1698 void LyXFunc::setupLocalKeymap()
1699 {
1700         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1701         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1702 }
1703
1704
1705 void LyXFunc::menuNew(bool fromTemplate)
1706 {
1707         string initpath = lyxrc.document_path;
1708
1709         if (owner->view()->available()) {
1710                 string const trypath = owner->buffer()->filepath;
1711                 // If directory is writeable, use this as default.
1712                 if (IsDirWriteable(trypath))
1713                         initpath = trypath;
1714         }
1715
1716         static int newfile_number;
1717         string s;
1718         
1719         if (lyxrc.new_ask_filename) {
1720                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1721                                    LFUN_SELECT_FILE_SYNC,
1722                         make_pair(string(_("Documents")),
1723                                   string(lyxrc.document_path)),
1724                         make_pair(string(_("Templates")),
1725                                   string(lyxrc.template_path)));
1726
1727                 FileDialog::Result result =
1728                         fileDlg.Select(initpath,
1729                                        _("*.lyx|LyX Documents (*.lyx)"),
1730                                        _("newfile"));
1731         
1732                 if (result.second.empty()) {
1733                         owner->message(_("Canceled."));
1734                         lyxerr[Debug::INFO] << "New Document Cancelled." << endl;
1735                         return;
1736                 }
1737         
1738                 // get absolute path of file and make sure the filename ends
1739                 // with .lyx
1740                 s = MakeAbsPath(result.second);
1741                 if (!IsLyXFilename(s))
1742                         s += ".lyx";
1743
1744                 // Check if the document already is open
1745                 if (bufferlist.exists(s)) {
1746                         switch (AskConfirmation(_("Document is already open:"),
1747                                                 MakeDisplayPath(s, 50),
1748                                                 _("Do you want to close that document now?\n"
1749                                                   "('No' will just switch to the open version)")))
1750                         {
1751                         case 1: // Yes: close the document
1752                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1753                                 // If close is canceled, we cancel here too.
1754                                         return;
1755                                 break;
1756                         case 2: // No: switch to the open document
1757                                 owner->view()->buffer(bufferlist.getBuffer(s));
1758                                 return;
1759                         case 3: // Cancel: Do nothing
1760                                 owner->message(_("Canceled."));
1761                                 return;
1762                         }
1763                 }
1764                 // Check whether the file already exists
1765                 FileInfo fi(s);
1766                 if (fi.readable() &&
1767                     AskQuestion(_("File already exists:"), 
1768                                 MakeDisplayPath(s, 50),
1769                                 _("Do you want to open the document?"))) {
1770                                 // loads document
1771                         string const disp_fn(MakeDisplayPath(s));
1772                         
1773                         ostringstream str;
1774                         str << _("Opening  document") << ' '
1775                             << disp_fn << "...";
1776                         
1777                         owner->message(str.str().c_str());
1778                         //XFlush(fl_get_display());
1779                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1780                         ostringstream str2;
1781                         str2 << _("Document") << ' '
1782                              << disp_fn << ' ' << _("opened.");
1783                         
1784                         owner->message(str2.str().c_str());
1785                         
1786                         return;
1787                 }
1788         } else {
1789                 s = AddName(lyxrc.document_path,
1790                             "newfile" + tostr(++newfile_number) + ".lyx");
1791                 FileInfo fi(s);
1792                 while (bufferlist.exists(s) || fi.readable()) {
1793                         ++newfile_number;
1794                         s = AddName(lyxrc.document_path,
1795                                     "newfile" + tostr(newfile_number) +
1796                                     ".lyx");
1797                         fi.newFile(s);
1798                 }
1799         }
1800
1801         // The template stuff
1802         string templname;
1803         if (fromTemplate) {
1804                 FileDialog fileDlg(owner, _("Select template file"),
1805                         LFUN_SELECT_FILE_SYNC,
1806                         make_pair(string(_("Documents")),
1807                                   string(lyxrc.document_path)),
1808                         make_pair(string(_("Templates")),
1809                                   string(lyxrc.template_path)));
1810
1811                 FileDialog::Result result =
1812                         fileDlg.Select(lyxrc.template_path,
1813                                        _("*.lyx|LyX Documents (*.lyx)"));
1814         
1815                 if (result.first == FileDialog::Later)
1816                         return;
1817
1818                 string const fname = result.second;
1819
1820                 if (fname.empty()) 
1821                         return;
1822                 templname = fname;
1823         }
1824   
1825         // find a free buffer
1826         lyxerr[Debug::INFO] << "Find a free buffer." << endl;
1827         owner->view()->buffer(bufferlist.newFile(s, templname));
1828 }
1829
1830
1831 void LyXFunc::open(string const & fname)
1832 {
1833         string initpath = lyxrc.document_path;
1834   
1835         if (owner->view()->available()) {
1836                 string const trypath = owner->buffer()->filepath;
1837                 // If directory is writeable, use this as default.
1838                 if (IsDirWriteable(trypath))
1839                         initpath = trypath;
1840         }
1841
1842         string filename;
1843  
1844         if (fname.empty()) {
1845                 FileDialog fileDlg(owner, _("Select document to open"),
1846                         LFUN_FILE_OPEN,
1847                         make_pair(string(_("Documents")),
1848                                   string(lyxrc.document_path)),
1849                         make_pair(string(_("Examples")),
1850                                   string(AddPath(system_lyxdir, "examples"))));
1851
1852                 FileDialog::Result result =
1853                         fileDlg.Select(initpath,
1854                                        "*.lyx|LyX Documents (*.lyx)");
1855         
1856                 if (result.first == FileDialog::Later)
1857                         return;
1858
1859                 filename = result.second;
1860  
1861                 // check selected filename
1862                 if (filename.empty()) {
1863                         owner->message(_("Canceled."));
1864                         return;
1865                 }
1866         } else
1867                 filename = fname;
1868
1869         // get absolute path of file and add ".lyx" to the filename if
1870         // necessary
1871         string const fullpath = FileSearch(string(), filename, "lyx");
1872         if (fullpath.empty()) {
1873                 WriteAlert(_("Error"), _("Could not find file"), filename);
1874                 return;
1875         }
1876
1877         filename = fullpath;
1878  
1879         // loads document
1880         string const disp_fn(MakeDisplayPath(filename));
1881
1882         ostringstream str;
1883         str << _("Opening document") << ' ' << disp_fn << "...";
1884         
1885         owner->message(str.str().c_str());
1886
1887         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1888         if (openbuf) {
1889                 owner->view()->buffer(openbuf);
1890                 ostringstream str;
1891                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1892                 owner->message(str.str().c_str());
1893         } else {
1894                 ostringstream str;
1895                 str << _("Could not open docuent") << ' ' << disp_fn;
1896                 owner->message(str.str().c_str());
1897         }
1898 }
1899
1900
1901 // checks for running without gui are missing.
1902 void LyXFunc::doImport(string const & argument)
1903 {
1904         string format;
1905         string filename = split(argument, format, ' ');
1906         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format 
1907                             << " file: " << filename << endl;
1908
1909         if (filename.empty()) { // need user interaction
1910                 string initpath = lyxrc.document_path;
1911                 
1912                 if (owner->view()->available()) {
1913                         string const trypath = owner->buffer()->filepath;
1914                         // If directory is writeable, use this as default.
1915                         if (IsDirWriteable(trypath))
1916                                 initpath = trypath;
1917                 }
1918
1919                 string const text = _("Select ") + formats.prettyName(format)
1920                         + _(" file to import");
1921
1922                 FileDialog fileDlg(owner, text, 
1923                         LFUN_IMPORT,
1924                         make_pair(string(_("Documents")),
1925                                   string(lyxrc.document_path)),
1926                         make_pair(string(_("Examples")),
1927                                   string(AddPath(system_lyxdir, "examples"))));
1928                         
1929                 string const extension = "*." + formats.extension(format)
1930                         + "| " + formats.prettyName(format)
1931                         + " (*." + formats.extension(format) + ")";
1932
1933                 FileDialog::Result result = fileDlg.Select(initpath,
1934                                                            extension);
1935
1936                 if (result.first == FileDialog::Later)
1937                         return;
1938
1939                 filename = result.second;
1940  
1941                 // check selected filename
1942                 if (filename.empty())
1943                         owner->message(_("Canceled."));
1944         }
1945
1946         // still no filename? abort
1947         if (filename.empty()) 
1948                 return;
1949
1950         // get absolute path of file
1951         filename = MakeAbsPath(filename);
1952
1953         string const lyxfile = ChangeExtension(filename, ".lyx");
1954
1955         // Check if the document already is open
1956         if (bufferlist.exists(lyxfile)) {
1957                 switch (AskConfirmation(_("Document is already open:"), 
1958                                         MakeDisplayPath(lyxfile, 50),
1959                                         _("Do you want to close that document now?\n"
1960                                           "('No' will just switch to the open version)")))
1961                         {
1962                         case 1: // Yes: close the document
1963                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1964                                 // If close is canceled, we cancel here too.
1965                                         return;
1966                                 break;
1967                         case 2: // No: switch to the open document
1968                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1969                                 return;
1970                         case 3: // Cancel: Do nothing
1971                                 owner->message(_("Canceled."));
1972                                 return;
1973                         }
1974         }
1975
1976         // Check if a LyX document by the same root exists in filesystem
1977         FileInfo const f(lyxfile, true);
1978         if (f.exist() && !AskQuestion(_("A document by the name"), 
1979                                       MakeDisplayPath(lyxfile),
1980                                       _("already exists. Overwrite?"))) {
1981                 owner->message(_("Canceled"));
1982                 return;
1983         }
1984         // filename should be valid now
1985         
1986         Importer::Import(owner, filename, format);
1987 }
1988
1989
1990 void LyXFunc::reloadBuffer()
1991 {
1992         string const fn = owner->buffer()->fileName();
1993         if (bufferlist.close(owner->buffer()))
1994                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1995 }
1996
1997
1998 void LyXFunc::closeBuffer()
1999 {
2000         if (bufferlist.close(owner->buffer()) && !quitting) {
2001                 if (bufferlist.empty()) {
2002                         // need this otherwise SEGV may occur while trying to
2003                         // set variables that don't exist
2004                         // since there's no current buffer
2005                         owner->getDialogs()->hideBufferDependent();
2006                 } else {
2007                         owner->view()->buffer(bufferlist.first());
2008                 }
2009         }
2010 }
2011
2012
2013 // Each "owner" should have it's own message method. lyxview and
2014 // the minibuffer would use the minibuffer, but lyxserver would
2015 // send an ERROR signal to its client.  Alejandro 970603
2016 // This func is bit problematic when it comes to NLS, to make the
2017 // lyx servers client be language indepenent we must not translate
2018 // strings sent to this func.
2019 void LyXFunc::setErrorMessage(string const & m) const
2020 {
2021         dispatch_buffer = m;
2022         errorstat = true;
2023 }
2024
2025
2026 void LyXFunc::setMessage(string const & m)
2027 {
2028         dispatch_buffer = m;
2029 }
2030
2031
2032 void LyXFunc::initMiniBuffer() 
2033 {
2034         string text = _("Welcome to LyX!");
2035         
2036         // When meta-fake key is pressed, show the key sequence so far + "M-".
2037         if (wasMetaKey()) {
2038                 keyseqStr();
2039                 text += "M-";
2040         }
2041
2042         // Else, when a non-complete key sequence is pressed,
2043         // show the available options.
2044         else if (keyseqUncomplete()) 
2045                 text = keyseqOptions();
2046    
2047         // Else, show the buffer state.
2048         else if (owner->view()->available()) {
2049                 Buffer * tmpbuf = owner->buffer();
2050                 
2051                 string const nicename = 
2052                         MakeDisplayPath(tmpbuf->fileName());
2053                 // Should we do this instead? (kindo like emacs)
2054                 // leaves more room for other information
2055                 text = "LyX: ";
2056                 text += nicename;
2057                 if (tmpbuf->lyxvc.inUse()) {
2058                         text += " [";
2059                         text += tmpbuf->lyxvc.version();
2060                         text += ' ';
2061                         text += tmpbuf->lyxvc.locker();
2062                         if (tmpbuf->isReadonly())
2063                                 text += " (RO)";
2064                         text += ']';
2065                 } else if (tmpbuf->isReadonly())
2066                         text += " [RO]";
2067                 if (!tmpbuf->isLyxClean())
2068                         text += _(" (Changed)");
2069         } else {
2070                 if (text != _("Welcome to LyX!")) // this is a hack
2071                         text = _("* No document open *");
2072         }
2073         
2074         owner->message(text);
2075 }
2076