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