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