]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Do not use \&@#^_~$ as lstinline delimiter, as suggested by Herbert
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "Text.h"
44 #include "TextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81
82 namespace lyx {
83
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::make_pair;
98 using std::min;
99 using std::max;
100 using std::mem_fun_ref;
101 using std::string;
102 using std::vector;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 void BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the actual cursor position and anchor inside the
153                 // buffer so that it can be restored in case we rechange
154                 // to this buffer later on.
155                 buffer_->saveCursor(cursor_.selectionBegin(),
156                                     cursor_.selectionEnd());
157                 // update bookmark pit of the current buffer before switch
158                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160                         if (buffer()->fileName() != bm.filename.absFilename())
161                                 continue;
162                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
164                         pit_type new_pit;
165                         pos_type new_pos;
166                         int new_id;
167                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 // Ideally, the whole cursor stack should be saved, but session
173                 // currently can only handle bottom (whole document) level pit and pos.
174                 // That is to say, if a cursor is in a nested inset, it will be
175                 // restore to the left of the top level inset.
176                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
178         }
179
180         // If we're quitting lyx, don't bother updating stuff
181         if (quitting) {
182                 buffer_ = 0;
183                 return;
184         }
185
186         //FIXME Fix for bug 3440 is here.
187         // If we are closing current buffer, switch to the first in
188         // buffer list.
189         if (!b) {
190                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191                                     << " No Buffer!" << endl;
192                 // We are closing the buffer, use the first buffer as current
193                 //FIXME 3440
194                 // if (last_buffer_) buffer_ = last_buffer_;
195                 // also check that this is in theBufferList()?
196                 buffer_ = theBufferList().first();
197         } else {
198                 //FIXME 3440
199                 // last_buffer = buffer_;
200                 // Set current buffer
201                 buffer_ = b;
202         }
203
204         // Reset old cursor
205         cursor_ = Cursor(*this);
206         anchor_ref_ = 0;
207         offset_ref_ = 0;
208
209         if (!buffer_)
210                 return;
211         
212                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213                                     << "Buffer addr: " << buffer_ << endl;
214                 cursor_.push(buffer_->inset());
215                 cursor_.resetAnchor();
216                 buffer_->text().setCurrentFont(cursor_);
217                 if (buffer_->getCursor().size() > 0 &&
218                     buffer_->getAnchor().size() > 0)
219                 {
220                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221                         cursor_.resetAnchor();
222                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223                         cursor_.setSelection();
224                         // do not set selection to the new buffer because we
225                         // only paste recent selection.
226
227                         // Make sure that the restored cursor is not broken. This can happen for
228                         // example if this Buffer has been modified by another view.
229                         cursor_.fixIfBroken();
230                 }
231                 updateMetrics(false);    
232         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233                 graphics::Previews::get().generateBufferPreviews(*buffer_);
234 }
235
236
237 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
238 {
239         // File already open?
240         if (theBufferList().exists(filename.absFilename())) {
241                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
242                 docstring text = bformat(_("The document %1$s is already "
243                                                      "loaded.\n\nDo you want to revert "
244                                                      "to the saved version?"), file);
245                 int const ret = Alert::prompt(_("Revert to saved document?"),
246                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
247
248                 if (ret != 0) {
249                         setBuffer(theBufferList().getBuffer(filename.absFilename()));
250                         return true;
251                 }
252                 // FIXME: should be LFUN_REVERT
253                 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
254                         return false;
255                 // Fall through to new load. (Asger)
256                 buffer_ = 0;
257         }
258
259         Buffer * b = 0;
260
261         if (isFileReadable(filename)) {
262                 b = theBufferList().newBuffer(filename.absFilename());
263                 if (!lyx::loadLyXFile(b, filename)) {
264                         theBufferList().release(b);
265                         return false;
266                 }
267         } else {
268                 docstring text = bformat(_("The document %1$s does not yet "
269                                                      "exist.\n\nDo you want to create "
270                                                      "a new document?"), from_utf8(filename.absFilename()));
271                 int const ret = Alert::prompt(_("Create new document?"),
272                          text, 0, 1, _("&Create"), _("Cancel"));
273
274                 if (ret == 0) {
275                         b = newFile(filename.absFilename(), string(), true);
276                         if (!b)
277                                 return false;
278                 } else
279                         return false;
280         }
281
282         setBuffer(b);
283         // Send the "errors" signal in case of parsing errors
284         b->errors("Parse");
285
286         // Update the labels and section numbering.
287         updateLabels(*buffer_);
288         // scroll to the position when the file was last closed
289         if (lyxrc.use_lastfilepos) {
290                 pit_type pit;
291                 pos_type pos;
292                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
293                 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
294                 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
295                         if (fitCursor())
296                                 updateMetrics(false);
297                         buffer_->text().setCurrentFont(cursor_);
298                 }
299         }
300
301         if (tolastfiles)
302                 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
303
304         return true;
305 }
306
307
308 void BufferView::resize()
309 {
310         if (!buffer_)
311                 return;
312
313         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
314
315         updateMetrics(false);
316         switchKeyMap();
317 }
318
319
320 bool BufferView::fitCursor()
321 {
322         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
323                 frontend::FontMetrics const & fm =
324                         theFontMetrics(cursor_.getFont());
325                 int const asc = fm.maxAscent();
326                 int const des = fm.maxDescent();
327                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
328                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
329                         return false;
330         }
331         center();
332         return true;
333 }
334
335
336 bool BufferView::multiParSel()
337 {
338         if (!cursor_.selection())
339                 return false;
340         bool ret = multiparsel_cache_;
341         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
342         // Either this, or previous selection spans paragraphs
343         return ret || multiparsel_cache_;
344 }
345
346
347 bool BufferView::update(Update::flags flags)
348 {
349         // last_inset_ points to the last visited inset. This pointer may become
350         // invalid because of keyboard editing. Since all such operations
351         // causes screen update(), I reset last_inset_ to avoid such a problem.
352         last_inset_ = 0;
353         // This is close to a hot-path.
354         LYXERR(Debug::DEBUG)
355                 << BOOST_CURRENT_FUNCTION
356                 << "[fitcursor = " << (flags & Update::FitCursor)
357                 << ", forceupdate = " << (flags & Update::Force)
358                 << ", singlepar = " << (flags & Update::SinglePar)
359                 << "]  buffer: " << buffer_ << endl;
360
361         // Check needed to survive LyX startup
362         if (!buffer_)
363                 return false;
364
365         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
366
367         // Update macro store
368         if (!(cursor().inMathed() && cursor().inMacroMode()))
369                 buffer_->buildMacros();
370
371         // Now do the first drawing step if needed. This consists on updating
372         // the CoordCache in updateMetrics().
373         // The second drawing step is done in WorkArea::redraw() if needed.
374
375         // Case when no explicit update is requested.
376         if (!flags) {
377                 // no need to redraw anything.
378                 metrics_info_.update_strategy = NoScreenUpdate;
379                 return false;
380         }
381
382         if (flags == Update::Decoration) {
383                 metrics_info_.update_strategy = DecorationUpdate;
384                 return true;
385         }
386
387         if (flags == Update::FitCursor 
388                 || flags == (Update::Decoration | Update::FitCursor)) {
389                 bool const fit_cursor = fitCursor();
390                 // tell the frontend to update the screen if needed.
391                 if (fit_cursor) {
392                         updateMetrics(false);
393                         return true;
394                 }
395                 if (flags & Update::Decoration) {
396                         metrics_info_.update_strategy = DecorationUpdate;
397                         return true;
398                 }
399                 // no screen update is needed.
400                 metrics_info_.update_strategy = NoScreenUpdate;
401                 return false;
402         }
403
404         bool full_metrics = flags & Update::Force;
405         if (flags & Update::MultiParSel)
406                 full_metrics |= multiParSel();
407
408         bool const single_par = !full_metrics;
409         updateMetrics(single_par);
410
411         if (flags & Update::FitCursor && fitCursor())
412                 updateMetrics(false);
413
414         // tell the frontend to update the screen.
415         return true;
416 }
417
418
419 void BufferView::updateScrollbar()
420 {
421         if (!buffer_) {
422                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
423                                      << " no text in updateScrollbar" << endl;
424                 scrollbarParameters_.reset();
425                 return;
426         }
427
428         Text & t = buffer_->text();
429         TextMetrics & tm = text_metrics_[&t];
430
431         int const parsize = int(t.paragraphs().size() - 1);
432         if (anchor_ref_ >  parsize)  {
433                 anchor_ref_ = parsize;
434                 offset_ref_ = 0;
435         }
436
437         LYXERR(Debug::GUI)
438                 << BOOST_CURRENT_FUNCTION
439                 << " Updating scrollbar: height: " << t.paragraphs().size()
440                 << " curr par: " << cursor_.bottom().pit()
441                 << " default height " << defaultRowHeight() << endl;
442
443         // It would be better to fix the scrollbar to understand
444         // values in [0..1] and divide everything by wh
445
446         // estimated average paragraph height:
447         if (wh_ == 0)
448                 wh_ = height_ / 4;
449
450         int h = tm.parMetrics(anchor_ref_).height();
451
452         // Normalize anchor/offset (MV):
453         while (offset_ref_ > h && anchor_ref_ < parsize) {
454                 anchor_ref_++;
455                 offset_ref_ -= h;
456                 h = tm.parMetrics(anchor_ref_).height();
457         }
458         // Look at paragraph heights on-screen
459         int sumh = 0;
460         int nh = 0;
461         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
462                 if (sumh > height_)
463                         break;
464                 int const h2 = tm.parMetrics(pit).height();
465                 sumh += h2;
466                 nh++;
467         }
468
469         BOOST_ASSERT(nh);
470         int const hav = sumh / nh;
471         // More realistic average paragraph height
472         if (hav > wh_)
473                 wh_ = hav;
474
475         BOOST_ASSERT(h);
476         scrollbarParameters_.height = (parsize + 1) * wh_;
477         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
478         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
479 }
480
481
482 ScrollbarParameters const & BufferView::scrollbarParameters() const
483 {
484         return scrollbarParameters_;
485 }
486
487
488 void BufferView::scrollDocView(int value)
489 {
490         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
491                            << "[ value = " << value << "]" << endl;
492
493         if (!buffer_)
494                 return;
495
496         Text & t = buffer_->text();
497         TextMetrics & tm = text_metrics_[&t];
498
499         float const bar = value / float(wh_ * t.paragraphs().size());
500
501         anchor_ref_ = int(bar * t.paragraphs().size());
502         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
503                 anchor_ref_ = int(t.paragraphs().size()) - 1;
504
505         tm.redoParagraph(anchor_ref_);
506         int const h = tm.parMetrics(anchor_ref_).height();
507         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
508         updateMetrics(false);
509 }
510
511
512 void BufferView::setCursorFromScrollbar()
513 {
514         if (!buffer_)
515                 return;
516
517         Text & t = buffer_->text();
518
519         int const height = 2 * defaultRowHeight();
520         int const first = height;
521         int const last = height_ - height;
522         Cursor & cur = cursor_;
523
524         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
525
526         switch (st) {
527         case bv_funcs::CUR_ABOVE:
528                 // We reset the cursor because bv_funcs::status() does not
529                 // work when the cursor is within mathed.
530                 cur.reset(buffer_->inset());
531                 t.setCursorFromCoordinates(cur, 0, first);
532                 cur.clearSelection();
533                 break;
534         case bv_funcs::CUR_BELOW:
535                 // We reset the cursor because bv_funcs::status() does not
536                 // work when the cursor is within mathed.
537                 cur.reset(buffer_->inset());
538                 t.setCursorFromCoordinates(cur, 0, last);
539                 cur.clearSelection();
540                 break;
541         case bv_funcs::CUR_INSIDE:
542                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
543                 int const newy = min(last, max(y, first));
544                 if (y != newy) {
545                         cur.reset(buffer_->inset());
546                         t.setCursorFromCoordinates(cur, 0, newy);
547                 }
548         }
549 }
550
551
552 Change const BufferView::getCurrentChange() const
553 {
554         if (!cursor_.selection())
555                 return Change(Change::UNCHANGED);
556
557         DocIterator dit = cursor_.selectionBegin();
558         return dit.paragraph().lookupChange(dit.pos());
559 }
560
561
562 void BufferView::saveBookmark(unsigned int idx)
563 {
564         // tenatively save bookmark, id and pos will be used to
565         // acturately locate a bookmark in a 'live' lyx session.
566         // pit and pos will be updated with bottom level pit/pos 
567         // when lyx exits.
568         LyX::ref().session().bookmarks().save(
569                 FileName(buffer_->fileName()),
570                 cursor_.bottom().pit(),
571                 cursor_.bottom().pos(),
572                 cursor_.paragraph().id(),
573                 cursor_.pos(),
574                 idx
575         );
576         if (idx)
577                 // emit message signal.
578                 message(_("Save bookmark"));
579 }
580
581
582 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
583         int top_id, pos_type top_pos)
584 {
585         cursor_.clearSelection();
586
587         // if a valid par_id is given, try it first
588         // This is the case for a 'live' bookmark when unique paragraph ID
589         // is used to track bookmarks.
590         if (top_id > 0) {
591                 ParIterator par = buffer_->getParFromID(top_id);
592                 if (par != buffer_->par_iterator_end()) {
593                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
594                         // Some slices of the iterator may not be
595                         // reachable (e.g. closed collapsable inset)
596                         // so the dociterator may need to be
597                         // shortened. Otherwise, setCursor may crash
598                         // lyx when the cursor can not be set to these
599                         // insets.
600                         size_t const n = dit.depth();
601                         for (size_t i = 0; i < n; ++i)
602                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
603                                         dit.resize(i);
604                                         break;
605                                 }
606                         setCursor(dit);
607                         // Note: return bottom (document) level pit.
608                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
609                 }
610         }
611         // if top_id == 0, or searching through top_id failed
612         // This is the case for a 'restored' bookmark when only bottom 
613         // (document level) pit was saved. Because of this, bookmark
614         // restoration is inaccurate. If a bookmark was within an inset,
615         // it will be restored to the left of the outmost inset that contains
616         // the bookmark.
617         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
618                 DocIterator it = doc_iterator_begin(buffer_->inset());
619                 it.pit() = bottom_pit;
620                 it.pos() = min(bottom_pos, it.paragraph().size());
621                 setCursor(it);
622                 return boost::make_tuple(it.pit(), it.pos(), 
623                                          it.paragraph().id());
624         }
625         // both methods fail
626         return boost::make_tuple(pit_type(0), pos_type(0), 0);
627 }
628
629
630 void BufferView::switchKeyMap()
631 {
632         if (!lyxrc.rtl_support)
633                 return;
634
635         if (cursor_.innerText()->real_current_font.isRightToLeft()) {
636                 if (intl_->keymap == Intl::PRIMARY)
637                         intl_->keyMapSec();
638         } else {
639                 if (intl_->keymap == Intl::SECONDARY)
640                         intl_->keyMapPrim();
641         }
642 }
643
644
645 int BufferView::workWidth() const
646 {
647         return width_;
648 }
649
650
651 void BufferView::center()
652 {
653         CursorSlice & bot = cursor_.bottom();
654         TextMetrics & tm = text_metrics_[bot.text()];
655         pit_type const pit = bot.pit();
656         tm.redoParagraph(pit);
657         ParagraphMetrics const & pm = tm.parMetrics(pit);
658         anchor_ref_ = pit;
659         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
660                 + pm.ascent() - height_ / 2;
661 }
662
663
664 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
665 {
666         FuncStatus flag;
667
668         switch (cmd.action) {
669
670         case LFUN_UNDO:
671                 flag.enabled(!buffer_->undostack().empty());
672                 break;
673         case LFUN_REDO:
674                 flag.enabled(!buffer_->redostack().empty());
675                 break;
676         case LFUN_FILE_INSERT:
677         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
678         case LFUN_FILE_INSERT_PLAINTEXT:
679         case LFUN_BOOKMARK_SAVE:
680                 // FIXME: Actually, these LFUNS should be moved to Text
681                 flag.enabled(cursor_.inTexted());
682                 break;
683         case LFUN_FONT_STATE:
684         case LFUN_LABEL_INSERT:
685         case LFUN_PARAGRAPH_GOTO:
686         // FIXME handle non-trivially
687         case LFUN_OUTLINE_UP:
688         case LFUN_OUTLINE_DOWN:
689         case LFUN_OUTLINE_IN:
690         case LFUN_OUTLINE_OUT:
691         case LFUN_NOTE_NEXT:
692         case LFUN_REFERENCE_NEXT:
693         case LFUN_WORD_FIND:
694         case LFUN_WORD_REPLACE:
695         case LFUN_MARK_OFF:
696         case LFUN_MARK_ON:
697         case LFUN_MARK_TOGGLE:
698         case LFUN_SCREEN_RECENTER:
699         case LFUN_BIBTEX_DATABASE_ADD:
700         case LFUN_BIBTEX_DATABASE_DEL:
701         case LFUN_WORDS_COUNT:
702         case LFUN_NEXT_INSET_TOGGLE:
703                 flag.enabled(true);
704                 break;
705
706         case LFUN_LABEL_GOTO: {
707                 flag.enabled(!cmd.argument().empty()
708                     || getInsetByCode<InsetRef>(cursor_, Inset::REF_CODE));
709                 break;
710         }
711
712         case LFUN_CHANGES_TRACK:
713                 flag.enabled(true);
714                 flag.setOnOff(buffer_->params().trackChanges);
715                 break;
716
717         case LFUN_CHANGES_OUTPUT:
718                 flag.enabled(buffer_);
719                 flag.setOnOff(buffer_->params().outputChanges);
720                 break;
721
722         case LFUN_CHANGES_MERGE:
723         case LFUN_CHANGE_NEXT:
724         case LFUN_ALL_CHANGES_ACCEPT:
725         case LFUN_ALL_CHANGES_REJECT:
726                 // TODO: context-sensitive enabling of LFUNs
727                 // In principle, these command should only be enabled if there
728                 // is a change in the document. However, without proper
729                 // optimizations, this will inevitably result in poor performance.
730                 flag.enabled(buffer_);
731                 break;
732
733         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
734                 flag.setOnOff(buffer_->params().compressed);
735                 break;
736         }
737
738         default:
739                 flag.enabled(false);
740         }
741
742         return flag;
743 }
744
745
746 Update::flags BufferView::dispatch(FuncRequest const & cmd)
747 {
748         //lyxerr << BOOST_CURRENT_FUNCTION
749         //       << [ cmd = " << cmd << "]" << endl;
750
751         // Make sure that the cached BufferView is correct.
752         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
753                 << " action[" << cmd.action << ']'
754                 << " arg[" << to_utf8(cmd.argument()) << ']'
755                 << " x[" << cmd.x << ']'
756                 << " y[" << cmd.y << ']'
757                 << " button[" << cmd.button() << ']'
758                 << endl;
759
760         // FIXME: this should not be possible.
761         if (!buffer_)
762                 return Update::None;
763
764         Cursor & cur = cursor_;
765         // Default Update flags.
766         Update::flags updateFlags = Update::Force | Update::FitCursor;
767
768         switch (cmd.action) {
769
770         case LFUN_UNDO:
771                 cur.message(_("Undo"));
772                 cur.clearSelection();
773                 if (!textUndo(*this)) {
774                         cur.message(_("No further undo information"));
775                         updateFlags = Update::None;
776                 }
777                 switchKeyMap();
778                 break;
779
780         case LFUN_REDO:
781                 cur.message(_("Redo"));
782                 cur.clearSelection();
783                 if (!textRedo(*this)) {
784                         cur.message(_("No further redo information"));
785                         updateFlags = Update::None;
786                 }
787                 switchKeyMap();
788                 break;
789
790         case LFUN_FILE_INSERT:
791                 // FIXME UNICODE
792                 menuInsertLyXFile(to_utf8(cmd.argument()));
793                 break;
794
795         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
796                 // FIXME UNICODE
797                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
798                 break;
799
800         case LFUN_FILE_INSERT_PLAINTEXT:
801                 // FIXME UNICODE
802                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
803                 break;
804
805         case LFUN_FONT_STATE:
806                 cur.message(cur.currentState());
807                 break;
808
809         case LFUN_BOOKMARK_SAVE:
810                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
811                 break;
812
813         case LFUN_LABEL_GOTO: {
814                 docstring label = cmd.argument();
815                 if (label.empty()) {
816                         InsetRef * inset =
817                                 getInsetByCode<InsetRef>(cursor_,
818                                                          Inset::REF_CODE);
819                         if (inset) {
820                                 label = inset->getParam("reference");
821                                 // persistent=false: use temp_bookmark
822                                 saveBookmark(0);
823                         }
824                 }
825
826                 if (!label.empty())
827                         gotoLabel(label);
828                 break;
829         }
830
831         case LFUN_PARAGRAPH_GOTO: {
832                 int const id = convert<int>(to_utf8(cmd.argument()));
833                 int i = 0;
834                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
835                         ParIterator par = b->getParFromID(id);
836                         if (par == b->par_iterator_end()) {
837                                 LYXERR(Debug::INFO)
838                                         << "No matching paragraph found! ["
839                                         << id << "]." << endl;
840                         } else {
841                                 LYXERR(Debug::INFO)
842                                         << "Paragraph " << par->id()
843                                         << " found in buffer `"
844                                         << b->fileName() << "'." << endl;
845
846                                 if (b == buffer_) {
847                                         // Set the cursor
848                                         setCursor(makeDocIterator(par, 0));
849                                         switchKeyMap();
850                                 } else {
851                                         // Switch to other buffer view and resend cmd
852                                         theLyXFunc().dispatch(FuncRequest(
853                                                 LFUN_BUFFER_SWITCH, b->fileName()));
854                                         theLyXFunc().dispatch(cmd);
855                                         updateFlags = Update::None;
856                                 }
857                                 break;
858                         }
859                         ++i;
860                 }
861                 break;
862         }
863
864         case LFUN_OUTLINE_UP:
865                 toc::outline(toc::Up, cursor_);
866                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
867                 updateLabels(*buffer_);
868                 break;
869         case LFUN_OUTLINE_DOWN:
870                 toc::outline(toc::Down, cursor_);
871                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
872                 updateLabels(*buffer_);
873                 break;
874         case LFUN_OUTLINE_IN:
875                 toc::outline(toc::In, cursor_);
876                 updateLabels(*buffer_);
877                 break;
878         case LFUN_OUTLINE_OUT:
879                 toc::outline(toc::Out, cursor_);
880                 updateLabels(*buffer_);
881                 break;
882
883         case LFUN_NOTE_NEXT:
884                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
885                 break;
886
887         case LFUN_REFERENCE_NEXT: {
888                 vector<Inset_code> tmp;
889                 tmp.push_back(Inset::LABEL_CODE);
890                 tmp.push_back(Inset::REF_CODE);
891                 bv_funcs::gotoInset(this, tmp, true);
892                 break;
893         }
894
895         case LFUN_CHANGES_TRACK:
896                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
897                 break;
898
899         case LFUN_CHANGES_OUTPUT:
900                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
901                 if (buffer_->params().outputChanges) {
902                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
903                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
904                                           LaTeXFeatures::isAvailable("xcolor");
905                 
906                         if (!dvipost && !xcolorsoul) {
907                                 Alert::warning(_("Changes not shown in LaTeX output"),
908                                                _("Changes will not be highlighted in LaTeX output, "
909                                                  "because neither dvipost nor xcolor/soul are installed.\n"
910                                                  "Please install these packages or redefine "
911                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
912                         } else if (!xcolorsoul) {
913                                 Alert::warning(_("Changes not shown in LaTeX output"),
914                                                _("Changes will not be highlighted in LaTeX output "
915                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
916                                                  "Please install both packages or redefine "
917                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
918                         }
919                 }
920                 break;
921
922         case LFUN_CHANGE_NEXT:
923                 findNextChange(this);
924                 break;
925
926         case LFUN_CHANGES_MERGE:
927                 if (findNextChange(this))
928                         showDialog("changes");
929                 break;
930
931         case LFUN_ALL_CHANGES_ACCEPT:
932                 // select complete document
933                 cursor_.reset(buffer_->inset());
934                 cursor_.selHandle(true);
935                 buffer_->text().cursorBottom(cursor_);
936                 // accept everything in a single step to support atomic undo
937                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
938                 break;
939
940         case LFUN_ALL_CHANGES_REJECT:
941                 // select complete document
942                 cursor_.reset(buffer_->inset());
943                 cursor_.selHandle(true);
944                 buffer_->text().cursorBottom(cursor_);
945                 // reject everything in a single step to support atomic undo
946                 // Note: reject does not work recursively; the user may have to repeat the operation
947                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
948                 break;
949
950         case LFUN_WORD_FIND:
951                 find(this, cmd);
952                 break;
953
954         case LFUN_WORD_REPLACE:
955                 replace(this, cmd);
956                 break;
957
958         case LFUN_MARK_OFF:
959                 cur.clearSelection();
960                 cur.resetAnchor();
961                 cur.message(from_utf8(N_("Mark off")));
962                 break;
963
964         case LFUN_MARK_ON:
965                 cur.clearSelection();
966                 cur.mark() = true;
967                 cur.resetAnchor();
968                 cur.message(from_utf8(N_("Mark on")));
969                 break;
970
971         case LFUN_MARK_TOGGLE:
972                 cur.clearSelection();
973                 if (cur.mark()) {
974                         cur.mark() = false;
975                         cur.message(from_utf8(N_("Mark removed")));
976                 } else {
977                         cur.mark() = true;
978                         cur.message(from_utf8(N_("Mark set")));
979                 }
980                 cur.resetAnchor();
981                 break;
982
983         case LFUN_SCREEN_RECENTER:
984                 center();
985                 break;
986
987         case LFUN_BIBTEX_DATABASE_ADD: {
988                 Cursor tmpcur = cursor_;
989                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
990                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
991                                                 Inset::BIBTEX_CODE);
992                 if (inset) {
993                         if (inset->addDatabase(to_utf8(cmd.argument())))
994                                 buffer_->updateBibfilesCache();
995                 }
996                 break;
997         }
998
999         case LFUN_BIBTEX_DATABASE_DEL: {
1000                 Cursor tmpcur = cursor_;
1001                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
1002                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1003                                                 Inset::BIBTEX_CODE);
1004                 if (inset) {
1005                         if (inset->delDatabase(to_utf8(cmd.argument())))
1006                                 buffer_->updateBibfilesCache();
1007                 }
1008                 break;
1009         }
1010
1011         case LFUN_WORDS_COUNT: {
1012                 DocIterator from, to;
1013                 if (cur.selection()) {
1014                         from = cur.selectionBegin();
1015                         to = cur.selectionEnd();
1016                 } else {
1017                         from = doc_iterator_begin(buffer_->inset());
1018                         to = doc_iterator_end(buffer_->inset());
1019                 }
1020                 int const count = countWords(from, to);
1021                 docstring message;
1022                 if (count != 1) {
1023                         if (cur.selection())
1024                                 message = bformat(_("%1$d words in selection."),
1025                                           count);
1026                                 else
1027                                         message = bformat(_("%1$d words in document."),
1028                                                           count);
1029                 }
1030                 else {
1031                         if (cur.selection())
1032                                 message = _("One word in selection.");
1033                         else
1034                                 message = _("One word in document.");
1035                 }
1036
1037                 Alert::information(_("Count words"), message);
1038         }
1039                 break;
1040
1041         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1042                 // turn compression on/off
1043                 buffer_->params().compressed = !buffer_->params().compressed;
1044                 break;
1045
1046         case LFUN_NEXT_INSET_TOGGLE: {
1047                 // this is the real function we want to invoke
1048                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1049                 // if there is an inset at cursor, see whether it
1050                 // wants to toggle.
1051                 Inset * inset = cur.nextInset();
1052                 if (inset && inset->isActive()) {
1053                         Cursor tmpcur = cur;
1054                         tmpcur.pushLeft(*inset);
1055                         inset->dispatch(tmpcur, tmpcmd);
1056                         if (tmpcur.result().dispatched()) {
1057                                 cur.dispatched();
1058                         }
1059                 }
1060                 // if it did not work, try the underlying inset.
1061                 if (!cur.result().dispatched())
1062                         cur.dispatch(tmpcmd);
1063
1064                 if (cur.result().dispatched())
1065                         cur.clearSelection();
1066
1067                 break;
1068         }
1069
1070         default:
1071                 updateFlags = Update::None;
1072         }
1073
1074         return updateFlags;
1075 }
1076
1077
1078 docstring const BufferView::requestSelection()
1079 {
1080         if (!buffer_)
1081                 return docstring();
1082
1083         Cursor & cur = cursor_;
1084
1085         if (!cur.selection()) {
1086                 xsel_cache_.set = false;
1087                 return docstring();
1088         }
1089
1090         if (!xsel_cache_.set ||
1091             cur.top() != xsel_cache_.cursor ||
1092             cur.anchor_.top() != xsel_cache_.anchor)
1093         {
1094                 xsel_cache_.cursor = cur.top();
1095                 xsel_cache_.anchor = cur.anchor_.top();
1096                 xsel_cache_.set = cur.selection();
1097                 return cur.selectionAsString(false);
1098         }
1099         return docstring();
1100 }
1101
1102
1103 void BufferView::clearSelection()
1104 {
1105         if (buffer_) {
1106                 cursor_.clearSelection();
1107                 // Clear the selection buffer. Otherwise a subsequent
1108                 // middle-mouse-button paste would use the selection buffer,
1109                 // not the more current external selection.
1110                 cap::clearSelection();
1111                 xsel_cache_.set = false;
1112                 // The buffer did not really change, but this causes the
1113                 // redraw we need because we cleared the selection above.
1114                 buffer_->changed();
1115         }
1116 }
1117
1118
1119 void BufferView::workAreaResize(int width, int height)
1120 {
1121         // Update from work area
1122         width_ = width;
1123         height_ = height;
1124
1125         // The complete text metrics will be redone.
1126         text_metrics_.clear();
1127
1128         if (buffer_)
1129                 resize();
1130 }
1131
1132
1133 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1134 {
1135         pit_type pit = text.getPitNearY(*this, y);
1136         BOOST_ASSERT(pit != -1);
1137         Paragraph const & par = text.getPar(pit);
1138
1139         LYXERR(Debug::DEBUG)
1140                 << BOOST_CURRENT_FUNCTION
1141                 << ": x: " << x
1142                 << " y: " << y
1143                 << "  pit: " << pit
1144                 << endl;
1145         InsetList::const_iterator iit = par.insetlist.begin();
1146         InsetList::const_iterator iend = par.insetlist.end();
1147         for (; iit != iend; ++iit) {
1148                 Inset * const inset = iit->inset;
1149                 if (inset->covers(*this, x, y)) {
1150                         if (!inset->descendable())
1151                                 // No need to go further down if the inset is not 
1152                                 // descendable.
1153                                 return inset;
1154
1155                         size_t cell_number = inset->nargs();
1156                         // Check all the inner cell.
1157                         for (size_t i = 0; i != cell_number; ++i) {
1158                                 Text const * inner_text = inset->getText(i);
1159                                 if (inner_text) {
1160                                         // Try deeper.
1161                                         Inset const * inset_deeper = 
1162                                                 getCoveringInset(*inner_text, x, y);
1163                                         if (inset_deeper)
1164                                                 return inset_deeper;
1165                                 }
1166                         }
1167
1168                         LYXERR(Debug::DEBUG)
1169                                 << BOOST_CURRENT_FUNCTION
1170                                 << ": Hit inset: " << inset << endl;
1171                         return inset;
1172                 }
1173         }
1174         LYXERR(Debug::DEBUG)
1175                 << BOOST_CURRENT_FUNCTION
1176                 << ": No inset hit. " << endl;
1177         return 0;
1178 }
1179
1180
1181 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1182 {
1183         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1184
1185         // This is only called for mouse related events including
1186         // LFUN_FILE_OPEN generated by drag-and-drop.
1187         FuncRequest cmd = cmd0;
1188
1189         // E.g. Qt mouse press when no buffer
1190         if (!buffer_)
1191                 return false;
1192
1193         Cursor cur(*this);
1194         cur.push(buffer_->inset());
1195         cur.selection() = cursor_.selection();
1196
1197         // Either the inset under the cursor or the
1198         // surrounding Text will handle this event.
1199
1200         // make sure we stay within the screen...
1201         cmd.y = min(max(cmd.y, -1), height_);
1202         
1203         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1204                 
1205                 // Get inset under mouse, if there is one.
1206                 Inset const * covering_inset = 
1207                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1208                 if (covering_inset == last_inset_)
1209                         // Same inset, no need to do anything...
1210                         return false;
1211
1212                 bool need_redraw = false;
1213                 // const_cast because of setMouseHover().
1214                 Inset * inset = const_cast<Inset *>(covering_inset);
1215                 if (last_inset_)
1216                         // Remove the hint on the last hovered inset (if any).
1217                         need_redraw |= last_inset_->setMouseHover(false);
1218                 if (inset)
1219                         // Highlighted the newly hovered inset (if any).
1220                         need_redraw |= inset->setMouseHover(true);
1221                 last_inset_ = inset;
1222
1223                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1224                 // not expose the button for redraw. We adjust here the metrics dimension
1225                 // to enable a full redraw.
1226                 // FIXME: It is possible to redraw only the area around the button!
1227                 if (need_redraw 
1228                         && metrics_info_.update_strategy == SingleParUpdate) {
1229                         // FIXME: It should be possible to redraw only the area around 
1230                         // the button by doing this:
1231                         //
1232                         //metrics_info_.singlepar = false;
1233                         //metrics_info_.y1 = ymin of button;
1234                         //metrics_info_.y2 = ymax of button;
1235                         //
1236                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1237                         // between background updates and text updates. So we use the hammer
1238                         // solution for now. We could also avoid the updateMetrics() below
1239                         // by using the first and last pit of the CoordCache. Have a look
1240                         // at Text::getPitNearY() to see what I mean.
1241                         //
1242                         //metrics_info_.pit1 = first pit of CoordCache;
1243                         //metrics_info_.pit2 = last pit of CoordCache;
1244                         //metrics_info_.singlepar = false;
1245                         //metrics_info_.y1 = 0;
1246                         //metrics_info_.y2 = height_;
1247                         //
1248                         updateMetrics(false);
1249                 }
1250
1251                 // This event (moving without mouse click) is not passed further.
1252                 // This should be changed if it is further utilized.
1253                 return need_redraw;
1254         }
1255         
1256         // Build temporary cursor.
1257         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1258
1259         // Put anchor at the same position.
1260         cur.resetAnchor();
1261
1262         // Try to dispatch to an non-editable inset near this position
1263         // via the temp cursor. If the inset wishes to change the real
1264         // cursor it has to do so explicitly by using
1265         //  cur.bv().cursor() = cur;  (or similar)
1266         if (inset) {
1267                 inset->dispatch(cur, cmd);
1268         }
1269
1270         // Now dispatch to the temporary cursor. If the real cursor should
1271         // be modified, the inset's dispatch has to do so explicitly.
1272         if (!cur.result().dispatched())
1273                 cur.dispatch(cmd);
1274
1275         // Redraw if requested and necessary.
1276         if (cur.result().dispatched() && cur.result().update())
1277                 return update(cur.result().update());
1278
1279         return false;
1280 }
1281
1282
1283 void BufferView::scroll(int /*lines*/)
1284 {
1285 //      if (!buffer_)
1286 //              return;
1287 //
1288 //      Text const * t = &buffer_->text();
1289 //      int const line_height = defaultRowHeight();
1290 //
1291 //      // The new absolute coordinate
1292 //      int new_top_y = top_y() + lines * line_height;
1293 //
1294 //      // Restrict to a valid value
1295 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1296 //      new_top_y = std::max(0, new_top_y);
1297 //
1298 //      scrollDocView(new_top_y);
1299 //
1300 }
1301
1302
1303 void BufferView::setCursorFromRow(int row)
1304 {
1305         int tmpid = -1;
1306         int tmppos = -1;
1307
1308         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1309
1310         if (tmpid == -1)
1311                 buffer_->text().setCursor(cursor_, 0, 0);
1312         else
1313                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1314 }
1315
1316
1317 void BufferView::gotoLabel(docstring const & label)
1318 {
1319         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1320                 vector<docstring> labels;
1321                 it->getLabelList(*buffer_, labels);
1322                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1323                         setCursor(it);
1324                         update();
1325                         return;
1326                 }
1327         }
1328 }
1329
1330
1331 TextMetrics const & BufferView::textMetrics(Text const * t) const
1332 {
1333         return const_cast<BufferView *>(this)->textMetrics(t);
1334 }
1335
1336
1337 TextMetrics & BufferView::textMetrics(Text const * t)
1338 {
1339         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1340         if (tmc_it == text_metrics_.end()) {
1341                 tmc_it = text_metrics_.insert(
1342                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1343         }       
1344         return tmc_it->second;
1345 }
1346
1347
1348 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1349                 pit_type pit) const
1350 {
1351         return textMetrics(t).parMetrics(pit);
1352 }
1353
1354
1355 int BufferView::workHeight() const
1356 {
1357         return height_;
1358 }
1359
1360
1361 void BufferView::setCursor(DocIterator const & dit)
1362 {
1363         size_t const n = dit.depth();
1364         for (size_t i = 0; i < n; ++i)
1365                 dit[i].inset().edit(cursor_, true);
1366
1367         cursor_.setCursor(dit);
1368         cursor_.selection() = false;
1369 }
1370
1371
1372 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1373 {
1374         // Would be wrong to delete anything if we have a selection.
1375         if (cur.selection())
1376                 return false;
1377
1378         bool need_anchor_change = false;
1379         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1380                 need_anchor_change);
1381
1382         if (need_anchor_change)
1383                 cur.resetAnchor();
1384         
1385         if (!changed)
1386                 return false;
1387
1388         updateLabels(*buffer_);
1389
1390         updateMetrics(false);
1391         buffer_->changed();
1392         return true;
1393 }
1394
1395
1396 bool BufferView::mouseSetCursor(Cursor & cur)
1397 {
1398         BOOST_ASSERT(&cur.bv() == this);
1399
1400         // Has the cursor just left the inset?
1401         bool badcursor = false;
1402         bool leftinset = (&cursor_.inset() != &cur.inset());
1403         if (leftinset)
1404                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1405
1406         // do the dEPM magic if needed
1407         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1408         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1409         // the leftinset bool would not be necessary (badcursor instead).
1410         bool update = leftinset;
1411         if (!badcursor && cursor_.inTexted())
1412                 update |= checkDepm(cur, cursor_);
1413
1414         // if the cursor was in an empty script inset and the new
1415         // position is in the nucleus of the inset, notifyCursorLeaves
1416         // will kill the script inset itself. So we check all the
1417         // elements of the cursor to make sure that they are correct.
1418         // For an example, see bug 2933: 
1419         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1420         // The code below could maybe be moved to a DocIterator method.
1421         //lyxerr << "cur before " << cur <<std::endl;
1422         DocIterator dit(cur.inset());
1423         dit.push_back(cur.bottom());
1424         size_t i = 1;
1425         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1426                 dit.push_back(cur[i]);
1427                 ++i;
1428         }
1429         //lyxerr << "5 cur after" << dit <<std::endl;
1430
1431         cursor_.setCursor(dit);
1432         cursor_.clearSelection();
1433         finishUndo();
1434         return update;
1435 }
1436
1437
1438 void BufferView::putSelectionAt(DocIterator const & cur,
1439                                 int length, bool backwards)
1440 {
1441         cursor_.clearSelection();
1442
1443         setCursor(cur);
1444
1445         if (length) {
1446                 if (backwards) {
1447                         cursor_.pos() += length;
1448                         cursor_.setSelection(cursor_, -length);
1449                 } else
1450                         cursor_.setSelection(cursor_, length);
1451                 cap::saveSelection(cursor_);
1452         }
1453 }
1454
1455
1456 Cursor & BufferView::cursor()
1457 {
1458         return cursor_;
1459 }
1460
1461
1462 Cursor const & BufferView::cursor() const
1463 {
1464         return cursor_;
1465 }
1466
1467
1468 pit_type BufferView::anchor_ref() const
1469 {
1470         return anchor_ref_;
1471 }
1472
1473
1474 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1475 {
1476         return metrics_info_;
1477 }
1478
1479
1480 // FIXME: We should split-up updateMetrics() for the singlepar case.
1481 void BufferView::updateMetrics(bool singlepar)
1482 {
1483         Text & buftext = buffer_->text();
1484         TextMetrics & tm = textMetrics(&buftext);
1485         pit_type size = int(buftext.paragraphs().size());
1486
1487         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1488                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1489                 offset_ref_ = 0;
1490         }
1491         
1492         // If the paragraph metrics has changed, we can not
1493         // use the singlepar optimisation.
1494         if (singlepar
1495                 // In Single Paragraph mode, rebreak only
1496                 // the (main text, not inset!) paragraph containing the cursor.
1497                 // (if this paragraph contains insets etc., rebreaking will
1498                 // recursively descend)
1499                 && tm.redoParagraph(cursor_.bottom().pit()))
1500                 singlepar = false;
1501
1502         pit_type const pit = anchor_ref_;
1503         int pit1 = pit;
1504         int pit2 = pit;
1505         size_t const npit = buftext.paragraphs().size();
1506
1507         // Rebreak anchor paragraph.
1508         if (!singlepar)
1509                 tm.redoParagraph(pit);
1510         
1511         // Clear out the position cache in case of full screen redraw.
1512         if (!singlepar)
1513                 coord_cache_.clear();
1514
1515         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1516
1517         // Redo paragraphs above anchor if necessary.
1518         int y1 = y0;
1519         while (y1 > 0 && pit1 > 0) {
1520                 y1 -= tm.parMetrics(pit1).ascent();
1521                 --pit1;
1522                 if (!singlepar)
1523                         tm.redoParagraph(pit1);
1524                 y1 -= tm.parMetrics(pit1).descent();
1525         }
1526
1527
1528         // Take care of ascent of first line
1529         y1 -= tm.parMetrics(pit1).ascent();
1530
1531         // Normalize anchor for next time
1532         anchor_ref_ = pit1;
1533         offset_ref_ = -y1;
1534
1535         // Grey at the beginning is ugly
1536         if (pit1 == 0 && y1 > 0) {
1537                 y0 -= y1;
1538                 y1 = 0;
1539                 anchor_ref_ = 0;
1540         }
1541
1542         // Redo paragraphs below the anchor if necessary.
1543         int y2 = y0;
1544         while (y2 < height_ && pit2 < int(npit) - 1) {
1545                 y2 += tm.parMetrics(pit2).descent();
1546                 ++pit2;
1547                 if (!singlepar)
1548                         tm.redoParagraph(pit2);
1549                 y2 += tm.parMetrics(pit2).ascent();
1550         }
1551
1552         // Take care of descent of last line
1553         y2 += tm.parMetrics(pit2).descent();
1554
1555         // The coordinates of all these paragraphs are correct, cache them
1556         int y = y1;
1557         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1558         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1559                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1560                 y += pm.ascent();
1561                 parPos[pit] = Point(0, y);
1562                 if (singlepar && pit == cursor_.bottom().pit()) {
1563                         // In Single Paragraph mode, collect here the
1564                         // y1 and y2 of the (one) paragraph the cursor is in
1565                         y1 = y - pm.ascent();
1566                         y2 = y + pm.descent();
1567                 }
1568                 y += pm.descent();
1569         }
1570
1571         if (singlepar) {
1572                 // collect cursor paragraph iter bounds
1573                 pit1 = cursor_.bottom().pit();
1574                 pit2 = cursor_.bottom().pit();
1575         }
1576
1577         LYXERR(Debug::DEBUG)
1578                 << BOOST_CURRENT_FUNCTION
1579                 << " y1: " << y1
1580                 << " y2: " << y2
1581                 << " pit1: " << pit1
1582                 << " pit2: " << pit2
1583                 << " npit: " << npit
1584                 << " singlepar: " << singlepar
1585                 << "size: " << size
1586                 << endl;
1587
1588         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, 
1589                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1590
1591         if (lyxerr.debugging(Debug::WORKAREA)) {
1592                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1593                 coord_cache_.dump();
1594         }
1595 }
1596
1597
1598 void BufferView::menuInsertLyXFile(string const & filenm)
1599 {
1600         BOOST_ASSERT(cursor_.inTexted());
1601         string filename = filenm;
1602
1603         if (filename.empty()) {
1604                 // Launch a file browser
1605                 // FIXME UNICODE
1606                 string initpath = lyxrc.document_path;
1607
1608                 if (buffer_) {
1609                         string const trypath = buffer_->filePath();
1610                         // If directory is writeable, use this as default.
1611                         if (isDirWriteable(FileName(trypath)))
1612                                 initpath = trypath;
1613                 }
1614
1615                 // FIXME UNICODE
1616                 FileDialog fileDlg(_("Select LyX document to insert"),
1617                         LFUN_FILE_INSERT,
1618                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1619                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support().absFilename(), "examples"))));
1620
1621                 FileDialog::Result result =
1622                         fileDlg.open(from_utf8(initpath),
1623                                      FileFilterList(_("LyX Documents (*.lyx)")),
1624                                      docstring());
1625
1626                 if (result.first == FileDialog::Later)
1627                         return;
1628
1629                 // FIXME UNICODE
1630                 filename = to_utf8(result.second);
1631
1632                 // check selected filename
1633                 if (filename.empty()) {
1634                         // emit message signal.
1635                         message(_("Canceled."));
1636                         return;
1637                 }
1638         }
1639
1640         // Get absolute path of file and add ".lyx"
1641         // to the filename if necessary
1642         filename = fileSearch(string(), filename, "lyx").absFilename();
1643
1644         docstring const disp_fn = makeDisplayPath(filename);
1645         // emit message signal.
1646         message(bformat(_("Inserting document %1$s..."), disp_fn));
1647
1648         docstring res;
1649         Buffer buf("", false);
1650         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1651                 ErrorList & el = buffer_->errorList("Parse");
1652                 // Copy the inserted document error list into the current buffer one.
1653                 el = buf.errorList("Parse");
1654                 recordUndo(cursor_);
1655                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1656                                              buf.params().textclass, el);
1657                 res = _("Document %1$s inserted.");
1658         } else
1659                 res = _("Could not insert document %1$s");
1660
1661         // emit message signal.
1662         message(bformat(res, disp_fn));
1663         buffer_->errors("Parse");
1664         resize();
1665 }
1666
1667 } // namespace lyx