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