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