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