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