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