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