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