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