]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
the lfun3 patches (overall cleanup and "localizing" dispatch() in mathed)
[lyx.git] / src / BufferView_pimpl.C
1 /**
2  * \file BufferView_pimpl.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author various
7  */
8
9 #include <config.h>
10
11 #ifdef __GNUG__
12 #pragma implementation
13 #endif
14
15 #include "BufferView_pimpl.h"
16 #include "frontends/WorkArea.h"
17 #include "frontends/screen.h"
18 #include "frontends/LyXScreenFactory.h"
19 #include "frontends/WorkAreaFactory.h"
20 #include "frontends/Dialogs.h"
21 #include "frontends/Alert.h"
22 #include "frontends/FileDialog.h"
23 #include "lyxtext.h"
24 #include "lyxrow.h"
25 #include "paragraph.h"
26 #include "frontends/LyXView.h"
27 #include "commandtags.h"
28 #include "lyxfunc.h"
29 #include "debug.h"
30 #include "bufferview_funcs.h"
31 #include "TextCache.h"
32 #include "bufferlist.h"
33 #include "lyxrc.h"
34 #include "intl.h"
35 // added for Dispatch functions
36 #include "lyx_cb.h"
37 #include "lyx_main.h"
38 #include "FloatList.h"
39 #include "gettext.h"
40 #include "ParagraphParameters.h"
41 #include "undo_funcs.h"
42 #include "funcrequest.h"
43
44 #include "insets/insetbib.h"
45 #include "insets/insettext.h"
46 #include "insets/inseturl.h"
47 #include "insets/insetlatexaccent.h"
48 #include "insets/insettoc.h"
49 #include "insets/insetref.h"
50 #include "insets/insetparent.h"
51 #include "insets/insetindex.h"
52 #include "insets/insetnote.h"
53 #include "insets/insetinclude.h"
54 #include "insets/insetcite.h"
55 #include "insets/insetert.h"
56 #include "insets/insetexternal.h"
57 #include "insets/insetgraphics.h"
58 #include "insets/insetfoot.h"
59 #include "insets/insetmarginal.h"
60 #include "insets/insetminipage.h"
61 #include "insets/insetfloat.h"
62 #include "insets/insettabular.h"
63 #if 0
64 #include "insets/insettheorem.h"
65 #include "insets/insetlist.h"
66 #endif
67 #include "insets/insetcaption.h"
68 #include "insets/insetfloatlist.h"
69 #include "insets/insetspecialchar.h"
70
71 #include "mathed/formulabase.h"
72
73 #include "graphics/Previews.h"
74
75 #include "support/LAssert.h"
76 #include "support/lstrings.h"
77 #include "support/filetools.h"
78 #include "support/lyxfunctional.h"
79
80 #include <boost/bind.hpp>
81 #include <boost/signals/connection.hpp>
82
83 #include <cstdio>
84 #include <ctime>
85 #include <unistd.h>
86 #include <sys/wait.h>
87 #include <clocale>
88
89
90 extern string current_layout;
91
92 #ifndef CXX_GLOBAL_CSTD
93 using std::tm;
94 using std::localtime;
95 using std::time;
96 using std::setlocale;
97 using std::strftime;
98 #endif
99
100 using std::vector;
101 using std::find_if;
102 using std::find;
103 using std::pair;
104 using std::endl;
105 using std::make_pair;
106 using std::min;
107
108 using lyx::pos_type;
109 using lyx::textclass_type;
110
111 /* the selection possible is needed, that only motion events are
112  * used, where the bottom press event was on the drawing area too */
113 bool selection_possible = false;
114
115 extern BufferList bufferlist;
116 extern char ascii_type;
117
118 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
119
120
121 namespace {
122
123 unsigned int const saved_positions_num = 20;
124
125 // All the below connection objects are needed because of a bug in some
126 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
127 // to these connections we avoid a segfault upon startup, and also at exit.
128 // (Lgb)
129
130 boost::signals::connection timecon;
131 boost::signals::connection doccon;
132 boost::signals::connection resizecon;
133 boost::signals::connection bpresscon;
134 boost::signals::connection breleasecon;
135 boost::signals::connection motioncon;
136 boost::signals::connection doublecon;
137 boost::signals::connection triplecon;
138 boost::signals::connection kpresscon;
139 boost::signals::connection selectioncon;
140 boost::signals::connection lostcon;
141
142 } // anon namespace
143
144
145 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
146              int xpos, int ypos, int width, int height)
147         : bv_(b), owner_(o), buffer_(0), cursor_timeout(400),
148           using_xterm_cursor(false)
149 {
150         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
151         screen_.reset(LyXScreenFactory::create(workarea()));
152
153         // Setup the signals
154         doccon = workarea().scrollDocView.connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
155         resizecon = workarea().workAreaResize
156                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
157         bpresscon = workarea().workAreaButtonPress
158                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonPress, this, _1, _2, _3));
159         breleasecon = workarea().workAreaButtonRelease
160                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonRelease, this, _1, _2, _3));
161         motioncon = workarea().workAreaMotionNotify
162                 .connect(boost::bind(&BufferView::Pimpl::workAreaMotionNotify, this, _1, _2, _3));
163         doublecon = workarea().workAreaDoubleClick
164                 .connect(boost::bind(&BufferView::Pimpl::doubleClick, this, _1, _2, _3));
165         triplecon = workarea().workAreaTripleClick
166                 .connect(boost::bind(&BufferView::Pimpl::tripleClick, this, _1, _2, _3));
167         kpresscon = workarea().workAreaKeyPress
168                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
169         selectioncon = workarea().selectionRequested
170                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
171         lostcon = workarea().selectionLost
172                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
173
174         timecon = cursor_timeout.timeout.connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
175         cursor_timeout.start();
176         saved_positions.resize(saved_positions_num);
177 }
178
179
180 WorkArea & BufferView::Pimpl::workarea() const
181 {
182         return *workarea_.get();
183 }
184
185
186 LyXScreen & BufferView::Pimpl::screen() const
187 {
188         return *screen_.get();
189 }
190
191
192 Painter & BufferView::Pimpl::painter() const
193 {
194         return workarea().getPainter();
195 }
196
197
198 void BufferView::Pimpl::buffer(Buffer * b)
199 {
200         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
201                             << b << ")" << endl;
202         if (buffer_) {
203                 buffer_->delUser(bv_);
204
205                 // Put the old text into the TextCache, but
206                 // only if the buffer is still loaded.
207                 // Also set the owner of the test to 0
208                 //              bv_->text->owner(0);
209                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
210                 if (lyxerr.debugging())
211                         textcache.show(lyxerr, "BufferView::buffer");
212
213                 bv_->text = 0;
214         }
215
216         // Set current buffer
217         buffer_ = b;
218
219         if (bufferlist.getState() == BufferList::CLOSING) return;
220
221         // If we are closing the buffer, use the first buffer as current
222         if (!buffer_) {
223                 buffer_ = bufferlist.first();
224         }
225
226         if (buffer_) {
227                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
228                 buffer_->addUser(bv_);
229
230                 // If we don't have a text object for this, we make one
231                 if (bv_->text == 0) {
232                         resizeCurrentBuffer();
233                 }
234
235                 // FIXME: needed when ?
236                 bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
237
238                 // Similarly, buffer-dependent dialogs should be updated or
239                 // hidden. This should go here because some dialogs (eg ToC)
240                 // require bv_->text.
241                 owner_->getDialogs().updateBufferDependent(true);
242         } else {
243                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
244                 owner_->getDialogs().hideBufferDependent();
245
246                 // Also remove all remaining text's from the testcache.
247                 // (there should not be any!) (if there is any it is a
248                 // bug!)
249                 if (lyxerr.debugging())
250                         textcache.show(lyxerr, "buffer delete all");
251                 textcache.clear();
252         }
253
254         repaint();
255         updateScrollbar();
256         owner_->updateMenubar();
257         owner_->updateToolbar();
258         owner_->updateLayoutChoice();
259         owner_->updateWindowTitle();
260
261         if (grfx::Previews::activated() && buffer_)
262                 grfx::Previews::get().generateBufferPreviews(*buffer_);
263 }
264
265
266 bool BufferView::Pimpl::fitCursor()
267 {
268         bool ret;
269
270         if (bv_->theLockingInset()) {
271                 bv_->theLockingInset()->fitInsetCursor(bv_);
272                 ret = true;
273         } else {
274                 ret = screen().fitCursor(bv_->text, bv_);
275         }
276
277         bv_->owner()->getDialogs().updateParagraph();
278         if (ret)
279                 updateScrollbar();
280         return ret;
281 }
282
283
284 void BufferView::Pimpl::redoCurrentBuffer()
285 {
286         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
287         if (buffer_ && bv_->text) {
288                 resizeCurrentBuffer();
289                 updateScrollbar();
290                 owner_->updateLayoutChoice();
291                 repaint();
292         }
293 }
294
295
296 int BufferView::Pimpl::resizeCurrentBuffer()
297 {
298         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
299
300         Paragraph * par = 0;
301         Paragraph * selstartpar = 0;
302         Paragraph * selendpar = 0;
303         UpdatableInset * the_locking_inset = 0;
304
305         pos_type pos = 0;
306         pos_type selstartpos = 0;
307         pos_type selendpos = 0;
308         bool selection = false;
309         bool mark_set  = false;
310
311         owner_->prohibitInput();
312
313         owner_->message(_("Formatting document..."));
314
315         if (bv_->text) {
316                 par = bv_->text->cursor.par();
317                 pos = bv_->text->cursor.pos();
318                 selstartpar = bv_->text->selection.start.par();
319                 selstartpos = bv_->text->selection.start.pos();
320                 selendpar = bv_->text->selection.end.par();
321                 selendpos = bv_->text->selection.end.pos();
322                 selection = bv_->text->selection.set();
323                 mark_set = bv_->text->selection.mark();
324                 the_locking_inset = bv_->theLockingInset();
325                 buffer_->resizeInsets(bv_);
326                 // I don't think the delete and new are necessary here we just could
327                 // call only init! (Jug 20020419)
328                 delete bv_->text;
329                 bv_->text = new LyXText(bv_);
330                 bv_->text->init(bv_);
331         } else {
332                 // See if we have a text in TextCache that fits
333                 // the new buffer_ with the correct width.
334                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
335                 if (bv_->text) {
336                         if (lyxerr.debugging()) {
337                                 lyxerr << "Found a LyXText that fits:\n";
338                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
339                         }
340                         // Set the owner of the newly found text
341                         //      bv_->text->owner(bv_);
342                         if (lyxerr.debugging())
343                                 textcache.show(lyxerr, "resizeCurrentBuffer");
344                 } else {
345                         bv_->text = new LyXText(bv_);
346                         bv_->text->init(bv_);
347                         //buffer_->resizeInsets(bv_);
348                 }
349         }
350
351         if (par) {
352                 bv_->text->selection.set(true);
353                 // At this point just to avoid the Delete-Empty-Paragraph-
354                 // Mechanism when setting the cursor.
355                 bv_->text->selection.mark(mark_set);
356                 if (selection) {
357                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
358                         bv_->text->selection.cursor = bv_->text->cursor;
359                         bv_->text->setCursor(bv_, selendpar, selendpos);
360                         bv_->text->setSelection(bv_);
361                         bv_->text->setCursor(bv_, par, pos);
362                 } else {
363                         bv_->text->setCursor(bv_, par, pos);
364                         bv_->text->selection.cursor = bv_->text->cursor;
365                         bv_->text->selection.set(false);
366                 }
367                 // remake the inset locking
368                 bv_->theLockingInset(the_locking_inset);
369         }
370
371         bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
372
373         switchKeyMap();
374         owner_->allowInput();
375
376         updateScrollbar();
377
378         return 0;
379 }
380
381
382 void BufferView::Pimpl::repaint()
383 {
384         // Regenerate the screen.
385         screen().redraw(bv_->text, bv_);
386 }
387
388
389 void BufferView::Pimpl::updateScrollbar()
390 {
391         if (!bv_->text) {
392                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
393                 workarea().setScrollbarParams(0, 0, 0);
394                 return;
395         }
396
397         LyXText const & t = *bv_->text;
398
399         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", first_y "
400                 << t.first_y << ", default height " << t.defaultHeight() << endl;
401
402         workarea().setScrollbarParams(t.height, t.first_y, t.defaultHeight());
403 }
404
405
406 void BufferView::Pimpl::scrollDocView(int value)
407 {
408         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
409
410         if (!buffer_) return;
411
412         screen().draw(bv_->text, bv_, value);
413
414         if (!lyxrc.cursor_follows_scrollbar) {
415                 return;
416         }
417
418         LyXText * vbt = bv_->text;
419
420         int const height = vbt->defaultHeight();
421         int const first = static_cast<int>((bv_->text->first_y + height));
422         int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
423
424         if (vbt->cursor.y() < first)
425                 vbt->setCursorFromCoordinates(bv_, 0, first);
426         else if (vbt->cursor.y() > last)
427                 vbt->setCursorFromCoordinates(bv_, 0, last);
428 }
429
430
431 int BufferView::Pimpl::scroll(long time)
432 {
433         if (!buffer_)
434                 return 0;
435
436         LyXText const * t = bv_->text;
437
438         double const diff = t->defaultHeight()
439                 + double(time) * double(time) * 0.125;
440
441         scrollDocView(int(diff));
442         workarea().setScrollbarParams(t->height, t->first_y, t->defaultHeight());
443         return 0;
444 }
445
446
447 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
448                                          key_modifier::state state)
449 {
450         bv_->owner()->getLyXFunc().processKeySym(key, state);
451 }
452
453
454 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, mouse_button::state state)
455 {
456         // Only use motion with button 1
457         if (!(state & mouse_button::button1))
458                 return;
459
460         if (!buffer_)
461                 return;
462
463         // Check for inset locking
464         if (bv_->theLockingInset()) {
465                 LyXCursor cursor = bv_->text->cursor;
466                 LyXFont font = bv_->text->getFont(buffer_,
467                                                   cursor.par(), cursor.pos());
468                 int width = bv_->theLockingInset()->width(bv_, font);
469                 int inset_x = font.isVisibleRightToLeft()
470                         ? cursor.ix() - width : cursor.ix();
471                 int start_x = inset_x + bv_->theLockingInset()->scroll();
472
473                 bv_->theLockingInset()->
474                         insetMotionNotify(bv_,
475                                           x - start_x,
476                                           y - cursor.iy() + bv_->text->first_y,
477                                           state);
478                 return;
479         }
480
481         /* The test for not selection possible is needed, that only motion
482            events are used, where the bottom press event was on
483            the drawing area too */
484         if (!selection_possible)
485                 return;
486
487         screen().hideCursor();
488
489         Row * cursorrow = bv_->text->cursor.row();
490         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
491 #if 0
492         // sorry for this but I have a strange error that the y value jumps at
493         // a certain point. This seems like an error in my xforms library or
494         // in some other local environment, but I would like to leave this here
495         // for the moment until I can remove this (Jug 20020418)
496         if (y_before < bv_->text->cursor.y())
497                 lyxerr << y_before << ":" << bv_->text->cursor.y() << endl;
498 #endif
499         // This is to allow jumping over large insets
500         if (cursorrow == bv_->text->cursor.row()) {
501                 if (y >= int(workarea().workHeight())) {
502                         bv_->text->cursorDown(bv_, false);
503                 } else if (y < 0) {
504                         bv_->text->cursorUp(bv_, false);
505                 }
506         }
507
508         if (!bv_->text->selection.set())
509                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
510
511         bv_->text->setSelection(bv_);
512         screen().toggleToggle(bv_->text, bv_);
513         fitCursor();
514         showCursor();
515 }
516
517
518 // Single-click on work area
519 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
520                                             mouse_button::state button)
521 {
522         if (!buffer_)
523                 return;
524
525         // ok ok, this is a hack (for xforms)
526         if (button == mouse_button::button4) {
527                 scroll(-lyxrc.wheel_jump);
528                 // We shouldn't go further down as we really should only do the
529                 // scrolling and be done with this. Otherwise we may open some
530                 // dialogs (Jug 20020424).
531                 return;
532         } else if (button == mouse_button::button5) {
533                 scroll(lyxrc.wheel_jump);
534                 // We shouldn't go further down as we really should only do the
535                 // scrolling and be done with this. Otherwise we may open some
536                 // dialogs (Jug 20020424).
537                 return;
538         }
539
540         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
541
542         // Middle button press pastes if we have a selection
543         // We do this here as if the selection was inside an inset
544         // it could get cleared on the unlocking of the inset so
545         // we have to check this first
546         bool paste_internally = false;
547         if (button == mouse_button::button2 && bv_->getLyXText()->selection.set()) {
548                 owner_->dispatch(FuncRequest(LFUN_COPY));
549                 paste_internally = true;
550         }
551
552         int const screen_first = bv_->text->first_y;
553
554         if (bv_->theLockingInset()) {
555                 // We are in inset locking mode
556
557                 /* Check whether the inset was hit. If not reset mode,
558                    otherwise give the event to the inset */
559                 if (inset_hit == bv_->theLockingInset()) {
560                         bv_->theLockingInset()->
561                                 insetButtonPress(bv_, xpos, ypos, button);
562                         return;
563                 } else {
564                         bv_->unlockInset(bv_->theLockingInset());
565                 }
566         }
567
568         if (!inset_hit)
569                 selection_possible = true;
570         screen().hideCursor();
571
572         // Clear the selection
573         screen().toggleSelection(bv_->text, bv_);
574         bv_->text->clearSelection();
575         bv_->text->fullRebreak(bv_);
576         update();
577         updateScrollbar();
578
579         // Single left click in math inset?
580         if (isHighlyEditableInset(inset_hit)) {
581                 // Highly editable inset, like math
582                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
583                 selection_possible = false;
584                 owner_->updateLayoutChoice();
585                 owner_->message(inset->editMessage());
586                 //inset->edit(bv_, xpos, ypos, button);
587                 // We just have to lock the inset before calling a PressEvent on it!
588                 // we don't need the edit() call here! (Jug20020329)
589                 if (!bv_->lockInset(inset)) {
590                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
591                 }
592                 inset->insetButtonPress(bv_, xpos, ypos, button);
593                 return;
594         }
595         // I'm not sure we should continue here if we hit an inset (Jug20020403)
596
597         // Right click on a footnote flag opens float menu
598         if (button == mouse_button::button3) {
599                 selection_possible = false;
600                 return;
601         }
602
603         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
604                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
605         finishUndo();
606         bv_->text->selection.cursor = bv_->text->cursor;
607         bv_->text->cursor.x_fix(bv_->text->cursor.x());
608
609         owner_->updateLayoutChoice();
610         if (fitCursor()) {
611                 selection_possible = false;
612         }
613
614         // Insert primary selection with middle mouse
615         // if there is a local selection in the current buffer,
616         // insert this
617         if (button == mouse_button::button2) {
618                 if (paste_internally)
619                         owner_->dispatch(FuncRequest(LFUN_PASTE));
620                 else
621                         owner_->dispatch(FuncRequest(LFUN_PASTESELECTION, "paragraph"));
622                 selection_possible = false;
623                 return;
624         }
625 }
626
627
628 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, mouse_button::state button)
629 {
630         if (!buffer_)
631                 return;
632
633         LyXText * text = bv_->getLyXText();
634
635         if (text->bv_owner && bv_->theLockingInset())
636                 return;
637
638         if (button == mouse_button::button1) {
639                 if (text->bv_owner) {
640                         screen().hideCursor();
641                         screen().toggleSelection(text, bv_);
642                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
643                         screen().toggleSelection(text, bv_, false);
644                 } else {
645                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
646                 }
647                 /* This will fit the cursor on the screen
648                  * if necessary */
649                 update(text, BufferView::SELECT|BufferView::FITCUR);
650                 workarea().haveSelection(bv_->getLyXText()->selection.set());
651         }
652 }
653
654
655 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, mouse_button::state button)
656 {
657         if (!buffer_)
658                 return;
659
660         LyXText * text = bv_->getLyXText();
661
662         if (text->bv_owner && bv_->theLockingInset())
663             return;
664
665         if (button == mouse_button::button1) {
666                 if (text->bv_owner) {
667                         screen().hideCursor();
668                         screen().toggleSelection(text, bv_);
669                 }
670                 text->cursorHome(bv_);
671                 text->selection.cursor = text->cursor;
672                 text->cursorEnd(bv_);
673                 text->setSelection(bv_);
674                 if (text->bv_owner) {
675                         screen().toggleSelection(text, bv_, false);
676                 }
677                 /* This will fit the cursor on the screen
678                  * if necessary */
679                 update(text, BufferView::SELECT|BufferView::FITCUR);
680                 workarea().haveSelection(bv_->getLyXText()->selection.set());
681         }
682 }
683
684
685 void BufferView::Pimpl::selectionRequested()
686 {
687         static string sel;
688
689         if (!available())
690                 return;
691
692         LyXText * text = bv_->getLyXText();
693
694         if (text->selection.set() &&
695                 (!bv_->text->xsel_cache.set() ||
696                  text->selection.start != bv_->text->xsel_cache.start ||
697                  text->selection.end != bv_->text->xsel_cache.end))
698         {
699                 bv_->text->xsel_cache = text->selection;
700                 sel = text->selectionAsString(bv_->buffer(), false);
701         } else if (!text->selection.set()) {
702                 sel = string();
703                 bv_->text->xsel_cache.set(false);
704         }
705         if (!sel.empty()) {
706                 workarea().putClipboard(sel);
707         }
708 }
709
710
711 void BufferView::Pimpl::selectionLost()
712 {
713         if (available()) {
714                 hideCursor();
715                 toggleSelection();
716                 bv_->getLyXText()->clearSelection();
717                 showCursor();
718                 bv_->text->xsel_cache.set(false);
719         }
720 }
721
722
723 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
724                                               mouse_button::state button)
725 {
726         // do nothing if we used the mouse wheel
727         if (!buffer_ || button == mouse_button::button4 || button == mouse_button::button5)
728                 return;
729
730         // If we hit an inset, we have the inset coordinates in these
731         // and inset_hit points to the inset.  If we do not hit an
732         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
733         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
734
735         if (bv_->theLockingInset()) {
736                 // We are in inset locking mode.
737
738                 /* LyX does a kind of work-area grabbing for insets.
739                    Only a ButtonPress FuncRequest outside the inset will
740                    force a insetUnlock. */
741                 bv_->theLockingInset()->
742                         insetButtonRelease(bv_, x, y, button);
743                 return;
744         }
745
746         selection_possible = false;
747
748         if (button == mouse_button::button2)
749                 return;
750
751         // finish selection
752         if (button == mouse_button::button1) {
753                 workarea().haveSelection(bv_->getLyXText()->selection.set());
754         }
755
756         switchKeyMap();
757         owner_->view_state_changed();
758         owner_->updateMenubar();
759         owner_->updateToolbar();
760
761         // Did we hit an editable inset?
762         if (inset_hit) {
763                 selection_possible = false;
764
765                 // if we reach this point with a selection, it
766                 // must mean we are currently selecting.
767                 // But we don't want to open the inset
768                 // because that is annoying for the user.
769                 // So just pretend we didn't hit it.
770                 // this is OK because a "kosher" ButtonRelease
771                 // will follow a ButtonPress that clears
772                 // the selection.
773                 // Note this also fixes selection drawing
774                 // problems if we end up opening an inset
775                 if (bv_->getLyXText()->selection.set())
776                         return;
777
778                 // CHECK fix this proper in 0.13
779                 // well, maybe 13.0 !!!!!!!!!
780
781                 // Following a ref shouldn't issue
782                 // a push on the undo-stack
783                 // anylonger, now that we have
784                 // keybindings for following
785                 // references and returning from
786                 // references.  IMHO though, it
787                 // should be the inset's own business
788                 // to push or not push on the undo
789                 // stack. They don't *have* to
790                 // alter the document...
791                 // (Joacim)
792                 // ...or maybe the SetCursorParUndo()
793                 // below isn't necessary at all anylonger?
794                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
795                         setCursorParUndo(bv_);
796                 }
797
798                 owner_->message(inset_hit->editMessage());
799
800                 if (isHighlyEditableInset(inset_hit)) {
801                         // Highly editable inset, like math
802                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
803                         inset->insetButtonRelease(bv_, x, y, button);
804                 } else {
805                         inset_hit->insetButtonRelease(bv_, x, y, button);
806                         // IMO this is a grosshack! Inset's should be changed so that
807                         // they call the actions they have to do with the insetButtonRel.
808                         // function and not in the edit(). This should be changed
809                         // (Jug 20020329)
810 #ifdef WITH_WARNINGS
811 #warning Please remove donot call inset->edit() here (Jug 20020812)
812 #endif
813                         inset_hit->edit(bv_, x, y, button);
814                 }
815                 return;
816         }
817
818         // Maybe we want to edit a bibitem ale970302
819         if (bv_->text->cursor.par()->bibkey) {
820                 bool const is_rtl = bv_->text->cursor.par()->isRightToLeftPar(buffer_->params);
821                 int const width = bibitemMaxWidth(bv_, buffer_->params.getLyXTextClass().defaultfont());
822                 if ((is_rtl && x > bv_->text->workWidth(bv_)-20-width) ||
823                     (!is_rtl && x < 20+width)) {
824                         bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, mouse_button::none);
825                 }
826         }
827
828         return;
829 }
830
831
832 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
833                                        LyXCursor const & cursor) const
834 {
835         Paragraph /*const*/ & par = *cursor.par();
836         pos_type const pos = cursor.pos();
837
838         lyx::Assert(par.getInset(pos));
839
840         Inset const & inset(*par.getInset(pos));
841
842         LyXFont const & font = text.getFont(buffer_, &par, pos);
843
844         int const width = inset.width(bv_, font);
845         int const inset_x = font.isVisibleRightToLeft()
846                 ? (cursor.ix() - width) : cursor.ix();
847
848         return Box(
849                 inset_x + inset.scroll(),
850                 inset_x + width,
851                 cursor.iy() - inset.ascent(bv_, font),
852                 cursor.iy() + inset.descent(bv_, font));
853 }
854
855
856 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
857                                       LyXCursor const & cursor,
858                                       int & x, int & y) const
859 {
860         pos_type const pos(cursor.pos());
861         Paragraph /*const*/ & par(*cursor.par());
862
863         if (pos >= par.size() || !par.isInset(pos)) {
864                 return 0;
865         }
866
867         Inset /*const*/ * inset = par.getInset(pos);
868
869         if (!isEditableInset(inset)) {
870                 return 0;
871         }
872
873         Box b(insetDimensions(text, cursor));
874
875         if (!b.contained(x, y)) {
876                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
877                         << " box " << b << endl;
878                 return 0;
879         }
880
881         text.setCursor(bv_, &par, pos, true);
882
883         x -= b.x1;
884         // The origin of an inset is on the baseline
885         y -= text.cursor.iy();
886
887         return inset;
888 }
889
890
891 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
892 {
893         int y_tmp = y + text->first_y;
894
895         LyXCursor cursor;
896         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
897
898         Inset * inset(checkInset(*text, cursor, x, y_tmp));
899
900         if (inset) {
901                 y = y_tmp;
902                 return inset;
903         }
904
905         // look at previous position
906
907         if (cursor.pos() == 0) {
908                 return 0;
909         }
910
911         // move back one
912         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
913
914         inset = checkInset(*text, cursor, x, y_tmp);
915         if (inset) {
916                 y = y_tmp;
917         }
918         return inset;
919 }
920
921
922 void BufferView::Pimpl::workAreaResize()
923 {
924         static int work_area_width;
925         static int work_area_height;
926
927         bool const widthChange = workarea().workWidth() != work_area_width;
928         bool const heightChange = workarea().workHeight() != work_area_height;
929
930         // update from work area
931         work_area_width = workarea().workWidth();
932         work_area_height = workarea().workHeight();
933
934         if (buffer_ != 0) {
935                 if (widthChange) {
936                         // The visible LyXView need a resize
937                         resizeCurrentBuffer();
938
939                         // Remove all texts from the textcache
940                         // This is not _really_ what we want to do. What
941                         // we really want to do is to delete in textcache
942                         // that does not have a BufferView with matching
943                         // width, but as long as we have only one BufferView
944                         // deleting all gives the same result.
945                         if (lyxerr.debugging())
946                                 textcache.show(lyxerr, "Expose delete all");
947                         textcache.clear();
948                         // FIXME: this is aalready done in resizeCurrentBuffer() ??
949                         buffer_->resizeInsets(bv_);
950                 } else if (heightChange) {
951                         // fitCursor() ensures we don't jump back
952                         // to the start of the document on vertical
953                         // resize
954                         fitCursor();
955                 }
956         }
957
958         if (widthChange || heightChange) {
959                 repaint();
960         }
961
962         // always make sure that the scrollbar is sane.
963         updateScrollbar();
964         owner_->updateLayoutChoice();
965         return;
966 }
967
968
969 void BufferView::Pimpl::update()
970 {
971         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
972                 LyXText::text_status st = bv_->text->status();
973                 screen().update(bv_->text, bv_);
974                 bool fitc = false;
975                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
976                         bv_->text->fullRebreak(bv_);
977                         st = LyXText::NEED_MORE_REFRESH;
978                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
979                                              bv_->text->cursor.pos());
980                         if (bv_->text->selection.set()) {
981                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
982                                                      bv_->text->selection.start.par(),
983                                                      bv_->text->selection.start.pos());
984                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
985                                                      bv_->text->selection.end.par(),
986                                                      bv_->text->selection.end.pos());
987                         }
988                         fitc = true;
989                         bv_->text->status(bv_, st);
990                         screen().update(bv_->text, bv_);
991                 }
992                 // do this here instead of in the screen::update because of
993                 // the above loop!
994                 bv_->text->status(bv_, LyXText::UNCHANGED);
995                 if (fitc)
996                         fitCursor();
997         }
998 }
999
1000 // Values used when calling update:
1001 // -3 - update
1002 // -2 - update, move sel_cursor if selection, fitcursor
1003 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1004 //  0 - update, move sel_cursor if selection, fitcursor
1005 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1006 //  3 - update, move sel_cursor if selection
1007 //
1008 // update -
1009 // a simple redraw of the parts that need refresh
1010 //
1011 // move sel_cursor if selection -
1012 // the text's sel_cursor is moved if there is selection is progress
1013 //
1014 // fitcursor -
1015 // fitCursor() is called and the scrollbar updated
1016 //
1017 // mark dirty -
1018 // the buffer is marked dirty.
1019 //
1020 // enum {
1021 //       UPDATE = 0,
1022 //       SELECT = 1,
1023 //       FITCUR = 2,
1024 //       CHANGE = 4
1025 // };
1026 //
1027 // UPDATE_ONLY = UPDATE;
1028 // UPDATE_SELECT = UPDATE | SELECT;
1029 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1030 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1031 //
1032 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1033 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1034 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1035 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1036 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1037
1038 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1039 {
1040         owner_->updateLayoutChoice();
1041
1042         if (!text->selection.set() && (f & SELECT)) {
1043                 text->selection.cursor = text->cursor;
1044         }
1045
1046         text->fullRebreak(bv_);
1047
1048         if (text->inset_owner) {
1049                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1050                 updateInset(text->inset_owner, false);
1051         } else {
1052                 update();
1053         }
1054
1055         if ((f & FITCUR)) {
1056                 fitCursor();
1057         }
1058
1059         if ((f & CHANGE)) {
1060                 buffer_->markDirty();
1061         }
1062 }
1063
1064
1065 // Callback for cursor timer
1066 void BufferView::Pimpl::cursorToggle()
1067 {
1068         if (!buffer_) {
1069                 cursor_timeout.restart();
1070                 return;
1071         }
1072
1073         /* FIXME */
1074         extern void reapSpellchecker(void);
1075         reapSpellchecker();
1076
1077         if (!bv_->theLockingInset()) {
1078                 screen().cursorToggle(bv_);
1079         } else {
1080                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1081         }
1082
1083         cursor_timeout.restart();
1084 }
1085
1086
1087 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1088 {
1089         if (!text->cursor.row()->previous()) {
1090                 if (text->first_y > 0) {
1091                         int new_y = bv_->text->first_y - workarea().workHeight();
1092                         screen().draw(bv_->text, bv_, new_y < 0 ? 0 : new_y);
1093                         updateScrollbar();
1094                 }
1095                 return;
1096         }
1097
1098         int y = text->first_y;
1099         Row * cursorrow = text->cursor.row();
1100
1101         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y);
1102         finishUndo();
1103
1104         int new_y;
1105         if (cursorrow == bv_->text->cursor.row()) {
1106                 // we have a row which is higher than the workarea so we leave the
1107                 // cursor on the start of the row and move only the draw up as soon
1108                 // as we move the cursor or do something while inside the row (it may
1109                 // span several workarea-heights) we'll move to the top again, but this
1110                 // is better than just jump down and only display part of the row.
1111                 new_y = bv_->text->first_y - workarea().workHeight();
1112         } else {
1113                 if (text->inset_owner) {
1114                         new_y = bv_->text->cursor.iy()
1115                                 + bv_->theLockingInset()->insetInInsetY() + y
1116                                 + text->cursor.row()->height()
1117                                 - workarea().workHeight() + 1;
1118                 } else {
1119                         new_y = text->cursor.y()
1120                                 - text->cursor.row()->baseline()
1121                                 + text->cursor.row()->height()
1122                                 - workarea().workHeight() + 1;
1123                 }
1124         }
1125         screen().draw(bv_->text, bv_,  new_y < 0 ? 0 : new_y);
1126         if (text->cursor.row()->previous()) {
1127                 LyXCursor cur;
1128                 text->setCursor(bv_, cur, text->cursor.row()->previous()->par(),
1129                                                 text->cursor.row()->previous()->pos(), false);
1130                 if (cur.y() > text->first_y) {
1131                         text->cursorUp(bv_, true);
1132                 }
1133         }
1134         updateScrollbar();
1135 }
1136
1137
1138 void BufferView::Pimpl::cursorNext(LyXText * text)
1139 {
1140         if (!text->cursor.row()->next()) {
1141                 int y = text->cursor.y() - text->cursor.row()->baseline() +
1142                         text->cursor.row()->height();
1143                 if (y > int(text->first_y + workarea().workHeight())) {
1144                         screen().draw(bv_->text, bv_,
1145                                                   bv_->text->first_y + workarea().workHeight());
1146                         updateScrollbar();
1147                 }
1148                 return;
1149         }
1150
1151         int y = text->first_y + workarea().workHeight();
1152         if (text->inset_owner && !text->first_y) {
1153                 y -= (bv_->text->cursor.iy()
1154                           - bv_->text->first_y
1155                           + bv_->theLockingInset()->insetInInsetY());
1156         }
1157
1158         text->getRowNearY(y);
1159
1160         Row * cursorrow = text->cursor.row();
1161         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea().workHeight());
1162         finishUndo();
1163
1164         int new_y;
1165         if (cursorrow == bv_->text->cursor.row()) {
1166                 // we have a row which is higher than the workarea so we leave the
1167                 // cursor on the start of the row and move only the draw down as soon
1168                 // as we move the cursor or do something while inside the row (it may
1169                 // span several workarea-heights) we'll move to the top again, but this
1170                 // is better than just jump down and only display part of the row.
1171                 new_y = bv_->text->first_y + workarea().workHeight();
1172         } else {
1173                 if (text->inset_owner) {
1174                         new_y = bv_->text->cursor.iy()
1175                                 + bv_->theLockingInset()->insetInInsetY()
1176                                 + y - text->cursor.row()->baseline();
1177                 } else {
1178                         new_y =  text->cursor.y() - text->cursor.row()->baseline();
1179                 }
1180         }
1181         screen().draw(bv_->text, bv_, new_y);
1182         if (text->cursor.row()->next()) {
1183                 LyXCursor cur;
1184                 text->setCursor(bv_, cur, text->cursor.row()->next()->par(),
1185                                                 text->cursor.row()->next()->pos(), false);
1186                 if (cur.y() < int(text->first_y + workarea().workHeight())) {
1187                         text->cursorDown(bv_, true);
1188                 }
1189         }
1190         updateScrollbar();
1191 }
1192
1193
1194 bool BufferView::Pimpl::available() const
1195 {
1196         if (buffer_ && bv_->text)
1197                 return true;
1198         return false;
1199 }
1200
1201
1202 void BufferView::Pimpl::beforeChange(LyXText * text)
1203 {
1204         toggleSelection();
1205         text->clearSelection();
1206 }
1207
1208
1209 void BufferView::Pimpl::savePosition(unsigned int i)
1210 {
1211         if (i >= saved_positions_num)
1212                 return;
1213         saved_positions[i] = Position(buffer_->fileName(),
1214                                       bv_->text->cursor.par()->id(),
1215                                       bv_->text->cursor.pos());
1216         if (i > 0) {
1217                 ostringstream str;
1218                 str << _("Saved bookmark") << ' ' << i;
1219                 owner_->message(str.str().c_str());
1220         }
1221 }
1222
1223
1224 void BufferView::Pimpl::restorePosition(unsigned int i)
1225 {
1226         if (i >= saved_positions_num)
1227                 return;
1228
1229         string const fname = saved_positions[i].filename;
1230
1231         beforeChange(bv_->text);
1232
1233         if (fname != buffer_->fileName()) {
1234                 Buffer * b = bufferlist.exists(fname) ?
1235                         bufferlist.getBuffer(fname) :
1236                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1237                 if (b != 0) buffer(b);
1238         }
1239
1240         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1241         if (!par)
1242                 return;
1243
1244         bv_->text->setCursor(bv_, par,
1245                              min(par->size(), saved_positions[i].par_pos));
1246
1247         update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1248         if (i > 0) {
1249                 ostringstream str;
1250                 str << _("Moved to bookmark") << ' ' << i;
1251                 owner_->message(str.str().c_str());
1252         }
1253 }
1254
1255
1256 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1257 {
1258         if (i >= saved_positions_num)
1259                 return false;
1260
1261         return !saved_positions[i].filename.empty();
1262 }
1263
1264
1265 void BufferView::Pimpl::switchKeyMap()
1266 {
1267         if (!lyxrc.rtl_support)
1268                 return;
1269
1270         LyXText * text = bv_->getLyXText();
1271         if (text->real_current_font.isRightToLeft()
1272             && !(bv_->theLockingInset()
1273                  && bv_->theLockingInset()->lyxCode()== Inset::ERT_CODE))
1274         {
1275                 if (owner_->getIntl().keymap == Intl::PRIMARY)
1276                         owner_->getIntl().KeyMapSec();
1277         } else {
1278                 if (owner_->getIntl().keymap == Intl::SECONDARY)
1279                         owner_->getIntl().KeyMapPrim();
1280         }
1281 }
1282
1283
1284 void BufferView::Pimpl::insetUnlock()
1285 {
1286         if (bv_->theLockingInset()) {
1287                 bv_->theLockingInset()->insetUnlock(bv_);
1288                 bv_->theLockingInset(0);
1289                 finishUndo();
1290         }
1291 }
1292
1293
1294 void BufferView::Pimpl::showCursor()
1295 {
1296         if (bv_->theLockingInset())
1297                 bv_->theLockingInset()->showInsetCursor(bv_);
1298         else
1299                 screen().showCursor(bv_->text, bv_);
1300 }
1301
1302
1303 void BufferView::Pimpl::hideCursor()
1304 {
1305         if (!bv_->theLockingInset())
1306                 screen().hideCursor();
1307 }
1308
1309
1310 void BufferView::Pimpl::toggleSelection(bool b)
1311 {
1312         if (bv_->theLockingInset())
1313                 bv_->theLockingInset()->toggleSelection(bv_, b);
1314         screen().toggleSelection(bv_->text, bv_, b);
1315 }
1316
1317
1318 void BufferView::Pimpl::toggleToggle()
1319 {
1320         screen().toggleToggle(bv_->text, bv_);
1321 }
1322
1323
1324 void BufferView::Pimpl::center()
1325 {
1326         LyXText * t = bv_->text;
1327
1328         beforeChange(t);
1329         int const half_height = workarea().workHeight() / 2;
1330         int new_y = 0;
1331
1332         if (t->cursor.y() > half_height) {
1333                 new_y = t->cursor.y() - half_height;
1334         }
1335
1336         // FIXME: can we do this w/o calling screen directly ?
1337         // This updates first_y but means the fitCursor() call
1338         // from the update(FITCUR) doesn't realise that we might
1339         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
1340         // the scrollbar to be updated as it should, so we have
1341         // to do it manually. Any operation that does a center()
1342         // and also might have moved first_y must make sure to call
1343         // updateScrollbar() currently. Never mind that this is a
1344         // pretty obfuscated way of updating t->first_y
1345         screen().draw(t, bv_, new_y);
1346
1347         update(t, BufferView::SELECT | BufferView::FITCUR);
1348 }
1349
1350
1351 void BufferView::Pimpl::pasteClipboard(bool asPara)
1352 {
1353         if (!buffer_)
1354                 return;
1355
1356         screen().hideCursor();
1357         beforeChange(bv_->text);
1358
1359         string const clip(workarea().getClipboard());
1360
1361         if (clip.empty())
1362                 return;
1363
1364         if (asPara) {
1365                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1366         } else {
1367                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1368         }
1369         bv_->getLyXText()->clearSelection();
1370         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1371 }
1372
1373
1374 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1375 {
1376         workarea().putClipboard(stuff);
1377 }
1378
1379
1380 /*
1381  * Dispatch functions for actions which can be valid for BufferView->text
1382  * and/or InsetText->text!!!
1383  */
1384
1385
1386 inline
1387 void BufferView::Pimpl::moveCursorUpdate(bool selecting, bool fitcur)
1388 {
1389         LyXText * lt = bv_->getLyXText();
1390
1391         if (selecting || lt->selection.mark()) {
1392                 lt->setSelection(bv_);
1393                 if (lt->bv_owner)
1394                         toggleToggle();
1395                 else
1396                         updateInset(lt->inset_owner, false);
1397         }
1398         if (lt->bv_owner) {
1399                 if (fitcur)
1400                         update(lt, BufferView::SELECT|BufferView::FITCUR);
1401                 else
1402                         update(lt, BufferView::SELECT);
1403                 showCursor();
1404         } else if (bv_->text->status() != LyXText::UNCHANGED) {
1405                 bv_->theLockingInset()->hideInsetCursor(bv_);
1406                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1407                 showCursor();
1408         }
1409
1410         if (!lt->selection.set())
1411                 workarea().haveSelection(false);
1412
1413         switchKeyMap();
1414 }
1415
1416
1417 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1418 {
1419         LyXCursor cursor = bv_->getLyXText()->cursor;
1420         Buffer::inset_iterator it =
1421                 find_if(Buffer::inset_iterator(
1422                         cursor.par(), cursor.pos()),
1423                         buffer_->inset_iterator_end(),
1424                         lyx::compare_memfun(&Inset::lyxCode, code));
1425         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1426 }
1427
1428
1429 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1430 {
1431         string filename = filen;
1432
1433         if (filename.empty()) {
1434                 // Launch a file browser
1435                 string initpath = lyxrc.document_path;
1436
1437                 if (available()) {
1438                         string const trypath = owner_->buffer()->filePath();
1439                         // If directory is writeable, use this as default.
1440                         if (IsDirWriteable(trypath))
1441                                 initpath = trypath;
1442                 }
1443
1444                 FileDialog fileDlg(bv_->owner(),
1445                                    _("Select LyX document to insert"),
1446                         LFUN_FILE_INSERT,
1447                         make_pair(string(_("Documents|#o#O")),
1448                                   string(lyxrc.document_path)),
1449                         make_pair(string(_("Examples|#E#e")),
1450                                   string(AddPath(system_lyxdir, "examples"))));
1451
1452                 FileDialog::Result result =
1453                         fileDlg.Select(initpath,
1454                                        _("*.lyx| LyX Documents (*.lyx)"));
1455
1456                 if (result.first == FileDialog::Later)
1457                         return;
1458
1459                 filename = result.second;
1460
1461                 // check selected filename
1462                 if (filename.empty()) {
1463                         owner_->message(_("Canceled."));
1464                         return;
1465                 }
1466         }
1467
1468         // get absolute path of file and add ".lyx" to the filename if
1469         // necessary
1470         filename = FileSearch(string(), filename, "lyx");
1471
1472         string const disp_fn(MakeDisplayPath(filename));
1473
1474         ostringstream s1;
1475         s1 << _("Inserting document") << ' '
1476            << disp_fn << " ...";
1477         owner_->message(s1.str().c_str());
1478         bool const res = bv_->insertLyXFile(filename);
1479         if (res) {
1480                 ostringstream str;
1481                 str << _("Document") << ' ' << disp_fn
1482                     << ' ' << _("inserted.");
1483                 owner_->message(str.str().c_str());
1484         } else {
1485                 ostringstream str;
1486                 str << _("Could not insert document") << ' '
1487                     << disp_fn;
1488                 owner_->message(str.str().c_str());
1489         }
1490 }
1491
1492
1493 bool BufferView::Pimpl::dispatch(FuncRequest const & ev)
1494 {
1495         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1496           << ev.action <<"] arg[" << ev.argument << "]" << endl;
1497
1498         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
1499
1500         switch (ev.action) {
1501                 // --- Misc -------------------------------------------
1502         case LFUN_APPENDIX:
1503         {
1504                 if (available()) {
1505                         LyXText * lt = bv_->getLyXText();
1506                         lt->toggleAppendix(bv_);
1507                         update(lt,
1508                                BufferView::SELECT
1509                                | BufferView::FITCUR
1510                                | BufferView::CHANGE);
1511                 }
1512         }
1513         break;
1514
1515         case LFUN_TOC_INSERT:
1516         {
1517                 InsetCommandParams p;
1518                 p.setCmdName("tableofcontents");
1519                 Inset * inset = new InsetTOC(p);
1520                 if (!insertInset(inset, tclass.defaultLayoutName()))
1521                         delete inset;
1522                 break;
1523         }
1524
1525         case LFUN_SCROLL_INSET:
1526                 // this is not handled here as this funktion is only aktive
1527                 // if we have a locking_inset and that one is (or contains)
1528                 // a tabular-inset
1529                 break;
1530
1531         case LFUN_INSET_GRAPHICS:
1532         {
1533                 Inset * new_inset = new InsetGraphics;
1534                 if (!insertInset(new_inset)) {
1535                         delete new_inset;
1536                 } else {
1537                         // this is need because you don't use a inset->Edit()
1538                         updateInset(new_inset, true);
1539                         new_inset->edit(bv_);
1540                 }
1541                 break;
1542         }
1543
1544         case LFUN_PASTE:
1545                 bv_->paste();
1546                 switchKeyMap();
1547                 break;
1548
1549         case LFUN_PASTESELECTION:
1550                 pasteClipboard(ev.argument == "paragraph");
1551                 break;
1552
1553         case LFUN_CUT:
1554                 bv_->cut();
1555                 break;
1556
1557         case LFUN_COPY:
1558                 bv_->copy();
1559                 break;
1560
1561         case LFUN_LAYOUT_COPY:
1562                 bv_->copyEnvironment();
1563                 break;
1564
1565         case LFUN_LAYOUT_PASTE:
1566                 bv_->pasteEnvironment();
1567                 switchKeyMap();
1568                 break;
1569
1570         case LFUN_GOTOERROR:
1571                 gotoInset(Inset::ERROR_CODE, false);
1572                 break;
1573
1574         case LFUN_GOTONOTE:
1575                 gotoInset(Inset::NOTE_CODE, false);
1576                 break;
1577
1578         case LFUN_REFERENCE_GOTO:
1579         {
1580                 vector<Inset::Code> tmp;
1581                 tmp.push_back(Inset::LABEL_CODE);
1582                 tmp.push_back(Inset::REF_CODE);
1583                 gotoInset(tmp, true);
1584                 break;
1585         }
1586
1587         case LFUN_HYPHENATION:
1588                 specialChar(InsetSpecialChar::HYPHENATION);
1589                 break;
1590
1591         case LFUN_LIGATURE_BREAK:
1592                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1593                 break;
1594
1595         case LFUN_LDOTS:
1596                 specialChar(InsetSpecialChar::LDOTS);
1597                 break;
1598
1599         case LFUN_END_OF_SENTENCE:
1600                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1601                 break;
1602
1603         case LFUN_MENU_SEPARATOR:
1604                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1605                 break;
1606
1607         case LFUN_HFILL:
1608                 hfill();
1609                 break;
1610
1611         case LFUN_DEPTH_MIN:
1612                 changeDepth(bv_, bv_->getLyXText(), -1);
1613                 break;
1614
1615         case LFUN_DEPTH_PLUS:
1616                 changeDepth(bv_, bv_->getLyXText(), 1);
1617                 break;
1618
1619         case LFUN_FREE:
1620                 owner_->getDialogs().setUserFreeFont();
1621                 break;
1622
1623         case LFUN_FILE_INSERT:
1624                 MenuInsertLyXFile(ev.argument);
1625                 break;
1626
1627         case LFUN_FILE_INSERT_ASCII_PARA:
1628                 InsertAsciiFile(bv_, ev.argument, true);
1629                 break;
1630
1631         case LFUN_FILE_INSERT_ASCII:
1632                 InsertAsciiFile(bv_, ev.argument, false);
1633                 break;
1634
1635         case LFUN_LAYOUT:
1636         {
1637                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1638                                     << ev.argument << endl;
1639
1640                 // This is not the good solution to the empty argument
1641                 // problem, but it will hopefully suffice for 1.2.0.
1642                 // The correct solution would be to augument the
1643                 // function list/array with information about what
1644                 // functions needs arguments and their type.
1645                 if (ev.argument.empty()) {
1646                         owner_->getLyXFunc().setErrorMessage(
1647                                 _("LyX function 'layout' needs an argument."));
1648                         break;
1649                 }
1650
1651                 // Derive layout number from given argument (string)
1652                 // and current buffer's textclass (number). */
1653                 bool hasLayout = tclass.hasLayout(ev.argument);
1654                 string layout = ev.argument;
1655
1656                 // If the entry is obsolete, use the new one instead.
1657                 if (hasLayout) {
1658                         string const & obs = tclass[layout]->obsoleted_by();
1659                         if (!obs.empty())
1660                                 layout = obs;
1661                 }
1662
1663                 if (!hasLayout) {
1664                         owner_->getLyXFunc().setErrorMessage(
1665                                 string(N_("Layout ")) + ev.argument +
1666                                 N_(" not known"));
1667                         break;
1668                 }
1669
1670                 bool change_layout = (current_layout != layout);
1671                 LyXText * lt = bv_->getLyXText();
1672                 if (!change_layout && lt->selection.set() &&
1673                         lt->selection.start.par() != lt->selection.end.par())
1674                 {
1675                         Paragraph * spar = lt->selection.start.par();
1676                         Paragraph * epar = lt->selection.end.par()->next();
1677                         while(spar != epar) {
1678                                 if (spar->layout()->name() != current_layout) {
1679                                         change_layout = true;
1680                                         break;
1681                                 }
1682                         }
1683                 }
1684                 if (change_layout) {
1685                         hideCursor();
1686                         current_layout = layout;
1687                         update(lt,
1688                                BufferView::SELECT
1689                                | BufferView::FITCUR);
1690                         lt->setLayout(bv_, layout);
1691                         owner_->setLayout(layout);
1692                         update(lt,
1693                                BufferView::SELECT
1694                                | BufferView::FITCUR
1695                                | BufferView::CHANGE);
1696                         switchKeyMap();
1697                 }
1698         }
1699         break;
1700
1701         case LFUN_LANGUAGE:
1702                 lang(bv_, ev.argument);
1703                 switchKeyMap();
1704                 owner_->view_state_changed();
1705                 break;
1706
1707         case LFUN_EMPH:
1708                 emph(bv_);
1709                 owner_->view_state_changed();
1710                 break;
1711
1712         case LFUN_BOLD:
1713                 bold(bv_);
1714                 owner_->view_state_changed();
1715                 break;
1716
1717         case LFUN_NOUN:
1718                 noun(bv_);
1719                 owner_->view_state_changed();
1720                 break;
1721
1722         case LFUN_CODE:
1723                 code(bv_);
1724                 owner_->view_state_changed();
1725                 break;
1726
1727         case LFUN_SANS:
1728                 sans(bv_);
1729                 owner_->view_state_changed();
1730                 break;
1731
1732         case LFUN_ROMAN:
1733                 roman(bv_);
1734                 owner_->view_state_changed();
1735                 break;
1736
1737         case LFUN_DEFAULT:
1738                 styleReset(bv_);
1739                 owner_->view_state_changed();
1740                 break;
1741
1742         case LFUN_UNDERLINE:
1743                 underline(bv_);
1744                 owner_->view_state_changed();
1745                 break;
1746
1747         case LFUN_FONT_SIZE:
1748                 fontSize(bv_, ev.argument);
1749                 owner_->view_state_changed();
1750                 break;
1751
1752         case LFUN_FONT_STATE:
1753                 owner_->getLyXFunc().setMessage(currentState(bv_));
1754                 break;
1755
1756         case LFUN_UPCASE_WORD:
1757         {
1758                 LyXText * lt = bv_->getLyXText();
1759
1760                 update(lt,
1761                        BufferView::SELECT
1762                        | BufferView::FITCUR);
1763                 lt->changeCase(bv_, LyXText::text_uppercase);
1764                 if (lt->inset_owner)
1765                         updateInset(lt->inset_owner, true);
1766                 update(lt,
1767                        BufferView::SELECT
1768                        | BufferView::FITCUR
1769                        | BufferView::CHANGE);
1770         }
1771         break;
1772
1773         case LFUN_LOWCASE_WORD:
1774         {
1775                 LyXText * lt = bv_->getLyXText();
1776
1777                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1778                 lt->changeCase(bv_, LyXText::text_lowercase);
1779                 if (lt->inset_owner)
1780                         updateInset(lt->inset_owner, true);
1781                 update(lt,
1782                        BufferView::SELECT
1783                        | BufferView::FITCUR
1784                        | BufferView::CHANGE);
1785         }
1786         break;
1787
1788         case LFUN_CAPITALIZE_WORD:
1789         {
1790                 LyXText * lt = bv_->getLyXText();
1791
1792                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1793                 lt->changeCase(bv_, LyXText::text_capitalization);
1794                 if (lt->inset_owner)
1795                         updateInset(lt->inset_owner, true);
1796                 update(lt,
1797                        BufferView::SELECT
1798                        | BufferView::FITCUR
1799                        | BufferView::CHANGE);
1800         }
1801         break;
1802
1803         case LFUN_TRANSPOSE_CHARS:
1804         {
1805                 LyXText * lt = bv_->getLyXText();
1806
1807                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1808                 lt->transposeChars(*bv_);
1809                 if (lt->inset_owner)
1810                         updateInset(lt->inset_owner, true);
1811                 update(lt,
1812                        BufferView::SELECT
1813                        | BufferView::FITCUR
1814                        | BufferView::CHANGE);
1815         }
1816         break;
1817
1818
1819         case LFUN_INSERT_LABEL:
1820                 MenuInsertLabel(bv_, ev.argument);
1821                 break;
1822
1823         case LFUN_REF_INSERT:
1824                 if (ev.argument.empty()) {
1825                         InsetCommandParams p("ref");
1826                         owner_->getDialogs().createRef(p.getAsString());
1827                 } else {
1828                         InsetCommandParams p;
1829                         p.setFromString(ev.argument);
1830
1831                         InsetRef * inset = new InsetRef(p, *buffer_);
1832                         if (!insertInset(inset))
1833                                 delete inset;
1834                         else
1835                                 updateInset(inset, true);
1836                 }
1837                 break;
1838
1839         case LFUN_BOOKMARK_SAVE:
1840                 savePosition(strToUnsignedInt(ev.argument));
1841                 break;
1842
1843         case LFUN_BOOKMARK_GOTO:
1844                 restorePosition(strToUnsignedInt(ev.argument));
1845                 break;
1846
1847         case LFUN_REF_GOTO:
1848         {
1849                 string label = ev.argument;
1850                 if (label.empty()) {
1851                         InsetRef * inset =
1852                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1853                         if (inset) {
1854                                 label = inset->getContents();
1855                                 savePosition(0);
1856                         }
1857                 }
1858
1859                 if (!label.empty()) {
1860                         //bv_->savePosition(0);
1861                         if (!bv_->gotoLabel(label))
1862                                 Alert::alert(_("Error"),
1863                                            _("Couldn't find this label"),
1864                                            _("in current document."));
1865                 }
1866         }
1867         break;
1868
1869                 // --- Cursor Movements -----------------------------
1870         case LFUN_RIGHT:
1871         {
1872                 LyXText * lt = bv_->getLyXText();
1873
1874                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1875                 if (!lt->selection.mark())
1876                         beforeChange(lt);
1877                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1878                 if (is_rtl)
1879                         lt->cursorLeft(bv_, false);
1880                 if (lt->cursor.pos() < lt->cursor.par()->size()
1881                     && lt->cursor.par()->isInset(lt->cursor.pos())
1882                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1883                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1884                         owner_->getLyXFunc().setMessage(tmpinset->editMessage());
1885                         if (is_rtl)
1886                                 tmpinset->edit(bv_, false);
1887                         else
1888                                 tmpinset->edit(bv_);
1889                         break;
1890                 }
1891                 if (!is_rtl)
1892                         lt->cursorRight(bv_, false);
1893                 finishUndo();
1894                 moveCursorUpdate(false);
1895                 owner_->view_state_changed();
1896         }
1897         break;
1898
1899         case LFUN_LEFT:
1900         {
1901                 // This is soooo ugly. Isn`t it possible to make
1902                 // it simpler? (Lgb)
1903                 LyXText * lt = bv_->getLyXText();
1904                 bool const is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1905                 if (!lt->selection.mark())
1906                         beforeChange(lt);
1907                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1908                 LyXCursor const cur = lt->cursor;
1909                 if (!is_rtl)
1910                         lt->cursorLeft(bv_, false);
1911                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1912                     lt->cursor.pos() < lt->cursor.par()->size() &&
1913                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
1914                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1915                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1916                         owner_->getLyXFunc().setMessage(tmpinset->editMessage());
1917                         if (is_rtl)
1918                                 tmpinset->edit(bv_);
1919                         else
1920                                 tmpinset->edit(bv_, false);
1921                         break;
1922                 }
1923                 if  (is_rtl)
1924                         lt->cursorRight(bv_, false);
1925
1926                 finishUndo();
1927                 moveCursorUpdate(false);
1928                 owner_->view_state_changed();
1929         }
1930         break;
1931
1932         case LFUN_UP:
1933         {
1934                 LyXText * lt = bv_->getLyXText();
1935
1936                 if (!lt->selection.mark())
1937                         beforeChange(lt);
1938                 update(lt, BufferView::UPDATE);
1939                 lt->cursorUp(bv_);
1940                 finishUndo();
1941                 moveCursorUpdate(false);
1942                 owner_->view_state_changed();
1943         }
1944         break;
1945
1946         case LFUN_DOWN:
1947         {
1948                 LyXText * lt = bv_->getLyXText();
1949
1950                 if (!lt->selection.mark())
1951                         beforeChange(lt);
1952                 update(lt, BufferView::UPDATE);
1953                 lt->cursorDown(bv_);
1954                 finishUndo();
1955                 moveCursorUpdate(false);
1956                 owner_->view_state_changed();
1957         }
1958         break;
1959
1960         case LFUN_UP_PARAGRAPH:
1961         {
1962                 LyXText * lt = bv_->getLyXText();
1963
1964                 if (!lt->selection.mark())
1965                         beforeChange(lt);
1966                 update(lt, BufferView::UPDATE);
1967                 lt->cursorUpParagraph(bv_);
1968                 finishUndo();
1969                 moveCursorUpdate(false);
1970                 owner_->view_state_changed();
1971         }
1972         break;
1973
1974         case LFUN_DOWN_PARAGRAPH:
1975         {
1976                 LyXText * lt = bv_->getLyXText();
1977
1978                 if (!lt->selection.mark())
1979                         beforeChange(lt);
1980                 update(lt, BufferView::UPDATE);
1981                 lt->cursorDownParagraph(bv_);
1982                 finishUndo();
1983                 moveCursorUpdate(false);
1984                 owner_->view_state_changed();
1985         }
1986         break;
1987
1988         case LFUN_PRIOR:
1989         {
1990                 LyXText * lt = bv_->getLyXText();
1991
1992                 if (!lt->selection.mark())
1993                         beforeChange(lt);
1994                 update(lt, BufferView::UPDATE);
1995                 cursorPrevious(lt);
1996                 finishUndo();
1997                 moveCursorUpdate(false, false);
1998                 owner_->view_state_changed();
1999         }
2000         break;
2001
2002         case LFUN_NEXT:
2003         {
2004                 LyXText * lt = bv_->getLyXText();
2005
2006                 if (!lt->selection.mark())
2007                         beforeChange(lt);
2008                 update(lt, BufferView::UPDATE);
2009                 cursorNext(lt);
2010                 finishUndo();
2011                 moveCursorUpdate(false, false);
2012                 owner_->view_state_changed();
2013         }
2014         break;
2015
2016         case LFUN_HOME:
2017         {
2018                 LyXText * lt = bv_->getLyXText();
2019
2020                 if (!lt->selection.mark())
2021                         beforeChange(lt);
2022                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2023                 lt->cursorHome(bv_);
2024                 finishUndo();
2025                 moveCursorUpdate(false);
2026                 owner_->view_state_changed();
2027         }
2028         break;
2029
2030         case LFUN_END:
2031         {
2032                 LyXText * lt = bv_->getLyXText();
2033
2034                 if (!lt->selection.mark())
2035                         beforeChange(lt);
2036                 update(lt,
2037                        BufferView::SELECT|BufferView::FITCUR);
2038                 lt->cursorEnd(bv_);
2039                 finishUndo();
2040                 moveCursorUpdate(false);
2041                 owner_->view_state_changed();
2042         }
2043         break;
2044
2045         case LFUN_SHIFT_TAB:
2046         case LFUN_TAB:
2047         {
2048                 LyXText * lt = bv_->getLyXText();
2049
2050                 if (!lt->selection.mark())
2051                         beforeChange(lt);
2052                 update(lt,
2053                        BufferView::SELECT|BufferView::FITCUR);
2054                 lt->cursorTab(bv_);
2055                 finishUndo();
2056                 moveCursorUpdate(false);
2057                 owner_->view_state_changed();
2058         }
2059         break;
2060
2061         case LFUN_WORDRIGHT:
2062         {
2063                 LyXText * lt = bv_->getLyXText();
2064
2065                 if (!lt->selection.mark())
2066                         beforeChange(lt);
2067                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2068                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2069                         lt->cursorLeftOneWord(bv_);
2070                 else
2071                         lt->cursorRightOneWord(bv_);
2072                 finishUndo();
2073                 moveCursorUpdate(false);
2074                 owner_->view_state_changed();
2075         }
2076         break;
2077
2078         case LFUN_WORDLEFT:
2079         {
2080                 LyXText * lt = bv_->getLyXText();
2081
2082                 if (!lt->selection.mark())
2083                         beforeChange(lt);
2084                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2085                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2086                         lt->cursorRightOneWord(bv_);
2087                 else
2088                         lt->cursorLeftOneWord(bv_);
2089                 finishUndo();
2090                 moveCursorUpdate(false);
2091                 owner_->view_state_changed();
2092         }
2093         break;
2094
2095         case LFUN_BEGINNINGBUF:
2096         {
2097                 LyXText * lt = bv_->getLyXText();
2098
2099                 if (!lt->selection.mark())
2100                         beforeChange(lt);
2101                 update(lt,
2102                        BufferView::SELECT|BufferView::FITCUR);
2103                 lt->cursorTop(bv_);
2104                 finishUndo();
2105                 moveCursorUpdate(false);
2106                 owner_->view_state_changed();
2107         }
2108         break;
2109
2110         case LFUN_ENDBUF:
2111         {
2112                 LyXText * lt = bv_->getLyXText();
2113
2114                 if (!lt->selection.mark())
2115                         beforeChange(lt);
2116                 update(lt,
2117                        BufferView::SELECT|BufferView::FITCUR);
2118                 lt->cursorBottom(bv_);
2119                 finishUndo();
2120                 moveCursorUpdate(false);
2121                 owner_->view_state_changed();
2122         }
2123         break;
2124
2125                 /* cursor selection ---------------------------- */
2126         case LFUN_RIGHTSEL:
2127         {
2128                 LyXText * lt = bv_->getLyXText();
2129
2130                 update(lt,
2131                        BufferView::SELECT|BufferView::FITCUR);
2132                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2133                         lt->cursorLeft(bv_);
2134                 else
2135                         lt->cursorRight(bv_);
2136                 finishUndo();
2137                 moveCursorUpdate(true);
2138                 owner_->view_state_changed();
2139         }
2140         break;
2141
2142         case LFUN_LEFTSEL:
2143         {
2144                 LyXText * lt = bv_->getLyXText();
2145
2146                 update(lt,
2147                        BufferView::SELECT|BufferView::FITCUR);
2148                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2149                         lt->cursorRight(bv_);
2150                 else
2151                         lt->cursorLeft(bv_);
2152                 finishUndo();
2153                 moveCursorUpdate(true);
2154                 owner_->view_state_changed();
2155         }
2156         break;
2157
2158         case LFUN_UPSEL:
2159         {
2160                 LyXText * lt = bv_->getLyXText();
2161
2162                 update(lt,
2163                        BufferView::SELECT|BufferView::FITCUR);
2164                 lt->cursorUp(bv_, true);
2165                 finishUndo();
2166                 moveCursorUpdate(true);
2167                 owner_->view_state_changed();
2168         }
2169         break;
2170
2171         case LFUN_DOWNSEL:
2172         {
2173                 LyXText * lt = bv_->getLyXText();
2174
2175                 update(lt,
2176                        BufferView::SELECT|BufferView::FITCUR);
2177                 lt->cursorDown(bv_, true);
2178                 finishUndo();
2179                 moveCursorUpdate(true);
2180                 owner_->view_state_changed();
2181         }
2182         break;
2183
2184         case LFUN_UP_PARAGRAPHSEL:
2185         {
2186                 LyXText * lt = bv_->getLyXText();
2187
2188                 update(lt,
2189                        BufferView::SELECT|BufferView::FITCUR);
2190                 lt->cursorUpParagraph(bv_);
2191                 finishUndo();
2192                 moveCursorUpdate(true);
2193                 owner_->view_state_changed();
2194         }
2195         break;
2196
2197         case LFUN_DOWN_PARAGRAPHSEL:
2198         {
2199                 LyXText * lt = bv_->getLyXText();
2200
2201                 update(lt,
2202                        BufferView::SELECT|BufferView::FITCUR);
2203                 lt->cursorDownParagraph(bv_);
2204                 finishUndo();
2205                 moveCursorUpdate(true);
2206                 owner_->view_state_changed();
2207         }
2208         break;
2209
2210         case LFUN_PRIORSEL:
2211         {
2212                 LyXText * lt = bv_->getLyXText();
2213
2214                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2215                 cursorPrevious(lt);
2216                 finishUndo();
2217                 moveCursorUpdate(true);
2218                 owner_->view_state_changed();
2219         }
2220         break;
2221
2222         case LFUN_NEXTSEL:
2223         {
2224                 LyXText * lt = bv_->getLyXText();
2225
2226                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2227                 cursorNext(lt);
2228                 finishUndo();
2229                 moveCursorUpdate(true);
2230                 owner_->view_state_changed();
2231         }
2232         break;
2233
2234         case LFUN_HOMESEL:
2235         {
2236                 LyXText * lt = bv_->getLyXText();
2237
2238                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2239                 lt->cursorHome(bv_);
2240                 finishUndo();
2241                 moveCursorUpdate(true);
2242                 owner_->view_state_changed();
2243         }
2244         break;
2245
2246         case LFUN_ENDSEL:
2247         {
2248                 LyXText * lt = bv_->getLyXText();
2249
2250                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2251                 lt->cursorEnd(bv_);
2252                 finishUndo();
2253                 moveCursorUpdate(true);
2254                 owner_->view_state_changed();
2255         }
2256         break;
2257
2258         case LFUN_WORDRIGHTSEL:
2259         {
2260                 LyXText * lt = bv_->getLyXText();
2261
2262                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2263                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2264                         lt->cursorLeftOneWord(bv_);
2265                 else
2266                         lt->cursorRightOneWord(bv_);
2267                 finishUndo();
2268                 moveCursorUpdate(true);
2269                 owner_->view_state_changed();
2270         }
2271         break;
2272
2273         case LFUN_WORDLEFTSEL:
2274         {
2275                 LyXText * lt = bv_->getLyXText();
2276
2277                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2278                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2279                         lt->cursorRightOneWord(bv_);
2280                 else
2281                         lt->cursorLeftOneWord(bv_);
2282                 finishUndo();
2283                 moveCursorUpdate(true);
2284                 owner_->view_state_changed();
2285         }
2286         break;
2287
2288         case LFUN_BEGINNINGBUFSEL:
2289         {
2290                 LyXText * lt = bv_->getLyXText();
2291
2292                 if (lt->inset_owner)
2293                         break;
2294                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2295                 lt->cursorTop(bv_);
2296                 finishUndo();
2297                 moveCursorUpdate(true);
2298                 owner_->view_state_changed();
2299         }
2300         break;
2301
2302         case LFUN_ENDBUFSEL:
2303         {
2304                 LyXText * lt = bv_->getLyXText();
2305
2306                 if (lt->inset_owner)
2307                         break;
2308                 update(lt,
2309                        BufferView::SELECT|BufferView::FITCUR);
2310                 lt->cursorBottom(bv_);
2311                 finishUndo();
2312                 moveCursorUpdate(true);
2313                 owner_->view_state_changed();
2314         }
2315         break;
2316
2317                 // --- text changing commands ------------------------
2318         case LFUN_BREAKLINE:
2319         {
2320                 LyXText * lt = bv_->getLyXText();
2321
2322                 beforeChange(lt);
2323                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2324                 update(lt,
2325                        BufferView::SELECT
2326                        | BufferView::FITCUR
2327                        | BufferView::CHANGE);
2328                 lt->setCursor(bv_, lt->cursor.par(), lt->cursor.pos());
2329                 moveCursorUpdate(false);
2330         }
2331         break;
2332
2333         case LFUN_PROTECTEDSPACE:
2334         {
2335                 LyXText * lt = bv_->getLyXText();
2336                 LyXLayout_ptr const & style = lt->cursor.par()->layout();
2337
2338                 if (style->free_spacing) {
2339                         lt->insertChar(bv_, ' ');
2340                         update(lt,
2341                                BufferView::SELECT
2342                                | BufferView::FITCUR
2343                                | BufferView::CHANGE);
2344                 } else {
2345                         specialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
2346                 }
2347                 moveCursorUpdate(false);
2348         }
2349         break;
2350
2351         case LFUN_SETMARK:
2352         {
2353                 LyXText * lt = bv_->getLyXText();
2354
2355                 if (lt->selection.mark()) {
2356                         beforeChange(lt);
2357                         update(lt,
2358                                BufferView::SELECT
2359                                | BufferView::FITCUR);
2360                         owner_->getLyXFunc().setMessage(N_("Mark removed"));
2361                 } else {
2362                         beforeChange(lt);
2363                         lt->selection.mark(true);
2364                         update(lt,
2365                                BufferView::SELECT
2366                                | BufferView::FITCUR);
2367                         owner_->getLyXFunc().setMessage(N_("Mark set"));
2368                 }
2369                 lt->selection.cursor = lt->cursor;
2370         }
2371         break;
2372
2373         case LFUN_DELETE:
2374         {
2375                 LyXText * lt = bv_->getLyXText();
2376
2377                 if (!lt->selection.set()) {
2378                         lt->Delete(bv_);
2379                         lt->selection.cursor = lt->cursor;
2380                         update(lt,
2381                                BufferView::SELECT
2382                                | BufferView::FITCUR
2383                                | BufferView::CHANGE);
2384                         // It is possible to make it a lot faster still
2385                         // just comment out the line below...
2386                         showCursor();
2387                 } else {
2388                         bv_->cut(false);
2389                 }
2390                 moveCursorUpdate(false);
2391                 owner_->view_state_changed();
2392                 switchKeyMap();
2393         }
2394         break;
2395
2396         case LFUN_DELETE_SKIP:
2397         {
2398                 LyXText * lt = bv_->getLyXText();
2399
2400                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2401
2402                 LyXCursor cursor = lt->cursor;
2403
2404                 if (!lt->selection.set()) {
2405                         if (cursor.pos() == cursor.par()->size()) {
2406                                 lt->cursorRight(bv_);
2407                                 cursor = lt->cursor;
2408                                 if (cursor.pos() == 0
2409                                     && !(cursor.par()->params().spaceTop()
2410                                          == VSpace (VSpace::NONE))) {
2411                                         lt->setParagraph
2412                                                 (bv_,
2413                                                  cursor.par()->params().lineTop(),
2414                                                  cursor.par()->params().lineBottom(),
2415                                                  cursor.par()->params().pagebreakTop(),
2416                                                  cursor.par()->params().pagebreakBottom(),
2417                                                  VSpace(VSpace::NONE),
2418                                                  cursor.par()->params().spaceBottom(),
2419                                                  cursor.par()->params().spacing(),
2420                                                  cursor.par()->params().align(),
2421                                                  cursor.par()->params().labelWidthString(), 0);
2422                                         lt->cursorLeft(bv_);
2423                                         update(lt,
2424                                                BufferView::SELECT
2425                                                | BufferView::FITCUR
2426                                                | BufferView::CHANGE);
2427                                 } else {
2428                                         lt->cursorLeft(bv_);
2429                                         lt->Delete(bv_);
2430                                         lt->selection.cursor = lt->cursor;
2431                                         update(lt,
2432                                                BufferView::SELECT
2433                                                | BufferView::FITCUR
2434                                                | BufferView::CHANGE);
2435                                 }
2436                         } else {
2437                                 lt->Delete(bv_);
2438                                 lt->selection.cursor = lt->cursor;
2439                                 update(lt,
2440                                        BufferView::SELECT
2441                                        | BufferView::FITCUR
2442                                        | BufferView::CHANGE);
2443                         }
2444                 } else {
2445                         bv_->cut(false);
2446                 }
2447         }
2448         break;
2449
2450         /* -------> Delete word forward. */
2451         case LFUN_DELETE_WORD_FORWARD:
2452                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2453                 bv_->getLyXText()->deleteWordForward(bv_);
2454                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2455                 moveCursorUpdate(false);
2456                 owner_->view_state_changed();
2457                 break;
2458
2459                 /* -------> Delete word backward. */
2460         case LFUN_DELETE_WORD_BACKWARD:
2461         {
2462                 LyXText * lt = bv_->getLyXText();
2463
2464                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2465                 lt->deleteWordBackward(bv_);
2466                 update(lt,
2467                        BufferView::SELECT
2468                        | BufferView::FITCUR
2469                        | BufferView::CHANGE);
2470                 moveCursorUpdate(false);
2471                 owner_->view_state_changed();
2472         }
2473         break;
2474
2475                 /* -------> Kill to end of line. */
2476         case LFUN_DELETE_LINE_FORWARD:
2477         {
2478                 LyXText * lt = bv_->getLyXText();
2479
2480                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2481                 lt->deleteLineForward(bv_);
2482                 update(lt,
2483                        BufferView::SELECT
2484                        | BufferView::FITCUR
2485                        | BufferView::CHANGE);
2486                 moveCursorUpdate(false);
2487         }
2488         break;
2489
2490                 /* -------> Set mark off. */
2491         case LFUN_MARK_OFF:
2492         {
2493                 LyXText * lt = bv_->getLyXText();
2494
2495                 beforeChange(lt);
2496                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2497                 lt->selection.cursor = lt->cursor;
2498                 owner_->getLyXFunc().setMessage(N_("Mark off"));
2499         }
2500         break;
2501
2502                 /* -------> Set mark on. */
2503         case LFUN_MARK_ON:
2504         {
2505                 LyXText * lt = bv_->getLyXText();
2506
2507                 beforeChange(lt);
2508                 lt->selection.mark(true);
2509                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2510                 lt->selection.cursor = lt->cursor;
2511                 owner_->getLyXFunc().setMessage(N_("Mark on"));
2512         }
2513         break;
2514
2515         case LFUN_BACKSPACE:
2516         {
2517                 LyXText * lt = bv_->getLyXText();
2518
2519                 if (!lt->selection.set()) {
2520                         if (owner_->getIntl().getTransManager().backspace()) {
2521                                 lt->backspace(bv_);
2522                                 lt->selection.cursor = lt->cursor;
2523                                 update(lt,
2524                                        BufferView::SELECT
2525                                        | BufferView::FITCUR
2526                                        | BufferView::CHANGE);
2527                                 // It is possible to make it a lot faster still
2528                                 // just comment out the line below...
2529                                 showCursor();
2530                         }
2531                 } else {
2532                         bv_->cut(false);
2533                 }
2534                 owner_->view_state_changed();
2535                 switchKeyMap();
2536         }
2537         break;
2538
2539         case LFUN_BACKSPACE_SKIP:
2540         {
2541                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2542                 LyXText * lt = bv_->getLyXText();
2543
2544                 LyXCursor cursor = lt->cursor;
2545
2546                 if (!lt->selection.set()) {
2547                         if (cursor.pos() == 0
2548                             && !(cursor.par()->params().spaceTop()
2549                                  == VSpace (VSpace::NONE))) {
2550                                 lt->setParagraph
2551                                         (bv_,
2552                                          cursor.par()->params().lineTop(),
2553                                          cursor.par()->params().lineBottom(),
2554                                          cursor.par()->params().pagebreakTop(),
2555                                          cursor.par()->params().pagebreakBottom(),
2556                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2557                                          cursor.par()->params().spacing(),
2558                                          cursor.par()->params().align(),
2559                                          cursor.par()->params().labelWidthString(), 0);
2560                                 update(lt,
2561                                        BufferView::SELECT
2562                                        | BufferView::FITCUR
2563                                        | BufferView::CHANGE);
2564                         } else {
2565                                 lt->backspace(bv_);
2566                                 lt->selection.cursor = cursor;
2567                                 update(lt,
2568                                        BufferView::SELECT
2569                                        | BufferView::FITCUR
2570                                        | BufferView::CHANGE);
2571                         }
2572                 } else
2573                         bv_->cut(false);
2574         }
2575         break;
2576
2577         case LFUN_BREAKPARAGRAPH:
2578         {
2579                 LyXText * lt = bv_->getLyXText();
2580
2581                 beforeChange(lt);
2582                 lt->breakParagraph(bv_, 0);
2583                 update(lt,
2584                        BufferView::SELECT
2585                        | BufferView::FITCUR
2586                        | BufferView::CHANGE);
2587                 lt->selection.cursor = lt->cursor;
2588                 switchKeyMap();
2589                 owner_->view_state_changed();
2590                 break;
2591         }
2592
2593         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2594         {
2595                 LyXText * lt = bv_->getLyXText();
2596
2597                 beforeChange(lt);
2598                 lt->breakParagraph(bv_, 1);
2599                 update(lt,
2600                        BufferView::SELECT
2601                        | BufferView::FITCUR
2602                        | BufferView::CHANGE);
2603                 lt->selection.cursor = lt->cursor;
2604                 switchKeyMap();
2605                 owner_->view_state_changed();
2606                 break;
2607         }
2608
2609         case LFUN_BREAKPARAGRAPH_SKIP:
2610         {
2611                 // When at the beginning of a paragraph, remove
2612                 // indentation and add a "defskip" at the top.
2613                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2614                 LyXText * lt = bv_->getLyXText();
2615
2616                 LyXCursor cursor = lt->cursor;
2617
2618                 beforeChange(lt);
2619                 if (cursor.pos() == 0) {
2620                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2621                                 lt->setParagraph
2622                                         (bv_,
2623                                          cursor.par()->params().lineTop(),
2624                                          cursor.par()->params().lineBottom(),
2625                                          cursor.par()->params().pagebreakTop(),
2626                                          cursor.par()->params().pagebreakBottom(),
2627                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2628                                          cursor.par()->params().spacing(),
2629                                          cursor.par()->params().align(),
2630                                          cursor.par()->params().labelWidthString(), 1);
2631                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2632                         }
2633                 }
2634                 else {
2635                         lt->breakParagraph(bv_, 0);
2636                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2637                 }
2638
2639                 update(lt,
2640                        BufferView::SELECT
2641                        | BufferView::FITCUR
2642                        | BufferView::CHANGE);
2643                 lt->selection.cursor = cursor;
2644                 switchKeyMap();
2645                 owner_->view_state_changed();
2646         }
2647         break;
2648
2649         case LFUN_PARAGRAPH_SPACING:
2650         {
2651                 LyXText * lt = bv_->getLyXText();
2652
2653                 Paragraph * par = lt->cursor.par();
2654                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2655                 float cur_value = 1.0;
2656                 if (cur_spacing == Spacing::Other) {
2657                         cur_value = par->params().spacing().getValue();
2658                 }
2659
2660                 istringstream istr(ev.argument.c_str());
2661
2662                 string tmp;
2663                 istr >> tmp;
2664                 Spacing::Space new_spacing = cur_spacing;
2665                 float new_value = cur_value;
2666                 if (tmp.empty()) {
2667                         lyxerr << "Missing argument to `paragraph-spacing'"
2668                                << endl;
2669                 } else if (tmp == "single") {
2670                         new_spacing = Spacing::Single;
2671                 } else if (tmp == "onehalf") {
2672                         new_spacing = Spacing::Onehalf;
2673                 } else if (tmp == "double") {
2674                         new_spacing = Spacing::Double;
2675                 } else if (tmp == "other") {
2676                         new_spacing = Spacing::Other;
2677                         float tmpval = 0.0;
2678                         istr >> tmpval;
2679                         lyxerr << "new_value = " << tmpval << endl;
2680                         if (tmpval != 0.0)
2681                                 new_value = tmpval;
2682                 } else if (tmp == "default") {
2683                         new_spacing = Spacing::Default;
2684                 } else {
2685                         lyxerr << _("Unknown spacing argument: ")
2686                                << ev.argument << endl;
2687                 }
2688                 if (cur_spacing != new_spacing || cur_value != new_value) {
2689                         par->params().spacing(Spacing(new_spacing, new_value));
2690                         lt->redoParagraph(bv_);
2691                         update(lt,
2692                                BufferView::SELECT
2693                                | BufferView::FITCUR
2694                                | BufferView::CHANGE);
2695                 }
2696         }
2697         break;
2698
2699         case LFUN_INSET_TOGGLE:
2700         {
2701                 LyXText * lt = bv_->getLyXText();
2702                 hideCursor();
2703                 beforeChange(lt);
2704                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2705                 lt->toggleInset(bv_);
2706                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2707                 switchKeyMap();
2708         }
2709                 break;
2710
2711         case LFUN_QUOTE:
2712                 smartQuote();
2713                 break;
2714
2715         case LFUN_HTMLURL:
2716         case LFUN_URL:
2717         {
2718                 InsetCommandParams p;
2719                 if (ev.action == LFUN_HTMLURL)
2720                         p.setCmdName("htmlurl");
2721                 else
2722                         p.setCmdName("url");
2723                 owner_->getDialogs().createUrl(p.getAsString());
2724         }
2725         break;
2726
2727         case LFUN_INSERT_URL:
2728         {
2729                 InsetCommandParams p;
2730                 p.setFromString(ev.argument);
2731
2732                 InsetUrl * inset = new InsetUrl(p);
2733                 if (!insertInset(inset))
2734                         delete inset;
2735                 else
2736                         updateInset(inset, true);
2737         }
2738         break;
2739
2740         case LFUN_INSET_ERT:
2741                 insertAndEditInset(new InsetERT(buffer_->params));
2742                 break;
2743
2744         case LFUN_INSET_EXTERNAL:
2745                 insertAndEditInset(new InsetExternal);
2746                 break;
2747
2748         case LFUN_INSET_FOOTNOTE:
2749                 insertAndEditInset(new InsetFoot(buffer_->params));
2750                 break;
2751
2752         case LFUN_INSET_MARGINAL:
2753                 insertAndEditInset(new InsetMarginal(buffer_->params));
2754                 break;
2755
2756         case LFUN_INSET_MINIPAGE:
2757                 insertAndEditInset(new InsetMinipage(buffer_->params));
2758                 break;
2759
2760         case LFUN_INSERT_NOTE:
2761                 insertAndEditInset(new InsetNote(buffer_->params));
2762                 break;
2763
2764         case LFUN_INSET_FLOAT:
2765                 // check if the float type exist
2766                 if (floatList.typeExist(ev.argument)) {
2767                         insertAndEditInset(new InsetFloat(buffer_->params,
2768                                                           ev.argument));
2769                 } else {
2770                         lyxerr << "Non-existent float type: "
2771                                << ev.argument << endl;
2772                 }
2773                 break;
2774
2775         case LFUN_INSET_WIDE_FLOAT:
2776                 // check if the float type exist
2777                 if (floatList.typeExist(ev.argument)) {
2778                         InsetFloat * new_inset =
2779                                 new InsetFloat(buffer_->params, ev.argument);
2780                         new_inset->wide(true);
2781                         insertAndEditInset(new_inset);
2782                 } else {
2783                         lyxerr << "Non-existent float type: "
2784                                << ev.argument << endl;
2785                 }
2786                 break;
2787
2788 #if 0
2789         case LFUN_INSET_LIST:
2790                 insertAndEditInset(new InsetList);
2791                 break;
2792
2793         case LFUN_INSET_THEOREM:
2794                 insertAndEditInset(new InsetTheorem);
2795                 break;
2796 #endif
2797
2798         case LFUN_INSET_CAPTION:
2799         {
2800                 // Do we have a locking inset...
2801                 if (bv_->theLockingInset()) {
2802                         lyxerr << "Locking inset code: "
2803                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2804                         InsetCaption * new_inset =
2805                                 new InsetCaption(buffer_->params);
2806                         new_inset->setOwner(bv_->theLockingInset());
2807                         new_inset->setAutoBreakRows(true);
2808                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2809                         new_inset->setFrameColor(0, LColor::captionframe);
2810                         if (insertInset(new_inset))
2811                                 new_inset->edit(bv_);
2812                         else
2813                                 delete new_inset;
2814                 }
2815         }
2816         break;
2817
2818         case LFUN_TABULAR_INSERT:
2819         {
2820                 if (ev.argument.empty()) {
2821                         owner_->getDialogs().showTabularCreate();
2822                         break;
2823                 }
2824
2825                 int r = 2;
2826                 int c = 2;
2827                 ::sscanf(ev.argument.c_str(),"%d%d", &r, &c);
2828                 InsetTabular * new_inset =
2829                         new InsetTabular(*buffer_, r, c);
2830                 bool const rtl =
2831                         bv_->getLyXText()->real_current_font.isRightToLeft();
2832                 if (!open_new_inset(new_inset, rtl))
2833                         delete new_inset;
2834         }
2835         break;
2836
2837         // --- lyxserver commands ----------------------------
2838
2839         case LFUN_CHARATCURSOR:
2840         {
2841                 pos_type pos = bv_->getLyXText()->cursor.pos();
2842                 if (pos < bv_->getLyXText()->cursor.par()->size())
2843                         owner_->getLyXFunc().setMessage(
2844                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2845                 else
2846                         owner_->getLyXFunc().setMessage("EOF");
2847         }
2848         break;
2849
2850         case LFUN_GETXY:
2851                 owner_->getLyXFunc().setMessage(tostr(bv_->getLyXText()->cursor.x())
2852                                                  + ' '
2853                                                  + tostr(bv_->getLyXText()->cursor.y()));
2854                 break;
2855
2856         case LFUN_SETXY:
2857         {
2858                 int x = 0;
2859                 int y = 0;
2860                 if (::sscanf(ev.argument.c_str(), " %d %d", &x, &y) != 2) {
2861                         lyxerr << "SETXY: Could not parse coordinates in '"
2862                                << ev.argument << std::endl;
2863                 }
2864                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2865         }
2866         break;
2867
2868         case LFUN_GETLAYOUT:
2869                 owner_->getLyXFunc().setMessage(tostr(bv_->getLyXText()->cursor.par()->layout()));
2870                 break;
2871
2872         case LFUN_GETFONT:
2873         {
2874                 LyXFont & font = bv_->getLyXText()->current_font;
2875                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2876                         owner_->getLyXFunc().setMessage("E");
2877                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2878                         owner_->getLyXFunc().setMessage("N");
2879                 else
2880                         owner_->getLyXFunc().setMessage("0");
2881
2882         }
2883         break;
2884
2885         // --- accented characters ---------------------------
2886
2887         case LFUN_UMLAUT:
2888         case LFUN_CIRCUMFLEX:
2889         case LFUN_GRAVE:
2890         case LFUN_ACUTE:
2891         case LFUN_TILDE:
2892         case LFUN_CEDILLA:
2893         case LFUN_MACRON:
2894         case LFUN_DOT:
2895         case LFUN_UNDERDOT:
2896         case LFUN_UNDERBAR:
2897         case LFUN_CARON:
2898         case LFUN_SPECIAL_CARON:
2899         case LFUN_BREVE:
2900         case LFUN_TIE:
2901         case LFUN_HUNG_UMLAUT:
2902         case LFUN_CIRCLE:
2903         case LFUN_OGONEK:
2904                 if (ev.argument.empty()) {
2905                         // As always...
2906                         owner_->getLyXFunc().handleKeyFunc(ev.action);
2907                 } else {
2908                         owner_->getLyXFunc().handleKeyFunc(ev.action);
2909                         owner_->getIntl().getTransManager()
2910                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
2911                         update(bv_->getLyXText(),
2912                                BufferView::SELECT
2913                                | BufferView::FITCUR
2914                                | BufferView::CHANGE);
2915                 }
2916                 break;
2917
2918         case LFUN_MATH:
2919                 mathDispatch(bv_, ev.argument);
2920                 break;
2921
2922         case LFUN_MATH_MACRO:
2923                 mathDispatchMathMacro(bv_, ev.argument);
2924                 break;
2925
2926         case LFUN_MATH_DELIM:
2927                 mathDispatchMathDelim(bv_, ev.argument);
2928                 break;
2929
2930         case LFUN_INSERT_MATRIX:
2931                 mathDispatchInsertMatrix(bv_, ev.argument);
2932                 break;
2933
2934         case LFUN_INSERT_MATH:
2935                 mathDispatchInsertMath(bv_, ev.argument);
2936                 break;
2937
2938         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2939                 mathDispatchMathImportSelection(bv_, ev.argument);
2940                 break;
2941
2942         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2943                 mathDispatchMathDisplay(bv_, ev.argument);
2944                 break;
2945
2946         case LFUN_MATH_MODE:             // Open or create an inlined math inset
2947                 mathDispatchMathMode(bv_, ev.argument);
2948                 break;
2949
2950         case LFUN_GREEK:                 // Insert a single greek letter
2951                 mathDispatchGreek(bv_, ev.argument);
2952                 break;
2953
2954         case LFUN_CITATION_INSERT:
2955         {
2956                 InsetCommandParams p;
2957                 p.setFromString(ev.argument);
2958
2959                 InsetCitation * inset = new InsetCitation(p);
2960                 if (!insertInset(inset))
2961                         delete inset;
2962                 else
2963                         updateInset(inset, true);
2964         }
2965         break;
2966
2967         case LFUN_INSERT_BIBTEX:
2968         {
2969                 // ale970405+lasgoutt970425
2970                 // The argument can be up to two tokens separated
2971                 // by a space. The first one is the bibstyle.
2972                 string const db       = token(ev.argument, ' ', 0);
2973                 string const bibstyle = token(ev.argument, ' ', 1);
2974
2975                 InsetCommandParams p("BibTeX", db, bibstyle);
2976                 InsetBibtex * inset = new InsetBibtex(p);
2977
2978                 if (insertInset(inset)) {
2979                         if (ev.argument.empty())
2980                                 inset->edit(bv_);
2981                 } else
2982                         delete inset;
2983         }
2984         break;
2985
2986         // BibTeX data bases
2987         case LFUN_BIBDB_ADD:
2988         {
2989                 InsetBibtex * inset =
2990                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2991                 if (inset) {
2992                         inset->addDatabase(ev.argument);
2993                 }
2994         }
2995         break;
2996
2997         case LFUN_BIBDB_DEL:
2998         {
2999                 InsetBibtex * inset =
3000                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3001                 if (inset) {
3002                         inset->delDatabase(ev.argument);
3003                 }
3004         }
3005         break;
3006
3007         case LFUN_BIBTEX_STYLE:
3008         {
3009                 InsetBibtex * inset =
3010                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3011                 if (inset) {
3012                         inset->setOptions(ev.argument);
3013                 }
3014         }
3015         break;
3016
3017         case LFUN_INDEX_INSERT:
3018         {
3019                 string entry = ev.argument;
3020                 if (entry.empty()) {
3021                         entry = bv_->getLyXText()->getStringToIndex(bv_);
3022                 }
3023
3024                 if (entry.empty()) {
3025                         owner_->getDialogs().createIndex();
3026                         break;
3027                 }
3028
3029                 InsetIndex * inset = new InsetIndex(InsetCommandParams("index", entry));
3030
3031                 if (!insertInset(inset)) {
3032                         delete inset;
3033                 } else {
3034                         updateInset(inset, true);
3035                 }
3036         }
3037         break;
3038
3039         case LFUN_INDEX_PRINT:
3040         {
3041                 InsetCommandParams p("printindex");
3042                 Inset * inset = new InsetPrintIndex(p);
3043                 if (!insertInset(inset, tclass.defaultLayoutName()))
3044                         delete inset;
3045         }
3046         break;
3047
3048         case LFUN_PARENTINSERT:
3049         {
3050                 InsetCommandParams p("lyxparent", ev.argument);
3051                 Inset * inset = new InsetParent(p, *buffer_);
3052                 if (!insertInset(inset, tclass.defaultLayoutName()))
3053                         delete inset;
3054         }
3055
3056         break;
3057
3058         case LFUN_CHILD_INSERT:
3059         {
3060                 InsetInclude::Params p;
3061                 p.cparams.setFromString(ev.argument);
3062                 p.masterFilename_ = buffer_->fileName();
3063
3064                 InsetInclude * inset = new InsetInclude(p);
3065                 if (!insertInset(inset))
3066                         delete inset;
3067                 else {
3068                         updateInset(inset, true);
3069                         bv_->owner()->getDialogs().showInclude(inset);
3070                 }
3071         }
3072         break;
3073
3074         case LFUN_FLOAT_LIST:
3075                 if (floatList.typeExist(ev.argument)) {
3076                         Inset * inset = new InsetFloatList(ev.argument);
3077                         if (!insertInset(inset, tclass.defaultLayoutName()))
3078                                 delete inset;
3079                 } else {
3080                         lyxerr << "Non-existent float type: "
3081                                << ev.argument << endl;
3082                 }
3083                 break;
3084
3085         case LFUN_THESAURUS_ENTRY:
3086         {
3087                 string arg = ev.argument;
3088
3089                 if (arg.empty()) {
3090                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3091                                                                    false);
3092
3093                         // FIXME
3094                         if (arg.size() > 100 || arg.empty()) {
3095                                 // Get word or selection
3096                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3097                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3098                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3099                         }
3100                 }
3101
3102                 bv_->owner()->getDialogs().showThesaurus(arg);
3103         }
3104                 break;
3105
3106         case LFUN_SELFINSERT:
3107         {
3108                 if (ev.argument.empty()) break;
3109
3110                 /* Automatically delete the currently selected
3111                  * text and replace it with what is being
3112                  * typed in now. Depends on lyxrc settings
3113                  * "auto_region_delete", which defaults to
3114                  * true (on). */
3115
3116                 LyXText * lt = bv_->getLyXText();
3117
3118                 if (lyxrc.auto_region_delete) {
3119                         if (lt->selection.set()) {
3120                                 lt->cutSelection(bv_, false, false);
3121                                 bv_->update(lt,
3122                                             BufferView::SELECT
3123                                             | BufferView::FITCUR
3124                                             | BufferView::CHANGE);
3125                         }
3126                         workarea().haveSelection(false);
3127                 }
3128
3129                 beforeChange(lt);
3130                 LyXFont const old_font(lt->real_current_font);
3131
3132                 string::const_iterator cit = ev.argument.begin();
3133                 string::const_iterator end = ev.argument.end();
3134                 for (; cit != end; ++cit) {
3135                         owner_->getIntl().getTransManager().
3136                                 TranslateAndInsert(*cit, lt);
3137                 }
3138
3139                 bv_->update(lt,
3140                             BufferView::SELECT
3141                             | BufferView::FITCUR
3142                             | BufferView::CHANGE);
3143
3144                 lt->selection.cursor = lt->cursor;
3145                 moveCursorUpdate(false);
3146
3147                 // real_current_font.number can change so we need to
3148                 // update the minibuffer
3149                 if (old_font != lt->real_current_font)
3150                         owner_->view_state_changed();
3151                 //return string();
3152         }
3153         break;
3154
3155         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3156         {
3157                 time_t now_time_t = time(NULL);
3158                 struct tm * now_tm = localtime(&now_time_t);
3159                 setlocale(LC_TIME, "");
3160                 string arg;
3161                 if (!ev.argument.empty())
3162                         arg = ev.argument;
3163                 else
3164                         arg = lyxrc.date_insert_format;
3165                 char datetmp[32];
3166                 int const datetmp_len =
3167                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3168
3169                 LyXText * lt = bv_->getLyXText();
3170
3171                 for (int i = 0; i < datetmp_len; i++) {
3172                         lt->insertChar(bv_, datetmp[i]);
3173                         update(lt,
3174                                BufferView::SELECT
3175                                | BufferView::FITCUR
3176                                | BufferView::CHANGE);
3177                 }
3178
3179                 lt->selection.cursor = lt->cursor;
3180                 moveCursorUpdate(false);
3181         }
3182         break;
3183
3184         case LFUN_UNKNOWN_ACTION:
3185                 owner_->getLyXFunc().setErrorMessage(N_("Unknown function!"));
3186                 break;
3187
3188         default:
3189                 return false;
3190         } // end of switch
3191
3192         return true;
3193 }
3194
3195
3196 void BufferView::Pimpl::newline()
3197 {
3198         if (available()) {
3199                 LyXText * lt = bv_->getLyXText();
3200                 hideCursor();
3201                 update(lt,
3202                        BufferView::SELECT
3203                        | BufferView::FITCUR);
3204                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3205                 update(lt,
3206                        BufferView::SELECT
3207                        | BufferView::FITCUR
3208                        | BufferView::CHANGE);
3209         }
3210 }
3211
3212
3213 void BufferView::Pimpl::hfill()
3214 {
3215         if (available()) {
3216                 LyXText * lt = bv_->getLyXText();
3217                 hideCursor();
3218                 update(lt,
3219                        BufferView::SELECT
3220                        | BufferView::FITCUR);
3221                 lt->insertChar(bv_, Paragraph::META_HFILL);
3222                 update(lt,
3223                        BufferView::SELECT
3224                        | BufferView::FITCUR
3225                        | BufferView::CHANGE);
3226         }
3227 }
3228
3229
3230 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3231 {
3232         if (available()) {
3233                 LyXText * lt = bv_->getLyXText();
3234
3235                 hideCursor();
3236                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3237                 InsetSpecialChar * new_inset =
3238                         new InsetSpecialChar(kind);
3239                 if (!insertInset(new_inset))
3240                         delete new_inset;
3241                 else
3242                         updateInset(new_inset, true);
3243         }
3244 }
3245
3246
3247 void BufferView::Pimpl::smartQuote()
3248 {
3249         LyXText const * lt = bv_->getLyXText();
3250         Paragraph const * par = lt->cursor.par();
3251         pos_type pos = lt->cursor.pos();
3252         char c;
3253
3254         if (!pos
3255             || (par->isInset(pos - 1)
3256                 && par->getInset(pos - 1)->isSpace()))
3257                 c = ' ';
3258         else
3259                 c = par->getChar(pos - 1);
3260
3261
3262         hideCursor();
3263
3264         LyXLayout_ptr const & style = par->layout();
3265
3266         if (style->pass_thru ||
3267                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3268                 bv_->owner()->dispatch(FuncRequest(LFUN_SELFINSERT, "\""));
3269 }
3270
3271
3272 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3273 {
3274 #if 0
3275         if (insertInset(inset))
3276                 inset->edit(bv_);
3277         else
3278                 delete inset;
3279 #else
3280         bool gotsel = false;
3281
3282         if (bv_->getLyXText()->selection.set()) {
3283                 bv_->getLyXText()->cutSelection(bv_, true, false);
3284                 gotsel = true;
3285         }
3286
3287         if (insertInset(inset)) {
3288                 inset->edit(bv_);
3289                 if (gotsel)
3290                         owner_->dispatch(FuncRequest(LFUN_PASTESELECTION));
3291         }
3292         else
3293                 delete inset;
3294 #endif
3295 }
3296
3297
3298 // Open and lock an updatable inset
3299 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3300 {
3301         LyXText * lt = bv_->getLyXText();
3302
3303         beforeChange(lt);
3304         finishUndo();
3305         if (!insertInset(new_inset)) {
3306                 delete new_inset;
3307                 return false;
3308         }
3309         new_inset->edit(bv_, !behind);
3310         return true;
3311 }
3312
3313
3314 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3315 {
3316         // if we are in a locking inset we should try to insert the
3317         // inset there otherwise this is a illegal function now
3318         if (bv_->theLockingInset()) {
3319                 if (bv_->theLockingInset()->insetAllowed(inset))
3320                     return bv_->theLockingInset()->insertInset(bv_, inset);
3321                 return false;
3322         }
3323
3324         // not quite sure if we want this...
3325         setCursorParUndo(bv_);
3326         freezeUndo();
3327
3328         beforeChange(bv_->text);
3329         if (!lout.empty()) {
3330                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3331                 bv_->text->breakParagraph(bv_);
3332                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3333
3334                 if (!bv_->text->cursor.par()->empty()) {
3335                         bv_->text->cursorLeft(bv_);
3336
3337                         bv_->text->breakParagraph(bv_);
3338                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3339                 }
3340
3341                 string lres = lout;
3342                 LyXTextClass const & tclass =
3343                         buffer_->params.getLyXTextClass();
3344                 bool hasLayout = tclass.hasLayout(lres);
3345                 string lay = tclass.defaultLayoutName();
3346
3347                 if (hasLayout != false) {
3348                         // layout found
3349                         lay = lres;
3350                 } else {
3351                         // layout not fount using default
3352                         lay = tclass.defaultLayoutName();
3353                 }
3354
3355                 bv_->text->setLayout(bv_, lay);
3356
3357                 bv_->text->setParagraph(bv_, 0, 0,
3358                                    0, 0,
3359                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3360                                    Spacing(),
3361                                    LYX_ALIGN_LAYOUT,
3362                                    string(),
3363                                    0);
3364                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3365         }
3366
3367         bv_->text->insertInset(bv_, inset);
3368         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3369
3370         unFreezeUndo();
3371         return true;
3372 }
3373
3374
3375 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3376 {
3377         if (!inset || !available())
3378                 return;
3379
3380         // first check for locking insets
3381         if (bv_->theLockingInset()) {
3382                 if (bv_->theLockingInset() == inset) {
3383                         if (bv_->text->updateInset(bv_, inset)) {
3384                                 update();
3385                                 if (mark_dirty) {
3386                                         buffer_->markDirty();
3387                                 }
3388                                 updateScrollbar();
3389                                 return;
3390                         }
3391                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3392                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3393                                 update();
3394                                 if (mark_dirty) {
3395                                         buffer_->markDirty();
3396                                 }
3397                                 updateScrollbar();
3398                                 return;
3399                         }
3400                 }
3401         }
3402
3403         // then check if the inset is a top_level inset (has no owner)
3404         // if yes do the update as always otherwise we have to update the
3405         // toplevel inset where this inset is inside
3406         Inset * tl_inset = inset;
3407         while(tl_inset->owner())
3408                 tl_inset = tl_inset->owner();
3409         hideCursor();
3410         if (tl_inset == inset) {
3411                 update(bv_->text, BufferView::UPDATE);
3412                 if (bv_->text->updateInset(bv_, inset)) {
3413                         if (mark_dirty) {
3414                                 update(bv_->text,
3415                                        BufferView::SELECT
3416                                        | BufferView::FITCUR
3417                                        | BufferView::CHANGE);
3418                         } else {
3419                                 update(bv_->text, SELECT);
3420                         }
3421                         return;
3422                 }
3423         } else if (static_cast<UpdatableInset *>(tl_inset)
3424                            ->updateInsetInInset(bv_, inset))
3425         {
3426                         if (bv_->text->updateInset(bv_,  tl_inset)) {
3427                                 update();
3428                                 updateScrollbar();
3429                         }
3430         }
3431 }
3432
3433
3434 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3435                                   bool same_content)
3436 {
3437         if (!available()) return;
3438
3439         hideCursor();
3440         beforeChange(bv_->text);
3441         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3442
3443         LyXCursor const & cursor = bv_->text->cursor;
3444
3445         string contents;
3446         if (same_content &&
3447             cursor.par()->isInset(cursor.pos())) {
3448                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3449                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3450                     != codes.end())
3451                         contents =
3452                                 static_cast<InsetCommand const *>(inset)->getContents();
3453         }
3454
3455
3456         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3457                 if (bv_->text->cursor.pos()
3458                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3459                         LyXCursor tmp = bv_->text->cursor;
3460                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3461                         bv_->text->cursor.pos(0);
3462                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3463                                 bv_->text->cursor = tmp;
3464                                 bv_->owner()->message(_("No more insets"));
3465                         }
3466                 } else {
3467                         bv_->owner()->message(_("No more insets"));
3468                 }
3469         }
3470         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3471         bv_->text->selection.cursor = bv_->text->cursor;
3472 }
3473
3474
3475 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3476 {
3477         gotoInset(vector<Inset::Code>(1, code), same_content);
3478 }