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