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