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