]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
Move fontloader into lyx_gui stuff. Now Qt should compile out of the box
[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                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
882                                                 TEXT()->cursorRight(owner->view());
883                                                 moveCursorUpdate(true, false);
884                                                 owner->showState();
885                                         }
886                                         goto exit_with_message;
887                         } else if (result == UpdatableInset::FINISHED_RIGHT) {
888                                 if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
889                                         TEXT()->cursorRight(owner->view());
890                                         moveCursorUpdate(true, false);
891                                         owner->showState();
892                                 }
893                                 goto exit_with_message;
894                         } else if (result == UpdatableInset::FINISHED_UP) {
895                                 if (TEXT()->cursor.irow()->previous()) {
896 #if 1
897                                         TEXT()->setCursorFromCoordinates(
898                                                 owner->view(), TEXT()->cursor.ix() + inset_x,
899                                                 TEXT()->cursor.iy() -
900                                                 TEXT()->cursor.irow()->baseline() - 1);
901                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
902 #else
903                                         TEXT()->cursorUp(owner->view());
904 #endif
905                                         moveCursorUpdate(true, false);
906                                         owner->showState();
907                                 } else {
908                                         owner->view()->update(TEXT(), BufferView::SELECT|BufferView::FITCUR);
909                                 }
910                                 goto exit_with_message;
911                         } else if (result == UpdatableInset::FINISHED_DOWN) {
912                                 if (TEXT()->cursor.irow()->next()) {
913 #if 1
914                                         TEXT()->setCursorFromCoordinates(
915                                                 owner->view(), TEXT()->cursor.ix() + inset_x,
916                                                 TEXT()->cursor.iy() -
917                                                 TEXT()->cursor.irow()->baseline() +
918                                                 TEXT()->cursor.irow()->height() + 1);
919                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
920 #else
921                                         TEXT()->cursorDown(owner->view());
922 #endif
923                                 } else {
924                                         TEXT()->cursorRight(owner->view());
925                                 }
926                                 moveCursorUpdate(true, false);
927                                 owner->showState();
928                                 goto exit_with_message;
929                         }
930 #warning I am not sure this is still right, please have a look! (Jug 20020417)
931                         else { // result == UNDISPATCHED
932                                 //setMessage(N_("Text mode"));
933                                 switch (action) {
934                                 case LFUN_UNKNOWN_ACTION:
935                                 case LFUN_BREAKPARAGRAPH:
936                                 case LFUN_BREAKLINE:
937                                         TEXT()->cursorRight(owner->view());
938                                         owner->view()->setState();
939                                         owner->showState();
940                                         break;
941                                 case LFUN_RIGHT:
942                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
943                                                 TEXT()->cursorRight(owner->view());
944                                                 moveCursorUpdate(true, false);
945                                                 owner->showState();
946                                         }
947                                         goto exit_with_message;
948                                 case LFUN_LEFT:
949                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
950                                                 TEXT()->cursorRight(owner->view());
951                                                 moveCursorUpdate(true, false);
952                                                 owner->showState();
953                                         }
954                                         goto exit_with_message;
955                                 case LFUN_DOWN:
956                                         if (TEXT()->cursor.row()->next())
957                                                 TEXT()->cursorDown(owner->view());
958                                         else
959                                                 TEXT()->cursorRight(owner->view());
960                                         moveCursorUpdate(true, false);
961                                         owner->showState();
962                                         goto exit_with_message;
963                                 default:
964                                         break;
965                                 }
966                         }
967                 }
968         }
969
970         switch (action) {
971
972         case LFUN_ESCAPE:
973         {
974                 if (!owner->view()->available()) break;
975                 // this function should be used always [asierra060396]
976                 UpdatableInset * tli =
977                         owner->view()->theLockingInset();
978                 if (tli) {
979                         UpdatableInset * lock = tli->getLockingInset();
980
981                         if (tli == lock) {
982                                 owner->view()->unlockInset(tli);
983                                 TEXT()->cursorRight(owner->view());
984                                 moveCursorUpdate(true, false);
985                                 owner->showState();
986                         } else {
987                                 tli->unlockInsetInInset(owner->view(),
988                                                         lock,
989                                                         true);
990                         }
991                         finishUndo();
992                         // Tell the paragraph dialog that we changed paragraph
993                         owner->getDialogs()->updateParagraph();
994                 }
995         }
996         break;
997
998                 // --- Misc -------------------------------------------
999         case LFUN_WORDFINDFORWARD  :
1000         case LFUN_WORDFINDBACKWARD : {
1001                 static string last_search;
1002                 string searched_string;
1003
1004                 if (!argument.empty()) {
1005                         last_search = argument;
1006                         searched_string = argument;
1007                 } else {
1008                         searched_string = last_search;
1009                 }
1010                 bool fw = (action == LFUN_WORDFINDBACKWARD);
1011                 if (!searched_string.empty()) {
1012                         lyxfind::LyXFind(owner->view(), searched_string, fw);
1013                 }
1014 //              owner->view()->showCursor();
1015         }
1016         break;
1017
1018         case LFUN_PREFIX:
1019         {
1020                 if (owner->view()->available() && !owner->view()->theLockingInset()) {
1021                         owner->view()->update(TEXT(),
1022                                               BufferView::SELECT|BufferView::FITCUR);
1023                 }
1024                 owner->message(keyseq.printOptions());
1025         }
1026         break;
1027
1028         // --- Misc -------------------------------------------
1029         case LFUN_EXEC_COMMAND:
1030         {
1031                 vector<string> allCmds;
1032                 transform(lyxaction.func_begin(), lyxaction.func_end(),
1033                           back_inserter(allCmds), lyx::firster());
1034                 static vector<string> hist;
1035                 owner->getMiniBuffer()->prepareForInput(allCmds, hist);
1036         }
1037         break;
1038
1039         case LFUN_CANCEL:                   // RVDK_PATCH_5
1040                 keyseq.reset();
1041                 meta_fake_bit = key_modifier::none;
1042                 if (owner->view()->available())
1043                         // cancel any selection
1044                         dispatch(LFUN_MARK_OFF);
1045                 setMessage(N_("Cancel"));
1046                 break;
1047
1048         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1049         {
1050                 meta_fake_bit = key_modifier::alt;
1051                 setMessage(keyseq.print());
1052         }
1053         break;
1054
1055         case LFUN_READ_ONLY_TOGGLE:
1056                 if (owner->buffer()->lyxvc.inUse()) {
1057                         owner->buffer()->lyxvc.toggleReadOnly();
1058                 } else {
1059                         owner->buffer()->setReadonly(
1060                                 !owner->buffer()->isReadonly());
1061                 }
1062                 break;
1063
1064         case LFUN_CENTER: // this is center and redraw.
1065                 owner->view()->center();
1066                 break;
1067
1068                 // --- Menus -----------------------------------------------
1069         case LFUN_MENUNEW:
1070                 menuNew(argument, false);
1071                 break;
1072
1073         case LFUN_MENUNEWTMPLT:
1074                 menuNew(argument, true);
1075                 break;
1076
1077         case LFUN_CLOSEBUFFER:
1078                 closeBuffer();
1079                 break;
1080
1081         case LFUN_MENUWRITE:
1082                 if (!owner->buffer()->isUnnamed()) {
1083                         ostringstream s1;
1084                         s1 << _("Saving document") << ' '
1085                            << MakeDisplayPath(owner->buffer()->fileName() + "...");
1086                         owner->message(s1.str().c_str());
1087                         MenuWrite(owner->view(), owner->buffer());
1088                 } else
1089                         WriteAs(owner->view(), owner->buffer());
1090                 break;
1091
1092         case LFUN_WRITEAS:
1093                 WriteAs(owner->view(), owner->buffer(), argument);
1094                 break;
1095
1096         case LFUN_MENURELOAD:
1097                 reloadBuffer();
1098                 break;
1099
1100         case LFUN_UPDATE:
1101                 Exporter::Export(owner->buffer(), argument, true);
1102                 break;
1103
1104         case LFUN_PREVIEW:
1105                 Exporter::Preview(owner->buffer(), argument);
1106                 break;
1107
1108         case LFUN_BUILDPROG:
1109                 Exporter::Export(owner->buffer(), "program", true);
1110                 break;
1111
1112         case LFUN_RUNCHKTEX:
1113                 MenuRunChktex(owner->buffer());
1114                 break;
1115
1116         case LFUN_MENUPRINT:
1117                 owner->getDialogs()->showPrint();
1118                 break;
1119
1120         case LFUN_EXPORT:
1121                 if (argument == "custom")
1122                         owner->getDialogs()->showSendto();
1123                 else
1124                         Exporter::Export(owner->buffer(), argument, false);
1125                 break;
1126
1127         case LFUN_IMPORT:
1128                 doImport(argument);
1129                 break;
1130
1131         case LFUN_QUIT:
1132                 QuitLyX();
1133                 break;
1134
1135         case LFUN_TOCVIEW:
1136 #if 0
1137         case LFUN_LOFVIEW:
1138         case LFUN_LOTVIEW:
1139         case LFUN_LOAVIEW:
1140 #endif
1141         {
1142                 InsetCommandParams p;
1143
1144 #if 0
1145                 if (action == LFUN_TOCVIEW)
1146 #endif
1147                         p.setCmdName("tableofcontents");
1148 #if 0
1149                 else if (action == LFUN_LOAVIEW)
1150                         p.setCmdName("listof{algorithm}{List of Algorithms}");
1151                 else if (action == LFUN_LOFVIEW)
1152                         p.setCmdName("listoffigures");
1153                 else
1154                         p.setCmdName("listoftables");
1155 #endif
1156                 owner->getDialogs()->createTOC(p.getAsString());
1157                 break;
1158         }
1159
1160         case LFUN_DIALOG_TABULAR_INSERT:
1161                 owner->getDialogs()->showTabularCreate();
1162                 break;
1163
1164         case LFUN_AUTOSAVE:
1165                 AutoSave(owner->view());
1166                 break;
1167
1168         case LFUN_UNDO:
1169                 owner->view()->menuUndo();
1170                 break;
1171
1172         case LFUN_REDO:
1173                 owner->view()->menuRedo();
1174                 break;
1175
1176         case LFUN_MENUSEARCH:
1177                 owner->getDialogs()->showSearch();
1178                 break;
1179
1180         case LFUN_REMOVEERRORS:
1181                 if (owner->view()->removeAutoInsets()) {
1182 #warning repaint() or update() or nothing ?
1183                         owner->view()->repaint();
1184                         owner->view()->fitCursor();
1185                 }
1186                 break;
1187
1188         case LFUN_DEPTH_MIN:
1189                 changeDepth(owner->view(), TEXT(false), -1);
1190                 break;
1191
1192         case LFUN_DEPTH_PLUS:
1193                 changeDepth(owner->view(), TEXT(false), 1);
1194                 break;
1195
1196         case LFUN_FREE:
1197                 owner->getDialogs()->setUserFreeFont();
1198                 break;
1199
1200         case LFUN_RECONFIGURE:
1201                 Reconfigure(owner->view());
1202                 break;
1203
1204 #if 0
1205         case LFUN_FLOATSOPERATE:
1206                 if (argument == "openfoot")
1207                         owner->view()->allFloats(1,0);
1208                 else if (argument == "closefoot")
1209                         owner->view()->allFloats(0,0);
1210                 else if (argument == "openfig")
1211                         owner->view()->allFloats(1,1);
1212                 else if (argument == "closefig")
1213                         owner->view()->allFloats(0,1);
1214                 break;
1215 #else
1216 #ifdef WITH_WARNINGS
1217 //#warning Find another implementation here (or another lyxfunc)!
1218 #endif
1219 #endif
1220         case LFUN_HELP_ABOUTLYX:
1221                 owner->getDialogs()->showAboutlyx();
1222                 break;
1223
1224         case LFUN_HELP_TEXINFO:
1225                 owner->getDialogs()->showTexinfo();
1226                 break;
1227
1228         case LFUN_HELP_OPEN:
1229         {
1230                 string const arg = argument;
1231                 if (arg.empty()) {
1232                         setErrorMessage(N_("Missing argument"));
1233                         break;
1234                 }
1235                 owner->prohibitInput();
1236                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1237                 if (fname.empty()) {
1238                         lyxerr << "LyX: unable to find documentation file `"
1239                                << arg << "'. Bad installation?" << endl;
1240                         owner->allowInput();
1241                         break;
1242                 }
1243                 ostringstream str;
1244                 str << _("Opening help file") << ' '
1245                     << MakeDisplayPath(fname) << "...";
1246                 owner->message(str.str().c_str());
1247                 owner->view()->buffer(bufferlist.loadLyXFile(fname, false));
1248                 owner->allowInput();
1249                 break;
1250         }
1251
1252                 // --- version control -------------------------------
1253         case LFUN_VC_REGISTER:
1254         {
1255                 if (!owner->buffer()->lyxvc.inUse())
1256                         owner->buffer()->lyxvc.registrer();
1257         }
1258         break;
1259
1260         case LFUN_VC_CHECKIN:
1261         {
1262                 if (owner->buffer()->lyxvc.inUse()
1263                     && !owner->buffer()->isReadonly())
1264                         owner->buffer()->lyxvc.checkIn();
1265         }
1266         break;
1267
1268         case LFUN_VC_CHECKOUT:
1269         {
1270                 if (owner->buffer()->lyxvc.inUse()
1271                     && owner->buffer()->isReadonly())
1272                         owner->buffer()->lyxvc.checkOut();
1273         }
1274         break;
1275
1276         case LFUN_VC_REVERT:
1277         {
1278                 owner->buffer()->lyxvc.revert();
1279         }
1280         break;
1281
1282         case LFUN_VC_UNDO:
1283         {
1284                 owner->buffer()->lyxvc.undoLast();
1285         }
1286         break;
1287
1288         case LFUN_VC_HISTORY:
1289         {
1290                 owner->getDialogs()->showVCLogFile();
1291                 break;
1292         }
1293
1294         // --- buffers ----------------------------------------
1295
1296         case LFUN_SWITCHBUFFER:
1297                 owner->view()->buffer(bufferlist.getBuffer(argument));
1298                 break;
1299
1300         case LFUN_FILE_NEW:
1301         {
1302                 // servercmd: argument must be <file>:<template>
1303                 Buffer * tmpbuf = NewLyxFile(argument);
1304                 if (tmpbuf)
1305                         owner->view()->buffer(tmpbuf);
1306         }
1307         break;
1308
1309         case LFUN_FILE_OPEN:
1310                 open(argument);
1311                 break;
1312
1313         case LFUN_LATEX_LOG:
1314                 owner->getDialogs()->showLogFile();
1315                 break;
1316
1317         case LFUN_LAYOUT_DOCUMENT:
1318                 owner->getDialogs()->showDocument();
1319                 break;
1320
1321         case LFUN_LAYOUT_PARAGRAPH:
1322                 owner->getDialogs()->showParagraph();
1323                 break;
1324
1325         case LFUN_LAYOUT_CHARACTER:
1326                 owner->getDialogs()->showCharacter();
1327                 break;
1328
1329         case LFUN_LAYOUT_TABULAR:
1330             if (owner->view()->theLockingInset()) {
1331                 if (owner->view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1332                     InsetTabular * inset = static_cast<InsetTabular *>
1333                         (owner->view()->theLockingInset());
1334                     inset->openLayoutDialog(owner->view());
1335                 } else if (owner->view()->theLockingInset()->
1336                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1337                     InsetTabular * inset = static_cast<InsetTabular *>(
1338                         owner->view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1339                     inset->openLayoutDialog(owner->view());
1340                 }
1341             }
1342             break;
1343
1344         case LFUN_LAYOUT_PREAMBLE:
1345                 owner->getDialogs()->showPreamble();
1346                 break;
1347
1348         case LFUN_DROP_LAYOUTS_CHOICE:
1349                 owner->getToolbar()->openLayoutList();
1350                 break;
1351
1352         case LFUN_MENU_OPEN_BY_NAME:
1353                 owner->getMenubar()->openByName(argument);
1354                 break; // RVDK_PATCH_5
1355
1356         case LFUN_SPELLCHECK:
1357                 if (lyxrc.isp_command != "none")
1358                         owner->getDialogs()->showSpellchecker();
1359                 break;
1360
1361         // --- lyxserver commands ----------------------------
1362
1363
1364         case LFUN_GETNAME:
1365                 setMessage(owner->buffer()->fileName());
1366                 lyxerr[Debug::INFO] << "FNAME["
1367                                << owner->buffer()->fileName()
1368                                << "] " << endl;
1369                 break;
1370
1371         case LFUN_NOTIFY:
1372         {
1373                 dispatch_buffer = keyseq.print();
1374                 lyxserver->notifyClient(dispatch_buffer);
1375         }
1376         break;
1377
1378         case LFUN_GOTOFILEROW:
1379         {
1380                 string file_name;
1381                 int row;
1382                 istringstream istr(argument.c_str());
1383                 istr >> file_name >> row;
1384                 // Must replace extension of the file to be .lyx and get full path
1385                 string const s(ChangeExtension(file_name, ".lyx"));
1386
1387                 // Either change buffer or load the file
1388                 if (bufferlist.exists(s)) {
1389                         owner->view()->buffer(bufferlist.getBuffer(s));
1390                 } else {
1391                         owner->view()->buffer(bufferlist.loadLyXFile(s));
1392                 }
1393
1394                 owner->view()->setCursorFromRow(row);
1395
1396                 owner->view()->center();
1397                 // see BufferView_pimpl::center() 
1398                 owner->view()->updateScrollbar();
1399         }
1400         break;
1401
1402         case LFUN_GOTO_PARAGRAPH:
1403         {
1404                 istringstream istr(argument.c_str());
1405
1406                 int id;
1407                 istr >> id;
1408                 Paragraph * par = owner->buffer()->getParFromID(id);
1409                 if (par == 0) {
1410                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1411                                             << id << "]" << endl;
1412                         break;
1413                 } else {
1414                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1415                                             << " found." << endl;
1416                 }
1417
1418                 if (owner->view()->theLockingInset())
1419                         owner->view()->unlockInset(owner->view()->theLockingInset());
1420                 if (par->inInset()) {
1421                         par->inInset()->edit(owner->view());
1422                 }
1423                 // Set the cursor
1424                 owner->view()->getLyXText()->setCursor(owner->view(), par, 0);
1425                 owner->view()->setState();
1426                 owner->showState();
1427
1428                 owner->view()->center();
1429                 // see BufferView_pimpl::center() 
1430                 owner->view()->updateScrollbar();
1431         }
1432         break;
1433
1434         case LFUN_APROPOS:
1435         case LFUN_GETTIP:
1436         {
1437                 int const qa = lyxaction.LookupFunc(argument);
1438                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
1439         }
1440         break;
1441
1442         // --- toolbar ----------------------------------
1443         case LFUN_PUSH_TOOLBAR:
1444         {
1445                 int nth = strToInt(argument);
1446                 if (nth <= 0) {
1447                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
1448                 } else {
1449                         owner->getToolbar()->push(nth);
1450                 }
1451         }
1452         break;
1453
1454         case LFUN_ADD_TO_TOOLBAR:
1455         {
1456                 if (lyxerr.debugging(Debug::GUI)) {
1457                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
1458                                 "argument = `" << argument << '\'' << endl;
1459                 }
1460                 string tmp(argument);
1461                 //lyxerr <<string("Argument: ") + argument);
1462                 //lyxerr <<string("Tmp     : ") + tmp);
1463                 if (tmp.empty()) {
1464                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
1465                 } else {
1466                         owner->getToolbar()->add(argument, false);
1467                         owner->getToolbar()->set();
1468                 }
1469         }
1470         break;
1471
1472         // --- insert characters ----------------------------------------
1473
1474         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1475         case LFUN_MATH_EXTERN:
1476         case LFUN_MATH_NUMBER:
1477         case LFUN_MATH_NONUMBER:
1478         case LFUN_MATH_LIMITS:
1479         {
1480                 setErrorMessage(N_("This is only allowed in math mode!"));
1481         }
1482         break;
1483
1484         // passthrough hat and underscore outside mathed:
1485         case LFUN_SUBSCRIPT:
1486                 dispatch(LFUN_SELFINSERT, "_");
1487                 break;
1488         case LFUN_SUPERSCRIPT:
1489                 dispatch(LFUN_SELFINSERT, "^");
1490                 break;
1491
1492         case LFUN_MATH_PANEL:
1493                 owner->getDialogs()->showMathPanel();
1494                 break;
1495
1496         case LFUN_CITATION_CREATE:
1497         {
1498                 InsetCommandParams p("cite");
1499
1500                 if (!argument.empty()) {
1501                         // This should be set at source, ie when typing
1502                         // "citation-insert foo" in the minibuffer.
1503                         // Question: would pybibliographer also need to be
1504                         // changed. Suspect so. Leave as-is therefore.
1505                         if (contains(argument, "|")) {
1506                                 p.setContents(token(argument, '|', 0));
1507                                 p.setOptions( token(argument, '|', 1));
1508                         } else {
1509                                 p.setContents(argument);
1510                         }
1511                         dispatch(LFUN_CITATION_INSERT, p.getAsString());
1512                 } else
1513                         owner->getDialogs()->createCitation(p.getAsString());
1514         }
1515         break;
1516
1517         case LFUN_CHILDOPEN:
1518         {
1519                 string const filename =
1520                         MakeAbsPath(argument,
1521                                     owner->buffer()->filePath());
1522                 setMessage(N_("Opening child document ") +
1523                            MakeDisplayPath(filename) + "...");
1524                 owner->view()->savePosition(0);
1525                 if (bufferlist.exists(filename))
1526                         owner->view()->buffer(bufferlist.getBuffer(filename));
1527                 else
1528                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
1529         }
1530         break;
1531
1532         case LFUN_TOGGLECURSORFOLLOW:
1533                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1534                 break;
1535
1536         case LFUN_KMAP_OFF:             // keymap off
1537                 owner->getIntl()->KeyMapOn(false);
1538                 break;
1539
1540         case LFUN_KMAP_PRIM:    // primary keymap
1541                 owner->getIntl()->KeyMapPrim();
1542                 break;
1543
1544         case LFUN_KMAP_SEC:             // secondary keymap
1545                 owner->getIntl()->KeyMapSec();
1546                 break;
1547
1548         case LFUN_KMAP_TOGGLE:  // toggle keymap
1549                 owner->getIntl()->ToggleKeyMap();
1550                 break;
1551
1552         case LFUN_SEQUENCE:
1553         {
1554                 // argument contains ';'-terminated commands
1555                 while (!argument.empty()) {
1556                         string first;
1557                         argument = split(argument, first, ';');
1558                         verboseDispatch(first, false);
1559                 }
1560         }
1561         break;
1562
1563         case LFUN_DIALOG_PREFERENCES:
1564                 owner->getDialogs()->showPreferences();
1565                 break;
1566
1567         case LFUN_SAVEPREFERENCES:
1568         {
1569                 Path p(user_lyxdir);
1570                 lyxrc.write("preferences");
1571         }
1572         break;
1573
1574         case LFUN_SCREEN_FONT_UPDATE:
1575         {
1576                 // handle the screen font changes.
1577                 //
1578                 lyxrc.set_font_norm_type();
1579                 lyx_gui::update_fonts();
1580                 // Of course we should only do the resize and the textcache.clear
1581                 // if values really changed...but not very important right now. (Lgb)
1582                 // All visible buffers will need resize
1583                 owner->view()->resize();
1584                 // We also need to empty the textcache so that
1585                 // the buffer will be formatted correctly after
1586                 // a zoom change.
1587                 textcache.clear();
1588         }
1589         break;
1590
1591         case LFUN_SET_COLOR:
1592         {
1593                 string lyx_name;
1594                 string const x11_name = split(argument, lyx_name, ' ');
1595                 if (lyx_name.empty() || x11_name.empty()) {
1596                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1597                                                 " <x11_name>"));
1598                         break;
1599                         }
1600
1601                 bool const graphicsbg_changed =
1602                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1603                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1604
1605                 if (!lcolor.setColor(lyx_name, x11_name)) {
1606                         static string const err1 (N_("Set-color \""));
1607                         static string const err2 (
1608                                 N_("\" failed - color is undefined "
1609                                    "or may not be redefined"));
1610                         setErrorMessage(_(err1) + lyx_name + _(err2));
1611                         break;
1612                 }
1613
1614                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1615
1616                 if (graphicsbg_changed) {
1617 #ifdef WITH_WARNINGS
1618 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1619 #endif
1620 #if 0
1621                         grfx::GCache & gc = grfx::GCache::get();
1622                         gc.changeDisplay(true);
1623 #endif
1624                 }
1625
1626                 owner->view()->repaint();
1627                 break;
1628         }
1629
1630         case LFUN_MESSAGE:
1631                 owner->message(argument);
1632                 break;
1633
1634         case LFUN_MESSAGE_PUSH:
1635                 owner->messagePush(argument);
1636                 break;
1637
1638         case LFUN_MESSAGE_POP:
1639                 owner->messagePop();
1640                 break;
1641
1642         case LFUN_FORKS_SHOW:
1643                 owner->getDialogs()->showForks();
1644                 break;
1645
1646         case LFUN_FORKS_KILL:
1647         {
1648                 if (!isStrInt(argument))
1649                         break;
1650
1651                 pid_t const pid = strToInt(argument);
1652                 ForkedcallsController & fcc = ForkedcallsController::get();
1653                 fcc.kill(pid);
1654                 break;
1655         }
1656
1657         case LFUN_TOOLTIPS_TOGGLE:
1658                 owner->getDialogs()->toggleTooltips();
1659                 break;
1660
1661         default:
1662                 // Then if it was none of the above
1663                 // Trying the BufferView::pimpl dispatch:
1664                 if (!owner->view()->Dispatch(action, argument))
1665                         lyxerr << "A truly unknown func ["
1666                                << lyxaction.getActionName(action) << "]!"
1667                                << endl;
1668                 break;
1669         } // end of switch
1670
1671 exit_with_message:
1672
1673         string const res = getMessage();
1674
1675         if (!res.empty())
1676                 owner->message(_(res));
1677         owner->updateMenubar();
1678         owner->updateToolbar();
1679
1680         return res;
1681 }
1682
1683
1684 void LyXFunc::setupLocalKeymap()
1685 {
1686         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1687         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1688 }
1689
1690
1691 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1692 {
1693         string initpath = lyxrc.document_path;
1694         string filename(name);
1695
1696         if (owner->view()->available()) {
1697                 string const trypath = owner->buffer()->filePath();
1698                 // If directory is writeable, use this as default.
1699                 if (IsDirWriteable(trypath))
1700                         initpath = trypath;
1701         }
1702
1703         static int newfile_number;
1704
1705         if (filename.empty()) {
1706                 filename = AddName(lyxrc.document_path,
1707                             "newfile" + tostr(++newfile_number) + ".lyx");
1708                 FileInfo fi(filename);
1709                 while (bufferlist.exists(filename) || fi.readable()) {
1710                         ++newfile_number;
1711                         filename = AddName(lyxrc.document_path,
1712                                     "newfile" + tostr(newfile_number) +
1713                                     ".lyx");
1714                         fi.newFile(filename);
1715                 }
1716         }
1717
1718         // The template stuff
1719         string templname;
1720         if (fromTemplate) {
1721                 FileDialog fileDlg(owner, _("Select template file"),
1722                         LFUN_SELECT_FILE_SYNC,
1723                         make_pair(string(_("Documents|#o#O")),
1724                                   string(lyxrc.document_path)),
1725                         make_pair(string(_("Templates|#T#t")),
1726                                   string(lyxrc.template_path)));
1727
1728                 FileDialog::Result result =
1729                         fileDlg.Select(lyxrc.template_path,
1730                                        _("*.lyx|LyX Documents (*.lyx)"));
1731
1732                 if (result.first == FileDialog::Later)
1733                         return;
1734
1735                 string const fname = result.second;
1736
1737                 if (fname.empty())
1738                         return;
1739                 templname = fname;
1740         }
1741
1742         owner->view()->buffer(bufferlist.newFile(filename, templname, !name.empty()));
1743 }
1744
1745
1746 void LyXFunc::open(string const & fname)
1747 {
1748         string initpath = lyxrc.document_path;
1749
1750         if (owner->view()->available()) {
1751                 string const trypath = owner->buffer()->filePath();
1752                 // If directory is writeable, use this as default.
1753                 if (IsDirWriteable(trypath))
1754                         initpath = trypath;
1755         }
1756
1757         string filename;
1758
1759         if (fname.empty()) {
1760                 FileDialog fileDlg(owner, _("Select document to open"),
1761                         LFUN_FILE_OPEN,
1762                         make_pair(string(_("Documents|#o#O")),
1763                                   string(lyxrc.document_path)),
1764                         make_pair(string(_("Examples|#E#e")),
1765                                   string(AddPath(system_lyxdir, "examples"))));
1766
1767                 FileDialog::Result result =
1768                         fileDlg.Select(initpath,
1769                                        "*.lyx|LyX Documents (*.lyx)");
1770
1771                 if (result.first == FileDialog::Later)
1772                         return;
1773
1774                 filename = result.second;
1775
1776                 // check selected filename
1777                 if (filename.empty()) {
1778                         owner->message(_("Canceled."));
1779                         return;
1780                 }
1781         } else
1782                 filename = fname;
1783
1784         // get absolute path of file and add ".lyx" to the filename if
1785         // necessary
1786         string const fullpath = FileSearch(string(), filename, "lyx");
1787         if (fullpath.empty()) {
1788                 Alert::alert(_("Error"), _("Could not find file"), filename);
1789                 return;
1790         }
1791
1792         filename = fullpath;
1793
1794         // loads document
1795         string const disp_fn(MakeDisplayPath(filename));
1796
1797         ostringstream str;
1798         str << _("Opening document") << ' ' << disp_fn << "...";
1799
1800         owner->message(str.str().c_str());
1801
1802         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1803         if (openbuf) {
1804                 owner->view()->buffer(openbuf);
1805                 ostringstream str;
1806                 str << _("Document") << ' ' << disp_fn << ' ' << _("opened.");
1807                 owner->message(str.str().c_str());
1808         } else {
1809                 ostringstream str;
1810                 str << _("Could not open document") << ' ' << disp_fn;
1811                 owner->message(str.str().c_str());
1812         }
1813 }
1814
1815
1816 void LyXFunc::doImport(string const & argument)
1817 {
1818         string format;
1819         string filename = split(argument, format, ' ');
1820
1821         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1822                             << " file: " << filename << endl;
1823
1824         // need user interaction
1825         if (filename.empty()) {
1826                 string initpath = lyxrc.document_path;
1827
1828                 if (owner->view()->available()) {
1829                         string const trypath = owner->buffer()->filePath();
1830                         // If directory is writeable, use this as default.
1831                         if (IsDirWriteable(trypath))
1832                                 initpath = trypath;
1833                 }
1834
1835                 string const text = _("Select ") + formats.prettyName(format)
1836                         + _(" file to import");
1837
1838                 FileDialog fileDlg(owner, text,
1839                         LFUN_IMPORT,
1840                         make_pair(string(_("Documents|#o#O")),
1841                                   string(lyxrc.document_path)),
1842                         make_pair(string(_("Examples|#E#e")),
1843                                   string(AddPath(system_lyxdir, "examples"))));
1844
1845                 string const extension = "*." + formats.extension(format)
1846                         + "| " + formats.prettyName(format)
1847                         + " (*." + formats.extension(format) + ")";
1848
1849                 FileDialog::Result result = fileDlg.Select(initpath,
1850                                                            extension);
1851
1852                 if (result.first == FileDialog::Later)
1853                         return;
1854
1855                 filename = result.second;
1856
1857                 // check selected filename
1858                 if (filename.empty())
1859                         owner->message(_("Canceled."));
1860         }
1861
1862         if (filename.empty())
1863                 return;
1864
1865         // get absolute path of file
1866         filename = MakeAbsPath(filename);
1867
1868         string const lyxfile = ChangeExtension(filename, ".lyx");
1869
1870         // Check if the document already is open
1871         if (lyxrc.use_gui && bufferlist.exists(lyxfile)) {
1872                 switch (Alert::askConfirmation(_("Document is already open:"),
1873                                         MakeDisplayPath(lyxfile, 50),
1874                                         _("Do you want to close that document now?\n"
1875                                           "('No' will just switch to the open version)")))
1876                         {
1877                         case 1:
1878                                 // If close is canceled, we cancel here too.
1879                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
1880                                         return;
1881                                 break;
1882                         case 2:
1883                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
1884                                 return;
1885                         case 3:
1886                                 owner->message(_("Canceled."));
1887                                 return;
1888                         }
1889         }
1890
1891         // if the file exists already, and we didn't do
1892         // -i lyx thefile.lyx, warn
1893         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1894                 if (!Alert::askQuestion(_("A document by the name"),
1895                         MakeDisplayPath(lyxfile), _("already exists. Overwrite?"))) {
1896                         owner->message(_("Canceled"));
1897                         return;
1898                 }
1899         }
1900
1901         Importer::Import(owner, filename, format);
1902 }
1903
1904
1905 void LyXFunc::reloadBuffer()
1906 {
1907         string const fn = owner->buffer()->fileName();
1908         if (bufferlist.close(owner->buffer()))
1909                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
1910 }
1911
1912
1913 void LyXFunc::closeBuffer()
1914 {
1915         if (bufferlist.close(owner->buffer()) && !quitting) {
1916                 if (bufferlist.empty()) {
1917                         // need this otherwise SEGV may occur while trying to
1918                         // set variables that don't exist
1919                         // since there's no current buffer
1920                         owner->getDialogs()->hideBufferDependent();
1921                 } else {
1922                         owner->view()->buffer(bufferlist.first());
1923                 }
1924         }
1925 }
1926
1927
1928 // Each "owner" should have it's own message method. lyxview and
1929 // the minibuffer would use the minibuffer, but lyxserver would
1930 // send an ERROR signal to its client.  Alejandro 970603
1931 // This func is bit problematic when it comes to NLS, to make the
1932 // lyx servers client be language indepenent we must not translate
1933 // strings sent to this func.
1934 void LyXFunc::setErrorMessage(string const & m) const
1935 {
1936         dispatch_buffer = m;
1937         errorstat = true;
1938 }
1939
1940
1941 void LyXFunc::setMessage(string const & m) const
1942 {
1943         dispatch_buffer = m;
1944 }
1945
1946
1947 void LyXFunc::setStatusMessage(string const & m) const
1948 {
1949         status_buffer = m;
1950 }
1951
1952
1953 void LyXFunc::initMiniBuffer()
1954 {
1955         string text = _("Welcome to LyX!");
1956
1957         // When meta-fake key is pressed, show the key sequence so far + "M-".
1958         if (wasMetaKey()) {
1959                 text = keyseq.print();
1960                 text += "M-";
1961         }
1962
1963         // Else, when a non-complete key sequence is pressed,
1964         // show the available options.
1965         if (keyseq.length() > 0 && !keyseq.deleted()) {
1966                 text = keyseq.printOptions();
1967         }
1968
1969         // Else, show the buffer state.
1970         else if (owner->view()->available()) {
1971                 Buffer * tmpbuf = owner->buffer();
1972
1973                 string const nicename =
1974                         MakeDisplayPath(tmpbuf->fileName());
1975                 // Should we do this instead? (kindo like emacs)
1976                 // leaves more room for other information
1977                 text = "LyX: ";
1978                 text += nicename;
1979                 if (tmpbuf->lyxvc.inUse()) {
1980                         text += " [";
1981                         text += tmpbuf->lyxvc.versionString();
1982                         text += ' ';
1983                         text += tmpbuf->lyxvc.locker();
1984                         if (tmpbuf->isReadonly())
1985                                 text += " (RO)";
1986                         text += ']';
1987                 } else if (tmpbuf->isReadonly())
1988                         text += " [RO]";
1989                 if (!tmpbuf->isLyxClean())
1990                         text += _(" (Changed)");
1991         } else {
1992                 if (text != _("Welcome to LyX!")) // this is a hack
1993                         text = _("* No document open *");
1994         }
1995
1996         owner->message(text);
1997 }