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