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