]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
make inset-toggle work when cursor is inside inset
[lyx.git] / src / lyxfunc.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *          Copyright 1995 Matthias Ettrich
7  *          Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation
15 #endif
16
17 #include "lyxfunc.h"
18 #include "version.h"
19 #include "kbmap.h"
20 #include "lyxrow.h"
21 #include "bufferlist.h"
22 #include "BufferView.h"
23 #include "ColorHandler.h"
24 #include "lyxserver.h"
25 #include "intl.h"
26 #include "lyx_main.h"
27 #include "lyx_cb.h"
28 #include "LyXAction.h"
29 #include "debug.h"
30 #include "lyxrc.h"
31 #include "lyxtext.h"
32 #include "gettext.h"
33 #include "Lsstream.h"
34 #include "trans_mgr.h"
35 #include "layout.h"
36 #include "WorkArea.h"
37 #include "bufferview_funcs.h"
38 #include "minibuffer.h"
39 #include "vspace.h"
40 #include "LyXView.h"
41 #include "lyx_gui_misc.h"
42 #include "FloatList.h"
43 #include "converter.h"
44 #include "exporter.h"
45 #include "importer.h"
46 #include "FontLoader.h"
47 #include "TextCache.h"
48 #include "lyxfind.h"
49 #include "undo_funcs.h"
50 #include "ParagraphParameters.h"
51 #include "figureForm.h"
52
53 #include "insets/inseturl.h"
54 #include "insets/insetlatexaccent.h"
55 #include "insets/insettoc.h"
56 #include "insets/insetref.h"
57 #include "insets/insetparent.h"
58 #include "insets/insetindex.h"
59 #include "insets/insetinclude.h"
60 #include "insets/insetbib.h"
61 #include "insets/insetcite.h"
62 #include "insets/insettext.h"
63 #include "insets/insetert.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetgraphics.h"
66 #include "insets/insetfoot.h"
67 #include "insets/insetmarginal.h"
68 #include "insets/insetminipage.h"
69 #include "insets/insetfloat.h"
70 #if 0
71 #include "insets/insetlist.h"
72 #include "insets/insettheorem.h"
73 #endif
74 #include "insets/insettabular.h"
75 #include "insets/insetcaption.h"
76
77 #include "mathed/formulamacro.h"
78 #include "mathed/math_cursor.h"
79 #include "mathed/math_inset.h"
80
81 #include "frontends/FileDialog.h"
82 #include "frontends/Dialogs.h"
83 #include "frontends/Toolbar.h"
84 #include "frontends/Menubar.h"
85 #include "frontends/Alert.h"
86
87 #include "support/lyxalgo.h"
88 #include "support/LAssert.h"
89 #include "support/filetools.h"
90 #include "support/FileInfo.h"
91 #include "support/syscall.h"
92 #include "support/lstrings.h"
93 #include "support/path.h"
94 #include "support/lyxfunctional.h"
95
96 #include <ctime>
97 #include <clocale>
98 #include <cstdlib>
99 #include <cctype>
100
101 #include <utility> 
102 #include <algorithm> 
103
104
105 using std::pair;
106 using std::make_pair; 
107 using std::endl;
108 using std::find_if;
109
110 extern BufferList bufferlist;
111 extern LyXServer * lyxserver;
112 extern bool selection_possible;
113 extern void MenuSendto();
114
115 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
116
117 extern void show_symbols_form(LyXFunc *);
118
119 extern LyXAction lyxaction;
120 // (alkis)
121 extern tex_accent_struct get_accent(kb_action action);
122
123 extern void ShowLatexLog();
124
125
126 #if 0
127
128 ///
129 class MiniBufferController : public SigC::Object {
130 public:
131         ///
132         MiniBufferController() {
133                 minibuffer
134                         .cmdReady
135                         .connect(slot(this,
136                                       &MiniBufferController::receiveCommand));
137                 minibuffer
138                         .argReady
139                         .connect(slot(this,
140                                       &MiniBufferController::receiveArg));
141         }
142         ///
143         void receiveCmd(string const & cmd) {}
144         ///
145         void receiveArg(string const & arg) {}
146         
147         
148 private:
149 };
150
151 namespace {
152
153 MiniBufferController mb_ctrl;
154
155 }
156 #endif
157
158
159 /* === globals =========================================================== */
160
161
162 LyXFunc::LyXFunc(LyXView * o)
163         : owner(o),
164         keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
165         cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get())
166 {
167         meta_fake_bit = 0;
168         lyx_dead_action = LFUN_NOACTION;
169         lyx_calling_dead_action = LFUN_NOACTION;
170 }
171
172
173 inline
174 LyXText * LyXFunc::TEXT(bool flag = true) const
175 {
176         if (flag)
177                 return owner->view()->text;
178         return owner->view()->getLyXText();
179 }
180
181
182 // I changed this func slightly. I commented out the ...FinishUndo(),
183 // this means that all places that used to have a moveCursorUpdate, now
184 // have a ...FinishUndo() as the preceeding statement. I have also added
185 // a moveCursorUpdate to some of the functions that updated the cursor, but
186 // that did not show its new position.
187 inline
188 void LyXFunc::moveCursorUpdate(bool flag, bool selecting)
189 {
190         if (selecting || TEXT(flag)->selection.mark()) {
191                 TEXT(flag)->setSelection(owner->view());
192                 if (TEXT(flag)->bv_owner)
193                     owner->view()->toggleToggle();
194         }
195         owner->view()->update(TEXT(flag), BufferView::SELECT|BufferView::FITCUR);
196         owner->view()->showCursor();
197         
198         /* ---> Everytime the cursor is moved, show the current font state. */
199         // should this too me moved out of this func?
200         owner->view()->setState();
201 }
202
203
204 void LyXFunc::handleKeyFunc(kb_action action)
205 {
206         char c = keyseq.getiso();
207
208         if (keyseq.length() > 1) {
209                 c = 0;
210         }
211         
212         owner->getIntl()->getTrans()
213                 .deadkey(c, get_accent(action).accent, TEXT(false));
214         // Need to clear, in case the minibuffer calls these
215         // actions
216         keyseq.clear();
217         // copied verbatim from do_accent_char
218         owner->view()->update(TEXT(false),
219                BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
220         TEXT(false)->selection.cursor = TEXT(false)->cursor;
221 }
222
223
224 void LyXFunc::processKeySym(KeySym keysym, unsigned int state) 
225 {
226         string argument;
227         
228         if (lyxerr.debugging(Debug::KEY)) {
229                 char const * tmp = XKeysymToString(keysym);
230                 string const stm = (tmp ? tmp : "");
231                 lyxerr << "KeySym is "
232                        << stm
233                        << "["
234                        << keysym << "] State is ["
235                        << state << "]"
236                        << endl;
237         }
238         // Do nothing if we have nothing (JMarc)
239         if (keysym == NoSymbol) {
240                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
241                                    << endl;
242                 return;
243         }
244
245         // Can we be sure that this will work for all X Window
246         // implementations? (Lgb)
247         // This code snippet makes lyx ignore some keys. Perhaps
248         // all of them should be explictly mentioned?
249         if ((keysym >= XK_Shift_L && keysym <= XK_Hyper_R)
250             || keysym == XK_Mode_switch || keysym == 0x0) {
251                 return;
252         }
253         
254         // Do a one-deep top-level lookup for
255         // cancel and meta-fake keys. RVDK_PATCH_5
256         cancel_meta_seq.reset();
257
258         int action = cancel_meta_seq.addkey(keysym, state
259                                             &(ShiftMask|ControlMask
260                                               |Mod1Mask)); 
261         if (lyxerr.debugging(Debug::KEY)) {
262                 lyxerr << "action first set to [" << action << "]" << endl;
263         }
264         
265         // When not cancel or meta-fake, do the normal lookup. 
266         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
267         // Mostly, meta_fake_bit = 0. RVDK_PATCH_5.
268         if ((action != LFUN_CANCEL) && (action != LFUN_META_FAKE)) {
269                 if (lyxerr.debugging(Debug::KEY)) {
270                         lyxerr << "meta_fake_bit is ["
271                                << meta_fake_bit << "]" << endl;
272                 }
273                 // remove Caps Lock and Mod2 as a modifiers
274                 action = keyseq.addkey(keysym,
275                                        (state | meta_fake_bit)
276                                        &(ShiftMask|ControlMask
277                                          |Mod1Mask));
278                 if (lyxerr.debugging(Debug::KEY)) {
279                         lyxerr << "action now set to ["
280                                << action << "]" << endl;
281                 }
282         }
283         // Dont remove this unless you know what you are doing.
284         meta_fake_bit = 0;
285                 
286         // can this happen now ? 
287         if (action == LFUN_NOACTION) {
288                 action = LFUN_PREFIX;
289         }
290
291         if (lyxerr.debugging(Debug::KEY)) {
292                 lyxerr << "Key [action="
293                        << action << "]["
294                        << keyseq.print() << "]"
295                        << endl;
296         }
297
298         // already here we know if it any point in going further
299         // why not return already here if action == -1 and
300         // num_bytes == 0? (Lgb)
301
302         if (keyseq.length() > 1 && !keyseq.deleted()) {
303                 owner->message(keyseq.print());
304         }
305
306         if (action == LFUN_UNKNOWN_ACTION) {
307                 // It is unknown, but what if we remove all
308                 // the modifiers? (Lgb)
309                 action = keyseq.addkey(keysym, 0);
310
311                 if (lyxerr.debugging(Debug::KEY)) {
312                         lyxerr << "Removing modifiers...\n"
313                                << "Action now set to ["
314                                << action << "]" << endl;
315                 }
316                 if (action == LFUN_UNKNOWN_ACTION) {
317                         owner->message(_("Unknown function."));
318                         return;
319                 }
320         }
321
322         if (action == LFUN_SELFINSERT) {
323                 // This is very X dependent.
324                 unsigned int c = keysym;
325                 string argument;
326                 
327                 c = kb_keymap::getiso(c);
328
329                 if (c > 0)
330                         argument = static_cast<char>(c);
331                 
332                 dispatch(LFUN_SELFINSERT, argument);
333                 lyxerr[Debug::KEY] << "SelfInsert arg[`"
334                                    << argument << "']" << endl;
335         }
336         else
337                 verboseDispatch(action, false);
338
339
340
341 FuncStatus LyXFunc::getStatus(int ac) const
342 {
343         kb_action action;
344         string argument;
345         action = lyxaction.retrieveActionArg(ac, argument);
346         return getStatus(action, argument);
347 }
348
349
350 FuncStatus LyXFunc::getStatus(kb_action action,
351                               string const & argument) const
352 {
353         FuncStatus flag;
354         Buffer * buf = owner->buffer();
355         
356         if (action == LFUN_UNKNOWN_ACTION) {
357                 setStatusMessage(N_("Unknown action"));
358                 return flag.unknown(true);
359         }
360
361         // the default error message if we disable the command
362         setStatusMessage(N_("Command disabled"));
363         
364         // Check whether we need a buffer
365         if (!lyxaction.funcHasFlag(action, LyXAction::NoBuffer)) {
366                 // Yes we need a buffer, do we have one?
367                 if (buf) {
368                         // yes
369                         // Can we use a readonly buffer?
370                         if (buf->isReadonly() && 
371                             !lyxaction.funcHasFlag(action,
372                                                    LyXAction::ReadOnly)) {
373                                 // no
374                                 setStatusMessage(N_("Document is read-only"));
375                                 flag.disabled(true);
376                         }
377                 } else {
378                         // no
379                         setStatusMessage(N_("Command not allowed with"
380                                            "out any document open"));
381                         return flag.disabled(true);
382                 }
383         }
384
385         UpdatableInset * tli = owner->view()->theLockingInset();
386         
387         // I would really like to avoid having this switch and rather try to
388         // encode this in the function itself.
389         bool disable = false;
390         switch (action) {
391         case LFUN_MENUPRINT:
392                 disable = !Exporter::IsExportable(buf, "dvi")
393                         || lyxrc.print_command == "none";
394                 break;
395         case LFUN_EXPORT:
396                 disable = argument == "fax" &&
397                         !Exporter::IsExportable(buf, argument);
398                 break;
399         case LFUN_UNDO:
400                 disable = buf->undostack.empty();
401                 break;
402         case LFUN_REDO:
403                 disable = buf->redostack.empty();
404                 break;
405         case LFUN_SPELLCHECK:
406                 disable = lyxrc.isp_command == "none";
407                 break;
408 #ifndef HAVE_LIBAIKSAURUS
409         case LFUN_THESAURUS_ENTRY:
410                 disable = true;
411                 break;
412 #endif
413         case LFUN_RUNCHKTEX:
414                 disable = lyxrc.chktex_command == "none";
415                 break;
416         case LFUN_BUILDPROG:
417                 disable = !Exporter::IsExportable(buf, "program");
418                 break;
419
420         case LFUN_LAYOUT_TABULAR:
421                 disable = !tli
422                         || (tli->lyxCode() != Inset::TABULAR_CODE
423                             && !tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
424                 break;
425
426         case LFUN_LAYOUT:
427         case LFUN_LAYOUT_PARAGRAPH: {
428                 Inset * inset = TEXT(false)->cursor.par()->inInset();
429                 disable = inset && inset->forceDefaultParagraphs(inset);
430                 break;
431         }
432
433         case LFUN_TABULAR_FEATURE:
434                 disable = true;
435                 if (tli) {
436                         FuncStatus ret;
437                         //ret.disabled(true);
438                         if (tli->lyxCode() == Inset::TABULAR_CODE) {
439                                 ret = static_cast<InsetTabular *>(tli)
440                                         ->getStatus(argument);
441                         } else if (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE)) {
442                                 ret = static_cast<InsetTabular *>
443                                         (tli->getFirstLockingInsetOfType(Inset::TABULAR_CODE))
444                                         ->getStatus(argument);
445                         }
446                         flag |= ret;
447                         disable = false;
448                 } else {
449                         static InsetTabular inset(*owner->buffer(), 1, 1);
450                         FuncStatus ret;
451
452                         disable = true;
453                         ret = inset.getStatus(argument);
454                         if (ret.onoff(true) || ret.onoff(false))
455                                 flag.setOnOff(false);
456                 }
457                 break;
458
459         case LFUN_VC_REGISTER:
460                 disable = buf->lyxvc.inUse();
461                 break;
462         case LFUN_VC_CHECKIN:
463                 disable = !buf->lyxvc.inUse() || buf->isReadonly();
464                 break;
465         case LFUN_VC_CHECKOUT:
466                 disable = !buf->lyxvc.inUse() || !buf->isReadonly();
467                 break;
468         case LFUN_VC_REVERT:
469         case LFUN_VC_UNDO:
470         case LFUN_VC_HISTORY:
471                 disable = !buf->lyxvc.inUse();
472                 break;
473         case LFUN_BOOKMARK_GOTO:
474                 disable =  !owner->view()->
475                         isSavedPosition(strToUnsignedInt(argument));
476                 break;
477
478
479         case LFUN_INSET_TOGGLE: {
480                 LyXText * lt = owner->view()->getLyXText();
481                 disable = !(isEditableInset(lt->getInset())
482                             || (lt->inset_owner
483                                 && lt->inset_owner->owner()
484                                 && lt->inset_owner->owner()->isOpen()));
485                 break;
486         }
487         case LFUN_MATH_VALIGN: 
488                 if (mathcursor) {
489                         char align = mathcursor->valign();
490                         if (align == '\0') {
491                                 disable = true;
492                                 break;
493                         }
494                         if (argument.empty()) {
495                                 flag.clear();
496                                 break;
497                         }
498                         if (!contains("tcb", argument[0])) {
499                                 disable = true;
500                                 break;
501                         }
502                         flag.setOnOff(argument[0] == align);
503                 } else
504                         disable = true;
505                 break;
506
507         case LFUN_MATH_HALIGN: 
508                 if (mathcursor) {
509                         char align = mathcursor->halign();
510                         if (align == '\0') {
511                                 disable = true;
512                                 break;
513                         }
514                         if (argument.empty()) {
515                                 flag.clear();
516                                 break;
517                         }
518                         if (!contains("lcr", argument[0])) {
519                                 disable = true;
520                                 break;
521                         }
522                         flag.setOnOff(argument[0] == align);
523                 } else
524                         disable = true;
525                 break;
526
527         case LFUN_MATH_MUTATE: 
528                 if (tli && (tli->lyxCode() == Inset::MATH_CODE)) {
529                         MathInsetTypes type = mathcursor->formula()->getType();
530                         if (argument == "inline") {
531                                 flag.setOnOff(type == LM_OT_SIMPLE);
532                         } else if (argument == "display") {
533                                 flag.setOnOff(type == LM_OT_EQUATION);
534                         } else if (argument == "eqnarray") {
535                                 flag.setOnOff(type == LM_OT_EQNARRAY);
536                         } else if (argument == "align") {
537                                 flag.setOnOff(type == LM_OT_ALIGN);
538                         } else {
539                                 disable = true;
540                         }
541                 } else
542                         disable = true;
543                 break;
544
545         // we just need to be in math mode to enable that
546         case LFUN_MATH_SIZE: 
547         case LFUN_MATH_SPACE:
548         case LFUN_MATH_LIMITS: 
549         case LFUN_MATH_NONUMBER: 
550         case LFUN_MATH_NUMBER:
551                 disable = !mathcursor;
552                 break;
553
554         // we need to be math mode and a math array for that
555         // Hack: halign produces non-zero result iff we are in a math array
556         case LFUN_MATH_ROW_INSERT: 
557         case LFUN_MATH_ROW_DELETE: 
558         case LFUN_MATH_COLUMN_INSERT: 
559         case LFUN_MATH_COLUMN_DELETE: 
560                 disable = !mathcursor || !mathcursor->halign();
561                 break;
562
563         default:
564                 break;
565         }
566
567         // the functions which insert insets
568         Inset::Code code = Inset::NO_CODE;
569         switch (action) {
570         case LFUN_INSET_TEXT:
571                 code = Inset::TEXT_CODE;
572                 break;
573         case LFUN_INSET_ERT:
574                 code = Inset::ERT_CODE;         
575                 break;
576         case LFUN_FIGURE:
577         case LFUN_INSET_GRAPHICS:
578                 code = Inset::GRAPHICS_CODE;
579                 break;
580         case LFUN_INSET_FOOTNOTE:
581                 code = Inset::FOOT_CODE;
582                 break;
583         case LFUN_DIALOG_TABULAR_INSERT:
584         case LFUN_INSET_TABULAR:
585                 code = Inset::TABULAR_CODE;
586                 break;
587         case LFUN_INSET_EXTERNAL:
588                 code = Inset::EXTERNAL_CODE;
589                 break;
590         case LFUN_INSET_MARGINAL:
591                 code = Inset::MARGIN_CODE;
592                 break;
593         case LFUN_INSET_MINIPAGE:
594                 code = Inset::MINIPAGE_CODE;
595                 break;
596         case LFUN_INSET_FLOAT:
597         case LFUN_INSET_WIDE_FLOAT:
598                 code = Inset::FLOAT_CODE;
599                 break;
600         case LFUN_FLOAT_LIST:
601                 code = Inset::FLOAT_LIST_CODE;
602                 break;
603 #if 0
604         case LFUN_INSET_LIST:
605                 code = Inset::LIST_CODE;
606                 break;
607         case LFUN_INSET_THEOREM:
608                 code = Inset::THEOREM_CODE;
609                 break;
610 #endif
611         case LFUN_INSET_CAPTION:
612                 code = Inset::CAPTION_CODE;
613                 break;
614         case LFUN_INSERT_NOTE:
615                 code = Inset::IGNORE_CODE;
616                 break;
617         case LFUN_INSERT_LABEL:
618                 code = Inset::LABEL_CODE;
619                 break;
620         case LFUN_REF_INSERT:
621                 code = Inset::REF_CODE;
622                 break;
623         case LFUN_CITATION_CREATE:
624         case LFUN_CITATION_INSERT:
625                 code = Inset::CITE_CODE;
626                 break;
627         case LFUN_INSERT_BIBTEX:
628                 code = Inset::BIBTEX_CODE;
629                 break;
630         case LFUN_INDEX_INSERT:
631         case LFUN_INDEX_INSERT_LAST:
632         case LFUN_INDEX_CREATE:
633                 code = Inset::INDEX_CODE;
634                 break;
635         case LFUN_INDEX_PRINT:
636                 code = Inset::INDEX_PRINT_CODE;
637                 break;
638         case LFUN_CHILD_INSERT:
639                 code = Inset::INCLUDE_CODE;
640                 break;
641         case LFUN_TOC_INSERT:
642                 code = Inset::TOC_CODE;
643                 break;
644         case LFUN_PARENTINSERT:
645                 code = Inset::PARENT_CODE;
646                 break;
647         case LFUN_HTMLURL:
648         case LFUN_URL:
649         case LFUN_INSERT_URL:
650                 code = Inset::URL_CODE;
651                 break;
652         case LFUN_QUOTE:
653                 // always allow this, since we will inset a raw quote
654                 // if an inset is not allowed.
655                 break;
656         case LFUN_HYPHENATION:
657         case LFUN_LIGATURE_BREAK:
658         case LFUN_HFILL:
659         case LFUN_MENU_SEPARATOR:
660         case LFUN_LDOTS:
661         case LFUN_END_OF_SENTENCE:
662         case LFUN_PROTECTEDSPACE:
663                 code = Inset::SPECIALCHAR_CODE;
664                 break;
665         default:
666                 break;
667         }
668         if (code != Inset::NO_CODE && tli && !tli->insetAllowed(code)) {
669                 disable = true;
670         }
671
672         if (disable)
673                         flag.disabled(true);
674         
675         // A few general toggles
676         switch (action) {
677         case LFUN_READ_ONLY_TOGGLE:
678                 flag.setOnOff(buf->isReadonly());
679                 break;
680         case LFUN_APPENDIX:
681                 flag.setOnOff(TEXT(false)->cursor.par()->params().startOfAppendix());
682                 break;
683         case LFUN_SWITCHBUFFER:
684                 // toggle on the current buffer, but do not toggle off
685                 // the other ones (is that a good idea?) 
686                 if (argument == buf->fileName())
687                         flag.setOnOff(true);
688                 break;
689         default:
690                 break;
691         }
692
693         // the font related toggles
694         if (!mathcursor) {
695                 LyXFont const & font = TEXT(false)->real_current_font;
696                 switch (action) {
697                 case LFUN_EMPH:
698                         flag.setOnOff(font.emph() == LyXFont::ON);
699                         break;
700                 case LFUN_NOUN:
701                         flag.setOnOff(font.noun() == LyXFont::ON);
702                         break;
703                 case LFUN_BOLD:
704                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
705                         break;
706                 case LFUN_SANS:
707                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
708                         break;
709                 case LFUN_ROMAN:
710                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
711                         break;
712                 case LFUN_CODE:
713                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
714                         break;
715                 default:
716                         break;
717                 }
718         }
719         else {
720                 MathTextCodes tc = mathcursor->getLastCode();
721                 switch (action) {
722                 case LFUN_BOLD:
723                         flag.setOnOff(tc == LM_TC_BF);
724                         break;
725                 case LFUN_SANS:
726                         flag.setOnOff(tc == LM_TC_SF);
727                         break;
728                 case LFUN_EMPH:
729                         flag.setOnOff(tc == LM_TC_CAL);
730                         break;
731                 case LFUN_ROMAN:
732                         flag.setOnOff(tc == LM_TC_RM);
733                         break;
734                 case LFUN_CODE:
735                         flag.setOnOff(tc == LM_TC_TT);
736                         break;
737                 case LFUN_NOUN:
738                         flag.setOnOff(tc == LM_TC_BB);
739                         break;
740                 case LFUN_DEFAULT:
741                         flag.setOnOff(tc == LM_TC_VAR);
742                         break;
743                 default:
744                         break;
745                 }
746         }
747         
748         return flag;
749 }
750
751
752 // temporary dispatch method
753 void LyXFunc::miniDispatch(string const & s) 
754 {
755         string s2(frontStrip(strip(s))); 
756  
757         if (!s2.empty()) {
758                 verboseDispatch(s2, true);
759         }
760 }
761
762
763 void LyXFunc::verboseDispatch(string const & s, bool show_sc) 
764 {
765         int action = lyxaction.LookupFunc(frontStrip(s));
766  
767         if (action == LFUN_UNKNOWN_ACTION) {
768                 string const msg = string(_("Unknown function ("))
769                         + s + ")";
770                 owner->message(msg);
771         } else {
772                 verboseDispatch(action, show_sc);
773         } 
774 }
775
776
777 void LyXFunc::verboseDispatch(int ac, bool show_sc) 
778 {
779         string argument;
780         kb_action action;
781         
782         // get the real action and argument
783         action = lyxaction.retrieveActionArg(ac, argument);
784
785         verboseDispatch(action, argument, show_sc);
786 }
787
788
789
790 void LyXFunc::verboseDispatch(kb_action action,
791                               string const & argument, bool show_sc)
792 {
793         string res = dispatch(action, argument);
794
795         commandshortcut.erase();
796         
797         if (lyxrc.display_shortcuts && show_sc) {
798                 if (action != LFUN_SELFINSERT) {
799                         // Put name of command and list of shortcuts
800                         // for it in minibuffer
801                         string comname = lyxaction.getActionName(action);
802                         
803                         int pseudoaction = action;
804                         bool argsadded = false;
805                         
806                         if (!argument.empty()) {
807                                 // the pseudoaction is useful for the bindings
808                                 pseudoaction = 
809                                         lyxaction.searchActionArg(action,
810                                                                   argument);
811
812                                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
813                                         pseudoaction = action;
814                                 } else {
815                                         comname += " " + argument;
816                                         argsadded = true;
817                                 }
818                         }
819
820                         string const shortcuts =
821                                 toplevel_keymap->findbinding(pseudoaction);
822
823                         if (!shortcuts.empty()) {
824                                 comname += ": " + shortcuts;
825                         } else if (!argsadded && !argument.empty()) {
826                                 comname += " " + argument;
827                         }
828
829                         if (!comname.empty()) {
830                                 comname = strip(comname);
831                                 commandshortcut = "(" + comname + ')';
832                         }
833                 }
834         }
835
836         if (res.empty()) {
837                 if (!commandshortcut.empty()) {
838                         owner->getMiniBuffer()->addSet(commandshortcut);
839                 }
840         } else {
841                 owner->getMiniBuffer()->addSet(' ' + commandshortcut);
842         }
843 }
844
845
846 string const LyXFunc::dispatch(kb_action action, string argument)
847 {
848         lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << action
849                               <<"] arg[" << argument << "]" << endl;
850
851         // we have not done anything wrong yet.
852         errorstat = false;
853         dispatch_buffer.erase();
854
855 #ifdef NEW_DISPATCHER
856         // We try do call the most specific dispatcher first:
857         //  1. the lockinginset's dispatch
858         //  2. the bufferview's dispatch
859         //  3. the lyxview's dispatch
860 #endif
861
862         selection_possible = false;
863
864         if (owner->view()->available())
865                 owner->view()->hideCursor();
866
867         // We cannot use this function here
868         if (getStatus(action, argument).disabled()) {
869                 lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: "
870                        << lyxaction.getActionName(action)
871                        << " [" << action << "] is disabled at this location"
872                        << endl;
873                 setErrorMessage(getStatusMessage());
874                 goto exit_with_message;
875         }
876
877         if (owner->view()->available() && owner->view()->theLockingInset()) {
878                 UpdatableInset::RESULT result;
879                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
880                                      (!keyseq.deleted())))
881                 {
882                         if ((action == LFUN_UNKNOWN_ACTION)
883                             && argument.empty()){
884                                 argument = keyseq.getiso();
885                         }
886                         // Undo/Redo is a bit tricky for insets.
887                         if (action == LFUN_UNDO) {
888                                 owner->view()->menuUndo();
889                                 goto exit_with_message;
890                         } else if (action == LFUN_REDO) {
891                                 owner->view()->menuRedo();
892                                 goto exit_with_message;
893                         } else if (((result=owner->view()->theLockingInset()->
894                                      // Hand-over to inset's own dispatch:
895                                      localDispatch(owner->view(), action, argument)) ==
896                                     UpdatableInset::DISPATCHED) ||
897                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
898                                 goto exit_with_message;
899                                         // If UNDISPATCHED, just soldier on
900                         else if (result == UpdatableInset::FINISHED) {
901                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
902                                                 TEXT()->cursorRight(owner->view());
903                                                 moveCursorUpdate(true, false);
904                                                 owner->showState();
905                                         }
906                                         goto exit_with_message;
907                         } else if (result == UpdatableInset::FINISHED_RIGHT) {
908                                 if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
909                                         TEXT()->cursorRight(owner->view());
910                                         moveCursorUpdate(true, false);
911                                         owner->showState();
912                                 }
913                                 goto exit_with_message;
914                         } else if (result == UpdatableInset::FINISHED_UP) {
915                                 if (TEXT()->cursor.row()->previous()) {
916                                         TEXT()->cursorUp(owner->view());
917                                         moveCursorUpdate(true, false);
918                                         owner->showState();
919                                 }
920                                 goto exit_with_message;
921                         } else if (result == UpdatableInset::FINISHED_DOWN) {
922                                 if (TEXT()->cursor.row()->next())
923                                         TEXT()->cursorDown(owner->view());
924                                 else
925                                         TEXT()->cursorRight(owner->view());
926                                 moveCursorUpdate(true, false);
927                                 owner->showState();
928                                 goto exit_with_message;
929                         } else {
930                                 //setMessage(N_("Text mode"));
931                                 switch (action) {
932                                 case LFUN_UNKNOWN_ACTION:
933                                 case LFUN_BREAKPARAGRAPH:
934                                 case LFUN_BREAKLINE:
935                                         TEXT()->cursorRight(owner->view());
936                                         owner->view()->setState();
937                                         owner->showState();
938                                         break;
939                                 case LFUN_RIGHT:
940                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
941                                                 TEXT()->cursorRight(owner->view());
942                                                 moveCursorUpdate(true, false);
943                                                 owner->showState();
944                                         }
945                                         goto exit_with_message;
946                                 case LFUN_LEFT: 
947                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
948                                                 TEXT()->cursorRight(owner->view());
949                                                 moveCursorUpdate(true, false);
950                                                 owner->showState();
951                                         }
952                                         goto exit_with_message;
953                                 case LFUN_DOWN:
954                                         if (TEXT()->cursor.row()->next())
955                                                 TEXT()->cursorDown(owner->view());
956                                         else
957                                                 TEXT()->cursorRight(owner->view());
958                                         moveCursorUpdate(true, false);
959                                         owner->showState();
960                                         goto exit_with_message;
961                                 default:
962                                         break;
963                                 }
964                         }
965                 }
966         }
967
968         switch (action) {
969                 
970         case LFUN_ESCAPE:
971         {
972                 if (!owner->view()->available()) break;
973                 // this function should be used always [asierra060396]
974                 UpdatableInset * tli =
975                         owner->view()->theLockingInset();
976                 if (tli) {
977                         UpdatableInset * lock = tli->getLockingInset();
978                         
979                         if (tli == lock) {
980                                 owner->view()->unlockInset(tli);
981                                 TEXT()->cursorRight(owner->view());
982                                 moveCursorUpdate(true, false);
983                                 owner->showState();
984                         } else {
985                                 tli->unlockInsetInInset(owner->view(),
986                                                         lock,
987                                                         true);
988                         }
989                         finishUndo();
990                 }
991         }
992         break;
993                         
994                 // --- Misc -------------------------------------------
995         case LFUN_WORDFINDFORWARD  : 
996         case LFUN_WORDFINDBACKWARD : {
997                 static string last_search;
998                 string searched_string;
999             
1000                 if (!argument.empty()) {
1001                         last_search = argument;
1002                         searched_string = argument;
1003                 } else {
1004                         searched_string = last_search;
1005                 }
1006                 bool fw = (action == LFUN_WORDFINDBACKWARD);
1007                 if (!searched_string.empty()) {
1008                         LyXFind(owner->view(), searched_string, fw);
1009                 }
1010 //              owner->view()->showCursor();
1011         }
1012         break;
1013                 
1014         case LFUN_PREFIX:
1015         {
1016                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
1017                         owner->view()->update(TEXT(),
1018                                               BufferView::SELECT|BufferView::FITCUR);
1019                 }
1020                 owner->message(keyseq.print());
1021         }
1022         break;
1023
1024         // --- Misc -------------------------------------------
1025         case LFUN_EXEC_COMMAND:
1026         {
1027                 std::vector<string> allCmds;
1028                 std::transform(lyxaction.func_begin(), lyxaction.func_end(),
1029                                std::back_inserter(allCmds), lyx::firster());
1030                 static std::vector<string> hist;
1031                 owner->getMiniBuffer()->getString(MiniBuffer::spaces,
1032                                                   allCmds, hist);
1033         }
1034         break;
1035                 
1036         case LFUN_CANCEL:                   // RVDK_PATCH_5
1037                 keyseq.reset();
1038                 meta_fake_bit = 0;
1039                 if (owner->view()->available())
1040                         // cancel any selection
1041                         dispatch(LFUN_MARK_OFF);
1042                 setMessage(N_("Cancel"));
1043                 break;
1044
1045         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1046         {
1047                 meta_fake_bit = Mod1Mask;
1048                 setMessage(keyseq.print());
1049         }
1050         break;  
1051
1052         case LFUN_READ_ONLY_TOGGLE:
1053                 if (owner->buffer()->lyxvc.inUse()) {
1054                         owner->buffer()->lyxvc.toggleReadOnly();
1055                 } else {
1056                         owner->buffer()->setReadonly(
1057                                 !owner->buffer()->isReadonly());
1058                 }
1059                 break;
1060                 
1061         case LFUN_CENTER: // this is center and redraw.
1062                 owner->view()->center();
1063                 break;
1064                 
1065                 // --- Menus -----------------------------------------------
1066         case LFUN_MENUNEW:
1067                 menuNew(false);
1068                 break;
1069                 
1070         case LFUN_MENUNEWTMPLT:
1071                 menuNew(true);
1072                 break;
1073                 
1074         case LFUN_CLOSEBUFFER:
1075                 closeBuffer();
1076                 break;
1077                 
1078         case LFUN_MENUWRITE:
1079                 if (!owner->buffer()->isUnnamed()) {
1080                         ostringstream s1;
1081                         s1 << _("Saving document") << ' '
1082                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1083                         owner->message(s1.str().c_str());
1084                         MenuWrite(owner->view(), owner->buffer());
1085                 } else
1086                         WriteAs(owner->view(), owner->buffer());
1087                 break;
1088                 
1089         case LFUN_WRITEAS:
1090                 WriteAs(owner->view(), owner->buffer(), argument);
1091                 break;
1092                 
1093         case LFUN_MENURELOAD:
1094                 reloadBuffer();
1095                 break;
1096                 
1097         case LFUN_UPDATE:
1098                 Exporter::Export(owner->buffer(), argument, true);
1099                 break;
1100
1101         case LFUN_PREVIEW:
1102                 Exporter::Preview(owner->buffer(), argument);
1103                 break;
1104                 
1105         case LFUN_BUILDPROG:
1106                 Exporter::Export(owner->buffer(), "program", true);
1107                 break;
1108                 
1109         case LFUN_RUNCHKTEX:
1110                 MenuRunChktex(owner->buffer());
1111                 break;
1112                                 
1113         case LFUN_MENUPRINT:
1114                 owner->getDialogs()->showPrint();
1115                 break;
1116
1117         case LFUN_EXPORT:
1118                 if (argument == "custom")
1119                         MenuSendto();
1120                 else
1121                         Exporter::Export(owner->buffer(), argument, false);
1122                 break;
1123
1124         case LFUN_IMPORT:
1125                 doImport(argument);
1126                 break;
1127                 
1128         case LFUN_QUIT:
1129                 QuitLyX();
1130                 break;
1131                 
1132         case LFUN_TOCVIEW:
1133 #if 0
1134         case LFUN_LOFVIEW:
1135         case LFUN_LOTVIEW:
1136         case LFUN_LOAVIEW:
1137 #endif
1138         {
1139                 InsetCommandParams p;
1140
1141 #if 0
1142                 if (action == LFUN_TOCVIEW)
1143 #endif
1144                         p.setCmdName("tableofcontents");
1145 #if 0
1146                 else if (action == LFUN_LOAVIEW )
1147                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1148                 else if (action == LFUN_LOFVIEW)
1149                         p.setCmdName("listoffigures");
1150                 else
1151                         p.setCmdName("listoftables");
1152 #endif
1153                 owner->getDialogs()->createTOC(p.getAsString());
1154                 break;
1155         }       
1156
1157         case LFUN_DIALOG_TABULAR_INSERT:
1158                 owner->getDialogs()->showTabularCreate();
1159                 break;
1160                 
1161         case LFUN_FIGURE:
1162                 Figure();
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 << "]" << std::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                 if (!lcolor.setColor(lyx_name, x11_name)) {
1605                         static string const err1 (N_("Set-color \""));
1606                         static string const err2 (
1607                                 N_("\" failed - color is undefined "
1608                                    "or may not be redefined"));
1609                         setErrorMessage(_(err1) + lyx_name + _(err2));
1610                         break;
1611                 }
1612                 lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
1613                 owner->view()->redraw();
1614                 break;
1615         }
1616
1617         case LFUN_MESSAGE:
1618                 owner->message(argument);
1619                 break;
1620
1621         case LFUN_MESSAGE_PUSH:
1622                 owner->messagePush(argument);
1623                 break;
1624
1625         case LFUN_MESSAGE_POP:
1626                 owner->messagePop();
1627                 break;
1628
1629         default:
1630                 // Then if it was none of the above
1631                 // Trying the BufferView::pimpl dispatch:
1632                 if (!owner->view()->Dispatch(action, argument))
1633                         lyxerr << "A truly unknown func ["
1634                                << lyxaction.getActionName(action) << "]!"
1635                                << endl;
1636                 break;
1637         } // end of switch
1638
1639 exit_with_message:
1640
1641         string const res = getMessage();
1642
1643         if (!res.empty())
1644                 owner->message(_(res));
1645         owner->updateMenubar();
1646         owner->updateToolbar();
1647         
1648         return res;
1649 }
1650
1651
1652 void LyXFunc::setupLocalKeymap()
1653 {
1654         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1655         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1656 }
1657
1658
1659 void LyXFunc::menuNew(bool fromTemplate)
1660 {
1661         string initpath = lyxrc.document_path;
1662
1663         if (owner->view()->available()) {
1664                 string const trypath = owner->buffer()->filePath();
1665                 // If directory is writeable, use this as default.
1666                 if (IsDirWriteable(trypath))
1667                         initpath = trypath;
1668         }
1669
1670         static int newfile_number;
1671         string s;
1672         
1673         if (lyxrc.new_ask_filename) {
1674                 FileDialog fileDlg(owner, _("Enter filename for new document"),
1675                                    LFUN_SELECT_FILE_SYNC,
1676                         make_pair(string(_("Documents|#o#O")),
1677                                   string(lyxrc.document_path)),
1678                         make_pair(string(_("Templates|#T#t")),
1679                                   string(lyxrc.template_path)));
1680
1681                 FileDialog::Result result =
1682                         fileDlg.Select(initpath,
1683                                        _("*.lyx|LyX Documents (*.lyx)"),
1684                                        _("newfile"));
1685         
1686                 if (result.second.empty()) {
1687                         owner->message(_("Canceled."));
1688                         lyxerr[Debug::INFO] << "New Document Cancelled." << endl;
1689                         return;
1690                 }
1691         
1692                 // get absolute path of file and make sure the filename ends
1693                 // with .lyx
1694                 s = MakeAbsPath(result.second);
1695                 if (!IsLyXFilename(s))
1696                         s += ".lyx";
1697
1698                 // Check if the document already is open
1699                 if (bufferlist.exists(s)) {
1700                         switch (Alert::askConfirmation(_("Document is already open:"),
1701                                                 MakeDisplayPath(s, 50),
1702                                                 _("Do you want to close that document now?\n"
1703                                                   "('No' will just switch to the open version)")))
1704                         {
1705                         case 1: // Yes: close the document
1706                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
1707                                 // If close is canceled, we cancel here too.
1708                                         return;
1709                                 break;
1710                         case 2: // No: switch to the open document
1711                                 owner->view()->buffer(bufferlist.getBuffer(s));
1712                                 return;
1713                         case 3: // Cancel: Do nothing
1714                                 owner->message(_("Canceled."));
1715                                 return;
1716                         }
1717                 }
1718                 // Check whether the file already exists
1719                 FileInfo fi(s);
1720                 if (fi.readable() &&
1721                     Alert::askQuestion(_("File already exists:"), 
1722                                 MakeDisplayPath(s, 50),
1723                                 _("Do you want to open the document?"))) {
1724                                 // loads document
1725                         string const disp_fn(MakeDisplayPath(s));
1726                         
1727                         ostringstream str;
1728                         str << _("Opening  document") << ' '
1729                             << disp_fn << "...";
1730                         
1731                         owner->message(str.str().c_str());
1732                         //XFlush(fl_get_display());
1733                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1734                         ostringstream str2;
1735                         str2 << _("Document") << ' '
1736                              << disp_fn << ' ' << _("opened.");
1737                         
1738                         owner->message(str2.str().c_str());
1739                         
1740                         return;
1741                 }
1742         } else {
1743                 s = AddName(lyxrc.document_path,
1744                             "newfile" + tostr(++newfile_number) + ".lyx");
1745                 FileInfo fi(s);
1746                 while (bufferlist.exists(s) || fi.readable()) {
1747                         ++newfile_number;
1748                         s = AddName(lyxrc.document_path,
1749                                     "newfile" + tostr(newfile_number) +
1750                                     ".lyx");
1751                         fi.newFile(s);
1752                 }
1753         }
1754
1755         // The template stuff
1756         string templname;
1757         if (fromTemplate) {
1758                 FileDialog fileDlg(owner, _("Select template file"),
1759                         LFUN_SELECT_FILE_SYNC,
1760                         make_pair(string(_("Documents|#o#O")),
1761                                   string(lyxrc.document_path)),
1762                         make_pair(string(_("Templates|#T#t")),
1763                                   string(lyxrc.template_path)));
1764
1765                 FileDialog::Result result =
1766                         fileDlg.Select(lyxrc.template_path,
1767                                        _("*.lyx|LyX Documents (*.lyx)"));
1768         
1769                 if (result.first == FileDialog::Later)
1770                         return;
1771
1772                 string const fname = result.second;
1773
1774                 if (fname.empty()) 
1775                         return;
1776                 templname = fname;
1777         }
1778   
1779         // find a free buffer
1780         lyxerr[Debug::INFO] << "Find a free buffer." << endl;
1781         owner->view()->buffer(bufferlist.newFile(s, templname));
1782 }
1783
1784
1785 void LyXFunc::open(string const & fname)
1786 {
1787         string initpath = lyxrc.document_path;
1788   
1789         if (owner->view()->available()) {
1790                 string const trypath = owner->buffer()->filePath();
1791                 // If directory is writeable, use this as default.
1792                 if (IsDirWriteable(trypath))
1793                         initpath = trypath;
1794         }
1795
1796         string filename;
1797  
1798         if (fname.empty()) {
1799                 FileDialog fileDlg(owner, _("Select document to open"),
1800                         LFUN_FILE_OPEN,
1801                         make_pair(string(_("Documents|#o#O")),
1802                                   string(lyxrc.document_path)),
1803                         make_pair(string(_("Examples|#E#e")),
1804                                   string(AddPath(system_lyxdir, "examples"))));
1805
1806                 FileDialog::Result result =
1807                         fileDlg.Select(initpath,
1808                                        "*.lyx|LyX Documents (*.lyx)");
1809         
1810                 if (result.first == FileDialog::Later)
1811                         return;
1812
1813                 filename = result.second;
1814  
1815                 // check selected filename
1816                 if (filename.empty()) {
1817                         owner->message(_("Canceled."));
1818                         return;
1819                 }
1820         } else
1821                 filename = fname;
1822
1823         // get absolute path of file and add ".lyx" to the filename if
1824         // necessary
1825         string const fullpath = FileSearch(string(), filename, "lyx");
1826         if (fullpath.empty()) {
1827                 Alert::alert(_("Error"), _("Could not find file"), filename);
1828                 return;
1829         }
1830
1831         filename = fullpath;
1832  
1833         // loads document
1834         string const disp_fn(MakeDisplayPath(filename));
1835
1836         ostringstream str;
1837         str << _("Opening document") << ' ' << disp_fn << "...";
1838         
1839         owner->message(str.str().c_str());
1840
1841         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1842         if (openbuf) {
1843                 owner->view()->buffer(openbuf);
1844                 ostringstream str;
1845                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1846                 owner->message(str.str().c_str());
1847         } else {
1848                 ostringstream str;
1849                 str << _("Could not open document") << ' ' << disp_fn;
1850                 owner->message(str.str().c_str());
1851         }
1852 }
1853
1854
1855 // checks for running without gui are missing.
1856 void LyXFunc::doImport(string const & argument)
1857 {
1858         string format;
1859         string filename = split(argument, format, ' ');
1860         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format 
1861                             << " file: " << filename << endl;
1862
1863         if (filename.empty()) { // need user interaction
1864                 string initpath = lyxrc.document_path;
1865                 
1866                 if (owner->view()->available()) {
1867                         string const trypath = owner->buffer()->filePath();
1868                         // If directory is writeable, use this as default.
1869                         if (IsDirWriteable(trypath))
1870                                 initpath = trypath;
1871                 }
1872
1873                 string const text = _("Select ") + formats.prettyName(format)
1874                         + _(" file to import");
1875
1876                 FileDialog fileDlg(owner, text, 
1877                         LFUN_IMPORT,
1878                         make_pair(string(_("Documents|#o#O")),
1879                                   string(lyxrc.document_path)),
1880                         make_pair(string(_("Examples|#E#e")),
1881                                   string(AddPath(system_lyxdir, "examples"))));
1882                         
1883                 string const extension = "*." + formats.extension(format)
1884                         + "| " + formats.prettyName(format)
1885                         + " (*." + formats.extension(format) + ")";
1886
1887                 FileDialog::Result result = fileDlg.Select(initpath,
1888                                                            extension);
1889
1890                 if (result.first == FileDialog::Later)
1891                         return;
1892
1893                 filename = result.second;
1894  
1895                 // check selected filename
1896                 if (filename.empty())
1897                         owner->message(_("Canceled."));
1898         }
1899
1900         // still no filename? abort
1901         if (filename.empty()) 
1902                 return;
1903
1904         // get absolute path of file
1905         filename = MakeAbsPath(filename);
1906
1907         string const lyxfile = ChangeExtension(filename, ".lyx");
1908
1909         // Check if the document already is open
1910         if (bufferlist.exists(lyxfile)) {
1911                 switch (Alert::askConfirmation(_("Document is already open:"), 
1912                                         MakeDisplayPath(lyxfile, 50),
1913                                         _("Do you want to close that document now?\n"
1914                                           "('No' will just switch to the open version)")))
1915                         {
1916                         case 1: // Yes: close the document
1917                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1918                                 // If close is canceled, we cancel here too.
1919                                         return;
1920                                 break;
1921                         case 2: // No: switch to the open document
1922                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1923                                 return;
1924                         case 3: // Cancel: Do nothing
1925                                 owner->message(_("Canceled."));
1926                                 return;
1927                         }
1928         }
1929
1930         // Check if a LyX document by the same root exists in filesystem
1931         FileInfo const f(lyxfile, true);
1932         if (f.exist() && !Alert::askQuestion(_("A document by the name"), 
1933                                       MakeDisplayPath(lyxfile),
1934                                       _("already exists. Overwrite?"))) {
1935                 owner->message(_("Canceled"));
1936                 return;
1937         }
1938         // filename should be valid now
1939         
1940         Importer::Import(owner, filename, format);
1941 }
1942
1943
1944 void LyXFunc::reloadBuffer()
1945 {
1946         string const fn = owner->buffer()->fileName();
1947         if (bufferlist.close(owner->buffer()))
1948                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1949 }
1950
1951
1952 void LyXFunc::closeBuffer()
1953 {
1954         if (bufferlist.close(owner->buffer()) && !quitting) {
1955                 if (bufferlist.empty()) {
1956                         // need this otherwise SEGV may occur while trying to
1957                         // set variables that don't exist
1958                         // since there's no current buffer
1959                         owner->getDialogs()->hideBufferDependent();
1960                 } else {
1961                         owner->view()->buffer(bufferlist.first());
1962                 }
1963         }
1964 }
1965
1966
1967 // Each "owner" should have it's own message method. lyxview and
1968 // the minibuffer would use the minibuffer, but lyxserver would
1969 // send an ERROR signal to its client.  Alejandro 970603
1970 // This func is bit problematic when it comes to NLS, to make the
1971 // lyx servers client be language indepenent we must not translate
1972 // strings sent to this func.
1973 void LyXFunc::setErrorMessage(string const & m) const
1974 {
1975         dispatch_buffer = m;
1976         errorstat = true;
1977 }
1978
1979
1980 void LyXFunc::setMessage(string const & m) const 
1981 {
1982         dispatch_buffer = m;
1983 }
1984
1985
1986 void LyXFunc::setStatusMessage(string const & m) const
1987 {
1988         status_buffer = m;
1989 }
1990
1991
1992 void LyXFunc::initMiniBuffer() 
1993 {
1994         string text = _("Welcome to LyX!");
1995         
1996         // When meta-fake key is pressed, show the key sequence so far + "M-".
1997         if (wasMetaKey()) {
1998                 text = keyseq.print();
1999                 text += "M-";
2000         }
2001
2002         // Else, when a non-complete key sequence is pressed,
2003         // show the available options.
2004         if (keyseq.length() > 0 && !keyseq.deleted()) {
2005                 text = keyseq.printOptions();
2006         }
2007    
2008         // Else, show the buffer state.
2009         else if (owner->view()->available()) {
2010                 Buffer * tmpbuf = owner->buffer();
2011                 
2012                 string const nicename = 
2013                         MakeDisplayPath(tmpbuf->fileName());
2014                 // Should we do this instead? (kindo like emacs)
2015                 // leaves more room for other information
2016                 text = "LyX: ";
2017                 text += nicename;
2018                 if (tmpbuf->lyxvc.inUse()) {
2019                         text += " [";
2020                         text += tmpbuf->lyxvc.versionString();
2021                         text += ' ';
2022                         text += tmpbuf->lyxvc.locker();
2023                         if (tmpbuf->isReadonly())
2024                                 text += " (RO)";
2025                         text += ']';
2026                 } else if (tmpbuf->isReadonly())
2027                         text += " [RO]";
2028                 if (!tmpbuf->isLyxClean())
2029                         text += _(" (Changed)");
2030         } else {
2031                 if (text != _("Welcome to LyX!")) // this is a hack
2032                         text = _("* No document open *");
2033         }
2034         
2035         owner->message(text);
2036 }
2037