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