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