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