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