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