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