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