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