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