]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
- remove some unused code
[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 bool selection_possible;
108 extern void MenuSendto();
109
110 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
111
112 extern void show_symbols_form(LyXFunc *);
113
114 extern LyXAction lyxaction;
115 // (alkis)
116 extern tex_accent_struct get_accent(kb_action action);
117
118 extern LyXTextClass::size_type current_layout;
119
120 extern void ShowLatexLog();
121
122
123 #if 0
124
125 ///
126 class MiniBufferController : public SigC::Object {
127 public:
128         ///
129         MiniBufferController() {
130                 minibuffer
131                         .cmdReady
132                         .connect(slot(this,
133                                       &MiniBufferController::receiveCommand));
134                 minibuffer
135                         .argReady
136                         .connect(slot(this,
137                                       &MiniBufferController::receiveArg));
138         }
139         ///
140         void receiveCmd(string const & cmd) {}
141         ///
142         void receiveArg(string const & arg) {}
143         
144         
145 private:
146 };
147
148 namespace {
149
150 MiniBufferController mb_ctrl;
151
152 }
153 #endif
154
155
156 /* === globals =========================================================== */
157
158 // Initialization of static member var
159 bool LyXFunc::show_sc = true;
160
161
162 LyXFunc::LyXFunc(LyXView * o)
163         : owner(o)
164 {
165         meta_fake_bit = 0;
166         lyx_dead_action = LFUN_NOACTION;
167         lyx_calling_dead_action = LFUN_NOACTION;
168         setupLocalKeymap();
169 }
170
171
172 inline
173 LyXText * LyXFunc::TEXT(bool flag = true) const
174 {
175         if (flag)
176                 return owner->view()->text;
177         return owner->view()->getLyXText();
178 }
179
180
181 // I changed this func slightly. I commented out the ...FinishUndo(),
182 // this means that all places that used to have a moveCursorUpdate, now
183 // have a ...FinishUndo() as the preceeding statement. I have also added
184 // a moveCursorUpdate to some of the functions that updated the cursor, but
185 // that did not show its new position.
186 inline
187 void LyXFunc::moveCursorUpdate(bool flag, bool selecting)
188 {
189         if (selecting || TEXT(flag)->selection.mark()) {
190                 TEXT(flag)->setSelection(owner->view());
191                 if (TEXT(flag)->bv_owner)
192                     owner->view()->toggleToggle();
193         }
194         owner->view()->update(TEXT(flag), BufferView::SELECT|BufferView::FITCUR);
195         owner->view()->showCursor();
196         
197         /* ---> Everytime the cursor is moved, show the current font state. */
198         // should this too me moved out of this func?
199         owner->view()->setState();
200 }
201
202
203 void LyXFunc::handleKeyFunc(kb_action action)
204 {
205         char c = keyseq.getiso();
206
207         if (keyseq.length != -1) c = 0;
208         
209         owner->getIntl()->getTrans()
210                 .deadkey(c, get_accent(action).accent, TEXT(false));
211         // Need to reset, in case the minibuffer calls these
212         // actions
213         keyseq.reset();
214         keyseq.length = 0;
215         // copied verbatim from do_accent_char
216         owner->view()->update(TEXT(false),
217                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
218         TEXT(false)->selection.cursor = TEXT(false)->cursor;
219 }
220
221
222 void LyXFunc::processKeySym(KeySym keysym, unsigned int state) 
223 {
224         string argument;
225         
226         if (lyxerr.debugging(Debug::KEY)) {
227                 char const * tmp = XKeysymToString(keysym);
228                 string const stm = (tmp ? tmp : "");
229                 lyxerr << "KeySym is "
230                        << stm
231                        << "["
232                        << keysym << "] State is ["
233                        << state << "]"
234                        << endl;
235         }
236         // Do nothing if we have nothing (JMarc)
237         if (keysym == NoSymbol) {
238                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
239                                    << endl;
240                 return;
241         }
242
243         // Can we be sure that this will work for all X Window
244         // implementations? (Lgb)
245         // This code snippet makes lyx ignore some keys. Perhaps
246         // all of them should be explictly mentioned?
247         if ((keysym >= XK_Shift_L && keysym <= XK_Hyper_R)
248             || keysym == XK_Mode_switch || keysym == 0x0) {
249                 return;
250         }
251         
252         // Do a one-deep top-level lookup for
253         // cancel and meta-fake keys. RVDK_PATCH_5
254         cancel_meta_seq.reset();
255
256         int action = cancel_meta_seq.addkey(keysym, state
257                                             &(ShiftMask|ControlMask
258                                               |Mod1Mask)); 
259         if (lyxerr.debugging(Debug::KEY)) {
260                 lyxerr << "action first set to [" << action << "]" << endl;
261         }
262         
263         // When not cancel or meta-fake, do the normal lookup. 
264         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
265         // Mostly, meta_fake_bit = 0. RVDK_PATCH_5.
266         if ((action != LFUN_CANCEL) && (action != LFUN_META_FAKE)) {
267                 if (lyxerr.debugging(Debug::KEY)) {
268                         lyxerr << "meta_fake_bit is ["
269                                << meta_fake_bit << "]" << endl;
270                 }
271                 // remove Caps Lock and Mod2 as a modifiers
272                 action = keyseq.addkey(keysym,
273                                        (state | meta_fake_bit)
274                                        &(ShiftMask|ControlMask
275                                          |Mod1Mask));
276                 if (lyxerr.debugging(Debug::KEY)) {
277                         lyxerr << "action now set to ["
278                                << action << "]" << endl;
279                 }
280         }
281         // Dont remove this unless you know what you are doing.
282         meta_fake_bit = 0;
283                 
284         if (action == 0) action = LFUN_PREFIX;
285
286         if (lyxerr.debugging(Debug::KEY)) {
287                 string buf;
288                 keyseq.print(buf);
289                 lyxerr << "Key [action="
290                        << action << "]["
291                        << buf << "]"
292                        << endl;
293         }
294
295         // already here we know if it any point in going further
296         // why not return already here if action == -1 and
297         // num_bytes == 0? (Lgb)
298
299         if (keyseq.length > 1 || keyseq.length < -1) {
300                 string buf;
301                 keyseq.print(buf);
302                 owner->message(buf);
303         }
304
305         if (action == -1) {
306                 // It is unknown, but what if we remove all
307                 // the modifiers? (Lgb)
308                 action = keyseq.addkey(keysym, 0);
309
310                 if (lyxerr.debugging(Debug::KEY)) {
311                         lyxerr << "Removing modifiers...\n"
312                                << "Action now set to ["
313                                << action << "]" << endl;
314                 }
315                 if (action == -1) {
316                         owner->message(_("Unknown function."));
317                         return;
318                 }
319         }
320
321         if (action == LFUN_SELFINSERT) {
322                 // This is very X dependant.
323                 unsigned int c = keysym;
324                 
325                 switch (c & 0x0000FF00) {
326                         // latin 1 byte 3 = 0
327                 case 0x00000000: break;
328                         // latin 2 byte 3 = 1
329                 case 0x00000100:
330                         // latin 3 byte 3 = 2
331                 case 0x00000200:
332                         // latin 4 byte 3 = 3
333                 case 0x00000300:
334                         // latin 8 byte 3 = 18 (0x12)
335                 case 0x00001200:
336                         // latin 9 byte 3 = 19 (0x13)
337                 case 0x00001300:
338                         c &= 0x000000FF;
339                         break;
340                 default:
341                         c = 0;
342                         break;
343                 }
344                 if (c > 0)
345                         argument = static_cast<char>(c);
346                 lyxerr[Debug::KEY] << "SelfInsert arg[`"
347                                    << argument << "']" << endl;
348         }
349         
350         bool tmp_sc = show_sc;
351         show_sc = false;
352         dispatch(action, argument);
353         show_sc = tmp_sc;
354         
355         //return 0;
356
357
358
359 func_status::value_type LyXFunc::getStatus(int ac) const
360 {
361         return getStatus(ac, string());
362 }
363
364
365 func_status::value_type LyXFunc::getStatus(int ac,
366                                            string const & not_to_use_arg) const
367 {
368         kb_action action;
369         func_status::value_type flag = func_status::OK;
370         string argument;
371         Buffer * buf = owner->buffer();
372         
373         if (lyxaction.isPseudoAction(ac)) 
374                 action = lyxaction.retrieveActionArg(ac, argument);
375         else {
376                 action = static_cast<kb_action>(ac);
377                 if (!not_to_use_arg.empty())
378                         argument = not_to_use_arg; // exept here
379         }
380         
381         if (action == LFUN_UNKNOWN_ACTION) {
382                 setErrorMessage(N_("Unknown action"));
383                 return func_status::Unknown;
384         }
385         
386         // Check whether we need a buffer
387         if (!lyxaction.funcHasFlag(action, LyXAction::NoBuffer)) {
388                 // Yes we need a buffer, do we have one?
389                 if (buf) {
390                         // yes
391                         // Can we use a readonly buffer?
392                         if (buf->isReadonly() && 
393                             !lyxaction.funcHasFlag(action,
394                                                    LyXAction::ReadOnly)) {
395                                 // no
396                                 setErrorMessage(N_("Document is read-only"));
397                                 flag |= func_status::Disabled;
398                         }
399                 } else {
400                         // no
401                         setErrorMessage(N_("Command not allowed with"
402                                            "out any document open"));
403                         flag |= func_status::Disabled;
404                         return flag;
405                 }
406         }
407
408         // I would really like to avoid having this switch and rather try to
409         // encode this in the function itself.
410         bool disable = false;
411         switch (action) {
412         case LFUN_MENUPRINT:
413                 disable = !Exporter::IsExportable(buf, "dvi")
414                         || lyxrc.print_command == "none";
415                 break;
416         case LFUN_EXPORT:
417                 disable = argument == "fax" &&
418                         !Exporter::IsExportable(buf, argument);
419                 break;
420         case LFUN_UNDO:
421                 disable = buf->undostack.empty();
422                 break;
423         case LFUN_REDO:
424                 disable = buf->redostack.empty();
425                 break;
426         case LFUN_SPELLCHECK:
427                 disable = lyxrc.isp_command == "none";
428                 break;
429 #ifndef HAVE_LIBAIKSAURUS
430         case LFUN_THESAURUS_ENTRY:
431                 disable = true;
432                 break;
433 #endif
434         case LFUN_RUNCHKTEX:
435                 disable = lyxrc.chktex_command == "none";
436                 break;
437         case LFUN_BUILDPROG:
438                 disable = !Exporter::IsExportable(buf, "program");
439                 break;
440
441         case LFUN_LAYOUT_TABULAR:
442                 disable = true;
443                 if (owner->view()->theLockingInset()) {
444                         disable = (owner->view()->theLockingInset()->lyxCode() != Inset::TABULAR_CODE) &&
445                                 !owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE);
446                 }
447                 break;
448
449         case LFUN_TABULAR_FEATURE:
450                 disable = true;
451                 if (owner->view()->theLockingInset()) {
452                         func_status::value_type ret = func_status::Disabled;
453                         if (owner->view()->theLockingInset()->lyxCode() == Inset::TABULAR_CODE) {
454                                 ret = static_cast<InsetTabular *>
455                                         (owner->view()->theLockingInset())->
456                                         getStatus(argument);
457                         } else if (owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE)) {
458                                 ret = static_cast<InsetTabular *>
459                                         (owner->view()->theLockingInset()->
460                                          getFirstLockingInsetOfType(Inset::TABULAR_CODE))->
461                                         getStatus(argument);
462                         }
463                         flag |= ret;
464                         disable = false;
465                 } else {
466                         static InsetTabular inset(*owner->buffer(), 1, 1);
467                         func_status::value_type ret;
468
469                         disable = true;
470                         ret = inset.getStatus(argument);
471                         if ((ret & func_status::ToggleOn) ||
472                             (ret & func_status::ToggleOff))
473                                 flag |= func_status::ToggleOff;
474                 }
475                 break;
476
477         case LFUN_VC_REGISTER:
478                 disable = buf->lyxvc.inUse();
479                 break;
480         case LFUN_VC_CHECKIN:
481                 disable = !buf->lyxvc.inUse() || buf->isReadonly();
482                 break;
483         case LFUN_VC_CHECKOUT:
484                 disable = !buf->lyxvc.inUse() || !buf->isReadonly();
485                 break;
486         case LFUN_VC_REVERT:
487         case LFUN_VC_UNDO:
488         case LFUN_VC_HISTORY:
489                 disable = !buf->lyxvc.inUse();
490                 break;
491         case LFUN_BOOKMARK_GOTO:
492                 disable =  !owner->view()->
493                         isSavedPosition(strToUnsignedInt(argument));
494                 break;
495
496
497         case LFUN_INSET_TOGGLE:
498                 disable = (TEXT(false)->getInset() == 0);
499                 break;
500
501         case LFUN_MATH_VALIGN: {
502     // I think this test can be simplified (Andre')
503                 // mathcursor is != 0  iff we are in math mode
504                 //Inset * tli = owner->view()->theLockingInset();
505                 //if (tli && (tli->lyxCode() == Inset::MATH_CODE 
506                 //          || tli->lyxCode() == Inset::MATHMACRO_CODE)) {
507                 //
508                 if (mathcursor) {
509                         char align = mathcursor->valign();
510                         if (align == '\0') {
511                                 disable = true;
512                                 break;
513                         }
514                         if (argument.empty()) {
515                                 flag = func_status::OK;
516                                 break;
517                         }
518                         if (!contains("tcb", argument[0])) {
519                                 disable = true;
520                                 break;
521                         }
522                         if (argument[0] == align) 
523                                 flag |= func_status::ToggleOn;
524                         else
525                                 flag |= func_status::ToggleOff;
526                 } else
527                         disable = true;
528                 break;
529         }
530         case LFUN_MATH_HALIGN: {
531                 //Inset * tli = owner->view()->theLockingInset();
532                 //if (tli && (tli->lyxCode() == Inset::MATH_CODE 
533                 //          || tli->lyxCode() == Inset::MATHMACRO_CODE)) {
534                 if (mathcursor) {
535                         char align = mathcursor->halign();
536                         if (align == '\0') {
537                                 disable = true;
538                                 break;
539                         }
540                         if (argument.empty()) {
541                                 flag = func_status::OK;
542                                 break;
543                         }
544                         if (!contains("lcr", argument[0])) {
545                                 disable = true;
546                                 break;
547                         }
548                         if (argument[0] == align) 
549                                 flag |= func_status::ToggleOn;
550                         else
551                                 flag |= func_status::ToggleOff;
552                 } else
553                         disable = true;
554                 break;
555         }
556         case LFUN_MATH_MUTATE: {
557                 Inset * tli = owner->view()->theLockingInset();
558                 if (tli && (tli->lyxCode() == Inset::MATH_CODE)) {
559                         MathInsetTypes type = mathcursor->formula()->getType();
560                         func_status::value_type box = func_status::ToggleOff;
561                         if (argument == "inline") {
562                                 if (type == LM_OT_SIMPLE)
563                                         box = func_status::ToggleOn;
564                         } else if (argument == "display") {
565                                 if (type == LM_OT_EQUATION)
566                                         box = func_status::ToggleOn;
567                         } else if (argument == "eqnarray") {
568                                 if (type == LM_OT_EQNARRAY)
569                                         box = func_status::ToggleOn;
570                         } else if (argument == "align") {
571                                 if (type == LM_OT_ALIGN)
572                                         box = func_status::ToggleOn;
573                         } else {
574                                 box = func_status::OK;
575                                 disable = true;
576                         }
577                         flag |= box;
578                 } else
579                         disable = true;
580                 break;
581         }
582
583         // we just need to be in math mode to enable that
584         case LFUN_MATH_SIZE: 
585         case LFUN_MATH_SPACE:
586         case LFUN_MATH_LIMITS: 
587         case LFUN_MATH_NONUMBER: 
588         case LFUN_MATH_NUMBER:
589                 disable = !mathcursor;
590                 break;
591
592         // we need to be math mode and a math array for that
593         // Hack: halign produces non-zero result iff we are in a math array
594         case LFUN_MATH_ROW_INSERT: 
595         case LFUN_MATH_ROW_DELETE: 
596         case LFUN_MATH_COLUMN_INSERT: 
597         case LFUN_MATH_COLUMN_DELETE: 
598                 disable = !mathcursor || !mathcursor->halign();
599                 break;
600
601         default:
602                 break;
603         }
604
605         // the functions which insert insets
606         Inset::Code code = Inset::NO_CODE;
607         switch (action) {
608         case LFUN_INSET_TEXT:
609                 code = Inset::TEXT_CODE;
610                 break;
611         case LFUN_INSET_ERT:
612                 code = Inset::ERT_CODE;         
613                 break;
614         case LFUN_FIGURE:
615         case LFUN_INSET_GRAPHICS:
616                 code = Inset::GRAPHICS_CODE;
617                 break;
618         case LFUN_INSET_FOOTNOTE:
619                 code = Inset::FOOT_CODE;
620                 break;
621         case LFUN_DIALOG_TABULAR_INSERT:
622         case LFUN_INSET_TABULAR:
623                 code = Inset::TABULAR_CODE;
624                 break;
625         case LFUN_INSET_EXTERNAL:
626                 code = Inset::EXTERNAL_CODE;
627                 break;
628         case LFUN_INSET_MARGINAL:
629                 code = Inset::MARGIN_CODE;
630                 break;
631         case LFUN_INSET_MINIPAGE:
632                 code = Inset::MINIPAGE_CODE;
633                 break;
634         case LFUN_INSET_FLOAT:
635         case LFUN_INSET_WIDE_FLOAT:
636                 code = Inset::FLOAT_CODE;
637                 break;
638         case LFUN_FLOAT_LIST:
639                 code = Inset::FLOAT_LIST_CODE;
640                 break;
641 #if 0
642         case LFUN_INSET_LIST:
643                 code = Inset::LIST_CODE;
644                 break;
645         case LFUN_INSET_THEOREM:
646                 code = Inset::THEOREM_CODE;
647                 break;
648 #endif
649         case LFUN_INSET_CAPTION:
650                 code = Inset::CAPTION_CODE;
651                 break;
652         case LFUN_INSERT_NOTE:
653                 code = Inset::IGNORE_CODE;
654                 break;
655         case LFUN_INSERT_LABEL:
656                 code = Inset::LABEL_CODE;
657                 break;
658         case LFUN_REF_INSERT:
659                 code = Inset::REF_CODE;
660                 break;
661         case LFUN_CITATION_CREATE:
662         case LFUN_CITATION_INSERT:
663                 code = Inset::CITE_CODE;
664                 break;
665         case LFUN_INSERT_BIBTEX:
666                 code = Inset::BIBTEX_CODE;
667                 break;
668         case LFUN_INDEX_INSERT:
669         case LFUN_INDEX_INSERT_LAST:
670         case LFUN_INDEX_CREATE:
671                 code = Inset::INDEX_CODE;
672                 break;
673         case LFUN_INDEX_PRINT:
674                 code = Inset::INDEX_PRINT_CODE;
675                 break;
676         case LFUN_CHILD_INSERT:
677                 code = Inset::INCLUDE_CODE;
678                 break;
679         case LFUN_TOC_INSERT:
680                 code = Inset::TOC_CODE;
681                 break;
682         case LFUN_PARENTINSERT:
683                 code = Inset::PARENT_CODE;
684                 break;
685         case LFUN_HTMLURL:
686         case LFUN_URL:
687         case LFUN_INSERT_URL:
688                 code = Inset::URL_CODE;
689                 break;
690         case LFUN_QUOTE:
691                 // always allow this, since we will inset a raw quote
692                 // if an inset is not allowed.
693                 break;
694         case LFUN_HYPHENATION:
695         case LFUN_LIGATURE_BREAK:
696         case LFUN_HFILL:
697         case LFUN_MENU_SEPARATOR:
698         case LFUN_LDOTS:
699         case LFUN_END_OF_SENTENCE:
700         case LFUN_PROTECTEDSPACE:
701                 code = Inset::SPECIALCHAR_CODE;
702                 break;
703         default:
704                 break;
705         }
706         if (code != Inset::NO_CODE 
707             && owner->view()->theLockingInset()
708             && !owner->view()->theLockingInset()->insetAllowed(code)) {
709                 disable = true;
710         }
711
712         if (disable)
713                 flag |= func_status::Disabled;
714         
715         // the font related functions (and a few others)
716         func_status::value_type box = func_status::ToggleOff;
717         LyXFont const & font =
718                 TEXT(false)->real_current_font;
719         switch (action) {
720         case LFUN_EMPH:
721                 if (font.emph() == LyXFont::ON)
722                         box = func_status::ToggleOn;
723                 break;
724         case LFUN_NOUN:
725                 if (font.noun() == LyXFont::ON)
726                         box = func_status::ToggleOn;
727                 break;
728         case LFUN_BOLD:
729                 if (font.series() == LyXFont::BOLD_SERIES)
730                         box = func_status::ToggleOn;
731                 break;
732         case LFUN_READ_ONLY_TOGGLE:
733                 if (buf->isReadonly())
734                         box = func_status::ToggleOn;
735                 break;
736         case LFUN_APPENDIX:
737                 if (TEXT(false)->cursor.par()->params().startOfAppendix())
738                         box = func_status::ToggleOn;
739                 break;
740         default:
741                 box = func_status::OK;
742                 break;
743         }
744         flag |= box;
745
746         return flag;
747 }
748
749
750 // temporary dispatch method
751 void LyXFunc::miniDispatch(string const & s) 
752 {
753         if (!s.empty()) {
754                 dispatch(s);
755         }
756 }
757
758
759 string const LyXFunc::dispatch(string const & s) 
760 {
761         // Split command string into command and argument
762         string cmd;
763         string line = frontStrip(s);
764         string const arg = strip(frontStrip(split(line, cmd, ' ')));
765
766         return dispatch(lyxaction.LookupFunc(cmd), arg);
767 }
768
769
770 string const LyXFunc::dispatch(int ac,
771                                string const & do_not_use_this_arg)
772 {
773         lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << ac
774                               <<"] arg[" << do_not_use_this_arg << "]" << endl;
775         
776         string argument;
777         kb_action action;
778         
779         // we have not done anything wrong yet.
780         errorstat = false;
781         dispatch_buffer.erase();
782         
783         // if action is a pseudo-action, we need the real action
784         if (lyxaction.isPseudoAction(ac)) {
785                 string tmparg;
786                 action = static_cast<kb_action>
787                         (lyxaction.retrieveActionArg(ac, tmparg));
788                 if (!tmparg.empty())
789                         argument = tmparg;
790         } else {
791                 action = static_cast<kb_action>(ac);
792                 if (!do_not_use_this_arg.empty())
793                         argument = do_not_use_this_arg; // except here
794         }
795
796 #ifdef NEW_DISPATCHER
797         // We try do call the most specific dispatcher first:
798         //  1. the lockinginset's dispatch
799         //  2. the bufferview's dispatch
800         //  3. the lyxview's dispatch
801 #endif
802         
803         selection_possible = false;
804         
805         if (owner->view()->available())
806                 owner->view()->hideCursor();
807
808         // We cannot use this function here
809         if (getStatus(ac, do_not_use_this_arg) & func_status::Disabled) {
810                 lyxerr << "LyXFunc::Dispatch: "
811                        << lyxaction.getActionName(ac)
812                        << " [" << ac << "] is disabled at this location"
813                        << endl;
814                 goto exit_with_message;
815         }
816
817         if (owner->view()->available() && owner->view()->theLockingInset()) {
818                 UpdatableInset::RESULT result;
819                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
820                                      (keyseq.length >= -1)))
821                 {
822                         if ((action==LFUN_UNKNOWN_ACTION) && argument.empty()){
823                                 argument = keyseq.getiso();
824                         }
825                         // Undo/Redo is a bit tricky for insets.
826                         if (action == LFUN_UNDO) {
827 #ifdef RETHINK_THIS_FOR_NOW_WE_LEAVE_ALL_UNLOCKED
828                                 int slx;
829                                 int sly;
830                                 UpdatableInset * inset = 
831                                         owner->view()->theLockingInset()->getLockingInset();
832                                 int inset_id = inset->id();
833                                 inset->getCursorPos(owner->view(), slx, sly);
834                                 owner->view()->unlockInset(inset);
835 #else
836                                 owner->view()->unlockInset(owner->view()->theLockingInset());
837 #endif
838                                 owner->view()->menuUndo();
839 #ifdef RETHINK_THIS_FOR_NOW_WE_LEAVE_ALL_UNLOCKED
840 #if 0
841                                 if (TEXT()->cursor.par()->
842                                     isInset(TEXT()->cursor.pos())) {
843                                         inset = static_cast<UpdatableInset*>(
844                                                 TEXT()->cursor.par()->
845                                                 getInset(TEXT()->
846                                                          cursor.pos()));
847                                 } else {
848                                         inset = 0;
849                                 }
850 #else
851                                 inset = static_cast<UpdatableInset *>(owner->view()->buffer()->getInsetFromID(inset_id));
852 #endif
853                                 if (inset)
854                                         inset->edit(owner->view(),slx,sly,0);
855 #endif
856                                 return string();
857                         } else if (action == LFUN_REDO) {
858                                 int slx;
859                                 int sly;
860                                 UpdatableInset * inset = owner->view()->
861                                         theLockingInset();
862                                 inset->getCursorPos(owner->view(), slx, sly);
863                                 owner->view()->unlockInset(inset);
864                                 owner->view()->menuRedo();
865                                 inset = static_cast<UpdatableInset*>(
866                                         TEXT()->cursor.par()->
867                                         getInset(TEXT()->
868                                                  cursor.pos()));
869                                 if (inset)
870                                         inset->edit(owner->view(),slx,sly,0); 
871                                 return string();
872                         } else if (((result=owner->view()->theLockingInset()->
873                                      localDispatch(owner->view(), action, argument)) ==
874                                     UpdatableInset::DISPATCHED) ||
875                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
876                                 return string();
877                         else if (result == UpdatableInset::FINISHED) {
878                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
879                                                 TEXT()->cursorRight(owner->view());
880                                                 moveCursorUpdate(true, false);
881                                                 owner->showState();
882                                         }
883                                         return string();
884                         } else if (result == UpdatableInset::FINISHED_RIGHT) {
885                                 if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
886                                         TEXT()->cursorRight(owner->view());
887                                         moveCursorUpdate(true, false);
888                                         owner->showState();
889                                 }
890                                 return string();
891                         } else if (result == UpdatableInset::FINISHED_UP) {
892                                 if (TEXT()->cursor.row()->previous()) {
893                                         TEXT()->cursorUp(owner->view());
894                                         moveCursorUpdate(true, false);
895                                         owner->showState();
896                                 }
897                                 return string();
898                         } else if (result == UpdatableInset::FINISHED_DOWN) {
899                                 if (TEXT()->cursor.row()->next())
900                                         TEXT()->cursorDown(owner->view());
901                                 else
902                                         TEXT()->cursorRight(owner->view());
903                                 moveCursorUpdate(true, false);
904                                 owner->showState();
905                                 return string();
906                         } else {
907                                 //setMessage(N_("Text mode"));
908                                 switch (action) {
909                                 case LFUN_UNKNOWN_ACTION:
910                                 case LFUN_BREAKPARAGRAPH:
911                                 case LFUN_BREAKLINE:
912                                         TEXT()->cursorRight(owner->view());
913                                         owner->view()->setState();
914                                         owner->showState();
915                                         break;
916                                 case LFUN_RIGHT:
917                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
918                                                 TEXT()->cursorRight(owner->view());
919                                                 moveCursorUpdate(true, false);
920                                                 owner->showState();
921                                         }
922                                         return string();
923                                 case LFUN_LEFT: 
924                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
925                                                 TEXT()->cursorRight(owner->view());
926                                                 moveCursorUpdate(true, false);
927                                                 owner->showState();
928                                         }
929                                         return string();
930                                 case LFUN_DOWN:
931                                         if (TEXT()->cursor.row()->next())
932                                                 TEXT()->cursorDown(owner->view());
933                                         else
934                                                 TEXT()->cursorRight(owner->view());
935                                         moveCursorUpdate(true, false);
936                                         owner->showState();
937                                         return string();
938                                 default:
939                                         break;
940                                 }
941                         }
942                 }
943         }
944
945         switch (action) {
946                 
947         case LFUN_ESCAPE:
948         {
949                 if (!owner->view()->available()) break;
950                 
951                 // this function should be used always [asierra060396]
952                 UpdatableInset * tli =
953                         owner->view()->theLockingInset();
954                 if (tli) {
955                         UpdatableInset * lock = tli->getLockingInset();
956                         
957                         if (tli == lock) {
958                                 owner->view()->unlockInset(tli);
959                                 TEXT()->cursorRight(owner->view());
960                                 moveCursorUpdate(true, false);
961                                 owner->showState();
962                         } else {
963                                 tli->unlockInsetInInset(owner->view(),
964                                                         lock,
965                                                         true);
966                         }
967                 }
968         }
969         break;
970                         
971                 // --- Misc -------------------------------------------
972         case LFUN_WORDFINDFORWARD  : 
973         case LFUN_WORDFINDBACKWARD : {
974                 static string last_search;
975                 string searched_string;
976             
977                 if (!argument.empty()) {
978                         last_search = argument;
979                         searched_string = argument;
980                 } else {
981                         searched_string = last_search;
982                 }
983                 bool fw = (action == LFUN_WORDFINDBACKWARD);
984                 if (!searched_string.empty()) {
985                         LyXFind(owner->view(), searched_string, fw);
986                 }
987 //              owner->view()->showCursor();
988         }
989         break;
990                 
991         case LFUN_PREFIX:
992         {
993                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
994                         owner->view()->update(TEXT(),
995                                               BufferView::SELECT|BufferView::FITCUR);
996                 }
997                 string buf;
998                 keyseq.print(buf, true);
999                 owner->message(buf);
1000         }
1001         break;
1002
1003         // --- Misc -------------------------------------------
1004         case LFUN_EXEC_COMMAND:
1005         {
1006                 std::vector<string> allCmds;
1007                 std::transform(lyxaction.func_begin(), lyxaction.func_end(),
1008                                std::back_inserter(allCmds), lyx::firster());
1009                 static std::vector<string> hist;
1010                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
1011                                                   allCmds, hist);
1012         }
1013         break;
1014                 
1015         case LFUN_CANCEL:                   // RVDK_PATCH_5
1016                 keyseq.reset();
1017                 meta_fake_bit = 0;
1018                 if (owner->view()->available())
1019                         // cancel any selection
1020                         dispatch(LFUN_MARK_OFF);
1021                 setMessage(N_("Cancel"));
1022                 break;
1023
1024         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1025         {
1026                 meta_fake_bit = Mod1Mask;
1027                 string buf;
1028                 keyseq.print(buf, true);
1029                 setMessage(buf); // RVDK_PATCH_5
1030         }
1031         break;  
1032
1033         case LFUN_READ_ONLY_TOGGLE:
1034                 if (owner->buffer()->lyxvc.inUse()) {
1035                         owner->buffer()->lyxvc.toggleReadOnly();
1036                 } else {
1037                         owner->buffer()->setReadonly(
1038                                 !owner->buffer()->isReadonly());
1039                 }
1040                 break;
1041                 
1042         case LFUN_CENTER: // this is center and redraw.
1043                 owner->view()->center();
1044                 break;
1045                 
1046                 // --- Menus -----------------------------------------------
1047         case LFUN_MENUNEW:
1048                 menuNew(false);
1049                 break;
1050                 
1051         case LFUN_MENUNEWTMPLT:
1052                 menuNew(true);
1053                 break;
1054                 
1055         case LFUN_CLOSEBUFFER:
1056                 closeBuffer();
1057                 break;
1058                 
1059         case LFUN_MENUWRITE:
1060                 if (!owner->buffer()->isUnnamed()) {
1061                         ostringstream s1;
1062                         s1 << _("Saving document") << ' '
1063                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1064                         owner->message(s1.str().c_str());
1065                         MenuWrite(owner->view(), owner->buffer());
1066                 } else
1067                         WriteAs(owner->view(), owner->buffer());
1068                 break;
1069                 
1070         case LFUN_WRITEAS:
1071                 WriteAs(owner->view(), owner->buffer(), argument);
1072                 break;
1073                 
1074         case LFUN_MENURELOAD:
1075                 reloadBuffer();
1076                 break;
1077                 
1078         case LFUN_UPDATE:
1079                 Exporter::Export(owner->buffer(), argument, true);
1080                 break;
1081
1082         case LFUN_PREVIEW:
1083                 Exporter::Preview(owner->buffer(), argument);
1084                 break;
1085                 
1086         case LFUN_BUILDPROG:
1087                 Exporter::Export(owner->buffer(), "program", true);
1088                 break;
1089                 
1090         case LFUN_RUNCHKTEX:
1091                 MenuRunChktex(owner->buffer());
1092                 break;
1093                                 
1094         case LFUN_MENUPRINT:
1095                 owner->getDialogs()->showPrint();
1096                 break;
1097
1098         case LFUN_EXPORT:
1099                 if (argument == "custom")
1100                         MenuSendto();
1101                 else
1102                         Exporter::Export(owner->buffer(), argument, false);
1103                 break;
1104
1105         case LFUN_IMPORT:
1106                 doImport(argument);
1107                 break;
1108                 
1109         case LFUN_QUIT:
1110                 QuitLyX();
1111                 break;
1112                 
1113         case LFUN_TOCVIEW:
1114 #if 0
1115         case LFUN_LOFVIEW:
1116         case LFUN_LOTVIEW:
1117         case LFUN_LOAVIEW:
1118 #endif
1119         {
1120                 InsetCommandParams p;
1121
1122 #if 0
1123                 if (action == LFUN_TOCVIEW)
1124 #endif
1125                         p.setCmdName("tableofcontents");
1126 #if 0
1127                 else if (action == LFUN_LOAVIEW )
1128                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1129                 else if (action == LFUN_LOFVIEW)
1130                         p.setCmdName("listoffigures");
1131                 else
1132                         p.setCmdName("listoftables");
1133 #endif
1134                 owner->getDialogs()->createTOC(p.getAsString());
1135                 break;
1136         }       
1137
1138         case LFUN_DIALOG_TABULAR_INSERT:
1139                 owner->getDialogs()->showTabularCreate();
1140                 break;
1141                 
1142         case LFUN_FIGURE:
1143                 Figure();
1144                 break;
1145
1146         case LFUN_AUTOSAVE:
1147                 AutoSave(owner->view());
1148                 break;
1149                 
1150         case LFUN_UNDO:
1151                 owner->view()->menuUndo();
1152                 break;
1153                 
1154         case LFUN_REDO:
1155                 owner->view()->menuRedo();
1156                 break;
1157                 
1158         case LFUN_MENUSEARCH:
1159                 owner->getDialogs()->showSearch();
1160                 break;
1161                 
1162         case LFUN_REMOVEERRORS:
1163                 if (owner->view()->removeAutoInsets()) {
1164                         owner->view()->redraw();
1165                         owner->view()->fitCursor();
1166                 }
1167                 break;
1168
1169         case LFUN_DEPTH:
1170                 changeDepth(owner->view(), TEXT(false), 0);
1171                 break;
1172                 
1173         case LFUN_DEPTH_MIN:
1174                 changeDepth(owner->view(), TEXT(false), -1);
1175                 break;
1176                 
1177         case LFUN_DEPTH_PLUS:
1178                 changeDepth(owner->view(), TEXT(false), 1);
1179                 break;
1180                 
1181         case LFUN_FREE:
1182                 owner->getDialogs()->setUserFreeFont();
1183                 break;
1184
1185         case LFUN_RECONFIGURE:
1186                 Reconfigure(owner->view());
1187                 break;
1188
1189 #if 0
1190         case LFUN_FLOATSOPERATE:
1191                 if (argument == "openfoot")
1192                         owner->view()->allFloats(1,0);
1193                 else if (argument == "closefoot")
1194                         owner->view()->allFloats(0,0);
1195                 else if (argument == "openfig")
1196                         owner->view()->allFloats(1,1);
1197                 else if (argument == "closefig")
1198                         owner->view()->allFloats(0,1);
1199                 break;
1200 #else
1201 #ifdef WITH_WARNINGS
1202 //#warning Find another implementation here (or another lyxfunc)!
1203 #endif
1204 #endif
1205         case LFUN_HELP_ABOUTLYX:
1206                 owner->getDialogs()->showAboutlyx();
1207                 break;
1208
1209         case LFUN_HELP_TEXINFO:
1210                 owner->getDialogs()->showTexinfo();
1211                 break;
1212
1213         case LFUN_HELP_OPEN:
1214         {
1215                 string const arg = argument;
1216                 if (arg.empty()) {
1217                         setErrorMessage(N_("Missing argument"));
1218                         break;
1219                 }
1220                 owner->prohibitInput();
1221                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1222                 if (fname.empty()) {
1223                         lyxerr << "LyX: unable to find documentation file `"
1224                                << arg << "'. Bad installation?" << endl;
1225                         owner->allowInput();
1226                         break;
1227                 }
1228                 ostringstream str;
1229                 str << _("Opening help file") << ' '
1230                     << MakeDisplayPath(fname) << "...";
1231                 owner->message(str.str().c_str());
1232                 owner->view()->buffer(bufferlist.loadLyXFile(fname, false));
1233                 owner->allowInput();
1234                 break;
1235         }
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 document") << ' ' << 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.versionString();
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