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