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