]> git.lyx.org Git - features.git/blob - src/lyxfunc.C
Various fixes and added some functionallity to insettabular.
[features.git] / src / lyxfunc.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *          Copyright 1995 Matthias Ettrich
7  *          Copyright 1995-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef HAVE_SSTREAM
14 #include <sstream>
15 using std::istringstream;
16 #else
17 #include <strstream>
18 #endif
19
20 #include <time.h>
21 #include <locale.h>
22
23 #include <cstdlib>
24 #include <cctype>
25 #include <cstring>
26
27 #ifdef __GNUG__
28 #pragma implementation
29 #endif
30
31 #include "lyxlookup.h"
32 #include "kbmap.h"
33 #include "lyxfunc.h"
34 #include "bufferlist.h"
35 #include "lyxserver.h"
36 #include "lyx.h"
37 #include "intl.h"
38 #include "lyx_main.h"
39 #include "lyx_cb.h"
40 #include "LyXAction.h"
41 #include "insets/inseturl.h"
42 #include "insets/insetlatexaccent.h"
43 #include "insets/insettoc.h"
44 #include "insets/insetlof.h"
45 #include "insets/insetloa.h"
46 #include "insets/insetlot.h"
47 #include "insets/insetref.h"
48 #include "insets/insetparent.h"
49 #include "insets/insetindex.h"
50 #include "insets/insetinclude.h"
51 #include "insets/insetbib.h"
52 #include "insets/insettext.h"
53 #include "insets/insetert.h"
54 #include "insets/insetgraphics.h"
55 #include "insets/insetfoot.h"
56 #include "insets/insettabular.h"
57 #include "mathed/formulamacro.h"
58 #include "toolbar.h"
59 #include "spellchecker.h" // RVDK_PATCH_5
60 #include "minibuffer.h"
61 #include "vspace.h"
62 #include "LyXView.h"
63 #include "filedlg.h"
64 #include "lyx_gui_misc.h"
65 #include "support/filetools.h"
66 #include "support/FileInfo.h"
67 #include "support/syscall.h"
68 #include "support/lstrings.h"
69 #include "support/path.h"
70 #include "debug.h"
71 #include "lyxrc.h"
72 #include "lyxtext.h"
73 #include "gettext.h"
74 #include "trans_mgr.h"
75 #include "ImportLaTeX.h"
76 #include "ImportNoweb.h"
77 #include "layout.h"
78 #include "WorkArea.h"
79 #include "lyxfr1.h"
80 #include "menus.h"
81 #include "bufferview_funcs.h"
82
83 using std::pair;
84 using std::endl;
85
86 extern bool cursor_follows_scrollbar;
87
88 extern void InsertAsciiFile(BufferView *, string const &, bool);
89 extern void math_insert_symbol(char const *);
90 extern Bool math_insert_greek(char const); // why "Bool"?
91 extern BufferList bufferlist;
92 extern LyXServer * lyxserver;
93 extern short greek_kb_flag;
94 extern FD_form_toc * fd_form_toc;
95 extern bool selection_possible;
96
97 extern kb_keymap * toplevel_keymap;
98
99 extern void MenuWrite(Buffer *);
100 extern void MenuWriteAs(Buffer *);
101 extern int  MenuRunLaTeX(Buffer *);
102 extern int  MenuBuildProg(Buffer *);
103 extern int  MenuRunChktex(Buffer *);
104 extern bool CreatePostscript(Buffer *, bool);
105 extern void MenuPrint(Buffer *);
106 extern void MenuSendto();
107 extern void QuitLyX();
108 extern void MenuFax(Buffer *);
109 extern void MenuExport(Buffer *, string const &);
110
111 #define XFORMS_CLIPBOARD 1
112
113 #ifndef XFORMS_CLIPBOARD
114 extern void MenuPasteSelection(char at);
115 #endif
116
117 extern LyXAction lyxaction;
118 // (alkis)
119 extern tex_accent_struct get_accent(kb_action action);
120
121 extern void AutoSave(BufferView *);
122 extern void SetUpdateTimer(float timer = 0.3);
123 extern void FreeUpdateTimer();
124 extern bool PreviewDVI(Buffer *);
125 extern bool PreviewPostscript(Buffer *);
126 extern void MenuInsertLabel(char const *);
127 extern void MenuInsertRef();
128 extern void MenuLayoutCharacter();
129 extern void MenuLayoutParagraph();
130 extern void MenuLayoutDocument();
131 extern void MenuLayoutPaper();
132 extern void MenuLayoutTable(int flag);
133 extern void MenuLayoutQuotes();
134 extern void MenuLayoutPreamble();
135 extern void MenuLayoutSave();
136 extern void bulletForm();
137
138 extern Buffer * NewLyxFile(string const &);
139 extern void LoadLyXFile(string const &);
140 extern void Reconfigure(BufferView *);
141
142 extern LyXTextClass::size_type current_layout;
143 extern int getISOCodeFromLaTeX(char *);
144
145 extern void ShowLatexLog();
146
147 /* === globals =========================================================== */
148
149 bool LyXFunc::show_sc = true;
150
151
152 LyXFunc::LyXFunc(LyXView * o)
153         : owner(o)
154 {
155         meta_fake_bit = 0;
156         lyx_dead_action = LFUN_NOACTION;
157         lyx_calling_dead_action = LFUN_NOACTION;
158         setupLocalKeymap();
159 }
160
161
162 // I changed this func slightly. I commented out the ...FinishUndo(),
163 // this means that all places that used to have a moveCursorUpdate, now
164 // have a ...FinishUndo() as the preceeding statement. I have also added
165 // a moveCursorUpdate to some of the functions that updated the cursor, but
166 // that did not show its new position.
167 inline
168 void LyXFunc::moveCursorUpdate(bool selecting)
169 {
170         if (selecting || owner->view()->text->mark_set) {
171                 owner->view()->text->SetSelection();
172                 owner->view()->toggleToggle();
173                 //owner->view()->update(0);
174                 //} else {
175                 //owner->view()->update(-2); // this IS necessary
176                 // (Matthias) 
177         }
178         owner->view()->update(0);
179         owner->view()->showCursor();
180         
181         /* ---> Everytime the cursor is moved, show the current font state. */
182         // should this too me moved out of this func?
183         //owner->getMiniBuffer()->Set(CurrentState());
184         owner->view()->setState();
185 }
186
187
188 int LyXFunc::processKeyEvent(XEvent * ev)
189 {
190         char s_r[10];
191         string argument;
192         XKeyEvent * keyevent = &ev->xkey;
193         KeySym keysym_return = 0;
194
195         int num_bytes = LyXLookupString(ev, s_r, 10, &keysym_return);
196         s_r[num_bytes] = '\0';
197
198         if (lyxerr.debugging(Debug::KEY)) {
199                 char * tmp = XKeysymToString(keysym_return);
200                 string stm = (tmp ? tmp : "");
201                 lyxerr << "KeySym is "
202                        << stm
203                        << "["
204                        << keysym_return << "]"
205                        << " and num_bytes is "
206                        << num_bytes
207                        << " the string returned is \""
208                        << s_r << '\"' << endl;
209         }
210         // Do nothing if we have nothing (JMarc)
211         if (num_bytes == 0 && keysym_return == NoSymbol) {
212                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
213                                    << endl;
214                 return 0;
215         }
216         
217         // this function should be used always [asierra060396]
218         UpdatableInset * tli = owner->view()->the_locking_inset;
219         if (owner->view()->available() && tli && (keysym_return==XK_Escape)) {
220                 if (tli == tli->GetLockingInset()) {
221                         owner->view()->unlockInset(tli);
222                         owner->view()->text->CursorRight();
223                         moveCursorUpdate(false);
224                         owner->getMiniBuffer()->Set(CurrentState(owner->view()));
225                 } else {
226                         tli->UnlockInsetInInset(owner->view(),
227                                                 tli->GetLockingInset());
228                 }
229                 return 0;
230         }
231
232         // Can we be sure that this will work for all X-Windows
233         // implementations? (Lgb)
234         // This code snippet makes lyx ignore some keys. Perhaps
235         // all of them should be explictly mentioned?
236         if((keysym_return >= XK_Shift_L && keysym_return <= XK_Hyper_R)
237            || keysym_return == XK_Mode_switch || keysym_return == 0x0)
238                 return 0;
239
240         // Do a one-deep top-level lookup for
241         // cancel and meta-fake keys. RVDK_PATCH_5
242         cancel_meta_seq.reset();
243
244         int action = cancel_meta_seq.addkey(keysym_return, keyevent->state
245                                             &(ShiftMask|ControlMask
246                                               |Mod1Mask)); 
247
248         // When not cancel or meta-fake, do the normal lookup. 
249         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
250         // Mostly, meta_fake_bit = 0. RVDK_PATCH_5.
251         if ( (action != LFUN_CANCEL) && (action != LFUN_META_FAKE) ) {
252
253                 // remove Caps Lock and Mod2 as a modifiers
254                 action = keyseq.addkey(keysym_return,
255                                        (keyevent->state | meta_fake_bit)
256                                        &(ShiftMask|ControlMask
257                                          |Mod1Mask));      
258         }
259         // Dont remove this unless you know what you are doing.
260         meta_fake_bit = 0;
261                 
262         if (action == 0) action = LFUN_PREFIX;
263
264         if (lyxerr.debugging(Debug::KEY)) {
265                 string buf;
266                 keyseq.print(buf);
267                 lyxerr << "Key ["
268                        << action << "]["
269                        << buf << "]["
270                        << num_bytes << "]" << endl;
271         }
272
273         // already here we know if it any point in going further
274         // why not return already here if action == -1 and
275         // num_bytes == 0? (Lgb)
276
277         if(keyseq.length > 1 || keyseq.length < -1) {
278                 string buf;
279                 keyseq.print(buf);
280                 owner->getMiniBuffer()->Set(buf);
281         }
282
283         if (action == -1) {
284                 if (keyseq.length < -1) { // unknown key sequence...
285                         string buf;
286                         LyXBell();
287                         keyseq.print(buf);
288                         owner->getMiniBuffer()->Set(_("Unknown sequence:"), buf);
289                         return 0;
290                 }
291         
292                 char isochar = keyseq.getiso();
293                 if (!(keyevent->state&ControlMask) &&
294                     !(keyevent->state&Mod1Mask) &&
295                     (isochar && keysym_return < 0xF000)) {
296                         argument += isochar;
297                 }
298                 if (argument.empty()) {
299                         lyxerr.debug() << "Empty argument!" << endl;
300                         // This can`t possibly be of any use
301                         // so we`ll skip the dispatch.
302                         return 0;
303                 }
304         } else
305                 if (action == LFUN_SELFINSERT) {
306                         argument = s_r[0];
307                 }
308     
309         bool tmp_sc = show_sc;
310         show_sc = false;
311         Dispatch(action, argument.c_str());
312         show_sc = tmp_sc;
313         
314         return 0;
315
316
317
318 LyXFunc::func_status LyXFunc::getStatus(int ac) const
319 {
320         kb_action action;
321         func_status flag = LyXFunc::OK;
322         string argument;
323         Buffer * buf = owner->buffer();
324         
325         if (lyxaction.isPseudoAction(ac)) 
326                 action = lyxaction.retrieveActionArg(ac, argument);
327         else 
328                 action = static_cast<kb_action>(ac);
329         
330         if (action == LFUN_UNKNOWN_ACTION) {
331                 setErrorMessage(N_("Unknown action"));
332                 return LyXFunc::Unknown;
333         } 
334         
335         // Check whether we need a buffer
336         if (!lyxaction.funcHasFlag(action, LyXAction::NoBuffer)) {
337                 // Yes we need a buffer, do we have one?
338                 if (buf) {
339                         // yes
340                         // Can we use a readonly buffer?
341                         if (buf->isReadonly() && 
342                             !lyxaction.funcHasFlag(action,
343                                                    LyXAction::ReadOnly)) {
344                                 // no
345                                 setErrorMessage(N_("Document is read-only"));
346                                 flag |= LyXFunc::Disabled;
347                         }
348                 } else {
349                         // no
350                         setErrorMessage(N_("Command not allowed with"
351                                            "out any document open"));
352                         flag |= LyXFunc::Disabled;
353                 }
354         }
355
356         if (flag & LyXFunc::Disabled)
357                 return flag;
358
359         // I would really like to avoid having this switch and rather try to
360         // encode this in the function itself.
361         static bool noLaTeX = lyxrc.latex_command == "none";
362         bool disable = false;
363         switch (action) {
364         case LFUN_PREVIEW:
365                 disable = noLaTeX || lyxrc.view_dvi_command == "none";
366                 break;  
367         case LFUN_PREVIEWPS: 
368                 disable = noLaTeX || lyxrc.view_ps_command == "none";
369                 break;
370         case LFUN_RUNLATEX:
371         case LFUN_RUNDVIPS:
372                 disable = noLaTeX;
373                 break;
374         case LFUN_MENUPRINT:
375                 disable = noLaTeX || lyxrc.print_command == "none";
376                 break;
377         case LFUN_FAX:
378                 disable = noLaTeX || lyxrc.fax_command == "none"; 
379                 break;
380         case LFUN_IMPORT:
381                 if (argument == "latex")
382                         disable = lyxrc.relyx_command == "none";
383                 if (argument == "linuxdoc")
384                         disable = lyxrc.linuxdoc_to_lyx_command == "none";
385                 break;
386         case LFUN_EXPORT:
387                 if (argument == "dvi" || argument == "postscript")
388                         disable = noLaTeX;
389                 if (argument == "html")
390                         disable = lyxrc.html_command == "none";
391                 if (argument == "html-linuxdoc")
392                         disable = lyxrc.linuxdoc_to_html_command == "none";
393                 if (argument == "html-docbook")
394                         disable = lyxrc.docbook_to_html_command == "none";
395                 break;
396         case LFUN_UNDO:
397                 disable = buf->undostack.empty();
398                 break;
399         case LFUN_REDO:
400                 disable = buf->redostack.empty();
401                 break;
402         case LFUN_SPELLCHECK:
403                 disable = lyxrc.isp_command == "none";
404                 break;
405         case LFUN_RUNCHKTEX:
406                 disable = lyxrc.chktex_command == "none";
407                 break;
408         case LFUN_LAYOUT_TABLE:
409                 disable = ! owner->view()->text->cursor.par->table;
410                 break;
411         default:
412                 break;
413         }
414         if (disable)
415                 flag |= LyXFunc::Disabled;
416
417         if (buf) {
418                 func_status box = LyXFunc::ToggleOff;
419                 LyXFont font = owner->view()->text->real_current_font;
420                 switch (action) {
421                 case LFUN_EMPH:
422                         if (font.emph() == LyXFont::ON)
423                                 box = LyXFunc::ToggleOn;
424                         break;
425                 case LFUN_NOUN:
426                         if (font.noun() == LyXFont::ON)
427                                 box = LyXFunc::ToggleOn;
428                         break;
429                 case LFUN_BOLD:
430                         if (font.series() == LyXFont::BOLD_SERIES)
431                                 box = LyXFunc::ToggleOn;
432                         break;
433                 case LFUN_TEX:
434                         if (font.latex() == LyXFont::ON)
435                                 box = LyXFunc::ToggleOn;
436                         break;
437                 default:
438                         box = LyXFunc::OK;
439                         break;
440                 }
441                 flag |= box;
442         }
443
444         return flag;
445 }
446
447
448 string LyXFunc::Dispatch(string const & s) 
449 {
450         // Split command string into command and argument
451         string cmd, line = frontStrip(s);
452         string arg = strip(frontStrip(split(line, cmd, ' ')));
453
454         return Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
455 }
456
457
458 string LyXFunc::Dispatch(int ac,
459                          char const * do_not_use_this_arg)
460 {
461         string argument;
462         kb_action action;
463         
464         // we have not done anything wrong yet.
465         errorstat = false;
466         dispatch_buffer.erase();
467         
468         // if action is a pseudo-action, we need the real action
469         if (lyxaction.isPseudoAction(ac)) {
470                 string tmparg;
471                 action = static_cast<kb_action>
472                         (lyxaction.retrieveActionArg(ac, tmparg));
473                 if (!tmparg.empty())
474                         argument = tmparg;
475         } else {
476                 action = static_cast<kb_action>(ac);
477                 if (do_not_use_this_arg)
478                         argument = do_not_use_this_arg; // except here
479         }
480     
481         selection_possible = false;
482         
483         if (owner->view()->available())
484                 owner->view()->hideCursor();
485
486         // We cannot use this function here
487         if (getStatus(action) & Disabled)
488                 goto exit_with_message;
489
490         commandshortcut.erase();
491         
492         if (lyxrc.display_shortcuts && show_sc) {
493                 if (action != LFUN_SELFINSERT) {
494                         // Put name of command and list of shortcuts
495                         // for it in minibuffer
496                         string comname = lyxaction.getActionName(action);
497
498                         int pseudoaction = action;
499                         bool argsadded = false;
500
501                         if (!argument.empty()) {
502                                 // If we have the command with argument, 
503                                 // this is better
504                                 pseudoaction = 
505                                         lyxaction.searchActionArg(action,
506                                                                   argument.c_str());
507
508                                 if (pseudoaction == -1) {
509                                         pseudoaction = action;
510                                 } else {
511                                         comname += " " + argument;
512                                         argsadded = true;
513                                 }
514                         }
515
516                         string shortcuts = toplevel_keymap->findbinding(pseudoaction);
517
518                         if (!shortcuts.empty()) {
519                                 comname += ": " + shortcuts;
520                         } else if (!argsadded) {
521                                 comname += " " + argument;
522                         }
523
524                         if (!comname.empty()) {
525                                 comname = strip(comname);
526                                 commandshortcut = "(" + comname + ')';
527                                 owner->getMiniBuffer()->Set(commandshortcut);
528                                 // Here we could even add a small pause,
529                                 // to annoy the user and make him learn
530                                 // the shortcuts.
531                                 // No! That will just annoy, not teach
532                                 // anything. The user will read the messages
533                                 // if they are interested. (Asger)
534                         }
535                 }
536         }
537
538         // If in math mode pass the control to
539         // the math inset [asierra060396]
540         if (owner->view()->available() &&
541             owner->view()->the_locking_inset) {
542                 UpdatableInset::RESULT result;
543                 if (action > 1
544                     || (action == LFUN_UNKNOWN_ACTION
545                         && keyseq.length >= -1)) {
546                         if (action == LFUN_UNKNOWN_ACTION
547                             && argument.empty()) {
548                                 argument = keyseq.getiso();
549                         }
550                         // Undo/Redo pre 0.13 is a bit tricky for insets.
551                         if (action == LFUN_UNDO) {
552                                 int slx, sly;
553                                 UpdatableInset * inset = 
554                                         owner->view()->the_locking_inset;
555                                 inset->GetCursorPos(slx, sly);
556                                 owner->view()->unlockInset(inset);
557                                 owner->view()->menuUndo();
558                                 if (owner->view()->text->cursor.par->
559                                     IsInset(owner->view()->text->cursor.pos)) {
560                                         inset = static_cast<UpdatableInset*>(
561                                                 owner->view()->text->cursor.par->
562                                                 GetInset(owner->view()->text->
563                                                          cursor.pos));
564                                 } else {
565                                         inset = 0;
566                                 }
567                                 if (inset)
568                                         inset->Edit(owner->view(),slx,sly,0);
569                                 return string();
570                         } else if (action == LFUN_REDO) {
571                                 int slx, sly;
572                                 UpdatableInset * inset = owner->view()->
573                                         the_locking_inset;
574                                 inset->GetCursorPos(slx, sly);
575                                 owner->view()->unlockInset(inset);
576                                 owner->view()->menuRedo();
577                                 inset = static_cast<UpdatableInset*>(
578                                         owner->view()->text->cursor.par->
579                                         GetInset(owner->view()->text->
580                                                  cursor.pos));
581                                 if (inset)
582                                         inset->Edit(owner->view(),slx,sly,0); 
583                                 return string();
584                         } else if (((result=owner->view()->the_locking_inset->
585                                    LocalDispatch(owner->view(), action,
586                                                  argument)) ==
587                                    UpdatableInset::DISPATCHED) ||
588                                    (result == UpdatableInset::DISPATCHED_NOUPDATE))
589                                 return string();
590                         else {
591                                 setMessage(N_("Text mode"));
592                                 switch(action) {
593                                 case LFUN_UNKNOWN_ACTION:
594                                 case LFUN_BREAKPARAGRAPH:
595                                 case LFUN_BREAKLINE:
596                                         owner->view()->text->CursorRight();
597                                         owner->view()->setState();
598                                         owner->getMiniBuffer()->Set(CurrentState(owner->view()));
599                                         break;
600                                 case LFUN_RIGHT:
601                                         if (!owner->view()->text->cursor.par->isRightToLeftPar()) {
602                                                 owner->view()->text->CursorRight();
603                                                 moveCursorUpdate(false);
604                                                 owner->getMiniBuffer()->
605                                                         Set(CurrentState(owner->view()));
606                                         }
607                                         return string();
608                                 case LFUN_LEFT: 
609                                         if (owner->view()->text->cursor.par->isRightToLeftPar()) {
610                                                 owner->view()->text->CursorRight();
611                                                 moveCursorUpdate(false);
612                                                 owner->getMiniBuffer()->
613                                                         Set(CurrentState(owner->view()));
614                                         }
615                                         return string();
616                                 case LFUN_DOWN:
617                                         owner->view()->text->CursorDown();
618                                         moveCursorUpdate(false);
619                                         owner->getMiniBuffer()->
620                                                 Set(CurrentState(owner->view()));
621                                         return string();
622                                 default:
623                                         break;
624                                 }
625                         }
626                 }
627         }
628
629         switch(action) {
630                 // --- Misc -------------------------------------------
631         case LFUN_WORDFINDFORWARD  : 
632         case LFUN_WORDFINDBACKWARD : {
633                 static string last_search;
634                 string searched_string;
635             
636                 if (!argument.empty()) {
637                         last_search = argument;
638                         searched_string = argument;
639                 } else {
640                         searched_string = last_search;
641                 }
642
643                 LyXText * ltCur = owner->view()->text ;
644
645                 if (!searched_string.empty() &&
646                     ((action == LFUN_WORDFINDBACKWARD) ? 
647                      ltCur->SearchBackward(searched_string.c_str()) :
648                      ltCur->SearchForward(searched_string.c_str()))) {
649
650                         // ??? What is that ???
651                         owner->view()->update(-2);
652
653                         // ??? Needed ???
654                         // clear the selection (if there is any) 
655                         owner->view()->toggleSelection();
656                         owner->view()->text->ClearSelection();
657
658                         // Move cursor so that successive C-s 's will not stand in place. 
659                         if( action == LFUN_WORDFINDFORWARD ) 
660                                 owner->view()->text->CursorRightOneWord();
661                         owner->view()->text->FinishUndo();
662                         moveCursorUpdate(false);
663
664                         // ??? Needed ???
665                         // set the new selection 
666                         // SetSelectionOverLenChars(owner->view()->currentBuffer()->text, iLenSelected);
667                         owner->view()->toggleSelection(false);
668                 } else 
669                         LyXBell();      
670          
671                 // REMOVED : if (owner->view()->getWorkArea()->focus)
672                 owner->view()->showCursor();
673         }
674         break;
675
676         case LFUN_PREFIX:
677         {
678                 if (owner->view()->available()) {
679                         owner->view()->update(-2);
680                 }
681                 string buf;
682                 keyseq.print(buf, true);
683                 owner->getMiniBuffer()->Set(buf, string(), string(), 1);
684         }
685         break;
686
687         // --- Misc -------------------------------------------
688         case LFUN_EXEC_COMMAND:
689                 owner->getMiniBuffer()->ExecCommand(); 
690                 break;
691                 
692         case LFUN_CANCEL:                   // RVDK_PATCH_5
693                 keyseq.reset();
694                 meta_fake_bit = 0;
695                 if(owner->view()->available())
696                         // cancel any selection
697                         Dispatch(LFUN_MARK_OFF, 0);
698                 setMessage(N_("Cancel"));
699                 break;
700
701         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
702         {
703                 meta_fake_bit = Mod1Mask;
704                 string buf;
705                 keyseq.print(buf, true);
706                 string res = string("M-") + buf;
707                 setMessage(buf); // RVDK_PATCH_5
708         }
709         break;  
710
711         case LFUN_READ_ONLY_TOGGLE:
712                 if (owner->buffer()->lyxvc.inUse()) {
713                         owner->buffer()->lyxvc.toggleReadOnly();
714                 } else {
715                         owner->buffer()->setReadonly(
716                                 !owner->buffer()->isReadonly());
717                 }
718                 break;
719                 
720         case LFUN_CENTER: // this is center and redraw.
721                 owner->view()->center();
722                 break;
723                 
724         case LFUN_APPENDIX:
725                 if (owner->view()->available()) {
726                         owner->view()->text->toggleAppendix();
727                         owner->view()->update(1);
728                 }
729                 break;
730
731                 // --- Menus -----------------------------------------------
732         case LFUN_MENUNEW:
733                 MenuNew(false);
734                 break;
735                 
736         case LFUN_MENUNEWTMPLT:
737                 MenuNew(true);
738                 break;
739                 
740         case LFUN_MENUOPEN:
741                 MenuOpen();
742                 break;
743                 
744         case LFUN_CLOSEBUFFER:
745                 CloseBuffer();
746                 break;
747                 
748         case LFUN_MENUWRITE:
749                 owner->getMiniBuffer()->Set(_("Saving document"),
750                                             MakeDisplayPath(owner->buffer()->fileName()),
751                                             "...");
752                 MenuWrite(owner->buffer());
753                 //owner->getMiniBuffer()-> {
754                 //      Set(_("Document saved as"),
755                 //          MakeDisplayPath(owner->buffer()->fileName()));
756                 //} else {
757                 //owner->getMiniBuffer()->Set(_("Save failed!"));
758                 //}
759                 break;
760                 
761         case LFUN_MENUWRITEAS:
762                 MenuWriteAs(owner->buffer());
763                 break;
764                 
765         case LFUN_MENURELOAD:
766                 reloadBuffer();
767                 break;
768                 
769         case LFUN_PREVIEW:
770                 PreviewDVI(owner->buffer());
771                 break;
772                         
773         case LFUN_PREVIEWPS:
774                 PreviewPostscript(owner->buffer());
775                 break;
776                 
777         case LFUN_RUNLATEX:
778                 MenuRunLaTeX(owner->buffer());
779                 break;
780                 
781         case LFUN_BUILDPROG:
782                 MenuBuildProg(owner->buffer());
783                 break;
784                 
785         case LFUN_RUNCHKTEX:
786                 MenuRunChktex(owner->buffer());
787                 break;
788                 
789         case LFUN_RUNDVIPS:
790                 CreatePostscript(owner->buffer(), false);
791                 break;
792                 
793         case LFUN_MENUPRINT:
794                 MenuPrint(owner->buffer());
795                 break;
796                 
797         case LFUN_FAX:
798                 MenuFax(owner->buffer());
799                 break;
800                         
801         case LFUN_EXPORT:
802                 MenuExport(owner->buffer(), argument);
803                 break;
804
805         case LFUN_IMPORT:
806                 doImport(argument);
807                 break;
808                 
809         case LFUN_QUIT:
810                 QuitLyX();
811                 break;
812                 
813         case LFUN_TOCVIEW:
814         case LFUN_LOFVIEW:
815         case LFUN_LOTVIEW:
816         case LFUN_LOAVIEW:
817         {
818                 Buffer::TocType type = Buffer::TOC_TOC;
819                 if (action == LFUN_LOFVIEW)
820                         type = Buffer::TOC_LOF;
821                 else if (action == LFUN_LOTVIEW)
822                         type = Buffer::TOC_LOT;
823                 else if (action == LFUN_LOAVIEW)
824                         type = Buffer::TOC_LOA;
825                 fl_set_choice(fd_form_toc->toctype,type + 1);
826                 TocUpdateCB(0, 0);
827                 if (fd_form_toc->form_toc->visible) {
828                         fl_raise_form(fd_form_toc->form_toc);
829                 } else {
830                         static int ow = -1, oh;
831                         fl_show_form(fd_form_toc->form_toc,
832                                      FL_PLACE_MOUSE |
833                                      FL_FREE_SIZE, FL_FULLBORDER,
834                                      _("Table of Contents"));
835                         if (ow < 0) {
836                                 ow = fd_form_toc->form_toc->w;
837                                 oh = fd_form_toc->form_toc->h;
838                         }
839                         fl_set_form_minsize(fd_form_toc->form_toc, ow, oh);
840                 }
841                 break;
842         }       
843         case LFUN_TOC_INSERT:
844         {
845                 Inset * new_inset = new InsetTOC(owner->buffer());
846                 if (!owner->view()->insertInset(new_inset, "Standard", true))
847                         delete new_inset;
848                 break;
849         }
850         
851         case LFUN_LOF_INSERT:
852         {
853                 Inset * new_inset = new InsetLOF(owner->buffer());
854                 if (!owner->view()->insertInset(new_inset, "Standard", true))
855                         delete new_inset;
856                 break;
857         }
858         
859         case LFUN_LOA_INSERT:
860         {
861                 Inset * new_inset = new InsetLOA(owner->buffer());
862                 if (!owner->view()->insertInset(new_inset, "Standard", true))
863                         delete new_inset;
864                 break;
865         }
866
867         case LFUN_LOT_INSERT:
868         {
869                 Inset * new_inset = new InsetLOT(owner->buffer());
870                 if (!owner->view()->insertInset(new_inset, "Standard", true))
871                         delete new_inset;
872                 break;
873         }
874                 
875         case LFUN_TABLE:
876                 Table();
877                 break;
878                 
879         case LFUN_FIGURE:
880                 Figure();
881                 break;
882
883         case LFUN_INSERT_GRAPHICS:
884         {
885                 Inset * new_inset = new InsetGraphics;
886                 if (!owner->view()->insertInset(new_inset))
887                         delete new_inset;
888                 break;
889         }
890         
891         case LFUN_AUTOSAVE:
892                 AutoSave(owner->view());
893                 break;
894                 
895         case LFUN_UNDO:
896                 owner->view()->menuUndo();
897                 break;
898                 
899         case LFUN_REDO:
900                 owner->view()->menuRedo();
901                 break;
902                 
903         case LFUN_MENUSEARCH:
904         {
905                 // Ok this is one _very_ bad solution, but I think that some
906                 // of this will be rewritten as part of GUI indep anyway.
907                 // Lgb
908                 static LyXFindReplace FR_;
909                 FR_.StartSearch(owner->view());
910         }
911         break;
912                 
913         case LFUN_PASTE:
914                 owner->view()->paste();
915                 owner->view()->setState();
916                 break;
917                 
918         case LFUN_PASTESELECTION:
919         {
920                 bool asPara = false;
921                 if (argument == "paragraph") asPara = true;
922 #ifdef XFORMS_CLIPBOARD
923                 owner->view()->pasteClipboard(asPara);
924 #else
925                 MenuPasteSelection(asPara);
926 #endif
927         }
928         break;
929         
930         case LFUN_CUT:
931                 owner->view()->cut();
932                 break;
933                 
934         case LFUN_COPY:
935                 owner->view()->copy();
936                 break;
937                 
938         case LFUN_LAYOUT_COPY:
939                 owner->view()->copyEnvironment();
940                 break;
941                 
942         case LFUN_LAYOUT_PASTE:
943                 owner->view()->pasteEnvironment();
944                 owner->view()->setState();
945                 break;
946                 
947         case LFUN_GOTOERROR:
948                 owner->view()->gotoError();
949                 break;
950                 
951         case LFUN_REMOVEERRORS:
952                 if (owner->view()->removeAutoInsets()) {
953                         owner->view()->redraw();
954                         owner->view()->fitCursor();
955                         //owner->view()->updateScrollbar();
956                 }
957                 break;
958                 
959         case LFUN_GOTONOTE:
960                 owner->view()->gotoNote();
961                 break;
962                 
963         case LFUN_OPENSTUFF:
964                 owner->view()->openStuff();
965                 break;
966                 
967         case LFUN_HYPHENATION:
968                 owner->view()->hyphenationPoint();
969                 break;
970                 
971         case LFUN_LDOTS:
972                 owner->view()->ldots();
973                 break;
974                 
975         case LFUN_END_OF_SENTENCE:
976                 owner->view()->endOfSentenceDot();
977                 break;
978
979         case LFUN_MENU_SEPARATOR:
980                 owner->view()->menuSeparator();
981                 break;
982                 
983         case LFUN_HFILL:
984                 owner->view()->hfill();
985                 break;
986                 
987         case LFUN_DEPTH:
988                 changeDepth(owner->view(), 0);
989                 break;
990                 
991         case LFUN_DEPTH_MIN:
992                 changeDepth(owner->view(), -1);
993                 break;
994                 
995         case LFUN_DEPTH_PLUS:
996                 changeDepth(owner->view(), 1);
997                 break;
998                 
999         case LFUN_FREE:
1000                 Free(owner->view());
1001                 owner->view()->setState();
1002                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1003                 break;
1004                 
1005         case LFUN_TEX:
1006                 Tex(owner->view());
1007                 owner->view()->setState();
1008                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1009                 break;
1010                 
1011         case LFUN_MELT:
1012                 Melt(owner->view());
1013                 break;
1014                 
1015         case LFUN_RECONFIGURE:
1016                 Reconfigure(owner->view());
1017                 break;
1018
1019         case LFUN_FOOTMELT:
1020                 if (owner->view()->available()
1021                     && !owner->view()->text->selection
1022                     && owner->view()->text->cursor.par->footnoteflag
1023                     != LyXParagraph::NO_FOOTNOTE)
1024                         { // only melt footnotes with FOOTMELT, not margins etc
1025                                 if(owner->view()->text->cursor.par->footnotekind == LyXParagraph::FOOTNOTE)
1026                                         Melt(owner->view());
1027                         }
1028                 else
1029                         Foot(owner->view()); 
1030                 owner->view()->setState();
1031                 break;
1032
1033         case LFUN_MARGINMELT:
1034                 if (owner->view()->available()
1035                     && !owner->view()->text->selection
1036                     && owner->view()->text->cursor.par->footnoteflag
1037                     != LyXParagraph::NO_FOOTNOTE) {
1038                         // only melt margins
1039                         if(owner->view()->text->cursor.par->footnotekind == LyXParagraph::MARGIN)
1040                                 Melt(owner->view());
1041                 } else
1042                         Margin(owner->view()); 
1043                 owner->view()->setState();
1044                 break;
1045                 
1046                 // --- version control -------------------------------
1047         case LFUN_VC_REGISTER:
1048         {
1049                 if (!owner->buffer()->lyxvc.inUse())
1050                         owner->buffer()->lyxvc.registrer();
1051         }
1052         break;
1053                 
1054         case LFUN_VC_CHECKIN:
1055         {
1056                 if (owner->buffer()->lyxvc.inUse()
1057                     && !owner->buffer()->isReadonly())
1058                         owner->buffer()->lyxvc.checkIn();
1059         }
1060         break;
1061                 
1062         case LFUN_VC_CHECKOUT:
1063         {
1064                 if (owner->buffer()->lyxvc.inUse()
1065                     && owner->buffer()->isReadonly())
1066                         owner->buffer()->lyxvc.checkOut();
1067         }
1068         break;
1069         
1070         case LFUN_VC_REVERT:
1071         {
1072                 owner->buffer()->lyxvc.revert();
1073         }
1074         break;
1075                 
1076         case LFUN_VC_UNDO:
1077         {
1078                 owner->buffer()->lyxvc.undoLast();
1079         }
1080         break;
1081                 
1082         case LFUN_VC_HISTORY:
1083         {
1084                 owner->buffer()->lyxvc.showLog();
1085                 break;
1086         }
1087         
1088         // --- buffers ----------------------------------------
1089
1090         case LFUN_FILE_INSERT:
1091         {
1092                 MenuInsertLyXFile(argument);
1093         }
1094         break;
1095         
1096         case LFUN_FILE_INSERT_ASCII:
1097         {
1098                 bool asPara = (argument == "paragraph");
1099                 InsertAsciiFile(owner->view(), string(), asPara);
1100         }
1101         break;
1102         
1103         case LFUN_FILE_NEW:
1104         {
1105                 // servercmd: argument must be <file>:<template>
1106                 Buffer * tmpbuf = NewLyxFile(argument);
1107                 if (tmpbuf)
1108                         owner->view()->buffer(tmpbuf);
1109         }
1110         break;
1111                         
1112         case LFUN_FILE_OPEN:
1113                 owner->view()->buffer(bufferlist.loadLyXFile(argument));
1114                 break;
1115
1116         case LFUN_LATEX_LOG:
1117                 ShowLatexLog();
1118                 break;
1119                 
1120         case LFUN_LAYOUTNO:
1121         {
1122                 lyxerr.debug() << "LFUN_LAYOUTNO: (arg) " << argument << endl;
1123                 int sel = strToInt(argument);
1124                 lyxerr.debug() << "LFUN_LAYOUTNO: (sel) "<< sel << endl;
1125                 
1126                 // Should this give a setMessage instead?
1127                 if (sel == 0) 
1128                         return string(); // illegal argument
1129
1130                 --sel; // sel 1..., but layout 0...
1131
1132                 // Pretend we got the name instead.
1133                 Dispatch(int(LFUN_LAYOUT), 
1134                          textclasslist.NameOfLayout(owner->view()
1135                                                     ->buffer()->params.textclass,
1136                                                     sel).c_str());
1137                 return string();
1138         }
1139                 
1140         case LFUN_LAYOUT:
1141         {
1142                 lyxerr.debug() << "LFUN_LAYOUT: (arg) "
1143                                << argument << endl;
1144                 
1145                 // Derive layout number from given argument (string)
1146                 // and current buffer's textclass (number). */    
1147                 LyXTextClassList::ClassList::size_type tclass =
1148                         owner->view()->buffer()->params.textclass;
1149                 pair <bool, LyXTextClass::size_type> layout = 
1150                         textclasslist.NumberOfLayout(tclass, argument);
1151
1152                 // If the entry is obsolete, use the new one instead.
1153                 if (layout.first) {
1154                         string obs = textclasslist.Style(tclass,layout.second)
1155                               .obsoleted_by();
1156                         if (!obs.empty()) 
1157                                 layout = 
1158                                   textclasslist.NumberOfLayout(tclass, obs);
1159                 }
1160
1161                 // see if we found the layout number:
1162                 if (!layout.first) {
1163                         setErrorMessage(string(N_("Layout ")) + argument + 
1164                                         N_(" not known"));
1165                         break;
1166                 }
1167
1168                 if (current_layout != layout.second) {
1169                         owner->view()->hideCursor();
1170                         current_layout = layout.second;
1171                         owner->view()->update(-2);
1172                         owner->view()->text->
1173                                 SetLayout(layout.second);
1174                         owner->getToolbar()->combox->
1175                                 select(owner->view()->
1176                                        text->cursor.par->
1177                                        GetLayout() + 1);
1178                         owner->view()->update(1);
1179                         owner->view()->setState();
1180                 }
1181         }
1182         break;
1183
1184         case LFUN_LAYOUT_DOCUMENT:
1185                 MenuLayoutDocument();
1186                 break;
1187                 
1188         case LFUN_LAYOUT_PARAGRAPH:
1189                 MenuLayoutParagraph();
1190                 break;
1191                 
1192         case LFUN_LAYOUT_CHARACTER:
1193                 MenuLayoutCharacter();
1194                 break;
1195                 
1196         case LFUN_LAYOUT_TABLE:
1197         {
1198                 int flag = 0;
1199                 if (argument == "true") flag = 1;
1200                 MenuLayoutTable(flag);
1201         }
1202         break;
1203                 
1204         case LFUN_LAYOUT_PAPER:
1205                 MenuLayoutPaper();
1206                 break;
1207                 
1208         case LFUN_LAYOUT_QUOTES:
1209                 MenuLayoutQuotes();
1210                 break;
1211                 
1212         case LFUN_LAYOUT_PREAMBLE:
1213                 MenuLayoutPreamble();
1214                 break;
1215                 
1216         case LFUN_LAYOUT_SAVE_DEFAULT:
1217                 MenuLayoutSave();
1218                 break;
1219                 
1220         case LFUN_DROP_LAYOUTS_CHOICE:
1221                 owner->getToolbar()->combox->Show();
1222                 break;
1223
1224         case LFUN_LANGUAGE:
1225         {
1226                 Lang(owner->view(), argument);
1227                 owner->view()->setState();
1228                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1229         }
1230                 break;
1231
1232         case LFUN_EMPH:
1233                 Emph(owner->view());
1234                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1235                 break;
1236                 
1237         case LFUN_BOLD:
1238                 Bold(owner->view());
1239                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1240                 break;
1241                 
1242         case LFUN_NOUN:
1243                 Noun(owner->view());
1244                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1245                 break;
1246                 
1247         case LFUN_CODE:
1248                 Code(owner->view());
1249                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1250                 break;
1251                 
1252         case LFUN_SANS:
1253                 Sans(owner->view());
1254                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1255                 break;
1256                 
1257         case LFUN_ROMAN:
1258                 Roman(owner->view());
1259                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1260                 break;
1261                 
1262         case LFUN_DEFAULT:
1263                 StyleReset(owner->view());
1264                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1265                 break;
1266                 
1267         case LFUN_UNDERLINE:
1268                 Underline(owner->view());
1269                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1270                 break;
1271                 
1272         case LFUN_FONT_SIZE:
1273                 FontSize(owner->view(), argument);
1274                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1275                 break;
1276                 
1277         case LFUN_FONT_STATE:
1278                 setMessage(CurrentState(owner->view()));
1279                 break;
1280                 
1281         case LFUN_UPCASE_WORD:
1282                 owner->view()->update(-2);
1283                 FreeUpdateTimer();
1284                 owner->view()->text->ChangeWordCase(LyXText::text_uppercase);
1285                 owner->view()->update(1);
1286                 SetUpdateTimer();
1287                 break;
1288                 
1289         case LFUN_LOWCASE_WORD:
1290                 owner->view()->update(-2);
1291                 FreeUpdateTimer();
1292                 owner->view()->text->ChangeWordCase(LyXText::text_lowercase);
1293                 owner->view()->update(1);
1294                 SetUpdateTimer();
1295                 break;
1296                 
1297         case LFUN_CAPITALIZE_WORD:
1298                 owner->view()->update(-2);
1299                 FreeUpdateTimer();
1300                 owner->view()->text->ChangeWordCase(LyXText::text_capitalization);
1301                 owner->view()->update(1);
1302                 SetUpdateTimer();
1303                 break;
1304                 
1305         case LFUN_INSERT_LABEL:
1306                 MenuInsertLabel(argument.c_str());
1307                 break;
1308                 
1309         case LFUN_INSERT_REF:
1310                 MenuInsertRef();
1311                 break;
1312                 
1313         case LFUN_REFTOGGLE:
1314         {
1315                 InsetRef * inset = 
1316                         static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1317                 if (inset) {
1318                         inset->Toggle();
1319                         owner->view()->updateInset(inset, true);
1320                 } else {
1321                         setErrorMessage(N_("No cross-reference to toggle"));
1322                 }
1323         }
1324         break;
1325         
1326         case LFUN_REFBACK:
1327         {
1328                 owner->view()->restorePosition();
1329         }
1330         break;
1331
1332         case LFUN_REFGOTO:
1333         {
1334                 string label(argument);
1335                 if (label.empty()) {
1336                         InsetRef * inset = 
1337                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1338                         if (inset)
1339                                 label = inset->getContents();
1340                 }
1341                 
1342                 if (!label.empty()) {
1343                         owner->view()->savePosition();
1344                         if (!owner->view()->gotoLabel(label))
1345                                 WriteAlert(_("Error"), 
1346                                            _("Couldn't find this label"), 
1347                                            _("in current document."));
1348                 }
1349         }
1350         break;
1351                 
1352         case LFUN_MENU_OPEN_BY_NAME:
1353                 owner->getMenus()->openByName(argument);
1354                 break; // RVDK_PATCH_5
1355                 
1356         case LFUN_SPELLCHECK:
1357                 if (lyxrc.isp_command != "none")
1358                         ShowSpellChecker(owner->view());
1359                 break; // RVDK_PATCH_5
1360                 
1361                 // --- Cursor Movements -----------------------------
1362         case LFUN_RIGHT:
1363         {
1364                 LyXText * tmptext = owner->view()->text;
1365                 bool is_rtl = tmptext->cursor.par->isRightToLeftPar();
1366                 if(!tmptext->mark_set)
1367                         owner->view()->beforeChange();
1368                 owner->view()->update(-2);
1369                 if (is_rtl)
1370                         tmptext->CursorLeft();
1371                 if (tmptext->cursor.pos < tmptext->cursor.par->Last()
1372                     && tmptext->cursor.par->GetChar(tmptext->cursor.pos)
1373                     == LyXParagraph::META_INSET
1374                     && tmptext->cursor.par->GetInset(tmptext->cursor.pos)
1375                     && tmptext->cursor.par->GetInset(tmptext->cursor.pos)->Editable() == Inset::HIGHLY_EDITABLE){
1376                         Inset * tmpinset = tmptext->cursor.par->GetInset(tmptext->cursor.pos);
1377                         setMessage(tmpinset->EditMessage());
1378                         tmpinset->Edit(owner->view(), 0, 0, 0);
1379                         break;
1380                 }
1381                 if (!is_rtl)
1382                         tmptext->CursorRight();
1383                 owner->view()->text->FinishUndo();
1384                 moveCursorUpdate(false);
1385                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1386         }
1387         break;
1388                 
1389         case LFUN_LEFT:
1390         {
1391                 // This is soooo ugly. Isn`t it possible to make
1392                 // it simpler? (Lgb)
1393                 LyXText * txt = owner->view()->text;
1394                 bool is_rtl = txt->cursor.par->isRightToLeftPar();
1395                 if(!txt->mark_set) owner->view()->beforeChange();
1396                 owner->view()->update(-2);
1397                 if (!is_rtl)
1398                         txt->CursorLeft();
1399                 if (txt->cursor.pos < txt->cursor.par->Last()
1400                     && txt->cursor.par->GetChar(txt->cursor.pos)
1401                     == LyXParagraph::META_INSET
1402                     && txt->cursor.par->GetInset(txt->cursor.pos)
1403                     && txt->cursor.par->GetInset(txt->cursor.pos)->Editable() == Inset::HIGHLY_EDITABLE) {
1404                         Inset * tmpinset = txt->cursor.par->GetInset(txt->cursor.pos);
1405                         setMessage(tmpinset->EditMessage());
1406                         LyXFont font = txt->GetFont(txt->cursor.par,
1407                                                     txt->cursor.pos);
1408                         tmpinset->Edit(owner->view(),
1409                                        tmpinset->x() + tmpinset->width(owner->view()->painter(),font),
1410                                        tmpinset->descent(owner->view()->painter(),font),
1411                                        0);
1412                         break;
1413                 }
1414                 if  (is_rtl)
1415                         txt->CursorRight();
1416
1417                 owner->view()->text->FinishUndo();
1418                 moveCursorUpdate(false);
1419                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1420         }
1421         break;
1422                 
1423         case LFUN_UP:
1424                 if(!owner->view()->text->mark_set) owner->view()->beforeChange();
1425                 owner->view()->update(-3);
1426                 owner->view()->text->CursorUp();
1427                 owner->view()->text->FinishUndo();
1428                 moveCursorUpdate(false);
1429                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1430                 break;
1431                 
1432         case LFUN_DOWN:
1433                 if(!owner->view()->text->mark_set)
1434                         owner->view()->beforeChange();
1435                 owner->view()->update(-3);
1436                 owner->view()->text->CursorDown();
1437                 owner->view()->text->FinishUndo();
1438                 moveCursorUpdate(false);
1439                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1440                 break;
1441
1442         case LFUN_UP_PARAGRAPH:
1443                 if(!owner->view()->text->mark_set)
1444                         owner->view()->beforeChange();
1445                 owner->view()->update(-3);
1446                 owner->view()->text->CursorUpParagraph();
1447                 owner->view()->text->FinishUndo();
1448                 moveCursorUpdate(false);
1449                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1450                 break;
1451                 
1452         case LFUN_DOWN_PARAGRAPH:
1453                 if(!owner->view()->text->mark_set)
1454                         owner->view()->beforeChange();
1455                 owner->view()->update(-3);
1456                 owner->view()->text->CursorDownParagraph();
1457                 owner->view()->text->FinishUndo();
1458                 moveCursorUpdate(false);
1459                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1460                 break;
1461                 
1462         case LFUN_PRIOR:
1463                 if(!owner->view()->text->mark_set)
1464                         owner->view()->beforeChange();
1465                 owner->view()->update(-3);
1466                 owner->view()->cursorPrevious();
1467                 owner->view()->text->FinishUndo();
1468                 moveCursorUpdate(false);
1469                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1470                 break;
1471                 
1472         case LFUN_NEXT:
1473                 if(!owner->view()->text->mark_set)
1474                         owner->view()->beforeChange();
1475                 owner->view()->update(-3);
1476                 owner->view()->cursorNext();
1477                 owner->view()->text->FinishUndo();
1478                 moveCursorUpdate(false);
1479                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1480                 break;
1481                 
1482         case LFUN_HOME:
1483                 if(!owner->view()->text->mark_set)
1484                         owner->view()->beforeChange();
1485                 owner->view()->update(-2);
1486                 owner->view()->text->CursorHome();
1487                 owner->view()->text->FinishUndo();
1488                 moveCursorUpdate(false);
1489                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1490                 break;
1491                 
1492         case LFUN_END:
1493                 if(!owner->view()->text->mark_set)
1494                         owner->view()->beforeChange();
1495                 owner->view()->update(-2);
1496                 owner->view()->text->CursorEnd();
1497                 owner->view()->text->FinishUndo();
1498                 moveCursorUpdate(false);
1499                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1500                 break;
1501                 
1502         case LFUN_SHIFT_TAB:
1503         case LFUN_TAB:
1504                 if(!owner->view()->text->mark_set)
1505                         owner->view()->beforeChange();
1506                 owner->view()->update(-2);
1507                 owner->view()->text->CursorTab();
1508                 owner->view()->text->FinishUndo();
1509                 moveCursorUpdate(false);
1510                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1511                 break;
1512                 
1513         case LFUN_WORDRIGHT:
1514                 if(!owner->view()->text->mark_set)
1515                         owner->view()->beforeChange();
1516                 owner->view()->update(-2);
1517                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1518                         owner->view()->text->CursorLeftOneWord();
1519                 else
1520                         owner->view()->text->CursorRightOneWord();
1521                 owner->view()->text->FinishUndo();
1522                 moveCursorUpdate(false);
1523                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1524                 break;
1525                 
1526         case LFUN_WORDLEFT:
1527                 if(!owner->view()->text->mark_set)
1528                         owner->view()->beforeChange();
1529                 owner->view()->update(-2);
1530                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1531                         owner->view()->text->CursorRightOneWord();
1532                 else
1533                         owner->view()->text->CursorLeftOneWord();
1534                 owner->view()->text->FinishUndo();
1535                 moveCursorUpdate(false);
1536                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1537                 break;
1538                 
1539         case LFUN_BEGINNINGBUF:
1540                 if(!owner->view()->text->mark_set)
1541                         owner->view()->beforeChange();
1542                 owner->view()->update(-2);
1543                 owner->view()->text->CursorTop();
1544                 owner->view()->text->FinishUndo();
1545                 moveCursorUpdate(false);
1546                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1547                 break;
1548                 
1549         case LFUN_ENDBUF:
1550                 if(!owner->view()->text->mark_set)
1551                         owner->view()->beforeChange();
1552                 owner->view()->update(-2);
1553                 owner->view()->text->CursorBottom();
1554                 owner->view()->text->FinishUndo();
1555                 moveCursorUpdate(false);
1556                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1557                 break;
1558
1559       
1560                 /* cursor selection ---------------------------- */
1561         case LFUN_RIGHTSEL:
1562                 owner->view()->update(-2);
1563                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1564                         owner->view()->text->CursorLeft();
1565                 else
1566                         owner->view()->text->CursorRight();
1567                 owner->view()->text->FinishUndo();
1568                 moveCursorUpdate(true);
1569                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1570                 break;
1571                 
1572         case LFUN_LEFTSEL:
1573                 owner->view()->update(-2);
1574                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1575                         owner->view()->text->CursorRight();
1576                 else
1577                         owner->view()->text->CursorLeft();
1578                 owner->view()->text->FinishUndo();
1579                 moveCursorUpdate(true);
1580                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1581                 break;
1582                 
1583         case LFUN_UPSEL:
1584                 owner->view()->update(-2);
1585                 owner->view()->text->CursorUp();
1586                 owner->view()->text->FinishUndo();
1587                 moveCursorUpdate(true);
1588                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1589                 break;
1590                 
1591         case LFUN_DOWNSEL:
1592                 owner->view()->update(-2);
1593                 owner->view()->text->CursorDown();
1594                 owner->view()->text->FinishUndo();
1595                 moveCursorUpdate(true);
1596                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1597                 break;
1598
1599         case LFUN_UP_PARAGRAPHSEL:
1600                 owner->view()->update(-2);
1601                 owner->view()->text->CursorUpParagraph();
1602                 owner->view()->text->FinishUndo();
1603                 moveCursorUpdate(true);
1604                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1605                 break;
1606                 
1607         case LFUN_DOWN_PARAGRAPHSEL:
1608                 owner->view()->update(-2);
1609                 owner->view()->text->CursorDownParagraph();
1610                 owner->view()->text->FinishUndo();
1611                 moveCursorUpdate(true);
1612                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1613                 break;
1614                 
1615         case LFUN_PRIORSEL:
1616                 owner->view()->update(-2);
1617                 owner->view()->cursorPrevious();
1618                 owner->view()->text->FinishUndo();
1619                 moveCursorUpdate(true);
1620                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1621                 break;
1622                 
1623         case LFUN_NEXTSEL:
1624                 owner->view()->update(-2);
1625                 owner->view()->cursorNext();
1626                 owner->view()->text->FinishUndo();
1627                 moveCursorUpdate(true);
1628                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1629                 break;
1630                 
1631         case LFUN_HOMESEL:
1632                 owner->view()->update(-2);
1633                 owner->view()->text->CursorHome();
1634                 owner->view()->text->FinishUndo();
1635                 moveCursorUpdate(true);
1636                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1637                 break;
1638                 
1639         case LFUN_ENDSEL:
1640                 owner->view()->update(-2);
1641                 owner->view()->text->CursorEnd();
1642                 owner->view()->text->FinishUndo();
1643                 moveCursorUpdate(true);
1644                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1645                 break;
1646                 
1647         case LFUN_WORDRIGHTSEL:
1648                 owner->view()->update(-2);
1649                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1650                         owner->view()->text->CursorLeftOneWord();
1651                 else
1652                         owner->view()->text->CursorRightOneWord();
1653                 owner->view()->text->FinishUndo();
1654                 moveCursorUpdate(true);
1655                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1656                 break;
1657                 
1658         case LFUN_WORDLEFTSEL:
1659                 owner->view()->update(-2);
1660                 if (owner->view()->text->cursor.par->isRightToLeftPar())
1661                         owner->view()->text->CursorRightOneWord();
1662                 else
1663                         owner->view()->text->CursorLeftOneWord();
1664                 owner->view()->text->FinishUndo();
1665                 moveCursorUpdate(true);
1666                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1667                 break;
1668                 
1669         case LFUN_BEGINNINGBUFSEL:
1670                 owner->view()->update(-2);
1671                 owner->view()->text->CursorTop();
1672                 owner->view()->text->FinishUndo();
1673                 moveCursorUpdate(true);
1674                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1675                 break;
1676                 
1677         case LFUN_ENDBUFSEL:
1678                 owner->view()->update(-2);
1679                 owner->view()->text->CursorBottom();
1680                 owner->view()->text->FinishUndo();
1681                 moveCursorUpdate(true);
1682                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1683                 break;
1684
1685                 // --- text changing commands ------------------------
1686         case LFUN_BREAKLINE:
1687                 owner->view()->beforeChange();
1688                 owner->view()->text->InsertChar(LyXParagraph::META_NEWLINE);
1689                 owner->view()->update(1);
1690                 SetUpdateTimer(0.01);
1691                 moveCursorUpdate(false);
1692                 break;
1693                 
1694         case LFUN_PROTECTEDSPACE:
1695         {
1696                 LyXLayout const & style =
1697                         textclasslist.Style(owner->view()->buffer()->params.textclass,
1698                                             owner->view()->text->cursor.par->GetLayout());
1699
1700                 if (style.free_spacing) {
1701                         owner->view()->text->InsertChar(' ');
1702                         owner->view()->update(-1);
1703                 } else {
1704                         owner->view()->protectedBlank();
1705                 }
1706                 moveCursorUpdate(false);
1707         }
1708         break;
1709                 
1710         case LFUN_SETMARK:
1711                 if(owner->view()->text->mark_set) {
1712                         owner->view()->beforeChange();
1713                         owner->view()->update(0);
1714                         setMessage(N_("Mark removed"));
1715                 } else {
1716                         owner->view()->beforeChange();
1717                         owner->view()->text->mark_set = 1;
1718                         owner->view()->update(0);
1719                         setMessage(N_("Mark set"));
1720                 }
1721                 owner->view()->text->sel_cursor = 
1722                         owner->view()->text->cursor;
1723                 break;
1724                 
1725         case LFUN_DELETE:
1726                 FreeUpdateTimer();
1727                 if (!owner->view()->text->selection) {
1728                         owner->view()->text->Delete();
1729                         owner->view()->text->sel_cursor = 
1730                                 owner->view()->text->cursor;
1731                         owner->view()->update(1);
1732                         // It is possible to make it a lot faster still
1733                         // just comment out the lone below...
1734                         owner->view()->showCursor();
1735                 } else {
1736                         owner->view()->cut();
1737                 }
1738                 SetUpdateTimer();
1739                 moveCursorUpdate(false);
1740                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1741                 owner->view()->setState();
1742                 break;
1743
1744         case LFUN_DELETE_SKIP:
1745         {
1746                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
1747                 
1748                 LyXCursor cursor = owner->view()->text->cursor;
1749
1750                 FreeUpdateTimer();
1751                 if (!owner->view()->text->selection) {
1752                         if (cursor.pos == cursor.par->Last()) {
1753                                 owner->view()->text->CursorRight();
1754                                 cursor = owner->view()->text->cursor;
1755                                 if (cursor.pos == 0
1756                                     && !(cursor.par->added_space_top 
1757                                          == VSpace (VSpace::NONE))) {
1758                                         owner->view()->text->SetParagraph
1759                                                 (cursor.par->line_top,
1760                                                  cursor.par->line_bottom,
1761                                                  cursor.par->pagebreak_top, 
1762                                                  cursor.par->pagebreak_bottom,
1763                                                  VSpace(VSpace::NONE), 
1764                                                  cursor.par->added_space_bottom,
1765                                                  cursor.par->align, 
1766                                                  cursor.par->labelwidthstring, 0);
1767                                         owner->view()->text->CursorLeft();
1768                                         owner->view()->update (1);
1769                                 } else {
1770                                         owner->view()->text->CursorLeft();
1771                                         owner->view()->text->Delete();
1772                                         owner->view()->text->sel_cursor = 
1773                                                 owner->view()->text->cursor;
1774                                         owner->view()->update(1);
1775                                 }
1776                         } else {
1777                                 owner->view()->text->Delete();
1778                                 owner->view()->text->sel_cursor = 
1779                                         owner->view()->text->cursor;
1780                                 owner->view()->update(1);
1781                         }
1782                 } else {
1783                         owner->view()->cut();
1784                 }
1785                 SetUpdateTimer();
1786         }
1787         break;
1788
1789         /* -------> Delete word forward. */
1790         case LFUN_DELETE_WORD_FORWARD:
1791                 owner->view()->update(-2);
1792                 FreeUpdateTimer();
1793                 owner->view()->text->DeleteWordForward();
1794                 owner->view()->update( 1 );
1795                 SetUpdateTimer();
1796                 moveCursorUpdate(false);
1797                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1798                 break;
1799
1800                 /* -------> Delete word backward. */
1801         case LFUN_DELETE_WORD_BACKWARD:
1802                 owner->view()->update(-2);
1803                 FreeUpdateTimer();
1804                 owner->view()->text->DeleteWordBackward();
1805                 owner->view()->update( 1 );
1806                 SetUpdateTimer();
1807                 moveCursorUpdate(false);
1808                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1809                 break;
1810                 
1811                 /* -------> Kill to end of line. */
1812         case LFUN_DELETE_LINE_FORWARD:
1813                 FreeUpdateTimer();
1814                 owner->view()->update(-2);
1815                 owner->view()->text->DeleteLineForward();
1816                 owner->view()->update( 1 );
1817                 SetUpdateTimer();
1818                 moveCursorUpdate(false);
1819                 break;
1820                 
1821                 /* -------> Set mark off. */
1822         case LFUN_MARK_OFF:
1823                 owner->view()->beforeChange();
1824                 owner->view()->update(0);
1825                 owner->view()->text->sel_cursor = 
1826                         owner->view()->text->cursor;
1827                 setMessage(N_("Mark off"));
1828                 break;
1829
1830                 /* -------> Set mark on. */
1831         case LFUN_MARK_ON:
1832                 owner->view()->beforeChange();
1833                 owner->view()->text->mark_set = 1;
1834                 owner->view()->update( 0 );
1835                 owner->view()->text->sel_cursor = 
1836                         owner->view()->text->cursor;
1837                 setMessage(N_("Mark on"));
1838                 break;
1839                 
1840         case LFUN_BACKSPACE:
1841         {
1842                 FreeUpdateTimer();
1843                 if (!owner->view()->text->selection) {
1844                         if (owner->getIntl()->getTrans()->backspace()) {
1845                                 owner->view()->text->Backspace();
1846                                 owner->view()->text->sel_cursor = 
1847                                         owner->view()->text->cursor;
1848                                 owner->view()->update(1);
1849                                 // It is possible to make it a lot faster still
1850                                 // just comment out the lone below...
1851                                 owner->view()->showCursor();
1852                         }
1853                 } else {
1854                         owner->view()->cut();
1855                 }
1856                 SetUpdateTimer();
1857                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1858                 owner->view()->setState();
1859         }
1860         break;
1861
1862         case LFUN_BACKSPACE_SKIP:
1863         {
1864                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
1865                 
1866                 LyXCursor cursor = owner->view()->text->cursor;
1867                 
1868                 FreeUpdateTimer();
1869                 if (!owner->view()->text->selection) {
1870                         if (cursor.pos == 0 
1871                             && !(cursor.par->added_space_top 
1872                                  == VSpace (VSpace::NONE))) {
1873                                 owner->view()->text->SetParagraph 
1874                                         (cursor.par->line_top,      
1875                                          cursor.par->line_bottom,
1876                                          cursor.par->pagebreak_top, 
1877                                          cursor.par->pagebreak_bottom,
1878                                          VSpace(VSpace::NONE), cursor.par->added_space_bottom,
1879                                          cursor.par->align, 
1880                                          cursor.par->labelwidthstring, 0);
1881                                 owner->view()->update (1);
1882                         } else {
1883                                 owner->view()->text->Backspace();
1884                                 owner->view()->text->sel_cursor 
1885                                         = cursor;
1886                                 owner->view()->update(1);
1887                         }
1888                 } else
1889                         owner->view()->cut();
1890                 SetUpdateTimer();
1891         }
1892         break;
1893
1894         case LFUN_BREAKPARAGRAPH:
1895         {
1896                 owner->view()->beforeChange();
1897                 owner->view()->text->BreakParagraph(0);
1898                 owner->view()->update(1);
1899                 SetUpdateTimer(0.01);
1900                 owner->view()->text->sel_cursor = 
1901                         owner->view()->text->cursor;
1902                 owner->view()->setState();
1903                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1904                 break;
1905         }
1906
1907         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1908         {
1909                 owner->view()->beforeChange();
1910                 owner->view()->text->BreakParagraph(1);
1911                 owner->view()->update(1);
1912                 SetUpdateTimer(0.01);
1913                 owner->view()->text->sel_cursor = 
1914                         owner->view()->text->cursor;
1915                 owner->view()->setState();
1916                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1917                 break;
1918         }
1919         
1920         case LFUN_BREAKPARAGRAPH_SKIP:
1921         {
1922                 // When at the beginning of a paragraph, remove
1923                 // indentation and add a "defskip" at the top.
1924                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
1925                 
1926                 LyXCursor cursor = owner->view()->text->cursor;
1927                 
1928                 owner->view()->beforeChange();
1929                 if (cursor.pos == 0) {
1930                         if (cursor.par->added_space_top == VSpace(VSpace::NONE)) {
1931                                 owner->view()->text->SetParagraph
1932                                         (cursor.par->line_top,      
1933                                          cursor.par->line_bottom,
1934                                          cursor.par->pagebreak_top, 
1935                                          cursor.par->pagebreak_bottom,
1936                                          VSpace(VSpace::DEFSKIP), cursor.par->added_space_bottom,
1937                                          cursor.par->align, 
1938                                          cursor.par->labelwidthstring, 1);
1939                                 owner->view()->update(1);
1940                         } 
1941                 }
1942                 else {
1943                         owner->view()->text->BreakParagraph(0);
1944                         owner->view()->update(1);
1945                 }
1946                 SetUpdateTimer(0.01);
1947                 owner->view()->text->sel_cursor = cursor;
1948                 owner->view()->setState();
1949                 owner->getMiniBuffer()->Set(CurrentState(owner->view()));
1950         }
1951         break;
1952
1953         case LFUN_PARAGRAPH_SPACING:
1954         {
1955                 LyXParagraph * par = owner->view()->text->cursor.par;
1956                 Spacing::Space cur_spacing = par->spacing.getSpace();
1957                 float cur_value = 1.0;
1958                 if (cur_spacing == Spacing::Other) {
1959                         cur_value = par->spacing.getValue();
1960                 }
1961                 
1962 #ifdef HAVE_SSTREAM
1963                 istringstream istr(argument);
1964 #else
1965                 istrstream istr(argument.c_str());
1966 #endif
1967                 string tmp;
1968                 istr >> tmp;
1969                 Spacing::Space new_spacing = cur_spacing;
1970                 float new_value = cur_value;
1971                 if (tmp.empty()) {
1972                         lyxerr << "Missing argument to `paragraph-spacing'"
1973                                << endl;
1974                 } else if (tmp == "single") {
1975                         new_spacing = Spacing::Single;
1976                 } else if (tmp == "onehalf") {
1977                         new_spacing = Spacing::Onehalf;
1978                 } else if (tmp == "double") {
1979                         new_spacing = Spacing::Double;
1980                 } else if (tmp == "other") {
1981                         new_spacing = Spacing::Other;
1982                         float tmpval = 0.0;
1983                         istr >> tmpval;
1984                         lyxerr << "new_value = " << tmpval << endl;
1985                         if (tmpval != 0.0)
1986                                 new_value = tmpval;
1987                 } else if (tmp == "default") {
1988                         new_spacing = Spacing::Default;
1989                 } else {
1990                         lyxerr << _("Unknown spacing argument: ")
1991                                << argument << endl;
1992                 }
1993                 if (cur_spacing != new_spacing || cur_value != new_value) {
1994                         par->spacing.set(new_spacing, new_value);
1995                         owner->view()->text->RedoParagraph();
1996                         owner->view()->update(-1);
1997                 }
1998         }
1999         break;
2000         
2001         case LFUN_QUOTE:
2002                 owner->view()->beforeChange();
2003                 owner->view()->text->InsertChar('\"');  // This " matches the single quote in the code
2004                 owner->view()->update(1);
2005                 SetUpdateTimer();
2006                 moveCursorUpdate(false);
2007                 break;
2008
2009         case LFUN_HTMLURL:
2010         case LFUN_URL:
2011         {
2012                 InsetCommand * new_inset;
2013                 if (action == LFUN_HTMLURL)
2014                         new_inset = new InsetUrl("htmlurl", "", "");
2015                 else
2016                         new_inset = new InsetUrl("url", "", "");
2017                 if (owner->view()->insertInset(new_inset))
2018                         new_inset->Edit(owner->view(), 0, 0, 0);
2019                 else
2020                         delete new_inset;
2021         }
2022         break;
2023         
2024         case LFUN_INSET_TEXT:
2025         {
2026                 InsetText * new_inset = new InsetText(owner->buffer());
2027                 if (owner->view()->insertInset(new_inset))
2028                         new_inset->Edit(owner->view(), 0, 0, 0);
2029                 else
2030                         delete new_inset;
2031         }
2032         break;
2033         case LFUN_INSET_ERT:
2034         {
2035                 InsetERT * new_inset = new InsetERT(owner->buffer());
2036                 if (owner->view()->insertInset(new_inset))
2037                         new_inset->Edit(owner->view(), 0, 0, 0);
2038                 else
2039                         delete new_inset;
2040         }
2041         break;
2042         
2043         case LFUN_INSET_FOOTNOTE:
2044         {
2045                 InsetFoot * new_inset = new InsetFoot(owner->buffer());
2046                 if (owner->view()->insertInset(new_inset))
2047                         new_inset->Edit(owner->view(), 0, 0, 0);
2048                 else
2049                         delete new_inset;
2050         }
2051         break;
2052
2053         case LFUN_INSET_TABULAR:
2054         {
2055                 int r = 2, c = 2;
2056                 if (!argument.empty())
2057                         sscanf(argument.c_str(),"%d%d",&r,&c);
2058                 InsetTabular * new_inset = new InsetTabular(owner->buffer(),r,c);
2059                 if (owner->view()->insertInset(new_inset))
2060                         new_inset->Edit(owner->view(), 0, 0, 0);
2061                 else
2062                         delete new_inset;
2063         }
2064         break;
2065
2066         // --- lyxserver commands ----------------------------
2067
2068         case LFUN_CHARATCURSOR:
2069         {
2070                 LyXParagraph::size_type pos = 
2071                         owner->view()->text->cursor.pos;
2072                 if(pos < owner->view()->text->cursor.par->size())
2073                         //dispatch_buffer = owner->view()->text->
2074                         //      cursor.par->text[pos];
2075                         dispatch_buffer =
2076                                 owner->view()->text->
2077                                 cursor.par->GetChar(pos);
2078                 else
2079                         dispatch_buffer = "EOF";
2080         }
2081         break;
2082         
2083         case LFUN_GETXY:
2084                 dispatch_buffer = 
2085                         tostr(owner->view()->text->cursor.x) + ' '
2086                         + tostr(owner->view()->text->cursor.y);
2087                 break;
2088                 
2089         case LFUN_SETXY:
2090         {
2091                 int  x;
2092                 long y;
2093                 sscanf(argument.c_str(), " %d %ld", &x, &y);
2094                 owner->view()->text->SetCursorFromCoordinates(x, y);
2095         }
2096         break;
2097         
2098         case LFUN_GETLAYOUT:
2099                 dispatch_buffer =  
2100                         tostr(owner->view()->text->cursor.par->layout);
2101                 break;
2102                         
2103         case LFUN_GETFONT:
2104         {
2105                 LyXFont & font = owner->view()->text->current_font;
2106                 if(font.shape() == LyXFont::ITALIC_SHAPE)
2107                         dispatch_buffer = 'E';
2108                 else if(font.shape() == LyXFont::SMALLCAPS_SHAPE)
2109                         dispatch_buffer = 'N';
2110                 else
2111                         dispatch_buffer = '0';
2112
2113         }
2114         break;
2115
2116         case LFUN_GETLATEX:
2117         {
2118                 LyXFont & font = owner->view()->text->current_font;
2119                 if(font.latex() == LyXFont::ON)
2120                         dispatch_buffer = 'L';
2121                 else
2122                         dispatch_buffer = '0';
2123         }
2124         break;
2125
2126         case LFUN_GETNAME:
2127                 setMessage(owner->buffer()->fileName());
2128                 lyxerr.debug() << "FNAME["
2129                                << owner->buffer()->fileName()
2130                                << "] " << endl;
2131                 break;
2132                 
2133         case LFUN_NOTIFY:
2134         {
2135                 string buf;
2136                 keyseq.print(buf);
2137                 dispatch_buffer = buf;
2138                 lyxserver->notifyClient(dispatch_buffer);
2139         }
2140         break;
2141
2142         case LFUN_GOTOFILEROW:
2143         {
2144                 char file_name[100];
2145                 int  row;
2146                 sscanf(argument.c_str(), " %s %d", file_name, &row);
2147
2148                 // Must replace extension of the file to be .lyx and get full path
2149                 string s = ChangeExtension(string(file_name), ".lyx");
2150
2151                 // Either change buffer or load the file
2152                 if (bufferlist.exists(s))
2153                         owner->view()->buffer(bufferlist.getBuffer(s));
2154                 else
2155                         owner->view()->buffer(bufferlist.loadLyXFile(s));
2156
2157                 // Set the cursor  
2158                 owner->view()->setCursorFromRow(row);
2159
2160                 // Recenter screen
2161                 owner->view()->center();
2162         }
2163         break;
2164
2165         case LFUN_APROPOS:
2166         case LFUN_GETTIP:
2167         {
2168                 int qa = lyxaction.LookupFunc(argument.c_str());
2169                 setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
2170         }
2171         break;
2172
2173         // --- accented characters ---------------------------
2174                 
2175         case LFUN_UMLAUT:
2176         case LFUN_CIRCUMFLEX:
2177         case LFUN_GRAVE:
2178         case LFUN_ACUTE:
2179         case LFUN_TILDE:
2180         case LFUN_CEDILLA:
2181         case LFUN_MACRON:
2182         case LFUN_DOT:
2183         case LFUN_UNDERDOT:
2184         case LFUN_UNDERBAR:
2185         case LFUN_CARON:
2186         case LFUN_SPECIAL_CARON:
2187         case LFUN_BREVE:
2188         case LFUN_TIE:
2189         case LFUN_HUNG_UMLAUT:
2190         case LFUN_CIRCLE:
2191         case LFUN_OGONEK:
2192         {
2193                 char c = 0;
2194                 
2195                 if (keyseq.length == -1 && keyseq.getiso() != 0) 
2196                         c = keyseq.getiso();
2197                 
2198                 owner->getIntl()->getTrans()->
2199                         deadkey(c, get_accent(action).accent, 
2200                                 owner->view()->text);
2201                 
2202                 // Need to reset, in case the minibuffer calls these
2203                 // actions
2204                 keyseq.reset();
2205                 keyseq.length = 0;
2206                 
2207                 // copied verbatim from do_accent_char
2208                 owner->view()->update(1);
2209
2210                 SetUpdateTimer();
2211                 owner->view()->text->sel_cursor = 
2212                         owner->view()->text->cursor;
2213         }   
2214         break;
2215         
2216         // --- toolbar ----------------------------------
2217         case LFUN_PUSH_TOOLBAR:
2218         {
2219                 int nth = strToInt(argument);
2220                 if (lyxerr.debugging(Debug::TOOLBAR)) {
2221                         lyxerr << "LFUN_PUSH_TOOLBAR: argument = `"
2222                                << argument << "'\n"
2223                                << "LFUN_PUSH_TOOLBAR: nth = `"
2224                                << nth << "'" << endl;
2225                 }
2226                 
2227                 if (nth <= 0) {
2228                         LyXBell();
2229                         setErrorMessage(N_("Push-toolbar needs argument > 0"));
2230                 } else {
2231                         owner->getToolbar()->push(nth);
2232                 }
2233         }
2234         break;
2235         
2236         case LFUN_ADD_TO_TOOLBAR:
2237         {
2238                 if (lyxerr.debugging(Debug::TOOLBAR)) {
2239                         lyxerr << "LFUN_ADD_TO_TOOLBAR:"
2240                                 "argument = `" << argument << '\'' << endl;
2241                 }
2242                 string tmp(argument);
2243                 //lyxerr <<string("Argument: ") + argument);
2244                 //lyxerr <<string("Tmp     : ") + tmp);
2245                 if (tmp.empty()) {
2246                         LyXBell();
2247                         setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
2248                 } else {
2249                         owner->getToolbar()->add(argument, false);
2250                         owner->getToolbar()->set();
2251                 }
2252         }
2253         break;
2254         
2255         // --- insert characters ----------------------------------------
2256
2257         // ---  Mathed stuff. If we are here, there is no locked inset yet.
2258         
2259         // Greek mode     
2260         case LFUN_GREEK:
2261         {
2262                 if (!greek_kb_flag) {
2263                         greek_kb_flag = 1;
2264                         setMessage(N_("Math greek mode on"));
2265                 } else
2266                         greek_kb_flag = 0;
2267         }  
2268         break;
2269       
2270         // Greek keyboard      
2271         case LFUN_GREEK_TOGGLE:
2272         {
2273                 greek_kb_flag = greek_kb_flag ? 0 : 2;
2274                 if (greek_kb_flag) {
2275                         setMessage(N_("Math greek keyboard on"));
2276                 } else {
2277                         setMessage(N_("Math greek keyboard off"));
2278                 }
2279         }
2280         break;
2281         
2282         case LFUN_MATH_DELIM:     
2283         case LFUN_INSERT_MATRIX:
2284         {          
2285                 if (owner->view()->available()) { 
2286                         owner->view()->
2287                                 open_new_inset(new InsetFormula(false));
2288                         owner->view()
2289                                 ->the_locking_inset
2290                                 ->LocalDispatch(owner->view(),
2291                                                 action,
2292                                                 argument);
2293                 }
2294         }          
2295         break;
2296                
2297         case LFUN_INSERT_MATH:
2298         {
2299                 math_insert_symbol(argument.c_str());
2300         }
2301         break;
2302         
2303         case LFUN_MATH_DISPLAY:
2304         {
2305                 if (owner->view()->available())
2306                         owner->view()->open_new_inset(new InsetFormula(true));
2307                 break;
2308         }
2309                     
2310         case LFUN_MATH_MACRO:
2311         {
2312                 if (owner->view()->available()) {
2313                         string s(argument);
2314                         if (s.empty())
2315                                 setErrorMessage(N_("Missing argument"));
2316                         else {
2317                                 string s1 = token(s, ' ', 1);
2318                                 int na = s1.empty() ? 0: atoi(s1.c_str());
2319                                 owner->view()->
2320                                         open_new_inset(new InsetFormulaMacro(token(s, ' ', 0), na));
2321                         }
2322                 }
2323         }
2324         break;
2325
2326         case LFUN_MATH_MODE:   // Open or create a math inset
2327         {
2328                 
2329                 if (owner->view()->available())
2330                         owner->view()->open_new_inset(new InsetFormula);
2331                 setMessage(N_("Math editor mode"));
2332         }
2333         break;
2334           
2335         case LFUN_MATH_NUMBER:
2336         case LFUN_MATH_LIMITS:
2337         {
2338                 setErrorMessage(N_("This is only allowed in math mode!"));
2339         }
2340         break;
2341         
2342         case LFUN_INSERT_CITATION:
2343         {   
2344                 InsetCitation * new_inset = new InsetCitation();
2345                 // ale970405
2346                 // The note, if any, must be after the key, delimited
2347                 // by a | so both key and remark can have spaces.
2348                 if (!argument.empty()) {
2349                         string lsarg(argument);
2350                         if (contains(lsarg, "|")) {
2351                                 new_inset->setContents(token(lsarg, '|', 0));
2352                                 new_inset->setOptions(token(lsarg, '|', 1));
2353                         } else
2354                                 new_inset->setContents(lsarg);
2355                         if (!owner->view()->insertInset(new_inset))
2356                                 delete new_inset;
2357                 } else {
2358                         if (owner->view()->insertInset(new_inset))
2359                                 new_inset->Edit(owner->view(), 0, 0, 0);
2360                         else
2361                                 delete new_inset;
2362                 }
2363         }
2364         break;
2365                     
2366         case LFUN_INSERT_BIBTEX:
2367         {   
2368                 // ale970405+lasgoutt970425
2369                 // The argument can be up to two tokens separated 
2370                 // by a space. The first one is the bibstyle.
2371                 string lsarg(argument);
2372                 string bibstyle = token(lsarg, ' ', 1);
2373                 if (bibstyle.empty())
2374                         bibstyle = "plain";
2375                 InsetBibtex * new_inset 
2376                         = new InsetBibtex(token(lsarg, ' ', 0),
2377                                           bibstyle,
2378                                           owner->buffer());
2379                 
2380                 if (owner->view()->insertInset(new_inset)) {
2381                         if (lsarg.empty())
2382                                 new_inset->Edit(owner->view(), 0, 0, 0);
2383                 } else
2384                         delete new_inset;
2385         }
2386         break;
2387                 
2388         // BibTeX data bases
2389         case LFUN_BIBDB_ADD:
2390         {
2391                 InsetBibtex * inset = 
2392                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2393                 if (inset) {
2394                         inset->addDatabase(argument);
2395                 }
2396         }
2397         break;
2398                     
2399         case LFUN_BIBDB_DEL:
2400         {
2401                 InsetBibtex * inset = 
2402                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2403                 if (inset) {
2404                         inset->delDatabase(argument);
2405                 }
2406         }
2407         break;
2408         
2409         case LFUN_BIBTEX_STYLE:
2410         {
2411                 InsetBibtex * inset = 
2412                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2413                 if (inset) {
2414                         inset->setOptions(argument);
2415                 }
2416         }
2417         break;
2418                 
2419         case LFUN_INDEX_INSERT:
2420         case LFUN_INDEX_INSERT_LAST:
2421         {
2422                 // Can't do that at the beginning of a paragraph.
2423                 if (owner->view()->text->cursor.pos - 1 < 0)
2424                         break;
2425
2426                 InsetIndex * new_inset = new InsetIndex();
2427                 if (!argument.empty()) {
2428                         string lsarg(argument);
2429                         new_inset->setContents(lsarg);
2430                         if (!owner->view()->insertInset(new_inset))
2431                                 delete new_inset;
2432                 } else {
2433                         //reh 98/09/21
2434                         //get the current word for an argument
2435                         LyXParagraph::size_type lastpos = 
2436                                 owner->view()->text->cursor.pos - 1;
2437                         // Get the current word. note that this must be done
2438                         // before inserting the inset, or the inset will
2439                         // break the word
2440                         string curstring(owner->view()
2441                                          ->text->cursor.par->GetWord(lastpos));
2442
2443                         //make the new inset and write the current word into it
2444                         InsetIndex * new_inset = new InsetIndex();
2445
2446                         new_inset->setContents(curstring);
2447
2448                         //don't edit it if the call was to INSERT_LAST
2449                         if(action != LFUN_INDEX_INSERT_LAST) {
2450                                 new_inset->Edit(owner->view(), 0, 0, 0);
2451                         } else {
2452                                 //it looks blank on the screen unless
2453                                 //we do  something.  put it here.
2454
2455                                 // move the cursor to the returned value of lastpos
2456                                 // but only for the auto-insert
2457                                 owner->view()->text->cursor.pos = lastpos;
2458                         }
2459
2460                         //put the new inset into the buffer.
2461                         // there should be some way of knowing the user
2462                         //cancelled & avoiding this, but i don't know how
2463                         if (!owner->view()->insertInset(new_inset))
2464                                 delete new_inset;
2465                 }
2466         }
2467         break;
2468
2469         case LFUN_INDEX_PRINT:
2470         {
2471                 Inset * new_inset = new InsetPrintIndex(owner->buffer());
2472                 if (!owner->view()->insertInset(new_inset, "Standard", true))
2473                         delete new_inset;
2474         }
2475         break;
2476
2477         case LFUN_PARENTINSERT:
2478         {
2479                 lyxerr << "arg " << argument << endl;
2480                 Inset * new_inset = new InsetParent(argument, owner->buffer());
2481                 if (!owner->view()->insertInset(new_inset, "Standard", true))
2482                         delete new_inset;
2483         }
2484         break;
2485
2486         case LFUN_CHILDINSERT:
2487         {
2488                 Inset * new_inset = new InsetInclude(argument,
2489                                                      owner->buffer());
2490                 if (owner->view()->insertInset(new_inset, "Standard", true))
2491                         new_inset->Edit(owner->view(), 0, 0, 0);
2492                 else
2493                         delete new_inset;
2494         }
2495         break;
2496
2497         case LFUN_CHILDOPEN:
2498         {
2499                 string filename =
2500                         MakeAbsPath(argument, 
2501                                     OnlyPath(owner->buffer()->fileName()));
2502                 setMessage(N_("Opening child document ") +
2503                            MakeDisplayPath(filename) + "...");
2504                 owner->view()->savePosition();
2505                 if (bufferlist.exists(filename))
2506                         owner->view()->buffer(bufferlist.getBuffer(filename));
2507                 else
2508                         owner->view()->buffer(bufferlist.loadLyXFile(filename));
2509         }
2510         break;
2511
2512         case LFUN_INSERT_NOTE:
2513                 owner->view()->insertNote();
2514                 break;
2515                 
2516         case LFUN_INSERTFOOTNOTE: 
2517         {
2518                 LyXParagraph::footnote_kind kind;
2519                 if (argument == "footnote")
2520                         { kind = LyXParagraph::FOOTNOTE; }
2521                 else if (argument == "margin")
2522                         { kind = LyXParagraph::MARGIN; }
2523                 else if (argument == "figure")
2524                         { kind = LyXParagraph::FIG; }
2525                 else if (argument == "table")
2526                         { kind = LyXParagraph::TAB; }
2527                 else if (argument == "wide-fig")
2528                         { kind = LyXParagraph::WIDE_FIG; }
2529                 else if (argument == "wide-tab")
2530                         { kind = LyXParagraph::WIDE_TAB; }
2531                 else if (argument == "algorithm")
2532                         { kind = LyXParagraph::ALGORITHM; }
2533                 else {
2534                         setErrorMessage(N_("Unknown kind of footnote"));
2535                         break;
2536                 }
2537                 owner->view()->text->InsertFootnoteEnvironment(kind);
2538                 owner->view()->update(1);
2539                 owner->view()->setState();
2540         }
2541         break;
2542         
2543         case LFUN_BUFFERBULLETSSELECT:
2544                 bulletForm();
2545                 break;
2546                 
2547         case LFUN_TOGGLECURSORFOLLOW:
2548                 cursor_follows_scrollbar = !cursor_follows_scrollbar;
2549                 break;
2550                 
2551         case LFUN_KMAP_OFF:             // keymap off
2552                 owner->getIntl()->KeyMapOn(false);
2553                 break;
2554                 
2555         case LFUN_KMAP_PRIM:    // primary keymap
2556                 owner->getIntl()->KeyMapPrim();
2557                 break;
2558                 
2559         case LFUN_KMAP_SEC:             // secondary keymap
2560                 owner->getIntl()->KeyMapSec();
2561                 break;
2562                 
2563         case LFUN_KMAP_TOGGLE:  // toggle keymap
2564                 owner->getIntl()->ToggleKeyMap();
2565                 break;
2566
2567         case LFUN_SELFINSERT:
2568         {
2569                 for (string::size_type i = 0; i < argument.length(); ++i) {
2570                         owner->view()->text->InsertChar(argument[i]);
2571                         // This needs to be in the loop, or else we
2572                         // won't break lines correctly. (Asger)
2573                         owner->view()->update(1);
2574                 }
2575                 SetUpdateTimer();
2576                 owner->view()->text->sel_cursor = 
2577                         owner->view()->text->cursor;
2578                 moveCursorUpdate(false);
2579         }
2580         break;
2581
2582         case LFUN_SEQUENCE: 
2583         {
2584                 // argument contains ';'-terminated commands
2585                 while (argument.find(';') != string::npos) {
2586                         string first;
2587                         argument = split(argument, first, ';');
2588                         Dispatch(first);
2589                 }
2590         }
2591         break;
2592
2593         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
2594         {
2595                 char datetmp[32];
2596                 int datetmp_len;
2597                 time_t now_time_t;
2598                 struct tm *now_tm;
2599                 static string arg;
2600                 
2601                 now_time_t = time(NULL);
2602                 now_tm = localtime(&now_time_t);
2603                 (void)setlocale(LC_TIME, "");
2604                 if (!argument.empty())
2605                         arg = argument;
2606                 else if (arg.empty())
2607                         arg = lyxrc.date_insert_format;
2608                 datetmp_len = (int) strftime(datetmp, 32, arg.c_str(), now_tm);
2609                 for (int i = 0; i < datetmp_len; i++) {
2610                         owner->view()->text->InsertChar(datetmp[i]);
2611                         owner->view()->update(1);
2612                 }
2613                 SetUpdateTimer();
2614                 owner->view()->text->sel_cursor = owner->view()->text->cursor;
2615                 moveCursorUpdate(false);
2616         }
2617         break;
2618
2619         case LFUN_SAVEPREFERENCES:
2620         {
2621                 Path p(user_lyxdir);
2622                 lyxrc.write("preferences");
2623         }
2624         break;
2625         
2626         case LFUN_UNKNOWN_ACTION:
2627         {
2628                 if(!owner->buffer()) {
2629                         LyXBell();
2630                         setErrorMessage(N_("No document open"));
2631                         break;
2632                 }
2633
2634                 if (owner->buffer()->isReadonly()) {
2635                         LyXBell();
2636                         setErrorMessage(N_("Document is read only"));
2637                         break;
2638                 }
2639                          
2640                 if (!argument.empty()) {
2641                         
2642                         /* Automatically delete the currently selected
2643                          * text and replace it with what is being
2644                          * typed in now. Depends on lyxrc settings
2645                          * "auto_region_delete", which defaults to
2646                          * true (on). */
2647                 
2648                         if ( lyxrc.auto_region_delete ) {
2649                                 if (owner->view()->text->selection){
2650                                         owner->view()->text->CutSelection(false);
2651                                         owner->view()->update(-1);
2652                                 }
2653                         }
2654                         
2655                         owner->view()->beforeChange();
2656                         
2657                         for (string::size_type i = 0;
2658                              i < argument.length(); ++i) {
2659                                 if (greek_kb_flag) {
2660                                         if (!math_insert_greek(argument[i]))
2661                                                 owner->getIntl()->getTrans()->TranslateAndInsert(argument[i], owner->view()->text);
2662                                 } else
2663                                         owner->getIntl()->getTrans()->TranslateAndInsert(argument[i], owner->view()->text);
2664                         }
2665
2666                         owner->view()->update(1);
2667                         SetUpdateTimer();
2668
2669                         owner->view()->text->sel_cursor = 
2670                                 owner->view()->text->cursor;
2671                         moveCursorUpdate(false);
2672                         return string();
2673                 } else {
2674                         // why is an "Unknown action" with empty
2675                         // argument even dispatched in the first
2676                         // place? I`ll probably change that. (Lgb)
2677                         LyXBell();
2678                         setErrorMessage(N_("Unknown action"));
2679                 }
2680                 break;
2681         default:
2682                 lyxerr << "A truly unknown func!" << endl;
2683                 break;
2684         }
2685         } // end of switch
2686   exit_with_message:
2687
2688         string res = getMessage();
2689
2690         if (res.empty()) {
2691                 if (!commandshortcut.empty()) {
2692                         string newbuf = owner->getMiniBuffer()->GetText();
2693                         if (newbuf != commandshortcut) {
2694                                 owner->getMiniBuffer()->Set(newbuf
2695                                                             + " " +
2696                                                             commandshortcut);
2697                         }
2698                 }
2699         } else {
2700                 owner->getMiniBuffer()->Set(string(_(res.c_str()))
2701                                             + " " + commandshortcut);
2702         }
2703
2704         return res;
2705 }
2706
2707
2708 void LyXFunc::setupLocalKeymap()
2709 {
2710         keyseq.stdmap = keyseq.curmap = toplevel_keymap;
2711         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap;
2712 }
2713
2714
2715 void LyXFunc::MenuNew(bool fromTemplate)
2716 {
2717         string fname, initpath = lyxrc.document_path;
2718         LyXFileDlg fileDlg;
2719
2720         if (owner->view()->available()) {
2721                 string trypath = owner->buffer()->filepath;
2722                 // If directory is writeable, use this as default.
2723                 if (IsDirWriteable(trypath) == 1)
2724                         initpath = trypath;
2725         }
2726
2727         ProhibitInput(owner->view());
2728         fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
2729         fileDlg.SetButton(1, _("Templates"), lyxrc.template_path);
2730         fname = fileDlg.Select(_("Enter Filename for new document"), 
2731                                initpath, "*.lyx", _("newfile"));
2732         AllowInput(owner->view());
2733         
2734         if (fname.empty()) {
2735                 owner->getMiniBuffer()->Set(_("Canceled."));
2736                 lyxerr.debug() << "New Document Cancelled." << endl;
2737                 return;
2738         }
2739         
2740         // get absolute path of file and make sure the filename ends
2741         // with .lyx
2742         string s = MakeAbsPath(fname);
2743         if (!IsLyXFilename(s))
2744                 s += ".lyx";
2745
2746         // Check if the document already is open
2747         if (bufferlist.exists(s)){
2748                 switch(AskConfirmation(_("Document is already open:"), 
2749                                        MakeDisplayPath(s, 50),
2750                                        _("Do you want to close that document now?\n"
2751                                          "('No' will just switch to the open version)")))
2752                         {
2753                         case 1: // Yes: close the document
2754                                 if (!bufferlist.close(bufferlist.getBuffer(s)))
2755                                 // If close is canceled, we cancel here too.
2756                                         return;
2757                                 break;
2758                         case 2: // No: switch to the open document
2759                                 owner->view()->buffer(bufferlist.getBuffer(s));
2760                                 return;
2761                         case 3: // Cancel: Do nothing
2762                                 owner->getMiniBuffer()->Set(_("Canceled."));
2763                                 return;
2764                         }
2765         }
2766         
2767         // Check whether the file already exists
2768         if (IsLyXFilename(s)) {
2769                 FileInfo fi(s);
2770                 if (fi.readable() &&
2771                     AskQuestion(_("File already exists:"), 
2772                                 MakeDisplayPath(s, 50),
2773                                 _("Do you want to open the document?"))) {
2774                         // loads document
2775                         owner->getMiniBuffer()->Set(_("Opening document"), 
2776                                                     MakeDisplayPath(s), "...");
2777                         XFlush(fl_display);
2778                         owner->view()->buffer(
2779                                 bufferlist.loadLyXFile(s));
2780                         owner->getMiniBuffer()->Set(_("Document"),
2781                                                     MakeDisplayPath(s),
2782                                                     _("opened."));
2783                         return;
2784                 }
2785         }
2786
2787         // The template stuff
2788         string templname;
2789         if (fromTemplate) {
2790                 ProhibitInput(owner->view());
2791                 fname = fileDlg.Select(_("Choose template"),
2792                                        lyxrc.template_path,
2793                                        "*.lyx");
2794                 templname = fname;
2795                 AllowInput(owner->view());
2796         }
2797   
2798         // find a free buffer
2799         lyxerr.debug() << "Find a free buffer." << endl;
2800         owner->view()->buffer(bufferlist.newFile(s, templname));
2801 }
2802
2803
2804 void LyXFunc::MenuOpen()
2805 {
2806         string initpath = lyxrc.document_path;
2807         LyXFileDlg fileDlg;
2808   
2809         if (owner->view()->available()) {
2810                 string trypath = owner->buffer()->filepath;
2811                 // If directory is writeable, use this as default.
2812                 if (IsDirWriteable(trypath) == 1)
2813                         initpath = trypath;
2814         }
2815
2816         // launches dialog
2817         ProhibitInput(owner->view());
2818         fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
2819         fileDlg.SetButton(1, _("Examples"), 
2820                           AddPath(system_lyxdir, "examples"));
2821         string filename = fileDlg.Select(_("Select Document to Open"),
2822                                          initpath, "*.lyx");
2823         AllowInput(owner->view());
2824  
2825         // check selected filename
2826         if (filename.empty()) {
2827                 owner->getMiniBuffer()->Set(_("Canceled."));
2828                 return;
2829         }
2830
2831         // get absolute path of file and make sure the filename ends
2832         // with .lyx
2833         filename = MakeAbsPath(filename);
2834         if (!IsLyXFilename(filename))
2835                 filename += ".lyx";
2836
2837         // loads document
2838         owner->getMiniBuffer()->Set(_("Opening document"),
2839                                     MakeDisplayPath(filename), "...");
2840         Buffer * openbuf = bufferlist.loadLyXFile(filename);
2841         if (openbuf) {
2842                 owner->view()->buffer(openbuf);
2843                 owner->getMiniBuffer()->Set(_("Document"),
2844                                             MakeDisplayPath(filename),
2845                                             _("opened."));
2846         } else {
2847                 owner->getMiniBuffer()->Set(_("Could not open document"),
2848                                             MakeDisplayPath(filename));
2849         }
2850 }
2851
2852 // returns filename if file must be imported,
2853 // empty string if either file not found or already loaded
2854 // checks for running without gui are missing.
2855
2856 void LyXFunc::doImportHelper(
2857         string const & file,          // filename (possibly empty)
2858         string const & text,          // info when asking for filename
2859         string const & pattern,       // filetype
2860         bool func(BufferView *, string const &)     // the real import function
2861 )
2862 {
2863         string filename = file;
2864
2865         if (filename.empty()) { // need user interaction
2866                 string initpath = lyxrc.document_path;
2867                 LyXFileDlg fileDlg;
2868                 
2869                 if (owner->view()->available()) {
2870                         string trypath = owner->buffer()->filepath;
2871                         // If directory is writeable, use this as default.
2872                         if (IsDirWriteable(trypath) == 1)
2873                                 initpath = trypath;
2874                 }
2875
2876                 // launches dialog
2877                 ProhibitInput(owner->view());
2878                 fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
2879                 fileDlg.SetButton(1, _("Examples"), 
2880                                         AddPath(system_lyxdir, "examples"));
2881                 filename = fileDlg.Select(text, initpath, pattern);
2882                 AllowInput(owner->view());
2883  
2884                 // check selected filename
2885                 if (filename.empty()) 
2886                         owner->getMiniBuffer()->Set(_("Canceled."));
2887         }
2888
2889         // still no filename? abort
2890         if (filename.empty()) 
2891                 return;
2892
2893         // get absolute path of file
2894         filename = MakeAbsPath(filename);
2895
2896         string lyxfile = ChangeExtension(filename, ".lyx");
2897
2898         // Check if the document already is open
2899         if (bufferlist.exists(lyxfile)) {
2900                 switch(AskConfirmation(_("Document is already open:"), 
2901                                        MakeDisplayPath(lyxfile, 50),
2902                                        _("Do you want to close that document now?\n"
2903                                          "('No' will just switch to the open version)")))
2904                         {
2905                         case 1: // Yes: close the document
2906                                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile)))
2907                                 // If close is canceled, we cancel here too.
2908                                         return;
2909                                 break;
2910                         case 2: // No: switch to the open document
2911                                 owner->view()->buffer(bufferlist.getBuffer(lyxfile));
2912                                 return;
2913                         case 3: // Cancel: Do nothing
2914                                 owner->getMiniBuffer()->Set(_("Canceled."));
2915                                 return;
2916                         }
2917         }
2918
2919         // Check if a LyX document by the same root exists in filesystem
2920         FileInfo f(lyxfile, true);
2921         if (f.exist() && !AskQuestion(_("A document by the name"), 
2922                                       MakeDisplayPath(lyxfile),
2923                                       _("already exists. Overwrite?"))) {
2924                 owner->getMiniBuffer()->Set(_("Canceled."));
2925                 return;
2926         }
2927         // filename should be valid now
2928
2929         // notify user of import ahead
2930         string displaypath = MakeDisplayPath(filename);
2931         owner->view()->buffer(bufferlist.newFile(lyxfile, string()));
2932         owner->getMiniBuffer()->Set(_("Importing"), displaypath, "...");
2933
2934         // call real importer
2935         bool result = func(owner->view(), filename);
2936
2937         // we are done
2938         if (result)
2939                 owner->getMiniBuffer()->Set(displaypath, _("imported."));
2940         else
2941                 owner->getMiniBuffer()->Set(displaypath, _(": import failed."));
2942 }
2943
2944 static
2945 bool doImportASCIIasLines(BufferView * view, string const & filename)
2946 {
2947         InsertAsciiFile(view, filename, false);
2948         return true;
2949 }
2950
2951 static
2952 bool doImportASCIIasParagraphs(BufferView * view, string const & filename)
2953 {
2954         InsertAsciiFile(view, filename, true);
2955         return true;
2956 }
2957
2958 static
2959 bool doImportLaTeX(BufferView *, string const & filename)
2960 {
2961         ImportLaTeX myImport(filename);
2962         Buffer * openbuf = myImport.run();
2963         return openbuf != NULL;         
2964 }
2965
2966 static
2967 bool doImportNoweb(BufferView *, string const & filename)
2968 {
2969         ImportNoweb myImport(filename);
2970         Buffer * openbuf = myImport.run();
2971         return openbuf != NULL;         
2972 }
2973
2974 static
2975 bool doImportLinuxDoc(BufferView *, string const & filename)
2976 {
2977         // run sgml2lyx
2978         string tmp = lyxrc.linuxdoc_to_lyx_command + filename;
2979         Systemcalls one;
2980         Buffer * buf = 0;
2981
2982         int result = one.startscript(Systemcalls::System, tmp);
2983         if (result == 0) {
2984                 string filename = ChangeExtension(filename, ".lyx");
2985                 // File was generated without problems. Load it.
2986                 buf = bufferlist.loadLyXFile(filename);
2987         }
2988
2989         return result == 0;
2990 }
2991
2992
2993 void LyXFunc::MenuInsertLyXFile(string const & filen)
2994 {
2995         string filename = filen;
2996
2997         if (filename.empty()) {
2998                 // Launch a file browser
2999                 string initpath = lyxrc.document_path;
3000                 LyXFileDlg fileDlg;
3001
3002                 if (owner->view()->available()) {
3003                         string trypath = owner->buffer()->filepath;
3004                         // If directory is writeable, use this as default.
3005                         if (IsDirWriteable(trypath) == 1)
3006                                 initpath = trypath;
3007                 }
3008
3009                 // launches dialog
3010                 ProhibitInput(owner->view());
3011                 fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
3012                 fileDlg.SetButton(1, _("Examples"), 
3013                                   AddPath(system_lyxdir, "examples"));
3014                 filename = fileDlg.Select(_("Select Document to Insert"),
3015                                           initpath, "*.lyx");
3016                 AllowInput(owner->view());
3017
3018                 // check selected filename
3019                 if (filename.empty()) {
3020                         owner->getMiniBuffer()->Set(_("Canceled."));
3021                         return;
3022                 }
3023         } 
3024
3025         // get absolute path of file and make sure the filename ends
3026         // with .lyx
3027         filename = MakeAbsPath(filename);
3028         if (!IsLyXFilename(filename))
3029                 filename += ".lyx";
3030
3031         // Inserts document
3032         owner->getMiniBuffer()->Set(_("Inserting document"),
3033                                     MakeDisplayPath(filename), "...");
3034         bool res = owner->view()->insertLyXFile(filename);
3035         if (res) {
3036                 owner->getMiniBuffer()->Set(_("Document"),
3037                                             MakeDisplayPath(filename),
3038                                             _("inserted."));
3039         } else {
3040                 owner->getMiniBuffer()->Set(_("Could not insert document"),
3041                                             MakeDisplayPath(filename));
3042         }
3043 }
3044
3045 void LyXFunc::doImport(string const & argument)
3046 {
3047         string type;
3048         string filename = split(argument, type, ' ');
3049         lyxerr.debug() << "LyXFunc::doImport: " << type 
3050                        << " file: " << filename << endl;
3051
3052         if (type == "latex") 
3053                 doImportHelper(filename,
3054                                _("Select LaTeX file to import"), "*.tex", 
3055                                doImportLaTeX);
3056         else if (type == "ascii") 
3057                 doImportHelper(filename,
3058                                _("Select ASCII file to import"), "*.txt", 
3059                                doImportASCIIasLines);
3060         else if (type == "asciiparagraph") 
3061                 doImportHelper(filename,
3062                                _("Select ASCII file to import"), "*.txt", 
3063                                doImportASCIIasParagraphs);
3064         else if (type == "noweb") 
3065                 doImportHelper(filename,
3066                                _("Select NoWeb file to import"), "*.nw", 
3067                                doImportNoweb);
3068         else if (type == "linuxdoc") 
3069                 doImportHelper(filename,
3070                                _("Select LinuxDoc file to import"), "*.doc", 
3071                                doImportLinuxDoc);
3072         else 
3073                 setErrorMessage(string(N_("Unknown import type: ")) + type);
3074 }
3075
3076 void LyXFunc::reloadBuffer()
3077 {
3078         string fn = owner->buffer()->fileName();
3079         if (bufferlist.close(owner->buffer()))
3080                 owner->view()->buffer(bufferlist.loadLyXFile(fn));
3081 }
3082
3083
3084 void LyXFunc::CloseBuffer()
3085 {
3086         if (bufferlist.close(owner->buffer()) && !quitting) {
3087                 if (bufferlist.empty()) {
3088                         // need this otherwise SEGV may occur while trying to
3089                         // set variables that don't exist
3090                         // since there's no current buffer
3091                         CloseAllBufferRelatedPopups();
3092                 }
3093                 else {
3094                         owner->view()->buffer(bufferlist.first());
3095                 }
3096         }
3097 }
3098
3099
3100 Inset * LyXFunc::getInsetByCode(Inset::Code code)
3101 {
3102         LyXCursor cursor = owner->view()->text->cursor;
3103         Buffer * buffer = owner->view()->buffer();
3104         for (Buffer::inset_iterator it = Buffer::inset_iterator(cursor.par,
3105                                                                 cursor.pos);
3106              it != buffer->inset_iterator_end(); ++it) {
3107                 if ((*it)->LyxCode() == code)
3108                         return *it;
3109         }
3110         return 0;
3111 }
3112
3113
3114 // Each "owner" should have it's own message method. lyxview and
3115 // the minibuffer would use the minibuffer, but lyxserver would
3116 // send an ERROR signal to its client.  Alejandro 970603
3117 // This func is bit problematic when it comes to NLS, to make the
3118 // lyx servers client be language indepenent we must not translate
3119 // strings sent to this func.
3120 void LyXFunc::setErrorMessage(string const & m) const
3121 {
3122         dispatch_buffer = m;
3123         errorstat = true;
3124 }
3125
3126
3127 void LyXFunc::setMessage(string const & m)
3128 {
3129         dispatch_buffer = m;
3130 }