]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Fix function disabling
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyX.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "SpellChecker.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "WordLangTuple.h"
49
50 #include "frontends/Application.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/Selection.h"
53
54 #include "insets/InsetArgument.h"
55 #include "insets/InsetCollapsable.h"
56 #include "insets/InsetCommand.h"
57 #include "insets/InsetExternal.h"
58 #include "insets/InsetFloat.h"
59 #include "insets/InsetFloatList.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetGraphicsParams.h"
62 #include "insets/InsetIPAMacro.h"
63 #include "insets/InsetNewline.h"
64 #include "insets/InsetQuotes.h"
65 #include "insets/InsetSpecialChar.h"
66 #include "insets/InsetText.h"
67 #include "insets/InsetWrap.h"
68
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/gettext.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/lyxtime.h"
75 #include "support/os.h"
76
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MathMacroTemplate.h"
79
80 #include <boost/next_prior.hpp>
81
82 #include <clocale>
83 #include <sstream>
84
85 using namespace std;
86 using namespace lyx::support;
87
88 namespace lyx {
89
90 using cap::copySelection;
91 using cap::cutSelection;
92 using cap::pasteFromStack;
93 using cap::pasteClipboardText;
94 using cap::pasteClipboardGraphics;
95 using cap::replaceSelection;
96 using cap::grabAndEraseSelection;
97 using cap::selClearOrDel;
98 using cap::pasteSimpleText;
99
100 // globals...
101 static Font freefont(ignore_font, ignore_language);
102 static bool toggleall = false;
103
104 static void toggleAndShow(Cursor & cur, Text * text,
105         Font const & font, bool toggleall = true)
106 {
107         text->toggleFree(cur, font, toggleall);
108
109         if (font.language() != ignore_language ||
110             font.fontInfo().number() != FONT_IGNORE) {
111                 TextMetrics const & tm = cur.bv().textMetrics(text);
112                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
113                                                        cur.real_current_font))
114                         text->setCursor(cur, cur.pit(), cur.pos(),
115                                         false, !cur.boundary());
116         }
117 }
118
119
120 static void moveCursor(Cursor & cur, bool selecting)
121 {
122         if (selecting || cur.mark())
123                 cur.setSelection();
124 }
125
126
127 static void finishChange(Cursor & cur, bool selecting)
128 {
129         cur.finishUndo();
130         moveCursor(cur, selecting);
131 }
132
133
134 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
135 {
136         cur.recordUndo();
137         docstring sel = cur.selectionAsString(false);
138
139         // It may happen that sel is empty but there is a selection
140         replaceSelection(cur);
141
142         // Is this a valid formula?
143         bool valid = true;
144
145         if (sel.empty()) {
146 #ifdef ENABLE_ASSERTIONS
147                 const int old_pos = cur.pos();
148 #endif
149                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
150 #ifdef ENABLE_ASSERTIONS
151                 LASSERT(old_pos == cur.pos(), /**/);
152 #endif
153                 cur.nextInset()->edit(cur, true);
154                 // don't do that also for LFUN_MATH_MODE
155                 // unless you want end up with always changing
156                 // to mathrm when opening an inlined inset --
157                 // I really hate "LyXfunc overloading"...
158                 if (display)
159                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
160                 // Avoid an unnecessary undo step if cmd.argument
161                 // is empty
162                 if (!cmd.argument().empty())
163                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
164                                                  cmd.argument()));
165         } else {
166                 // create a macro if we see "\\newcommand"
167                 // somewhere, and an ordinary formula
168                 // otherwise
169                 if (sel.find(from_ascii("\\newcommand")) == string::npos
170                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
171                                 && sel.find(from_ascii("\\def")) == string::npos)
172                 {
173                         InsetMathHull * formula = new InsetMathHull(cur.buffer());
174                         string const selstr = to_utf8(sel);
175                         istringstream is(selstr);
176                         Lexer lex;
177                         lex.setStream(is);
178                         if (!formula->readQuiet(lex)) {
179                                 // No valid formula, let's try with delims
180                                 is.str("$" + selstr + "$");
181                                 lex.setStream(is);
182                                 if (!formula->readQuiet(lex)) {
183                                         // Still not valid, leave it as is
184                                         valid = false;
185                                         delete formula;
186                                         cur.insert(sel);
187                                 } else
188                                         cur.insert(formula);
189                         } else
190                                 cur.insert(formula);
191                 } else {
192                         cur.insert(new MathMacroTemplate(cur.buffer(), sel));
193                 }
194         }
195         if (valid)
196                 cur.message(from_utf8(N_("Math editor mode")));
197         else
198                 cur.message(from_utf8(N_("No valid math formula")));
199 }
200
201
202 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
203 {
204         LASSERT(cmd.action() == LFUN_REGEXP_MODE, return);
205         if (cur.inRegexped()) {
206                 cur.message(_("Already in regular expression mode"));
207                 return;
208         }
209         cur.recordUndo();
210         docstring sel = cur.selectionAsString(false);
211
212         // It may happen that sel is empty but there is a selection
213         replaceSelection(cur);
214
215         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
216         cur.nextInset()->edit(cur, true);
217         cur.niceInsert(sel);
218
219         cur.message(_("Regexp editor mode"));
220 }
221
222
223 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
224 {
225         cur.recordUndo();
226         cap::replaceSelection(cur);
227         cur.insert(new InsetSpecialChar(kind));
228         cur.posForward();
229 }
230
231
232 static void ipaChar(Cursor & cur, InsetIPAChar::Kind kind)
233 {
234         cur.recordUndo();
235         cap::replaceSelection(cur);
236         cur.insert(new InsetIPAChar(kind));
237         cur.posForward();
238 }
239
240
241 static bool doInsertInset(Cursor & cur, Text * text,
242         FuncRequest const & cmd, bool edit, bool pastesel)
243 {
244         Buffer & buffer = cur.bv().buffer();
245         BufferParams const & bparams = buffer.params();
246         Inset * inset = createInset(&buffer, cmd);
247         if (!inset)
248                 return false;
249
250         if (InsetCollapsable * ci = inset->asInsetCollapsable())
251                 ci->setButtonLabel();
252
253         cur.recordUndo();
254         if (cmd.action() == LFUN_INDEX_INSERT) {
255                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
256                 text->insertInset(cur, inset);
257                 if (edit)
258                         inset->edit(cur, true);
259                 // Now put this into inset
260                 Font const f(inherit_font, cur.current_font.language());
261                 if (!ds.empty()) {
262                         cur.text()->insertStringAsLines(cur, ds, f);
263                         cur.leaveInset(*inset);
264                 }
265                 return true;
266         }
267
268         bool gotsel = false;
269         if (cur.selection()) {
270                 cutSelection(cur, false, pastesel);
271                 cur.clearSelection();
272                 gotsel = true;
273         }
274         text->insertInset(cur, inset);
275
276         if (edit)
277                 inset->edit(cur, true);
278
279         if (!gotsel || !pastesel)
280                 return true;
281
282         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
283         cur.buffer()->errors("Paste");
284         cur.clearSelection(); // bug 393
285         cur.finishUndo();
286         InsetText * inset_text = inset->asInsetText();
287         if (inset_text) {
288                 inset_text->fixParagraphsFont();
289                 if (!inset_text->allowMultiPar() || cur.lastpit() == 0) {
290                         // reset first par to default
291                         cur.text()->paragraphs().begin()
292                                 ->setPlainOrDefaultLayout(bparams.documentClass());
293                         cur.pos() = 0;
294                         cur.pit() = 0;
295                         // Merge multiple paragraphs -- hack
296                         while (cur.lastpit() > 0)
297                                 mergeParagraph(bparams, cur.text()->paragraphs(), 0);
298                         Cursor old = cur;
299                         cur.leaveInset(*inset);
300                         if (cmd.action() == LFUN_PREVIEW_INSERT
301                             || cmd.action() == LFUN_IPA_INSERT)
302                                 // trigger preview
303                                 notifyCursorLeavesOrEnters(old, cur);
304                 }
305         } else {
306                 cur.leaveInset(*inset);
307                 // reset surrounding par to default
308                 DocumentClass const & dc = bparams.documentClass();
309                 docstring const layoutname = inset->usePlainLayout()
310                         ? dc.plainLayoutName()
311                         : dc.defaultLayoutName();
312                 text->setLayout(cur, layoutname);
313         }
314         return true;
315 }
316
317
318 string const freefont2string()
319 {
320         return freefont.toString(toggleall);
321 }
322
323
324 /// the type of outline operation
325 enum OutlineOp {
326         OutlineUp, // Move this header with text down
327         OutlineDown,   // Move this header with text up
328         OutlineIn, // Make this header deeper
329         OutlineOut // Make this header shallower
330 };
331
332
333 static void outline(OutlineOp mode, Cursor & cur)
334 {
335         Buffer & buf = *cur.buffer();
336         pit_type & pit = cur.pit();
337         ParagraphList & pars = buf.text().paragraphs();
338         ParagraphList::iterator const bgn = pars.begin();
339         // The first paragraph of the area to be copied:
340         ParagraphList::iterator start = boost::next(bgn, pit);
341         // The final paragraph of area to be copied:
342         ParagraphList::iterator finish = start;
343         ParagraphList::iterator const end = pars.end();
344
345         DocumentClass const & tc = buf.params().documentClass();
346
347         int const thistoclevel = start->layout().toclevel;
348         int toclevel;
349
350         // Move out (down) from this section header
351         if (finish != end)
352                 ++finish;
353
354         // Seek the one (on same level) below
355         for (; finish != end; ++finish) {
356                 toclevel = finish->layout().toclevel;
357                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
358                         break;
359         }
360
361         switch (mode) {
362                 case OutlineUp: {
363                         if (start == pars.begin())
364                                 // Nothing to move.
365                                 return;
366                         ParagraphList::iterator dest = start;
367                         // Move out (up) from this header
368                         if (dest == bgn)
369                                 return;
370                         // Search previous same-level header above
371                         do {
372                                 --dest;
373                                 toclevel = dest->layout().toclevel;
374                         } while(dest != bgn
375                                 && (toclevel == Layout::NOT_IN_TOC
376                                     || toclevel > thistoclevel));
377                         // Not found; do nothing
378                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
379                                 return;
380                         pit_type const newpit = distance(bgn, dest);
381                         pit_type const len = distance(start, finish);
382                         pit_type const deletepit = pit + len;
383                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
384                         pars.splice(dest, start, finish);
385                         cur.pit() = newpit;
386                         break;
387                 }
388                 case OutlineDown: {
389                         if (finish == end)
390                                 // Nothing to move.
391                                 return;
392                         // Go one down from *this* header:
393                         ParagraphList::iterator dest = boost::next(finish, 1);
394                         // Go further down to find header to insert in front of:
395                         for (; dest != end; ++dest) {
396                                 toclevel = dest->layout().toclevel;
397                                 if (toclevel != Layout::NOT_IN_TOC
398                                       && toclevel <= thistoclevel)
399                                         break;
400                         }
401                         // One such was found:
402                         pit_type newpit = distance(bgn, dest);
403                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
404                         pit_type const len = distance(start, finish);
405                         pars.splice(dest, start, finish);
406                         cur.pit() = newpit - len;
407                         break;
408                 }
409                 case OutlineIn: {
410                         pit_type const len = distance(start, finish);
411                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
412                         for (; start != finish; ++start) {
413                                 toclevel = start->layout().toclevel;
414                                 if (toclevel == Layout::NOT_IN_TOC)
415                                         continue;
416                                 DocumentClass::const_iterator lit = tc.begin();
417                                 DocumentClass::const_iterator len = tc.end();
418                                 for (; lit != len; ++lit) {
419                                         if (lit->toclevel == toclevel + 1 &&
420                                             start->layout().labeltype == lit->labeltype) {
421                                                 start->setLayout(*lit);
422                                                 break;
423                                         }
424                                 }
425                         }
426                         break;
427                 }
428                 case OutlineOut: {
429                         pit_type const len = distance(start, finish);
430                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
431                         for (; start != finish; ++start) {
432                                 toclevel = start->layout().toclevel;
433                                 if (toclevel == Layout::NOT_IN_TOC)
434                                         continue;
435                                 DocumentClass::const_iterator lit = tc.begin();
436                                 DocumentClass::const_iterator len = tc.end();
437                                 for (; lit != len; ++lit) {
438                                         if (lit->toclevel == toclevel - 1 &&
439                                                 start->layout().labeltype == lit->labeltype) {
440                                                         start->setLayout(*lit);
441                                                         break;
442                                         }
443                                 }
444                         }
445                         break;
446                 }
447         }
448 }
449
450
451 void Text::number(Cursor & cur)
452 {
453         FontInfo font = ignore_font;
454         font.setNumber(FONT_TOGGLE);
455         toggleAndShow(cur, this, Font(font, ignore_language));
456 }
457
458
459 bool Text::isRTL(Paragraph const & par) const
460 {
461         Buffer const & buffer = owner_->buffer();
462         return par.isRTL(buffer.params());
463 }
464
465
466 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
467 {
468         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
469
470         // Dispatch if the cursor is inside the text. It is not the
471         // case for context menus (bug 5797).
472         if (cur.text() != this) {
473                 cur.undispatched();
474                 return;
475         }
476
477         BufferView * bv = &cur.bv();
478         TextMetrics * tm = &bv->textMetrics(this);
479         if (!tm->contains(cur.pit())) {
480                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
481                 tm = &bv->textMetrics(this);
482         }
483
484         // FIXME: We use the update flag to indicates wether a singlePar or a
485         // full screen update is needed. We reset it here but shall we restore it
486         // at the end?
487         cur.noScreenUpdate();
488
489         LASSERT(cur.text() == this, /**/);
490         CursorSlice const oldTopSlice = cur.top();
491         bool const oldBoundary = cur.boundary();
492         bool const oldSelection = cur.selection();
493         // Signals that, even if needsUpdate == false, an update of the
494         // cursor paragraph is required
495         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action(),
496                 LyXAction::SingleParUpdate);
497         // Signals that a full-screen update is required
498         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action(),
499                 LyXAction::NoUpdate) || singleParUpdate);
500         bool const last_misspelled = lyxrc.spellcheck_continuously
501                 && cur.paragraph().isMisspelled(cur.pos(), true);
502         
503         FuncCode const act = cmd.action();
504         switch (act) {
505
506         case LFUN_PARAGRAPH_MOVE_DOWN: {
507                 pit_type const pit = cur.pit();
508                 recUndo(cur, pit, pit + 1);
509                 cur.finishUndo();
510                 pars_.swap(pit, pit + 1);
511                 needsUpdate = true;
512                 cur.forceBufferUpdate();
513                 ++cur.pit();
514                 break;
515         }
516
517         case LFUN_PARAGRAPH_MOVE_UP: {
518                 pit_type const pit = cur.pit();
519                 recUndo(cur, pit - 1, pit);
520                 cur.finishUndo();
521                 pars_.swap(pit, pit - 1);
522                 --cur.pit();
523                 needsUpdate = true;
524                 cur.forceBufferUpdate();
525                 break;
526         }
527
528         case LFUN_APPENDIX: {
529                 Paragraph & par = cur.paragraph();
530                 bool start = !par.params().startOfAppendix();
531
532 // FIXME: The code below only makes sense at top level.
533 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
534                 // ensure that we have only one start_of_appendix in this document
535                 // FIXME: this don't work for multipart document!
536                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
537                         if (pars_[tmp].params().startOfAppendix()) {
538                                 recUndo(cur, tmp);
539                                 pars_[tmp].params().startOfAppendix(false);
540                                 break;
541                         }
542                 }
543
544                 cur.recordUndo();
545                 par.params().startOfAppendix(start);
546
547                 // we can set the refreshing parameters now
548                 cur.forceBufferUpdate();
549                 break;
550         }
551
552         case LFUN_WORD_DELETE_FORWARD:
553                 if (cur.selection())
554                         cutSelection(cur, true, false);
555                 else
556                         deleteWordForward(cur);
557                 finishChange(cur, false);
558                 break;
559
560         case LFUN_WORD_DELETE_BACKWARD:
561                 if (cur.selection())
562                         cutSelection(cur, true, false);
563                 else
564                         deleteWordBackward(cur);
565                 finishChange(cur, false);
566                 break;
567
568         case LFUN_LINE_DELETE:
569                 if (cur.selection())
570                         cutSelection(cur, true, false);
571                 else
572                         tm->deleteLineForward(cur);
573                 finishChange(cur, false);
574                 break;
575
576         case LFUN_BUFFER_BEGIN:
577         case LFUN_BUFFER_BEGIN_SELECT:
578                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_BEGIN_SELECT);
579                 if (cur.depth() == 1)
580                         needsUpdate |= cursorTop(cur);
581                 else
582                         cur.undispatched();
583                 cur.screenUpdateFlags(Update::FitCursor);
584                 break;
585
586         case LFUN_BUFFER_END:
587         case LFUN_BUFFER_END_SELECT:
588                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_END_SELECT);
589                 if (cur.depth() == 1)
590                         needsUpdate |= cursorBottom(cur);
591                 else
592                         cur.undispatched();
593                 cur.screenUpdateFlags(Update::FitCursor);
594                 break;
595
596         case LFUN_INSET_BEGIN:
597         case LFUN_INSET_BEGIN_SELECT:
598                 needsUpdate |= cur.selHandle(act == LFUN_INSET_BEGIN_SELECT);
599                 if (cur.depth() == 1 || !cur.top().at_begin())
600                         needsUpdate |= cursorTop(cur);
601                 else
602                         cur.undispatched();
603                 cur.screenUpdateFlags(Update::FitCursor);
604                 break;
605
606         case LFUN_INSET_END:
607         case LFUN_INSET_END_SELECT:
608                 needsUpdate |= cur.selHandle(act == LFUN_INSET_END_SELECT);
609                 if (cur.depth() == 1 || !cur.top().at_end())
610                         needsUpdate |= cursorBottom(cur);
611                 else
612                         cur.undispatched();
613                 cur.screenUpdateFlags(Update::FitCursor);
614                 break;
615
616         case LFUN_INSET_SELECT_ALL:
617                 if (cur.depth() == 1 || !cur.selection() || !cur.selBegin().at_begin()
618                           || !cur.selEnd().at_end()) {
619                         needsUpdate |= cur.selHandle(false);
620                         needsUpdate |= cursorTop(cur);
621                         needsUpdate |= cur.selHandle(true);
622                         needsUpdate |= cursorBottom(cur);
623                 } else 
624                         cur.undispatched();
625                 cur.screenUpdateFlags(Update::FitCursor);
626                 break;
627
628         case LFUN_CHAR_FORWARD:
629         case LFUN_CHAR_FORWARD_SELECT:
630                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
631                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_FORWARD_SELECT);
632                 needsUpdate |= cursorForward(cur);
633
634                 if (!needsUpdate && oldTopSlice == cur.top()
635                                 && cur.boundary() == oldBoundary) {
636                         cur.undispatched();
637                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
638                 
639                         // we will probably be moving out the inset, so we should execute
640                         // the depm-mechanism, but only when the cursor has a place to 
641                         // go outside this inset, i.e. in a slice above.
642                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
643                                   && cur.pit() == cur.lastpit()) {
644                                 // The cursor hasn't changed yet. To give the 
645                                 // DEPM the possibility of doing something we must
646                                 // provide it with two different cursors.
647                                 Cursor dummy = cur;
648                                 dummy.pos() = dummy.pit() = 0;
649                                 if (cur.bv().checkDepm(dummy, cur)) {
650                                         cur.forceBufferUpdate();
651                                         // DEPM may have requested a screen update
652                                         cur.screenUpdateFlags(
653                                                 cur.screenUpdate() | dummy.screenUpdate());
654                                 }
655                         }
656                 }
657                 break;
658
659         case LFUN_CHAR_BACKWARD:
660         case LFUN_CHAR_BACKWARD_SELECT:
661                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
662                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_BACKWARD_SELECT);
663                 needsUpdate |= cursorBackward(cur);
664
665                 if (!needsUpdate && oldTopSlice == cur.top()
666                         && cur.boundary() == oldBoundary) {
667                         cur.undispatched();
668                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
669
670                         // we will probably be moving out the inset, so we should execute
671                         // the depm-mechanism, but only when the cursor has a place to 
672                         // go outside this inset, i.e. in a slice above.
673                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
674                                 // The cursor hasn't changed yet. To give the 
675                                 // DEPM the possibility of doing something we must
676                                 // provide it with two different cursors.
677                                 Cursor dummy = cur;
678                                 dummy.pos() = cur.lastpos();
679                                 dummy.pit() = cur.lastpit();
680                                 if (cur.bv().checkDepm(dummy, cur)) {
681                                         cur.forceBufferUpdate();
682                                         // DEPM may have requested a screen update
683                                         cur.screenUpdateFlags(
684                                                 cur.screenUpdate() | dummy.screenUpdate());
685                                 }
686                         }
687                 }
688                 break;
689
690         case LFUN_CHAR_LEFT:
691         case LFUN_CHAR_LEFT_SELECT:
692                 if (lyxrc.visual_cursor) {
693                         needsUpdate |= cur.selHandle(act == LFUN_CHAR_LEFT_SELECT);
694                         needsUpdate |= cursorVisLeft(cur);
695                         if (!needsUpdate && oldTopSlice == cur.top()
696                                         && cur.boundary() == oldBoundary) {
697                                 cur.undispatched();
698                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
699                         }
700                 } else {
701                         if (reverseDirectionNeeded(cur)) {
702                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
703                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
704                         } else {
705                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
706                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
707                         }
708                         dispatch(cur, cmd);
709                         return;
710                 }
711                 break;
712
713         case LFUN_CHAR_RIGHT:
714         case LFUN_CHAR_RIGHT_SELECT:
715                 if (lyxrc.visual_cursor) {
716                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_CHAR_RIGHT_SELECT);
717                         needsUpdate |= cursorVisRight(cur);
718                         if (!needsUpdate && oldTopSlice == cur.top()
719                                         && cur.boundary() == oldBoundary) {
720                                 cur.undispatched();
721                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
722                         }
723                 } else {
724                         if (reverseDirectionNeeded(cur)) {
725                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
726                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
727                         } else {
728                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
729                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
730                         }
731                         dispatch(cur, cmd);
732                         return;
733                 }
734                 break;
735
736
737         case LFUN_UP_SELECT:
738         case LFUN_DOWN_SELECT:
739         case LFUN_UP:
740         case LFUN_DOWN: {
741                 // stop/start the selection
742                 bool select = cmd.action() == LFUN_DOWN_SELECT ||
743                         cmd.action() == LFUN_UP_SELECT;
744
745                 // move cursor up/down
746                 bool up = cmd.action() == LFUN_UP_SELECT || cmd.action() == LFUN_UP;
747                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
748
749                 if (!atFirstOrLastRow) {
750                         needsUpdate |= cur.selHandle(select);   
751                         cur.selHandle(select);
752                         cur.upDownInText(up, needsUpdate);
753                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
754                 } else {
755                         // if the cursor cannot be moved up or down do not remove
756                         // the selection right now, but wait for the next dispatch.
757                         if (select)
758                                 needsUpdate |= cur.selHandle(select);   
759                         cur.upDownInText(up, needsUpdate);
760                         cur.undispatched();
761                 }
762
763                 break;
764         }
765
766         case LFUN_PARAGRAPH_UP:
767         case LFUN_PARAGRAPH_UP_SELECT:
768                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_UP_SELECT);
769                 needsUpdate |= cursorUpParagraph(cur);
770                 break;
771
772         case LFUN_PARAGRAPH_DOWN:
773         case LFUN_PARAGRAPH_DOWN_SELECT:
774                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_DOWN_SELECT);
775                 needsUpdate |= cursorDownParagraph(cur);
776                 break;
777
778         case LFUN_LINE_BEGIN:
779         case LFUN_LINE_BEGIN_SELECT:
780                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_BEGIN_SELECT);
781                 needsUpdate |= tm->cursorHome(cur);
782                 break;
783
784         case LFUN_LINE_END:
785         case LFUN_LINE_END_SELECT:
786                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_END_SELECT);
787                 needsUpdate |= tm->cursorEnd(cur);
788                 break;
789
790         case LFUN_SECTION_SELECT: {
791                 Buffer const & buf = *cur.buffer();
792                 pit_type const pit = cur.pit();
793                 ParagraphList & pars = buf.text().paragraphs();
794                 ParagraphList::iterator bgn = pars.begin();
795                 // The first paragraph of the area to be selected:
796                 ParagraphList::iterator start = boost::next(bgn, pit);
797                 // The final paragraph of area to be selected:
798                 ParagraphList::iterator finish = start;
799                 ParagraphList::iterator end = pars.end();
800
801                 int const thistoclevel = start->layout().toclevel;
802                 if (thistoclevel == Layout::NOT_IN_TOC)
803                         break;
804
805                 cur.pos() = 0;
806                 Cursor const old_cur = cur;
807                 needsUpdate |= cur.selHandle(true);
808
809                 // Move out (down) from this section header
810                 if (finish != end)
811                         ++finish;
812
813                 // Seek the one (on same level) below
814                 for (; finish != end; ++finish, ++cur.pit()) {
815                         int const toclevel = finish->layout().toclevel;
816                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
817                                 break;
818                 }
819                 cur.pos() = cur.lastpos();
820                 
821                 needsUpdate |= cur != old_cur;
822                 break;
823         }
824
825         case LFUN_WORD_RIGHT:
826         case LFUN_WORD_RIGHT_SELECT:
827                 if (lyxrc.visual_cursor) {
828                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_RIGHT_SELECT);
829                         needsUpdate |= cursorVisRightOneWord(cur);
830                         if (!needsUpdate && oldTopSlice == cur.top()
831                                         && cur.boundary() == oldBoundary) {
832                                 cur.undispatched();
833                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
834                         }
835                 } else {
836                         if (reverseDirectionNeeded(cur)) {
837                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
838                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
839                         } else {
840                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
841                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
842                         }
843                         dispatch(cur, cmd);
844                         return;
845                 }
846                 break;
847
848         case LFUN_WORD_FORWARD:
849         case LFUN_WORD_FORWARD_SELECT:
850                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_FORWARD_SELECT);
851                 needsUpdate |= cursorForwardOneWord(cur);
852
853                 if (!needsUpdate && oldTopSlice == cur.top()
854                                 && cur.boundary() == oldBoundary) {
855                         cur.undispatched();
856                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
857                 
858                         // we will probably be moving out the inset, so we should execute
859                         // the depm-mechanism, but only when the cursor has a place to 
860                         // go outside this inset, i.e. in a slice above.
861                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
862                                   && cur.pit() == cur.lastpit()) {
863                                 // The cursor hasn't changed yet. To give the 
864                                 // DEPM the possibility of doing something we must
865                                 // provide it with two different cursors.
866                                 Cursor dummy = cur;
867                                 dummy.pos() = dummy.pit() = 0;
868                                 if (cur.bv().checkDepm(dummy, cur)) {
869                                         cur.forceBufferUpdate();
870                                         // DEPM may have requested a screen update
871                                         cur.screenUpdateFlags(
872                                                 cur.screenUpdate() | dummy.screenUpdate());
873                                 }
874                         }
875                 }
876                 break;
877
878         case LFUN_WORD_LEFT:
879         case LFUN_WORD_LEFT_SELECT:
880                 if (lyxrc.visual_cursor) {
881                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_LEFT_SELECT);
882                         needsUpdate |= cursorVisLeftOneWord(cur);
883                         if (!needsUpdate && oldTopSlice == cur.top()
884                                         && cur.boundary() == oldBoundary) {
885                                 cur.undispatched();
886                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
887                         }
888                 } else {
889                         if (reverseDirectionNeeded(cur)) {
890                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
891                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
892                         } else {
893                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
894                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
895                         }
896                         dispatch(cur, cmd);
897                         return;
898                 }
899                 break;
900
901         case LFUN_WORD_BACKWARD:
902         case LFUN_WORD_BACKWARD_SELECT:
903                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_BACKWARD_SELECT);
904                 needsUpdate |= cursorBackwardOneWord(cur);
905         
906                 if (!needsUpdate && oldTopSlice == cur.top()
907                                 && cur.boundary() == oldBoundary) {
908                         cur.undispatched();
909                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
910                 
911                         // we will probably be moving out the inset, so we should execute
912                         // the depm-mechanism, but only when the cursor has a place to 
913                         // go outside this inset, i.e. in a slice above.
914                         if (cur.depth() > 1 && cur.pos() == 0 
915                                   && cur.pit() == 0) {
916                                 // The cursor hasn't changed yet. To give the 
917                                 // DEPM the possibility of doing something we must
918                                 // provide it with two different cursors.
919                                 Cursor dummy = cur;
920                                 dummy.pos() = cur.lastpos();
921                                 dummy.pit() = cur.lastpit();
922                                 if (cur.bv().checkDepm(dummy, cur)) {
923                                         cur.forceBufferUpdate();
924                                         // DEPM may have requested a screen update
925                                         cur.screenUpdateFlags(
926                                                 cur.screenUpdate() | dummy.screenUpdate());
927                                 }
928                         }
929                 }
930                 break;
931
932         case LFUN_WORD_SELECT: {
933                 selectWord(cur, WHOLE_WORD);
934                 finishChange(cur, true);
935                 break;
936         }
937
938         case LFUN_NEWLINE_INSERT: {
939                 InsetNewlineParams inp;
940                 docstring arg = cmd.argument();
941                 // this avoids a double undo
942                 // FIXME: should not be needed, ideally
943                 if (!cur.selection())
944                         cur.recordUndo();
945                 cap::replaceSelection(cur);
946                 if (arg == "linebreak")
947                         inp.kind = InsetNewlineParams::LINEBREAK;
948                 else
949                         inp.kind = InsetNewlineParams::NEWLINE;
950                 cur.insert(new InsetNewline(inp));
951                 cur.posForward();
952                 moveCursor(cur, false);
953                 break;
954         }
955
956         case LFUN_TAB_INSERT: {
957                 bool const multi_par_selection = cur.selection() &&
958                         cur.selBegin().pit() != cur.selEnd().pit();
959                 if (multi_par_selection) {
960                         // If there is a multi-paragraph selection, a tab is inserted
961                         // at the beginning of each paragraph.
962                         cur.recordUndoSelection();
963                         pit_type const pit_end = cur.selEnd().pit();
964                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
965                                 pars_[pit].insertChar(0, '\t', 
966                                                       bv->buffer().params().trackChanges);
967                                 // Update the selection pos to make sure the selection does not
968                                 // change as the inserted tab will increase the logical pos.
969                                 if (cur.realAnchor().pit() == pit)
970                                         cur.realAnchor().forwardPos();
971                                 if (cur.pit() == pit)
972                                         cur.forwardPos();
973                         }
974                         cur.finishUndo();
975                 } else {
976                         // Maybe we shouldn't allow tabs within a line, because they
977                         // are not (yet) aligned as one might do expect.
978                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
979                         dispatch(cur, cmd);     
980                 }
981                 break;
982         }
983
984         case LFUN_TAB_DELETE: {
985                 bool const tc = bv->buffer().params().trackChanges;
986                 if (cur.selection()) {
987                         // If there is a selection, a tab (if present) is removed from
988                         // the beginning of each paragraph.
989                         cur.recordUndoSelection();
990                         pit_type const pit_end = cur.selEnd().pit();
991                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
992                                 Paragraph & par = paragraphs()[pit];
993                                 if (par.empty())
994                                         continue;
995                                 char_type const c = par.getChar(0);
996                                 if (c == '\t' || c == ' ') {
997                                         // remove either 1 tab or 4 spaces.
998                                         int const n = (c == ' ' ? 4 : 1);
999                                         for (int i = 0; i < n 
1000                                                   && !par.empty() && par.getChar(0) == c; ++i) {
1001                                                 if (cur.pit() == pit)
1002                                                         cur.posBackward();
1003                                                 if (cur.realAnchor().pit() == pit 
1004                                                           && cur.realAnchor().pos() > 0 )
1005                                                         cur.realAnchor().backwardPos();
1006                                                 par.eraseChar(0, tc);
1007                                         }
1008                                 }
1009                         }
1010                         cur.finishUndo();
1011                 } else {
1012                         // If there is no selection, try to remove a tab or some spaces 
1013                         // before the position of the cursor.
1014                         Paragraph & par = paragraphs()[cur.pit()];
1015                         pos_type const pos = cur.pos();
1016                         
1017                         if (pos == 0)
1018                                 break;
1019                         
1020                         char_type const c = par.getChar(pos - 1);
1021                         cur.recordUndo();
1022                         if (c == '\t') {
1023                                 cur.posBackward();
1024                                 par.eraseChar(cur.pos(), tc);
1025                         } else
1026                                 for (int n_spaces = 0; 
1027                                      cur.pos() > 0
1028                                              && par.getChar(cur.pos() - 1) == ' ' 
1029                                              && n_spaces < 4;
1030                                      ++n_spaces) {
1031                                         cur.posBackward();
1032                                         par.eraseChar(cur.pos(), tc);
1033                                 }
1034                         cur.finishUndo();
1035                 }
1036                 break;
1037         }
1038
1039         case LFUN_CHAR_DELETE_FORWARD:
1040                 if (!cur.selection()) {
1041                         if (cur.pos() == cur.paragraph().size())
1042                                 // Par boundary, force full-screen update
1043                                 singleParUpdate = false;
1044                         needsUpdate |= erase(cur);
1045                         cur.resetAnchor();
1046                         // It is possible to make it a lot faster still
1047                         // just comment out the line below...
1048                 } else {
1049                         cutSelection(cur, true, false);
1050                         singleParUpdate = false;
1051                 }
1052                 moveCursor(cur, false);
1053                 break;
1054
1055         case LFUN_CHAR_DELETE_BACKWARD:
1056                 if (!cur.selection()) {
1057                         if (bv->getIntl().getTransManager().backspace()) {
1058                                 // Par boundary, full-screen update
1059                                 if (cur.pos() == 0)
1060                                         singleParUpdate = false;
1061                                 needsUpdate |= backspace(cur);
1062                                 cur.resetAnchor();
1063                                 // It is possible to make it a lot faster still
1064                                 // just comment out the line below...
1065                         }
1066                 } else {
1067                         cutSelection(cur, true, false);
1068                         singleParUpdate = false;
1069                 }
1070                 break;
1071
1072         case LFUN_PARAGRAPH_BREAK:
1073                 cap::replaceSelection(cur);
1074                 breakParagraph(cur, cmd.argument() == "inverse");
1075                 cur.resetAnchor();
1076                 break;
1077
1078         case LFUN_INSET_INSERT: {
1079                 cur.recordUndo();
1080
1081                 // We have to avoid triggering InstantPreview loading
1082                 // before inserting into the document. See bug #5626.
1083                 bool loaded = bv->buffer().isFullyLoaded();
1084                 bv->buffer().setFullyLoaded(false);
1085                 Inset * inset = createInset(&bv->buffer(), cmd);
1086                 bv->buffer().setFullyLoaded(loaded);
1087
1088                 if (inset) {
1089                         // FIXME (Abdel 01/02/2006):
1090                         // What follows would be a partial fix for bug 2154:
1091                         //   http://www.lyx.org/trac/ticket/2154
1092                         // This automatically put the label inset _after_ a
1093                         // numbered section. It should be possible to extend the mechanism
1094                         // to any kind of LateX environement.
1095                         // The correct way to fix that bug would be at LateX generation.
1096                         // I'll let the code here for reference as it could be used for some
1097                         // other feature like "automatic labelling".
1098                         /*
1099                         Paragraph & par = pars_[cur.pit()];
1100                         if (inset->lyxCode() == LABEL_CODE
1101                                 && par.layout().labeltype == LABEL_COUNTER) {
1102                                 // Go to the end of the paragraph
1103                                 // Warning: Because of Change-Tracking, the last
1104                                 // position is 'size()' and not 'size()-1':
1105                                 cur.pos() = par.size();
1106                                 // Insert a new paragraph
1107                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1108                                 dispatch(cur, fr);
1109                         }
1110                         */
1111                         if (cur.selection())
1112                                 cutSelection(cur, true, false);
1113                         cur.insert(inset);
1114                         if (inset->editable() && inset->asInsetText())
1115                                 inset->edit(cur, true);
1116                         else
1117                                 cur.posForward();
1118
1119                         // trigger InstantPreview now
1120                         if (inset->lyxCode() == EXTERNAL_CODE) {
1121                                 InsetExternal & ins =
1122                                         static_cast<InsetExternal &>(*inset);
1123                                 ins.updatePreview();
1124                         }
1125                 }
1126
1127                 break;
1128         }
1129
1130         case LFUN_INSET_DISSOLVE: {
1131                 if (dissolveInset(cur)) {
1132                         needsUpdate = true;
1133                         cur.forceBufferUpdate();
1134                 }
1135                 break;
1136         }
1137
1138         case LFUN_SET_GRAPHICS_GROUP: {
1139                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1140                 if (!ins)
1141                         break;
1142
1143                 cur.recordUndo();
1144
1145                 string id = to_utf8(cmd.argument());
1146                 string grp = graphics::getGroupParams(bv->buffer(), id);
1147                 InsetGraphicsParams tmp, inspar = ins->getParams();
1148
1149                 if (id.empty())
1150                         inspar.groupId = to_utf8(cmd.argument());
1151                 else {
1152                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1153                         tmp.filename = inspar.filename;
1154                         inspar = tmp;
1155                 }
1156
1157                 ins->setParams(inspar);
1158         }
1159
1160         case LFUN_SPACE_INSERT:
1161                 if (cur.paragraph().layout().free_spacing)
1162                         insertChar(cur, ' ');
1163                 else {
1164                         doInsertInset(cur, this, cmd, false, false);
1165                         cur.posForward();
1166                 }
1167                 moveCursor(cur, false);
1168                 break;
1169
1170         case LFUN_SPECIALCHAR_INSERT: {
1171                 string const name = to_utf8(cmd.argument());
1172                 if (name == "hyphenation")
1173                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1174                 else if (name == "ligature-break")
1175                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1176                 else if (name == "slash")
1177                         specialChar(cur, InsetSpecialChar::SLASH);
1178                 else if (name == "nobreakdash")
1179                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1180                 else if (name == "dots")
1181                         specialChar(cur, InsetSpecialChar::LDOTS);
1182                 else if (name == "end-of-sentence")
1183                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1184                 else if (name == "menu-separator")
1185                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1186                 else if (name.empty())
1187                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1188                 else
1189                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1190                 break;
1191         }
1192
1193         case LFUN_IPAMACRO_INSERT: {
1194                 string const arg = cmd.getArg(0);
1195                 if (arg == "deco") {
1196                         // Open the inset, and move the current selection
1197                         // inside it.
1198                         doInsertInset(cur, this, cmd, true, true);
1199                         cur.posForward();
1200                         // Some insets are numbered, others are shown in the outline pane so
1201                         // let's update the labels and the toc backend.
1202                         cur.forceBufferUpdate();
1203                         break;
1204                 }
1205                 if (arg == "tone-falling")
1206                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1207                 else if (arg == "tone-rising")
1208                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1209                 else if (arg == "tone-high-rising")
1210                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1211                 else if (arg == "tone-low-rising")
1212                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1213                 else if (arg == "tone-high-rising-falling")
1214                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1215                 else if (arg.empty())
1216                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1217                 else
1218                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1219                 break;
1220         }
1221
1222         case LFUN_WORD_UPCASE:
1223                 changeCase(cur, text_uppercase);
1224                 break;
1225
1226         case LFUN_WORD_LOWCASE:
1227                 changeCase(cur, text_lowercase);
1228                 break;
1229
1230         case LFUN_WORD_CAPITALIZE:
1231                 changeCase(cur, text_capitalization);
1232                 break;
1233
1234         case LFUN_CHARS_TRANSPOSE:
1235                 charsTranspose(cur);
1236                 break;
1237
1238         case LFUN_PASTE: {
1239                 cur.message(_("Paste"));
1240                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1241                 cap::replaceSelection(cur);
1242
1243                 // without argument?
1244                 string const arg = to_utf8(cmd.argument());
1245                 if (arg.empty()) {
1246                         if (theClipboard().isInternal())
1247                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1248                         else if (theClipboard().hasGraphicsContents() 
1249                                      && !theClipboard().hasTextContents())
1250                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1251                         else
1252                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1253                 } else if (isStrUnsignedInt(arg)) {
1254                         // we have a numerical argument
1255                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1256                                        convert<unsigned int>(arg));
1257                 } else {
1258                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1259                         if (arg == "pdf")
1260                                 type = Clipboard::PdfGraphicsType;
1261                         else if (arg == "png")
1262                                 type = Clipboard::PngGraphicsType;
1263                         else if (arg == "jpeg")
1264                                 type = Clipboard::JpegGraphicsType;
1265                         else if (arg == "linkback")
1266                                 type = Clipboard::LinkBackGraphicsType;
1267                         else if (arg == "emf")
1268                                 type = Clipboard::EmfGraphicsType;
1269                         else if (arg == "wmf")
1270                                 type = Clipboard::WmfGraphicsType;
1271
1272                         else
1273                                 LASSERT(false, /**/);
1274
1275                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1276                 }
1277
1278                 bv->buffer().errors("Paste");
1279                 cur.clearSelection(); // bug 393
1280                 cur.finishUndo();
1281                 break;
1282         }
1283
1284         case LFUN_CUT:
1285                 cutSelection(cur, true, true);
1286                 cur.message(_("Cut"));
1287                 break;
1288
1289         case LFUN_COPY:
1290                 copySelection(cur);
1291                 cur.message(_("Copy"));
1292                 break;
1293
1294         case LFUN_SERVER_GET_XY:
1295                 cur.message(from_utf8(
1296                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1297                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1298                 break;
1299
1300         case LFUN_SERVER_SET_XY: {
1301                 int x = 0;
1302                 int y = 0;
1303                 istringstream is(to_utf8(cmd.argument()));
1304                 is >> x >> y;
1305                 if (!is)
1306                         lyxerr << "SETXY: Could not parse coordinates in '"
1307                                << to_utf8(cmd.argument()) << endl;
1308                 else
1309                         tm->setCursorFromCoordinates(cur, x, y);
1310                 break;
1311         }
1312
1313         case LFUN_SERVER_GET_LAYOUT:
1314                 cur.message(cur.paragraph().layout().name());
1315                 break;
1316
1317         case LFUN_LAYOUT: {
1318                 docstring layout = cmd.argument();
1319                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1320
1321                 Paragraph const & para = cur.paragraph();
1322                 docstring const old_layout = para.layout().name();
1323                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1324
1325                 if (layout.empty())
1326                         layout = tclass.defaultLayoutName();
1327
1328                 if (owner_->forcePlainLayout())
1329                         // in this case only the empty layout is allowed
1330                         layout = tclass.plainLayoutName();
1331                 else if (para.usePlainLayout()) {
1332                         // in this case, default layout maps to empty layout
1333                         if (layout == tclass.defaultLayoutName())
1334                                 layout = tclass.plainLayoutName();
1335                 } else {
1336                         // otherwise, the empty layout maps to the default
1337                         if (layout == tclass.plainLayoutName())
1338                                 layout = tclass.defaultLayoutName();
1339                 }
1340
1341                 bool hasLayout = tclass.hasLayout(layout);
1342
1343                 // If the entry is obsolete, use the new one instead.
1344                 if (hasLayout) {
1345                         docstring const & obs = tclass[layout].obsoleted_by();
1346                         if (!obs.empty())
1347                                 layout = obs;
1348                 }
1349
1350                 if (!hasLayout) {
1351                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1352                                 from_utf8(N_(" not known")));
1353                         break;
1354                 }
1355
1356                 bool change_layout = (old_layout != layout);
1357
1358                 if (!change_layout && cur.selection() &&
1359                         cur.selBegin().pit() != cur.selEnd().pit())
1360                 {
1361                         pit_type spit = cur.selBegin().pit();
1362                         pit_type epit = cur.selEnd().pit() + 1;
1363                         while (spit != epit) {
1364                                 if (pars_[spit].layout().name() != old_layout) {
1365                                         change_layout = true;
1366                                         break;
1367                                 }
1368                                 ++spit;
1369                         }
1370                 }
1371
1372                 if (change_layout)
1373                         setLayout(cur, layout);
1374
1375                 break;
1376         }
1377
1378         case LFUN_CLIPBOARD_PASTE:
1379                 cap::replaceSelection(cur);
1380                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1381                                cmd.argument() == "paragraph");
1382                 bv->buffer().errors("Paste");
1383                 break;
1384
1385         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1386                 cap::replaceSelection(cur);
1387                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1388                 break;
1389
1390         case LFUN_PRIMARY_SELECTION_PASTE:
1391                 cap::replaceSelection(cur);
1392                 pasteString(cur, theSelection().get(),
1393                             cmd.argument() == "paragraph");
1394                 break;
1395
1396         case LFUN_SELECTION_PASTE:
1397                 // Copy the selection buffer to the clipboard stack,
1398                 // because we want it to appear in the "Edit->Paste
1399                 // recent" menu.
1400                 cap::replaceSelection(cur);
1401                 cap::copySelectionToStack();
1402                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1403                 bv->buffer().errors("Paste");
1404                 break;
1405
1406         case LFUN_UNICODE_INSERT: {
1407                 if (cmd.argument().empty())
1408                         break;
1409                 docstring hexstring = cmd.argument();
1410                 if (isHex(hexstring)) {
1411                         char_type c = hexToInt(hexstring);
1412                         if (c >= 32 && c < 0x10ffff) {
1413                                 lyxerr << "Inserting c: " << c << endl;
1414                                 docstring s = docstring(1, c);
1415                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1416                         }
1417                 }
1418                 break;
1419         }
1420
1421         case LFUN_QUOTE_INSERT: {
1422                 // this avoids a double undo
1423                 // FIXME: should not be needed, ideally
1424                 if (!cur.selection())
1425                         cur.recordUndo();
1426                 cap::replaceSelection(cur);
1427
1428                 Paragraph const & par = cur.paragraph();
1429                 pos_type pos = cur.pos();
1430
1431                 BufferParams const & bufparams = bv->buffer().params();
1432                 bool const hebrew = 
1433                         par.getFontSettings(bufparams, pos).language()->lang() == "hebrew";
1434                 bool const allow_inset_quote = !(par.isPassThru() || hebrew);
1435                 
1436                 if (allow_inset_quote) {
1437                         char_type c = ' ';
1438                         if (pos > 0 && (!cur.prevInset() || !cur.prevInset()->isSpace()))
1439                                 c = par.getChar(pos - 1);
1440                         string const arg = to_utf8(cmd.argument());
1441                         InsetQuotes::QuoteTimes const quote_type = (arg == "single")
1442                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes;
1443                         cur.insert(new InsetQuotes(cur.buffer(), c, quote_type));
1444                         cur.posForward();
1445                 } else {
1446                         // The cursor might have been invalidated by the replaceSelection.
1447                         cur.buffer()->changed(true);
1448                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1449                 }                       
1450                 break;
1451         }
1452
1453         case LFUN_DATE_INSERT: {
1454                 string const format = cmd.argument().empty()
1455                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1456                 string const time = formatted_time(current_time(), format);
1457                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1458                 break;
1459         }
1460
1461         case LFUN_MOUSE_TRIPLE:
1462                 if (cmd.button() == mouse_button::button1) {
1463                         tm->cursorHome(cur);
1464                         cur.resetAnchor();
1465                         tm->cursorEnd(cur);
1466                         cur.setSelection();
1467                         bv->cursor() = cur;
1468                 }
1469                 break;
1470
1471         case LFUN_MOUSE_DOUBLE:
1472                 if (cmd.button() == mouse_button::button1) {
1473                         selectWord(cur, WHOLE_WORD_STRICT);
1474                         bv->cursor() = cur;
1475                 }
1476                 break;
1477
1478         // Single-click on work area
1479         case LFUN_MOUSE_PRESS: {
1480                 // We are not marking a selection with the keyboard in any case.
1481                 Cursor & bvcur = cur.bv().cursor();
1482                 bvcur.setMark(false);
1483                 switch (cmd.button()) {
1484                 case mouse_button::button1:
1485                         // Set the cursor
1486                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1487                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1488                         if (bvcur.wordSelection())
1489                                 selectWord(bvcur, WHOLE_WORD);
1490                         break;
1491
1492                 case mouse_button::button2:
1493                         // Middle mouse pasting.
1494                         bv->mouseSetCursor(cur);
1495                         lyx::dispatch(
1496                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1497                                             "selection-paste ; primary-selection-paste paragraph"));
1498                         cur.noScreenUpdate();
1499                         break;
1500
1501                 case mouse_button::button3: {
1502                         // Don't do anything if we right-click a
1503                         // selection, a context menu will popup.
1504                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1505                             && cur < bvcur.selectionEnd()) {
1506                                 cur.noScreenUpdate();
1507                                 return;
1508                         }
1509                         if (!bv->mouseSetCursor(cur, false))
1510                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1511                         break;
1512                 }
1513
1514                 default:
1515                         break;
1516                 } // switch (cmd.button())
1517                 break;
1518         }
1519         case LFUN_MOUSE_MOTION: {
1520                 // Mouse motion with right or middle mouse do nothing for now.
1521                 if (cmd.button() != mouse_button::button1) {
1522                         cur.noScreenUpdate();
1523                         return;
1524                 }
1525                 // ignore motions deeper nested than the real anchor
1526                 Cursor & bvcur = cur.bv().cursor();
1527                 if (!bvcur.realAnchor().hasPart(cur)) {
1528                         cur.undispatched();
1529                         break;
1530                 }
1531                 CursorSlice old = bvcur.top();
1532
1533                 int const wh = bv->workHeight();
1534                 int const y = max(0, min(wh - 1, cmd.y()));
1535
1536                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1537                 cur.setTargetX(cmd.x());
1538                 if (cmd.y() >= wh)
1539                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1540                 else if (cmd.y() < 0)
1541                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1542                 // This is to allow jumping over large insets
1543                 if (cur.top() == old) {
1544                         if (cmd.y() >= wh)
1545                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1546                         else if (cmd.y() < 0)
1547                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1548                 }
1549                 // We continue with our existing selection or start a new one, so don't
1550                 // reset the anchor.
1551                 bvcur.setCursor(cur);
1552                 bvcur.setSelection(true);
1553                 if (cur.top() == old) {
1554                         // We didn't move one iota, so no need to update the screen.
1555                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1556                         //cur.noScreenUpdate();
1557                         return;
1558                 }
1559                 break;
1560         }
1561
1562         case LFUN_MOUSE_RELEASE:
1563                 switch (cmd.button()) {
1564                 case mouse_button::button1:
1565                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1566                         // If there is a new selection, update persistent selection;
1567                         // otherwise, single click does not clear persistent selection
1568                         // buffer.
1569                         if (cur.selection()) {
1570                                 // Finish selection. If double click,
1571                                 // cur is moved to the end of word by
1572                                 // selectWord but bvcur is current
1573                                 // mouse position.
1574                                 cur.bv().cursor().setSelection();
1575                                 // We might have removed an empty but drawn selection
1576                                 // (probably a margin)
1577                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1578                         } else
1579                                 cur.noScreenUpdate();
1580                         // FIXME: We could try to handle drag and drop of selection here.
1581                         return;
1582
1583                 case mouse_button::button2:
1584                         // Middle mouse pasting is handled at mouse press time,
1585                         // see LFUN_MOUSE_PRESS.
1586                         cur.noScreenUpdate();
1587                         return;
1588
1589                 case mouse_button::button3:
1590                         // Cursor was set at LFUN_MOUSE_PRESS time.
1591                         // FIXME: If there is a selection we could try to handle a special
1592                         // drag & drop context menu.
1593                         cur.noScreenUpdate();
1594                         return;
1595
1596                 case mouse_button::none:
1597                 case mouse_button::button4:
1598                 case mouse_button::button5:
1599                         break;
1600                 } // switch (cmd.button())
1601
1602                 break;
1603
1604         case LFUN_SELF_INSERT: {
1605                 if (cmd.argument().empty())
1606                         break;
1607
1608                 // Automatically delete the currently selected
1609                 // text and replace it with what is being
1610                 // typed in now. Depends on lyxrc settings
1611                 // "auto_region_delete", which defaults to
1612                 // true (on).
1613
1614                 if (lyxrc.auto_region_delete && cur.selection())
1615                         cutSelection(cur, false, false);
1616
1617                 cur.clearSelection();
1618
1619                 docstring::const_iterator cit = cmd.argument().begin();
1620                 docstring::const_iterator const end = cmd.argument().end();
1621                 for (; cit != end; ++cit)
1622                         bv->translateAndInsert(*cit, this, cur);
1623
1624                 cur.resetAnchor();
1625                 moveCursor(cur, false);
1626                 cur.markNewWordPosition();
1627                 bv->bookmarkEditPosition();
1628                 break;
1629         }
1630
1631         case LFUN_HYPERLINK_INSERT: {
1632                 InsetCommandParams p(HYPERLINK_CODE);
1633                 docstring content;
1634                 if (cur.selection()) {
1635                         content = cur.selectionAsString(false);
1636                         cutSelection(cur, true, false);
1637                 }
1638                 p["target"] = (cmd.argument().empty()) ?
1639                         content : cmd.argument();
1640                 string const data = InsetCommand::params2string(p);
1641                 if (p["target"].empty()) {
1642                         bv->showDialog("href", data);
1643                 } else {
1644                         FuncRequest fr(LFUN_INSET_INSERT, data);
1645                         dispatch(cur, fr);
1646                 }
1647                 break;
1648         }
1649
1650         case LFUN_LABEL_INSERT: {
1651                 InsetCommandParams p(LABEL_CODE);
1652                 // Try to generate a valid label
1653                 p["name"] = (cmd.argument().empty()) ?
1654                         cur.getPossibleLabel() :
1655                         cmd.argument();
1656                 string const data = InsetCommand::params2string(p);
1657
1658                 if (cmd.argument().empty()) {
1659                         bv->showDialog("label", data);
1660                 } else {
1661                         FuncRequest fr(LFUN_INSET_INSERT, data);
1662                         dispatch(cur, fr);
1663                 }
1664                 break;
1665         }
1666
1667         case LFUN_INFO_INSERT: {
1668                 Inset * inset;
1669                 if (cmd.argument().empty() && cur.selection()) {
1670                         // if command argument is empty use current selection as parameter.
1671                         docstring ds = cur.selectionAsString(false);
1672                         cutSelection(cur, true, false);
1673                         FuncRequest cmd0(cmd, ds);
1674                         inset = createInset(cur.buffer(), cmd0);
1675                 } else {
1676                         inset = createInset(cur.buffer(), cmd);
1677                 }
1678                 if (!inset)
1679                         break;
1680                 cur.recordUndo();
1681                 insertInset(cur, inset);
1682                 cur.posForward();
1683                 break;
1684         }
1685         case LFUN_CAPTION_INSERT:
1686         case LFUN_FOOTNOTE_INSERT:
1687         case LFUN_NOTE_INSERT:
1688         case LFUN_FLEX_INSERT:
1689         case LFUN_BOX_INSERT:
1690         case LFUN_BRANCH_INSERT:
1691         case LFUN_PHANTOM_INSERT:
1692         case LFUN_ERT_INSERT:
1693         case LFUN_LISTING_INSERT:
1694         case LFUN_MARGINALNOTE_INSERT:
1695         case LFUN_ARGUMENT_INSERT:
1696         case LFUN_INDEX_INSERT:
1697         case LFUN_PREVIEW_INSERT:
1698         case LFUN_SCRIPT_INSERT:
1699         case LFUN_IPA_INSERT:
1700                 // Open the inset, and move the current selection
1701                 // inside it.
1702                 doInsertInset(cur, this, cmd, true, true);
1703                 cur.posForward();
1704                 // Some insets are numbered, others are shown in the outline pane so
1705                 // let's update the labels and the toc backend.
1706                 cur.forceBufferUpdate();
1707                 break;
1708
1709         case LFUN_TABULAR_INSERT:
1710                 // if there were no arguments, just open the dialog
1711                 if (doInsertInset(cur, this, cmd, false, true))
1712                         cur.posForward();
1713                 else
1714                         bv->showDialog("tabularcreate");
1715
1716                 break;
1717
1718         case LFUN_FLOAT_INSERT:
1719         case LFUN_FLOAT_WIDE_INSERT:
1720         case LFUN_WRAP_INSERT: {
1721                 // will some content be moved into the inset?
1722                 bool const content = cur.selection();
1723                 // does the content consist of multiple paragraphs?
1724                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
1725
1726                 doInsertInset(cur, this, cmd, true, true);
1727                 cur.posForward();
1728
1729                 // If some single-par content is moved into the inset,
1730                 // doInsertInset puts the cursor outside the inset.
1731                 // To insert the caption we put it back into the inset.
1732                 // FIXME cleanup doInsertInset to avoid such dances!
1733                 if (content && singlepar)
1734                         cur.backwardPos();
1735
1736                 ParagraphList & pars = cur.text()->paragraphs();
1737
1738                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1739
1740                 // add a separate paragraph for the caption inset
1741                 pars.push_back(Paragraph());
1742                 pars.back().setInsetOwner(&cur.text()->inset());
1743                 pars.back().setPlainOrDefaultLayout(tclass);
1744                 int cap_pit = pars.size() - 1;
1745
1746                 // if an empty inset was created, we create an additional empty
1747                 // paragraph at the bottom so that the user can choose where to put
1748                 // the graphics (or table).
1749                 if (!content) {
1750                         pars.push_back(Paragraph());
1751                         pars.back().setInsetOwner(&cur.text()->inset());
1752                         pars.back().setPlainOrDefaultLayout(tclass);
1753                 }
1754
1755                 // reposition the cursor to the caption
1756                 cur.pit() = cap_pit;
1757                 cur.pos() = 0;
1758                 // FIXME: This Text/Cursor dispatch handling is a mess!
1759                 // We cannot use Cursor::dispatch here it needs access to up to
1760                 // date metrics.
1761                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1762                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1763                 cur.forceBufferUpdate();
1764                 cur.screenUpdateFlags(Update::Force);
1765                 // FIXME: When leaving the Float (or Wrap) inset we should
1766                 // delete any empty paragraph left above or below the
1767                 // caption.
1768                 break;
1769         }
1770
1771         case LFUN_NOMENCL_INSERT: {
1772                 InsetCommandParams p(NOMENCL_CODE);
1773                 if (cmd.argument().empty())
1774                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1775                 else
1776                         p["symbol"] = cmd.argument();
1777                 string const data = InsetCommand::params2string(p);
1778                 bv->showDialog("nomenclature", data);
1779                 break;
1780         }
1781
1782         case LFUN_INDEX_PRINT: {
1783                 InsetCommandParams p(INDEX_PRINT_CODE);
1784                 if (cmd.argument().empty())
1785                         p["type"] = from_ascii("idx");
1786                 else
1787                         p["type"] = cmd.argument();
1788                 string const data = InsetCommand::params2string(p);
1789                 FuncRequest fr(LFUN_INSET_INSERT, data);
1790                 dispatch(cur, fr);
1791                 break;
1792         }
1793         
1794         case LFUN_NOMENCL_PRINT:
1795         case LFUN_NEWPAGE_INSERT:
1796                 // do nothing fancy
1797                 doInsertInset(cur, this, cmd, false, false);
1798                 cur.posForward();
1799                 break;
1800
1801         case LFUN_DEPTH_DECREMENT:
1802                 changeDepth(cur, DEC_DEPTH);
1803                 break;
1804
1805         case LFUN_DEPTH_INCREMENT:
1806                 changeDepth(cur, INC_DEPTH);
1807                 break;
1808
1809         case LFUN_MATH_DISPLAY:
1810                 mathDispatch(cur, cmd, true);
1811                 break;
1812
1813         case LFUN_REGEXP_MODE:
1814                 regexpDispatch(cur, cmd);
1815                 break;
1816
1817         case LFUN_MATH_MODE:
1818                 if (cmd.argument() == "on")
1819                         // don't pass "on" as argument
1820                         // (it would appear literally in the first cell)
1821                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1822                 else
1823                         mathDispatch(cur, cmd, false);
1824                 break;
1825
1826         case LFUN_MATH_MACRO:
1827                 if (cmd.argument().empty())
1828                         cur.errorMessage(from_utf8(N_("Missing argument")));
1829                 else {
1830                         cur.recordUndo();
1831                         string s = to_utf8(cmd.argument());
1832                         string const s1 = token(s, ' ', 1);
1833                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1834                         string const s2 = token(s, ' ', 2);
1835                         MacroType type = MacroTypeNewcommand;
1836                         if (s2 == "def")
1837                                 type = MacroTypeDef;
1838                         MathMacroTemplate * inset = new MathMacroTemplate(cur.buffer(),
1839                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
1840                         inset->setBuffer(bv->buffer());
1841                         insertInset(cur, inset);
1842
1843                         // enter macro inset and select the name
1844                         cur.push(*inset);
1845                         cur.top().pos() = cur.top().lastpos();
1846                         cur.resetAnchor();
1847                         cur.setSelection(true);
1848                         cur.top().pos() = 0;
1849                 }
1850                 break;
1851
1852         // passthrough hat and underscore outside mathed:
1853         case LFUN_MATH_SUBSCRIPT:
1854                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1855                 break;
1856         case LFUN_MATH_SUPERSCRIPT:
1857                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1858                 break;
1859
1860         case LFUN_MATH_INSERT:
1861         case LFUN_MATH_AMS_MATRIX:
1862         case LFUN_MATH_MATRIX:
1863         case LFUN_MATH_DELIM:
1864         case LFUN_MATH_BIGDELIM: {
1865                 cur.recordUndo();
1866                 cap::replaceSelection(cur);
1867                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
1868                 checkAndActivateInset(cur, true);
1869                 LASSERT(cur.inMathed(), /**/);
1870                 cur.dispatch(cmd);
1871                 break;
1872         }
1873
1874         case LFUN_FONT_EMPH: {
1875                 Font font(ignore_font, ignore_language);
1876                 font.fontInfo().setEmph(FONT_TOGGLE);
1877                 toggleAndShow(cur, this, font);
1878                 break;
1879         }
1880
1881         case LFUN_FONT_ITAL: {
1882                 Font font(ignore_font, ignore_language);
1883                 font.fontInfo().setShape(ITALIC_SHAPE);
1884                 toggleAndShow(cur, this, font);
1885                 break;
1886         }
1887
1888         case LFUN_FONT_BOLD:
1889         case LFUN_FONT_BOLDSYMBOL: {
1890                 Font font(ignore_font, ignore_language);
1891                 font.fontInfo().setSeries(BOLD_SERIES);
1892                 toggleAndShow(cur, this, font);
1893                 break;
1894         }
1895
1896         case LFUN_FONT_NOUN: {
1897                 Font font(ignore_font, ignore_language);
1898                 font.fontInfo().setNoun(FONT_TOGGLE);
1899                 toggleAndShow(cur, this, font);
1900                 break;
1901         }
1902
1903         case LFUN_FONT_TYPEWRITER: {
1904                 Font font(ignore_font, ignore_language);
1905                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1906                 toggleAndShow(cur, this, font);
1907                 break;
1908         }
1909
1910         case LFUN_FONT_SANS: {
1911                 Font font(ignore_font, ignore_language);
1912                 font.fontInfo().setFamily(SANS_FAMILY);
1913                 toggleAndShow(cur, this, font);
1914                 break;
1915         }
1916
1917         case LFUN_FONT_ROMAN: {
1918                 Font font(ignore_font, ignore_language);
1919                 font.fontInfo().setFamily(ROMAN_FAMILY);
1920                 toggleAndShow(cur, this, font);
1921                 break;
1922         }
1923
1924         case LFUN_FONT_DEFAULT: {
1925                 Font font(inherit_font, ignore_language);
1926                 toggleAndShow(cur, this, font);
1927                 break;
1928         }
1929
1930         case LFUN_FONT_STRIKEOUT: {
1931                 Font font(ignore_font, ignore_language);
1932                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1933                 toggleAndShow(cur, this, font);
1934                 break;
1935         }
1936
1937         case LFUN_FONT_UULINE: {
1938                 Font font(ignore_font, ignore_language);
1939                 font.fontInfo().setUuline(FONT_TOGGLE);
1940                 toggleAndShow(cur, this, font);
1941                 break;
1942         }
1943
1944         case LFUN_FONT_UWAVE: {
1945                 Font font(ignore_font, ignore_language);
1946                 font.fontInfo().setUwave(FONT_TOGGLE);
1947                 toggleAndShow(cur, this, font);
1948                 break;
1949         }
1950
1951         case LFUN_FONT_UNDERLINE: {
1952                 Font font(ignore_font, ignore_language);
1953                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1954                 toggleAndShow(cur, this, font);
1955                 break;
1956         }
1957
1958         case LFUN_FONT_SIZE: {
1959                 Font font(ignore_font, ignore_language);
1960                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1961                 toggleAndShow(cur, this, font);
1962                 break;
1963         }
1964
1965         case LFUN_LANGUAGE: {
1966                 string const lang_arg = cmd.getArg(0);
1967                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
1968                 Language const * lang =
1969                         reset ? reset_language
1970                               : languages.getLanguage(lang_arg);
1971                 // we allow reset_language, which is 0, but only if it
1972                 // was requested via empty or "reset" arg.
1973                 if (!lang && !reset)
1974                         break;
1975                 bool const toggle = (cmd.getArg(1) != "set");
1976                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
1977                 Font font(ignore_font, lang);
1978                 toggleAndShow(cur, this, font, toggle);
1979                 break;
1980         }
1981
1982         case LFUN_TEXTSTYLE_APPLY:
1983                 toggleAndShow(cur, this, freefont, toggleall);
1984                 cur.message(_("Character set"));
1985                 break;
1986
1987         // Set the freefont using the contents of \param data dispatched from
1988         // the frontends and apply it at the current cursor location.
1989         case LFUN_TEXTSTYLE_UPDATE: {
1990                 Font font;
1991                 bool toggle;
1992                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1993                         freefont = font;
1994                         toggleall = toggle;
1995                         toggleAndShow(cur, this, freefont, toggleall);
1996                         cur.message(_("Character set"));
1997                 } else {
1998                         lyxerr << "Argument not ok";
1999                 }
2000                 break;
2001         }
2002
2003         case LFUN_FINISHED_LEFT:
2004                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2005                 // We're leaving an inset, going left. If the inset is LTR, we're
2006                 // leaving from the front, so we should not move (remain at --- but
2007                 // not in --- the inset). If the inset is RTL, move left, without
2008                 // entering the inset itself; i.e., move to after the inset.
2009                 if (cur.paragraph().getFontSettings(
2010                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2011                         cursorVisLeft(cur, true);
2012                 break;
2013
2014         case LFUN_FINISHED_RIGHT:
2015                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2016                 // We're leaving an inset, going right. If the inset is RTL, we're
2017                 // leaving from the front, so we should not move (remain at --- but
2018                 // not in --- the inset). If the inset is LTR, move right, without
2019                 // entering the inset itself; i.e., move to after the inset.
2020                 if (!cur.paragraph().getFontSettings(
2021                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2022                         cursorVisRight(cur, true);
2023                 break;
2024
2025         case LFUN_FINISHED_BACKWARD:
2026                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2027                 break;
2028
2029         case LFUN_FINISHED_FORWARD:
2030                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2031                 ++cur.pos();
2032                 cur.setCurrentFont();
2033                 break;
2034
2035         case LFUN_LAYOUT_PARAGRAPH: {
2036                 string data;
2037                 params2string(cur.paragraph(), data);
2038                 data = "show\n" + data;
2039                 bv->showDialog("paragraph", data);
2040                 break;
2041         }
2042
2043         case LFUN_PARAGRAPH_UPDATE: {
2044                 string data;
2045                 params2string(cur.paragraph(), data);
2046
2047                 // Will the paragraph accept changes from the dialog?
2048                 bool const accept =
2049                         cur.inset().allowParagraphCustomization(cur.idx());
2050
2051                 data = "update " + convert<string>(accept) + '\n' + data;
2052                 bv->updateDialog("paragraph", data);
2053                 break;
2054         }
2055
2056         case LFUN_ACCENT_UMLAUT:
2057         case LFUN_ACCENT_CIRCUMFLEX:
2058         case LFUN_ACCENT_GRAVE:
2059         case LFUN_ACCENT_ACUTE:
2060         case LFUN_ACCENT_TILDE:
2061         case LFUN_ACCENT_CEDILLA:
2062         case LFUN_ACCENT_MACRON:
2063         case LFUN_ACCENT_DOT:
2064         case LFUN_ACCENT_UNDERDOT:
2065         case LFUN_ACCENT_UNDERBAR:
2066         case LFUN_ACCENT_CARON:
2067         case LFUN_ACCENT_BREVE:
2068         case LFUN_ACCENT_TIE:
2069         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2070         case LFUN_ACCENT_CIRCLE:
2071         case LFUN_ACCENT_OGONEK:
2072                 theApp()->handleKeyFunc(cmd.action());
2073                 if (!cmd.argument().empty())
2074                         // FIXME: Are all these characters encoded in one byte in utf8?
2075                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2076                 cur.screenUpdateFlags(Update::FitCursor);
2077                 break;
2078
2079         case LFUN_FLOAT_LIST_INSERT: {
2080                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2081                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2082                         cur.recordUndo();
2083                         if (cur.selection())
2084                                 cutSelection(cur, true, false);
2085                         breakParagraph(cur);
2086
2087                         if (cur.lastpos() != 0) {
2088                                 cursorBackward(cur);
2089                                 breakParagraph(cur);
2090                         }
2091
2092                         docstring const laystr = cur.inset().usePlainLayout() ?
2093                                 tclass.plainLayoutName() :
2094                                 tclass.defaultLayoutName();
2095                         setLayout(cur, laystr);
2096                         ParagraphParameters p;
2097                         // FIXME If this call were replaced with one to clearParagraphParams(),
2098                         // then we could get rid of this method altogether.
2099                         setParagraphs(cur, p);
2100                         // FIXME This should be simplified when InsetFloatList takes a
2101                         // Buffer in its constructor.
2102                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2103                         ifl->setBuffer(bv->buffer());
2104                         insertInset(cur, ifl);
2105                         cur.posForward();
2106                 } else {
2107                         lyxerr << "Non-existent float type: "
2108                                << to_utf8(cmd.argument()) << endl;
2109                 }
2110                 break;
2111         }
2112
2113         case LFUN_CHANGE_ACCEPT: {
2114                 acceptOrRejectChanges(cur, ACCEPT);
2115                 break;
2116         }
2117
2118         case LFUN_CHANGE_REJECT: {
2119                 acceptOrRejectChanges(cur, REJECT);
2120                 break;
2121         }
2122
2123         case LFUN_THESAURUS_ENTRY: {
2124                 docstring arg = cmd.argument();
2125                 if (arg.empty()) {
2126                         arg = cur.selectionAsString(false);
2127                         // FIXME
2128                         if (arg.size() > 100 || arg.empty()) {
2129                                 // Get word or selection
2130                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2131                                 arg = cur.selectionAsString(false);
2132                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2133                         }
2134                 }
2135                 bv->showDialog("thesaurus", to_utf8(arg));
2136                 break;
2137         }
2138
2139         case LFUN_SPELLING_ADD: {
2140                 docstring word = from_utf8(cmd.getArg(0));
2141                 Language * lang;
2142                 if (word.empty()) {
2143                         word = cur.selectionAsString(false);
2144                         // FIXME
2145                         if (word.size() > 100 || word.empty()) {
2146                                 // Get word or selection
2147                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2148                                 word = cur.selectionAsString(false);
2149                         }
2150                         lang = const_cast<Language *>(cur.getFont().language());
2151                 } else
2152                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2153                 WordLangTuple wl(word, lang);
2154                 theSpellChecker()->insert(wl);
2155                 break;
2156         }
2157
2158         case LFUN_SPELLING_IGNORE: {
2159                 docstring word = from_utf8(cmd.getArg(0));
2160                 Language * lang;
2161                 if (word.empty()) {
2162                         word = cur.selectionAsString(false);
2163                         // FIXME
2164                         if (word.size() > 100 || word.empty()) {
2165                                 // Get word or selection
2166                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2167                                 word = cur.selectionAsString(false);
2168                         }
2169                         lang = const_cast<Language *>(cur.getFont().language());
2170                 } else
2171                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2172                 WordLangTuple wl(word, lang);
2173                 theSpellChecker()->accept(wl);
2174                 break;
2175         }
2176
2177         case LFUN_SPELLING_REMOVE: {
2178                 docstring word = from_utf8(cmd.getArg(0));
2179                 Language * lang;
2180                 if (word.empty()) {
2181                         word = cur.selectionAsString(false);
2182                         // FIXME
2183                         if (word.size() > 100 || word.empty()) {
2184                                 // Get word or selection
2185                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2186                                 word = cur.selectionAsString(false);
2187                         }
2188                         lang = const_cast<Language *>(cur.getFont().language());
2189                 } else
2190                         lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
2191                 WordLangTuple wl(word, lang);
2192                 theSpellChecker()->remove(wl);
2193                 break;
2194         }
2195
2196         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2197                 // Given data, an encoding of the ParagraphParameters
2198                 // generated in the Paragraph dialog, this function sets
2199                 // the current paragraph, or currently selected paragraphs,
2200                 // appropriately.
2201                 // NOTE: This function overrides all existing settings.
2202                 setParagraphs(cur, cmd.argument());
2203                 cur.message(_("Paragraph layout set"));
2204                 break;
2205         }
2206
2207         case LFUN_PARAGRAPH_PARAMS: {
2208                 // Given data, an encoding of the ParagraphParameters as we'd
2209                 // find them in a LyX file, this function modifies the current paragraph,
2210                 // or currently selected paragraphs.
2211                 // NOTE: This function only modifies, and does not override, existing
2212                 // settings.
2213                 setParagraphs(cur, cmd.argument(), true);
2214                 cur.message(_("Paragraph layout set"));
2215                 break;
2216         }
2217
2218         case LFUN_ESCAPE:
2219                 if (cur.selection()) {
2220                         cur.setSelection(false);
2221                 } else {
2222                         cur.undispatched();
2223                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2224                         // correct, but I'm not 100% sure -- dov, 071019
2225                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2226                 }
2227                 break;
2228
2229         case LFUN_OUTLINE_UP:
2230                 outline(OutlineUp, cur);
2231                 setCursor(cur, cur.pit(), 0);
2232                 cur.forceBufferUpdate();
2233                 needsUpdate = true;
2234                 break;
2235
2236         case LFUN_OUTLINE_DOWN:
2237                 outline(OutlineDown, cur);
2238                 setCursor(cur, cur.pit(), 0);
2239                 cur.forceBufferUpdate();
2240                 needsUpdate = true;
2241                 break;
2242
2243         case LFUN_OUTLINE_IN:
2244                 outline(OutlineIn, cur);
2245                 cur.forceBufferUpdate();
2246                 needsUpdate = true;
2247                 break;
2248
2249         case LFUN_OUTLINE_OUT:
2250                 outline(OutlineOut, cur);
2251                 cur.forceBufferUpdate();
2252                 needsUpdate = true;
2253                 break;
2254
2255         default:
2256                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2257                 cur.undispatched();
2258                 break;
2259         }
2260
2261         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2262
2263         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2264                 // Check for misspelled text
2265                 // The redraw is useful because of the painting of
2266                 // misspelled markers depends on the cursor position.
2267                 // Trigger a redraw for cursor moves inside misspelled text.
2268                 if (!cur.inTexted()) {
2269                         // move from regular text to math
2270                         needsUpdate = last_misspelled;
2271                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2272                         // move inside regular text
2273                         needsUpdate = last_misspelled
2274                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2275                 }
2276         }
2277
2278         // FIXME: The cursor flag is reset two lines below
2279         // so we need to check here if some of the LFUN did touch that.
2280         // for now only Text::erase() and Text::backspace() do that.
2281         // The plan is to verify all the LFUNs and then to remove this
2282         // singleParUpdate boolean altogether.
2283         if (cur.result().screenUpdate() & Update::Force) {
2284                 singleParUpdate = false;
2285                 needsUpdate = true;
2286         }
2287
2288         // FIXME: the following code should go in favor of fine grained
2289         // update flag treatment.
2290         if (singleParUpdate) {
2291                 // Inserting characters does not change par height in general. So, try
2292                 // to update _only_ this paragraph. BufferView will detect if a full
2293                 // metrics update is needed anyway.
2294                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2295                 return;
2296         }
2297         if (!needsUpdate
2298             && &oldTopSlice.inset() == &cur.inset()
2299             && oldTopSlice.idx() == cur.idx()
2300             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2301             && !cur.selection())
2302                 // FIXME: it would be better if we could just do this
2303                 //
2304                 //if (cur.result().update() != Update::FitCursor)
2305                 //      cur.noScreenUpdate();
2306                 //
2307                 // But some LFUNs do not set Update::FitCursor when needed, so we
2308                 // do it for all. This is not very harmfull as FitCursor will provoke
2309                 // a full redraw only if needed but still, a proper review of all LFUN
2310                 // should be done and this needsUpdate boolean can then be removed.
2311                 cur.screenUpdateFlags(Update::FitCursor);
2312         else
2313                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2314 }
2315
2316
2317 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2318                         FuncStatus & flag) const
2319 {
2320         LASSERT(cur.text() == this, /**/);
2321
2322         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2323         bool enable = true;
2324         InsetCode code = NO_CODE;
2325
2326         switch (cmd.action()) {
2327
2328         case LFUN_DEPTH_DECREMENT:
2329                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2330                 break;
2331
2332         case LFUN_DEPTH_INCREMENT:
2333                 enable = changeDepthAllowed(cur, INC_DEPTH);
2334                 break;
2335
2336         case LFUN_APPENDIX:
2337                 // FIXME We really should not allow this to be put, e.g.,
2338                 // in a footnote, or in ERT. But it would make sense in a 
2339                 // branch, so I'm not sure what to do.
2340                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2341                 break;
2342
2343         case LFUN_DIALOG_SHOW_NEW_INSET:
2344                 if (cmd.argument() == "bibitem")
2345                         code = BIBITEM_CODE;
2346                 else if (cmd.argument() == "bibtex") {
2347                         code = BIBTEX_CODE;
2348                         // not allowed in description items
2349                         enable = !inDescriptionItem(cur);
2350                 }
2351                 else if (cmd.argument() == "box")
2352                         code = BOX_CODE;
2353                 else if (cmd.argument() == "branch")
2354                         code = BRANCH_CODE;
2355                 else if (cmd.argument() == "citation")
2356                         code = CITE_CODE;
2357                 else if (cmd.argument() == "ert")
2358                         code = ERT_CODE;
2359                 else if (cmd.argument() == "external")
2360                         code = EXTERNAL_CODE;
2361                 else if (cmd.argument() == "float")
2362                         code = FLOAT_CODE;
2363                 else if (cmd.argument() == "graphics")
2364                         code = GRAPHICS_CODE;
2365                 else if (cmd.argument() == "href")
2366                         code = HYPERLINK_CODE;
2367                 else if (cmd.argument() == "include")
2368                         code = INCLUDE_CODE;
2369                 else if (cmd.argument() == "index")
2370                         code = INDEX_CODE;
2371                 else if (cmd.argument() == "index_print")
2372                         code = INDEX_PRINT_CODE;
2373                 else if (cmd.argument() == "nomenclature")
2374                         code = NOMENCL_CODE;
2375                 else if (cmd.argument() == "nomencl_print")
2376                         code = NOMENCL_PRINT_CODE;
2377                 else if (cmd.argument() == "label")
2378                         code = LABEL_CODE;
2379                 else if (cmd.argument() == "line")
2380                         code = LINE_CODE;
2381                 else if (cmd.argument() == "note")
2382                         code = NOTE_CODE;
2383                 else if (cmd.argument() == "phantom")
2384                         code = PHANTOM_CODE;
2385                 else if (cmd.argument() == "ref")
2386                         code = REF_CODE;
2387                 else if (cmd.argument() == "space")
2388                         code = SPACE_CODE;
2389                 else if (cmd.argument() == "toc")
2390                         code = TOC_CODE;
2391                 else if (cmd.argument() == "vspace")
2392                         code = VSPACE_CODE;
2393                 else if (cmd.argument() == "wrap")
2394                         code = WRAP_CODE;
2395                 else if (cmd.argument() == "listings")
2396                         code = LISTINGS_CODE;
2397                 break;
2398
2399         case LFUN_ERT_INSERT:
2400                 code = ERT_CODE;
2401                 break;
2402         case LFUN_LISTING_INSERT:
2403                 code = LISTINGS_CODE;
2404                 // not allowed in description items
2405                 enable = !inDescriptionItem(cur);
2406                 break;
2407         case LFUN_FOOTNOTE_INSERT:
2408                 code = FOOT_CODE;
2409                 break;
2410         case LFUN_TABULAR_INSERT:
2411                 code = TABULAR_CODE;
2412                 break;
2413         case LFUN_MARGINALNOTE_INSERT:
2414                 code = MARGIN_CODE;
2415                 break;
2416         case LFUN_FLOAT_INSERT:
2417         case LFUN_FLOAT_WIDE_INSERT:
2418                 // FIXME: If there is a selection, we should check whether there
2419                 // are floats in the selection, but this has performance issues, see
2420                 // LFUN_CHANGE_ACCEPT/REJECT.
2421                 code = FLOAT_CODE;
2422                 if (inDescriptionItem(cur))
2423                         // not allowed in description items
2424                         enable = false;
2425                 else {
2426                         InsetCode const inset_code = cur.inset().lyxCode();
2427
2428                         // algorithm floats cannot be put in another float
2429                         if (to_utf8(cmd.argument()) == "algorithm") {
2430                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2431                                 break;
2432                         }
2433
2434                         // for figures and tables: only allow in another
2435                         // float or wrap if it is of the same type and
2436                         // not a subfloat already
2437                         if(cur.inset().lyxCode() == code) {
2438                                 InsetFloat const & ins =
2439                                         static_cast<InsetFloat const &>(cur.inset());
2440                                 enable = ins.params().type == to_utf8(cmd.argument())
2441                                         && !ins.params().subfloat;
2442                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2443                                 InsetWrap const & ins =
2444                                         static_cast<InsetWrap const &>(cur.inset());
2445                                 enable = ins.params().type == to_utf8(cmd.argument());
2446                         }
2447                 }
2448                 break;
2449         case LFUN_WRAP_INSERT:
2450                 code = WRAP_CODE;
2451                 // not allowed in description items
2452                 enable = !inDescriptionItem(cur);
2453                 break;
2454         case LFUN_FLOAT_LIST_INSERT: {
2455                 code = FLOAT_LIST_CODE;
2456                 // not allowed in description items
2457                 enable = !inDescriptionItem(cur);
2458                 if (enable) {
2459                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2460                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2461                         // make sure we know about such floats
2462                         if (cit == floats.end() ||
2463                                         // and that we know how to generate a list of them
2464                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2465                                 flag.setUnknown(true);
2466                                 // probably not necessary, but...
2467                                 enable = false;
2468                         }
2469                 }
2470                 break;
2471         }
2472         case LFUN_CAPTION_INSERT:
2473                 code = CAPTION_CODE;
2474                 // not allowed in description items
2475                 enable = !inDescriptionItem(cur);
2476                 break;
2477         case LFUN_NOTE_INSERT:
2478                 code = NOTE_CODE;
2479                 // in commands (sections etc.) and description items,
2480                 // only Notes are allowed
2481                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2482                           (!cur.paragraph().layout().isCommand()
2483                            && !inDescriptionItem(cur)));
2484                 break;
2485         case LFUN_FLEX_INSERT: {
2486                 code = FLEX_CODE;
2487                 string s = cmd.getArg(0);
2488                 InsetLayout il =
2489                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2490                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2491                     il.lyxtype() != InsetLayout::CUSTOM &&
2492                     il.lyxtype() != InsetLayout::ELEMENT &&
2493                     il.lyxtype ()!= InsetLayout::STANDARD)
2494                         enable = false;
2495                 break;
2496                 }
2497         case LFUN_BOX_INSERT:
2498                 code = BOX_CODE;
2499                 break;
2500         case LFUN_BRANCH_INSERT:
2501                 code = BRANCH_CODE;
2502                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2503                     && cur.buffer()->params().branchlist().empty())
2504                         enable = false;
2505                 break;
2506         case LFUN_IPA_INSERT:
2507                 code = IPA_CODE;
2508                 break;
2509         case LFUN_PHANTOM_INSERT:
2510                 code = PHANTOM_CODE;
2511                 break;
2512         case LFUN_LABEL_INSERT:
2513                 code = LABEL_CODE;
2514                 break;
2515         case LFUN_INFO_INSERT:
2516                 code = INFO_CODE;
2517                 break;
2518         case LFUN_ARGUMENT_INSERT: {
2519                 code = ARG_CODE;
2520                 string const arg = cmd.getArg(0);
2521                 if (arg.empty()) {
2522                         enable = false;
2523                         break;
2524                 }
2525                 Layout const & lay = cur.paragraph().layout();
2526                 Layout::LaTeXArgMap args = lay.latexargs();
2527                 Layout::LaTeXArgMap::const_iterator const lait =
2528                                 args.find(convert<unsigned int>(arg));
2529                 if (lait != args.end()) {
2530                         enable = true;
2531                         InsetList::const_iterator it = cur.paragraph().insetList().begin();
2532                         InsetList::const_iterator end = cur.paragraph().insetList().end();
2533                         for (; it != end; ++it) {
2534                                 if (it->inset->lyxCode() == ARG_CODE) {
2535                                         InsetArgument const * ins =
2536                                                 static_cast<InsetArgument const *>(it->inset);
2537                                         if (ins->name() == arg) {
2538                                                 // we have this already
2539                                                 enable = false;
2540                                                 break;
2541                                         }
2542                                 }
2543                         }
2544                 } else
2545                         enable = false;
2546                 break;
2547         }
2548         case LFUN_INDEX_INSERT:
2549                 code = INDEX_CODE;
2550                 break;
2551         case LFUN_INDEX_PRINT:
2552                 code = INDEX_PRINT_CODE;
2553                 // not allowed in description items
2554                 enable = !inDescriptionItem(cur);
2555                 break;
2556         case LFUN_NOMENCL_INSERT:
2557                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2558                         enable = false;
2559                         break;
2560                 }
2561                 code = NOMENCL_CODE;
2562                 break;
2563         case LFUN_NOMENCL_PRINT:
2564                 code = NOMENCL_PRINT_CODE;
2565                 // not allowed in description items
2566                 enable = !inDescriptionItem(cur);
2567                 break;
2568         case LFUN_HYPERLINK_INSERT:
2569                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2570                         enable = false;
2571                         break;
2572                 }
2573                 code = HYPERLINK_CODE;
2574                 break;
2575         case LFUN_IPAMACRO_INSERT: {
2576                 string const arg = cmd.getArg(0);
2577                 if (arg == "deco")
2578                         code = IPADECO_CODE;
2579                 else
2580                         code = IPACHAR_CODE;
2581                 break;
2582         }
2583         case LFUN_QUOTE_INSERT:
2584                 // always allow this, since we will inset a raw quote
2585                 // if an inset is not allowed.
2586                 break;
2587         case LFUN_SPECIALCHAR_INSERT:
2588                 code = SPECIALCHAR_CODE;
2589                 break;
2590         case LFUN_SPACE_INSERT:
2591                 // slight hack: we know this is allowed in math mode
2592                 if (cur.inTexted())
2593                         code = SPACE_CODE;
2594                 break;
2595         case LFUN_PREVIEW_INSERT:
2596                 code = PREVIEW_CODE;
2597                 break;
2598         case LFUN_SCRIPT_INSERT:
2599                 code = SCRIPT_CODE;
2600                 break;
2601
2602         case LFUN_MATH_INSERT:
2603         case LFUN_MATH_AMS_MATRIX:
2604         case LFUN_MATH_MATRIX:
2605         case LFUN_MATH_DELIM:
2606         case LFUN_MATH_BIGDELIM:
2607         case LFUN_MATH_DISPLAY:
2608         case LFUN_MATH_MODE:
2609         case LFUN_MATH_MACRO:
2610         case LFUN_MATH_SUBSCRIPT:
2611         case LFUN_MATH_SUPERSCRIPT:
2612                 code = MATH_HULL_CODE;
2613                 break;
2614
2615         case LFUN_REGEXP_MODE:
2616                 code = MATH_HULL_CODE;
2617                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
2618                 break;
2619
2620         case LFUN_INSET_MODIFY:
2621                 // We need to disable this, because we may get called for a
2622                 // tabular cell via
2623                 // InsetTabular::getStatus() -> InsetText::getStatus()
2624                 // and we don't handle LFUN_INSET_MODIFY.
2625                 enable = false;
2626                 break;
2627
2628         case LFUN_FONT_EMPH:
2629                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2630                 enable = !cur.paragraph().isPassThru();
2631                 break;
2632
2633         case LFUN_FONT_ITAL:
2634                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2635                 enable = !cur.paragraph().isPassThru();
2636                 break;
2637
2638         case LFUN_FONT_NOUN:
2639                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2640                 enable = !cur.paragraph().isPassThru();
2641                 break;
2642
2643         case LFUN_FONT_BOLD:
2644         case LFUN_FONT_BOLDSYMBOL:
2645                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2646                 enable = !cur.paragraph().isPassThru();
2647                 break;
2648
2649         case LFUN_FONT_SANS:
2650                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2651                 enable = !cur.paragraph().isPassThru();
2652                 break;
2653
2654         case LFUN_FONT_ROMAN:
2655                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2656                 enable = !cur.paragraph().isPassThru();
2657                 break;
2658
2659         case LFUN_FONT_TYPEWRITER:
2660                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2661                 enable = !cur.paragraph().isPassThru();
2662                 break;
2663
2664         case LFUN_CUT:
2665         case LFUN_COPY:
2666                 enable = cur.selection();
2667                 break;
2668
2669         case LFUN_PASTE: {
2670                 if (cmd.argument().empty()) {
2671                         if (theClipboard().isInternal())
2672                                 enable = cap::numberOfSelections() > 0;
2673                         else
2674                                 enable = !theClipboard().empty();
2675                         break;
2676                 }
2677
2678                 // we have an argument
2679                 string const arg = to_utf8(cmd.argument());
2680                 if (isStrUnsignedInt(arg)) {
2681                         // it's a number and therefore means the internal stack
2682                         unsigned int n = convert<unsigned int>(arg);
2683                         enable = cap::numberOfSelections() > n;
2684                         break;
2685                 }
2686
2687                 // explicit graphics type?
2688                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2689                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2690                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2691                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2692                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2693                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2694                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2695                         enable = theClipboard().hasGraphicsContents(type);
2696                         break;
2697                 }
2698
2699                 // unknown argument
2700                 enable = false;
2701                 break;
2702          }
2703
2704         case LFUN_CLIPBOARD_PASTE:
2705         case LFUN_CLIPBOARD_PASTE_SIMPLE:
2706                 enable = !theClipboard().empty();
2707                 break;
2708
2709         case LFUN_PRIMARY_SELECTION_PASTE:
2710                 enable = cur.selection() || !theSelection().empty();
2711                 break;
2712
2713         case LFUN_SELECTION_PASTE:
2714                 enable = cap::selection();
2715                 break;
2716
2717         case LFUN_PARAGRAPH_MOVE_UP:
2718                 enable = cur.pit() > 0 && !cur.selection();
2719                 break;
2720
2721         case LFUN_PARAGRAPH_MOVE_DOWN:
2722                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2723                 break;
2724
2725         case LFUN_CHANGE_ACCEPT:
2726         case LFUN_CHANGE_REJECT:
2727                 // In principle, these LFUNs should only be enabled if there
2728                 // is a change at the current position/in the current selection.
2729                 // However, without proper optimizations, this will inevitably
2730                 // result in unacceptable performance - just imagine a user who
2731                 // wants to select the complete content of a long document.
2732                 if (!cur.selection())
2733                         enable = cur.paragraph().isChanged(cur.pos());
2734                 else
2735                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2736                         // for selections.
2737                         enable = true;
2738                 break;
2739
2740         case LFUN_OUTLINE_UP:
2741         case LFUN_OUTLINE_DOWN:
2742         case LFUN_OUTLINE_IN:
2743         case LFUN_OUTLINE_OUT:
2744                 // FIXME: LyX is not ready for outlining within inset.
2745                 enable = isMainText()
2746                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2747                 break;
2748
2749         case LFUN_NEWLINE_INSERT:
2750                 // LaTeX restrictions (labels or empty par)
2751                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2752                 break;
2753
2754         case LFUN_TAB_INSERT:
2755         case LFUN_TAB_DELETE:
2756                 enable = cur.paragraph().isPassThru();
2757                 break;
2758
2759         case LFUN_SET_GRAPHICS_GROUP: {
2760                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2761                 if (!ins)
2762                         enable = false;
2763                 else
2764                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2765                 break;
2766         }
2767
2768         case LFUN_NEWPAGE_INSERT:
2769                 // not allowed in description items
2770                 code = NEWPAGE_CODE;
2771                 enable = !inDescriptionItem(cur);
2772                 break;
2773
2774         case LFUN_DATE_INSERT: {
2775                 string const format = cmd.argument().empty()
2776                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2777                 enable = support::os::is_valid_strftime(format);
2778                 break;
2779         }
2780
2781         case LFUN_LANGUAGE:
2782                 enable = !cur.paragraph().isPassThru();
2783                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
2784                 break;
2785
2786         case LFUN_PARAGRAPH_BREAK:
2787                 enable = cur.inset().getLayout().isMultiPar();
2788                 break;
2789         
2790         case LFUN_SPELLING_ADD:
2791         case LFUN_SPELLING_IGNORE:
2792         case LFUN_SPELLING_REMOVE:
2793                 enable = theSpellChecker();
2794                 break;
2795
2796         case LFUN_LAYOUT:
2797                 enable = !cur.inset().forcePlainLayout();
2798                 break;
2799                 
2800         case LFUN_LAYOUT_PARAGRAPH:
2801         case LFUN_PARAGRAPH_PARAMS:
2802         case LFUN_PARAGRAPH_PARAMS_APPLY:
2803         case LFUN_PARAGRAPH_UPDATE:
2804                 enable = cur.inset().allowParagraphCustomization();
2805                 break;
2806
2807         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
2808         case LFUN_ACCENT_ACUTE:
2809         case LFUN_ACCENT_BREVE:
2810         case LFUN_ACCENT_CARON:
2811         case LFUN_ACCENT_CEDILLA:
2812         case LFUN_ACCENT_CIRCLE:
2813         case LFUN_ACCENT_CIRCUMFLEX:
2814         case LFUN_ACCENT_DOT:
2815         case LFUN_ACCENT_GRAVE:
2816         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2817         case LFUN_ACCENT_MACRON:
2818         case LFUN_ACCENT_OGONEK:
2819         case LFUN_ACCENT_TIE:
2820         case LFUN_ACCENT_TILDE:
2821         case LFUN_ACCENT_UMLAUT:
2822         case LFUN_ACCENT_UNDERBAR:
2823         case LFUN_ACCENT_UNDERDOT:
2824         case LFUN_FONT_DEFAULT:
2825         case LFUN_FONT_FRAK:
2826         case LFUN_FONT_SIZE:
2827         case LFUN_FONT_STATE:
2828         case LFUN_FONT_UNDERLINE:
2829         case LFUN_FONT_STRIKEOUT:
2830         case LFUN_FONT_UULINE:
2831         case LFUN_FONT_UWAVE:
2832         case LFUN_TEXTSTYLE_APPLY:
2833         case LFUN_TEXTSTYLE_UPDATE:
2834                 enable = !cur.paragraph().isPassThru();
2835                 break;
2836
2837         case LFUN_WORD_DELETE_FORWARD:
2838         case LFUN_WORD_DELETE_BACKWARD:
2839         case LFUN_LINE_DELETE:
2840         case LFUN_WORD_FORWARD:
2841         case LFUN_WORD_BACKWARD:
2842         case LFUN_WORD_RIGHT:
2843         case LFUN_WORD_LEFT:
2844         case LFUN_CHAR_FORWARD:
2845         case LFUN_CHAR_FORWARD_SELECT:
2846         case LFUN_CHAR_BACKWARD:
2847         case LFUN_CHAR_BACKWARD_SELECT:
2848         case LFUN_CHAR_LEFT:
2849         case LFUN_CHAR_LEFT_SELECT:
2850         case LFUN_CHAR_RIGHT:
2851         case LFUN_CHAR_RIGHT_SELECT:
2852         case LFUN_UP:
2853         case LFUN_UP_SELECT:
2854         case LFUN_DOWN:
2855         case LFUN_DOWN_SELECT:
2856         case LFUN_PARAGRAPH_UP_SELECT:
2857         case LFUN_PARAGRAPH_DOWN_SELECT:
2858         case LFUN_LINE_BEGIN_SELECT:
2859         case LFUN_LINE_END_SELECT:
2860         case LFUN_WORD_FORWARD_SELECT:
2861         case LFUN_WORD_BACKWARD_SELECT:
2862         case LFUN_WORD_RIGHT_SELECT:
2863         case LFUN_WORD_LEFT_SELECT:
2864         case LFUN_WORD_SELECT:
2865         case LFUN_SECTION_SELECT:
2866         case LFUN_BUFFER_BEGIN:
2867         case LFUN_BUFFER_END:
2868         case LFUN_BUFFER_BEGIN_SELECT:
2869         case LFUN_BUFFER_END_SELECT:
2870         case LFUN_INSET_BEGIN:
2871         case LFUN_INSET_END:
2872         case LFUN_INSET_BEGIN_SELECT:
2873         case LFUN_INSET_END_SELECT:
2874         case LFUN_INSET_SELECT_ALL:
2875         case LFUN_PARAGRAPH_UP:
2876         case LFUN_PARAGRAPH_DOWN:
2877         case LFUN_LINE_BEGIN:
2878         case LFUN_LINE_END:
2879         case LFUN_CHAR_DELETE_FORWARD:
2880         case LFUN_CHAR_DELETE_BACKWARD:
2881         case LFUN_WORD_UPCASE:
2882         case LFUN_WORD_LOWCASE:
2883         case LFUN_WORD_CAPITALIZE:
2884         case LFUN_CHARS_TRANSPOSE:
2885         case LFUN_SERVER_GET_XY:
2886         case LFUN_SERVER_SET_XY:
2887         case LFUN_SERVER_GET_LAYOUT:
2888         case LFUN_SELF_INSERT:
2889         case LFUN_UNICODE_INSERT:
2890         case LFUN_THESAURUS_ENTRY:
2891         case LFUN_ESCAPE:
2892                 // these are handled in our dispatch()
2893                 enable = true;
2894                 break;
2895
2896         case LFUN_INSET_INSERT: {
2897                 string const type = cmd.getArg(0);
2898                 if (type == "toc") {
2899                         code = TOC_CODE;
2900                         // not allowed in description items
2901                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
2902                         enable = !inDescriptionItem(cur);
2903                 } else {
2904                         enable = true;
2905                 }
2906                 break;
2907         }
2908
2909         default:
2910                 return false;
2911         }
2912
2913         if (code != NO_CODE
2914             && (cur.empty() 
2915                 || !cur.inset().insetAllowed(code)
2916                 || cur.paragraph().layout().pass_thru))
2917                 enable = false;
2918
2919         flag.setEnabled(enable);
2920         return true;
2921 }
2922
2923
2924 void Text::pasteString(Cursor & cur, docstring const & clip,
2925                 bool asParagraphs)
2926 {
2927         if (!clip.empty()) {
2928                 cur.recordUndo();
2929                 if (asParagraphs)
2930                         insertStringAsParagraphs(cur, clip, cur.current_font);
2931                 else
2932                         insertStringAsLines(cur, clip, cur.current_font);
2933         }
2934 }
2935
2936
2937 // FIXME: an item inset would make things much easier.
2938 bool Text::inDescriptionItem(Cursor & cur) const
2939 {
2940         Paragraph & par = cur.paragraph();
2941         pos_type const pos = cur.pos();
2942         pos_type const body_pos = par.beginOfBody();
2943
2944         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2945             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2946                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2947                 return false;
2948
2949         return (pos < body_pos
2950                 || (pos == body_pos
2951                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2952 }
2953
2954 } // namespace lyx