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