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