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