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