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