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