]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
* Only enter inset which return true on isActive(). This is the behavior in the curso...
[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         Cursor & cur = cursor_;
669
670         switch (cmd.action) {
671
672         case LFUN_UNDO:
673                 flag.enabled(!buffer_->undostack().empty());
674                 break;
675         case LFUN_REDO:
676                 flag.enabled(!buffer_->redostack().empty());
677                 break;
678         case LFUN_FILE_INSERT:
679         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
680         case LFUN_FILE_INSERT_PLAINTEXT:
681         case LFUN_BOOKMARK_SAVE:
682                 // FIXME: Actually, these LFUNS should be moved to Text
683                 flag.enabled(cur.inTexted());
684                 break;
685         case LFUN_FONT_STATE:
686         case LFUN_LABEL_INSERT:
687         case LFUN_PARAGRAPH_GOTO:
688         // FIXME handle non-trivially
689         case LFUN_OUTLINE_UP:
690         case LFUN_OUTLINE_DOWN:
691         case LFUN_OUTLINE_IN:
692         case LFUN_OUTLINE_OUT:
693         case LFUN_NOTE_NEXT:
694         case LFUN_REFERENCE_NEXT:
695         case LFUN_WORD_FIND:
696         case LFUN_MARK_OFF:
697         case LFUN_MARK_ON:
698         case LFUN_MARK_TOGGLE:
699         case LFUN_SCREEN_RECENTER:
700         case LFUN_BIBTEX_DATABASE_ADD:
701         case LFUN_BIBTEX_DATABASE_DEL:
702         case LFUN_WORDS_COUNT:
703         case LFUN_NEXT_INSET_TOGGLE:
704                 flag.enabled(true);
705                 break;
706
707         case LFUN_WORD_REPLACE:
708                 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
709                 break;
710
711         case LFUN_LABEL_GOTO: {
712                 flag.enabled(!cmd.argument().empty()
713                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
714                 break;
715         }
716
717         case LFUN_CHANGES_TRACK:
718                 flag.enabled(true);
719                 flag.setOnOff(buffer_->params().trackChanges);
720                 break;
721
722         case LFUN_CHANGES_OUTPUT:
723                 flag.enabled(buffer_);
724                 flag.setOnOff(buffer_->params().outputChanges);
725                 break;
726
727         case LFUN_CHANGES_MERGE:
728         case LFUN_CHANGE_NEXT:
729         case LFUN_ALL_CHANGES_ACCEPT:
730         case LFUN_ALL_CHANGES_REJECT:
731                 // TODO: context-sensitive enabling of LFUNs
732                 // In principle, these command should only be enabled if there
733                 // is a change in the document. However, without proper
734                 // optimizations, this will inevitably result in poor performance.
735                 flag.enabled(buffer_);
736                 break;
737
738         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
739                 flag.setOnOff(buffer_->params().compressed);
740                 break;
741         }
742
743         default:
744                 flag.enabled(false);
745         }
746
747         return flag;
748 }
749
750
751 Update::flags BufferView::dispatch(FuncRequest const & cmd)
752 {
753         //lyxerr << BOOST_CURRENT_FUNCTION
754         //       << [ cmd = " << cmd << "]" << endl;
755
756         // Make sure that the cached BufferView is correct.
757         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
758                 << " action[" << cmd.action << ']'
759                 << " arg[" << to_utf8(cmd.argument()) << ']'
760                 << " x[" << cmd.x << ']'
761                 << " y[" << cmd.y << ']'
762                 << " button[" << cmd.button() << ']'
763                 << endl;
764
765         // FIXME: this should not be possible.
766         if (!buffer_)
767                 return Update::None;
768
769         Cursor & cur = cursor_;
770         // Default Update flags.
771         Update::flags updateFlags = Update::Force | Update::FitCursor;
772
773         switch (cmd.action) {
774
775         case LFUN_UNDO:
776                 cur.message(_("Undo"));
777                 cur.clearSelection();
778                 if (!textUndo(*this)) {
779                         cur.message(_("No further undo information"));
780                         updateFlags = Update::None;
781                 }
782                 switchKeyMap();
783                 break;
784
785         case LFUN_REDO:
786                 cur.message(_("Redo"));
787                 cur.clearSelection();
788                 if (!textRedo(*this)) {
789                         cur.message(_("No further redo information"));
790                         updateFlags = Update::None;
791                 }
792                 switchKeyMap();
793                 break;
794
795         case LFUN_FILE_INSERT:
796                 // FIXME UNICODE
797                 menuInsertLyXFile(to_utf8(cmd.argument()));
798                 break;
799
800         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
801                 // FIXME UNICODE
802                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
803                 break;
804
805         case LFUN_FILE_INSERT_PLAINTEXT:
806                 // FIXME UNICODE
807                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
808                 break;
809
810         case LFUN_FONT_STATE:
811                 cur.message(cur.currentState());
812                 break;
813
814         case LFUN_BOOKMARK_SAVE:
815                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
816                 break;
817
818         case LFUN_LABEL_GOTO: {
819                 docstring label = cmd.argument();
820                 if (label.empty()) {
821                         InsetRef * inset =
822                                 getInsetByCode<InsetRef>(cursor_,
823                                                          Inset::REF_CODE);
824                         if (inset) {
825                                 label = inset->getParam("reference");
826                                 // persistent=false: use temp_bookmark
827                                 saveBookmark(0);
828                         }
829                 }
830
831                 if (!label.empty())
832                         gotoLabel(label);
833                 break;
834         }
835
836         case LFUN_PARAGRAPH_GOTO: {
837                 int const id = convert<int>(to_utf8(cmd.argument()));
838                 int i = 0;
839                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
840                         ParIterator par = b->getParFromID(id);
841                         if (par == b->par_iterator_end()) {
842                                 LYXERR(Debug::INFO)
843                                         << "No matching paragraph found! ["
844                                         << id << "]." << endl;
845                         } else {
846                                 LYXERR(Debug::INFO)
847                                         << "Paragraph " << par->id()
848                                         << " found in buffer `"
849                                         << b->fileName() << "'." << endl;
850
851                                 if (b == buffer_) {
852                                         // Set the cursor
853                                         setCursor(makeDocIterator(par, 0));
854                                         switchKeyMap();
855                                 } else {
856                                         // Switch to other buffer view and resend cmd
857                                         theLyXFunc().dispatch(FuncRequest(
858                                                 LFUN_BUFFER_SWITCH, b->fileName()));
859                                         theLyXFunc().dispatch(cmd);
860                                         updateFlags = Update::None;
861                                 }
862                                 break;
863                         }
864                         ++i;
865                 }
866                 break;
867         }
868
869         case LFUN_OUTLINE_UP:
870                 toc::outline(toc::Up, cursor_);
871                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
872                 updateLabels(*buffer_);
873                 break;
874         case LFUN_OUTLINE_DOWN:
875                 toc::outline(toc::Down, cursor_);
876                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
877                 updateLabels(*buffer_);
878                 break;
879         case LFUN_OUTLINE_IN:
880                 toc::outline(toc::In, cursor_);
881                 updateLabels(*buffer_);
882                 break;
883         case LFUN_OUTLINE_OUT:
884                 toc::outline(toc::Out, cursor_);
885                 updateLabels(*buffer_);
886                 break;
887
888         case LFUN_NOTE_NEXT:
889                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
890                 break;
891
892         case LFUN_REFERENCE_NEXT: {
893                 vector<Inset_code> tmp;
894                 tmp.push_back(Inset::LABEL_CODE);
895                 tmp.push_back(Inset::REF_CODE);
896                 bv_funcs::gotoInset(this, tmp, true);
897                 break;
898         }
899
900         case LFUN_CHANGES_TRACK:
901                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
902                 break;
903
904         case LFUN_CHANGES_OUTPUT:
905                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
906                 if (buffer_->params().outputChanges) {
907                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
908                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
909                                           LaTeXFeatures::isAvailable("xcolor");
910
911                         if (!dvipost && !xcolorsoul) {
912                                 Alert::warning(_("Changes not shown in LaTeX output"),
913                                                _("Changes will not be highlighted in LaTeX output, "
914                                                  "because neither dvipost nor xcolor/soul are installed.\n"
915                                                  "Please install these packages or redefine "
916                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
917                         } else if (!xcolorsoul) {
918                                 Alert::warning(_("Changes not shown in LaTeX output"),
919                                                _("Changes will not be highlighted in LaTeX output "
920                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
921                                                  "Please install both packages or redefine "
922                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
923                         }
924                 }
925                 break;
926
927         case LFUN_CHANGE_NEXT:
928                 findNextChange(this);
929                 break;
930
931         case LFUN_CHANGES_MERGE:
932                 if (findNextChange(this))
933                         showDialog("changes");
934                 break;
935
936         case LFUN_ALL_CHANGES_ACCEPT:
937                 // select complete document
938                 cursor_.reset(buffer_->inset());
939                 cursor_.selHandle(true);
940                 buffer_->text().cursorBottom(cursor_);
941                 // accept everything in a single step to support atomic undo
942                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
943                 break;
944
945         case LFUN_ALL_CHANGES_REJECT:
946                 // select complete document
947                 cursor_.reset(buffer_->inset());
948                 cursor_.selHandle(true);
949                 buffer_->text().cursorBottom(cursor_);
950                 // reject everything in a single step to support atomic undo
951                 // Note: reject does not work recursively; the user may have to repeat the operation
952                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
953                 break;
954
955         case LFUN_WORD_FIND:
956                 find(this, cmd);
957                 break;
958
959         case LFUN_WORD_REPLACE:
960                 replace(this, cmd);
961                 break;
962
963         case LFUN_MARK_OFF:
964                 cur.clearSelection();
965                 cur.resetAnchor();
966                 cur.message(from_utf8(N_("Mark off")));
967                 break;
968
969         case LFUN_MARK_ON:
970                 cur.clearSelection();
971                 cur.mark() = true;
972                 cur.resetAnchor();
973                 cur.message(from_utf8(N_("Mark on")));
974                 break;
975
976         case LFUN_MARK_TOGGLE:
977                 cur.clearSelection();
978                 if (cur.mark()) {
979                         cur.mark() = false;
980                         cur.message(from_utf8(N_("Mark removed")));
981                 } else {
982                         cur.mark() = true;
983                         cur.message(from_utf8(N_("Mark set")));
984                 }
985                 cur.resetAnchor();
986                 break;
987
988         case LFUN_SCREEN_RECENTER:
989                 center();
990                 break;
991
992         case LFUN_BIBTEX_DATABASE_ADD: {
993                 Cursor tmpcur = cursor_;
994                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
995                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
996                                                 Inset::BIBTEX_CODE);
997                 if (inset) {
998                         if (inset->addDatabase(to_utf8(cmd.argument())))
999                                 buffer_->updateBibfilesCache();
1000                 }
1001                 break;
1002         }
1003
1004         case LFUN_BIBTEX_DATABASE_DEL: {
1005                 Cursor tmpcur = cursor_;
1006                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
1007                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1008                                                 Inset::BIBTEX_CODE);
1009                 if (inset) {
1010                         if (inset->delDatabase(to_utf8(cmd.argument())))
1011                                 buffer_->updateBibfilesCache();
1012                 }
1013                 break;
1014         }
1015
1016         case LFUN_WORDS_COUNT: {
1017                 DocIterator from, to;
1018                 if (cur.selection()) {
1019                         from = cur.selectionBegin();
1020                         to = cur.selectionEnd();
1021                 } else {
1022                         from = doc_iterator_begin(buffer_->inset());
1023                         to = doc_iterator_end(buffer_->inset());
1024                 }
1025                 int const count = countWords(from, to);
1026                 docstring message;
1027                 if (count != 1) {
1028                         if (cur.selection())
1029                                 message = bformat(_("%1$d words in selection."),
1030                                           count);
1031                                 else
1032                                         message = bformat(_("%1$d words in document."),
1033                                                           count);
1034                 }
1035                 else {
1036                         if (cur.selection())
1037                                 message = _("One word in selection.");
1038                         else
1039                                 message = _("One word in document.");
1040                 }
1041
1042                 Alert::information(_("Count words"), message);
1043         }
1044                 break;
1045
1046         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1047                 // turn compression on/off
1048                 buffer_->params().compressed = !buffer_->params().compressed;
1049                 break;
1050
1051         case LFUN_NEXT_INSET_TOGGLE: {
1052                 // this is the real function we want to invoke
1053                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1054                 // if there is an inset at cursor, see whether it
1055                 // wants to toggle.
1056                 Inset * inset = cur.nextInset();
1057                 if (inset && inset->isActive()) {
1058                         Cursor tmpcur = cur;
1059                         tmpcur.pushLeft(*inset);
1060                         inset->dispatch(tmpcur, tmpcmd);
1061                         if (tmpcur.result().dispatched()) {
1062                                 cur.dispatched();
1063                         }
1064                 }
1065                 // if it did not work, try the underlying inset.
1066                 if (!cur.result().dispatched())
1067                         cur.dispatch(tmpcmd);
1068
1069                 if (cur.result().dispatched())
1070                         cur.clearSelection();
1071
1072                 break;
1073         }
1074
1075         default:
1076                 updateFlags = Update::None;
1077         }
1078
1079         return updateFlags;
1080 }
1081
1082
1083 docstring const BufferView::requestSelection()
1084 {
1085         if (!buffer_)
1086                 return docstring();
1087
1088         Cursor & cur = cursor_;
1089
1090         if (!cur.selection()) {
1091                 xsel_cache_.set = false;
1092                 return docstring();
1093         }
1094
1095         if (!xsel_cache_.set ||
1096             cur.top() != xsel_cache_.cursor ||
1097             cur.anchor_.top() != xsel_cache_.anchor)
1098         {
1099                 xsel_cache_.cursor = cur.top();
1100                 xsel_cache_.anchor = cur.anchor_.top();
1101                 xsel_cache_.set = cur.selection();
1102                 return cur.selectionAsString(false);
1103         }
1104         return docstring();
1105 }
1106
1107
1108 void BufferView::clearSelection()
1109 {
1110         if (buffer_) {
1111                 cursor_.clearSelection();
1112                 // Clear the selection buffer. Otherwise a subsequent
1113                 // middle-mouse-button paste would use the selection buffer,
1114                 // not the more current external selection.
1115                 cap::clearSelection();
1116                 xsel_cache_.set = false;
1117                 // The buffer did not really change, but this causes the
1118                 // redraw we need because we cleared the selection above.
1119                 buffer_->changed();
1120         }
1121 }
1122
1123
1124 void BufferView::workAreaResize(int width, int height)
1125 {
1126         // Update from work area
1127         width_ = width;
1128         height_ = height;
1129
1130         // The complete text metrics will be redone.
1131         text_metrics_.clear();
1132
1133         if (buffer_)
1134                 resize();
1135 }
1136
1137
1138 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1139 {
1140         pit_type pit = text.getPitNearY(*this, y);
1141         BOOST_ASSERT(pit != -1);
1142         Paragraph const & par = text.getPar(pit);
1143
1144         LYXERR(Debug::DEBUG)
1145                 << BOOST_CURRENT_FUNCTION
1146                 << ": x: " << x
1147                 << " y: " << y
1148                 << "  pit: " << pit
1149                 << endl;
1150         InsetList::const_iterator iit = par.insetlist.begin();
1151         InsetList::const_iterator iend = par.insetlist.end();
1152         for (; iit != iend; ++iit) {
1153                 Inset * const inset = iit->inset;
1154                 if (inset->covers(*this, x, y)) {
1155                         if (!inset->descendable())
1156                                 // No need to go further down if the inset is not
1157                                 // descendable.
1158                                 return inset;
1159
1160                         size_t cell_number = inset->nargs();
1161                         // Check all the inner cell.
1162                         for (size_t i = 0; i != cell_number; ++i) {
1163                                 Text const * inner_text = inset->getText(i);
1164                                 if (inner_text) {
1165                                         // Try deeper.
1166                                         Inset const * inset_deeper =
1167                                                 getCoveringInset(*inner_text, x, y);
1168                                         if (inset_deeper)
1169                                                 return inset_deeper;
1170                                 }
1171                         }
1172
1173                         LYXERR(Debug::DEBUG)
1174                                 << BOOST_CURRENT_FUNCTION
1175                                 << ": Hit inset: " << inset << endl;
1176                         return inset;
1177                 }
1178         }
1179         LYXERR(Debug::DEBUG)
1180                 << BOOST_CURRENT_FUNCTION
1181                 << ": No inset hit. " << endl;
1182         return 0;
1183 }
1184
1185
1186 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1187 {
1188         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1189
1190         // This is only called for mouse related events including
1191         // LFUN_FILE_OPEN generated by drag-and-drop.
1192         FuncRequest cmd = cmd0;
1193
1194         // E.g. Qt mouse press when no buffer
1195         if (!buffer_)
1196                 return false;
1197
1198         Cursor cur(*this);
1199         cur.push(buffer_->inset());
1200         cur.selection() = cursor_.selection();
1201
1202         // Either the inset under the cursor or the
1203         // surrounding Text will handle this event.
1204
1205         // make sure we stay within the screen...
1206         cmd.y = min(max(cmd.y, -1), height_);
1207
1208         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1209
1210                 // Get inset under mouse, if there is one.
1211                 Inset const * covering_inset =
1212                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1213                 if (covering_inset == last_inset_)
1214                         // Same inset, no need to do anything...
1215                         return false;
1216
1217                 bool need_redraw = false;
1218                 // const_cast because of setMouseHover().
1219                 Inset * inset = const_cast<Inset *>(covering_inset);
1220                 if (last_inset_)
1221                         // Remove the hint on the last hovered inset (if any).
1222                         need_redraw |= last_inset_->setMouseHover(false);
1223                 if (inset)
1224                         // Highlighted the newly hovered inset (if any).
1225                         need_redraw |= inset->setMouseHover(true);
1226                 last_inset_ = inset;
1227
1228                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1229                 // not expose the button for redraw. We adjust here the metrics dimension
1230                 // to enable a full redraw.
1231                 // FIXME: It is possible to redraw only the area around the button!
1232                 if (need_redraw
1233                         && metrics_info_.update_strategy == SingleParUpdate) {
1234                         // FIXME: It should be possible to redraw only the area around
1235                         // the button by doing this:
1236                         //
1237                         //metrics_info_.singlepar = false;
1238                         //metrics_info_.y1 = ymin of button;
1239                         //metrics_info_.y2 = ymax of button;
1240                         //
1241                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1242                         // between background updates and text updates. So we use the hammer
1243                         // solution for now. We could also avoid the updateMetrics() below
1244                         // by using the first and last pit of the CoordCache. Have a look
1245                         // at Text::getPitNearY() to see what I mean.
1246                         //
1247                         //metrics_info_.pit1 = first pit of CoordCache;
1248                         //metrics_info_.pit2 = last pit of CoordCache;
1249                         //metrics_info_.singlepar = false;
1250                         //metrics_info_.y1 = 0;
1251                         //metrics_info_.y2 = height_;
1252                         //
1253                         updateMetrics(false);
1254                 }
1255
1256                 // This event (moving without mouse click) is not passed further.
1257                 // This should be changed if it is further utilized.
1258                 return need_redraw;
1259         }
1260
1261         // Build temporary cursor.
1262         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1263
1264         // Put anchor at the same position.
1265         cur.resetAnchor();
1266
1267         // Try to dispatch to an non-editable inset near this position
1268         // via the temp cursor. If the inset wishes to change the real
1269         // cursor it has to do so explicitly by using
1270         //  cur.bv().cursor() = cur;  (or similar)
1271         if (inset) {
1272                 inset->dispatch(cur, cmd);
1273         }
1274
1275         // Now dispatch to the temporary cursor. If the real cursor should
1276         // be modified, the inset's dispatch has to do so explicitly.
1277         if (!cur.result().dispatched())
1278                 cur.dispatch(cmd);
1279
1280         // Redraw if requested and necessary.
1281         if (cur.result().dispatched() && cur.result().update())
1282                 return update(cur.result().update());
1283
1284         return false;
1285 }
1286
1287
1288 void BufferView::scroll(int /*lines*/)
1289 {
1290 //      if (!buffer_)
1291 //              return;
1292 //
1293 //      Text const * t = &buffer_->text();
1294 //      int const line_height = defaultRowHeight();
1295 //
1296 //      // The new absolute coordinate
1297 //      int new_top_y = top_y() + lines * line_height;
1298 //
1299 //      // Restrict to a valid value
1300 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1301 //      new_top_y = std::max(0, new_top_y);
1302 //
1303 //      scrollDocView(new_top_y);
1304 //
1305 }
1306
1307
1308 void BufferView::setCursorFromRow(int row)
1309 {
1310         int tmpid = -1;
1311         int tmppos = -1;
1312
1313         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1314
1315         if (tmpid == -1)
1316                 buffer_->text().setCursor(cursor_, 0, 0);
1317         else
1318                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1319 }
1320
1321
1322 void BufferView::gotoLabel(docstring const & label)
1323 {
1324         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1325                 vector<docstring> labels;
1326                 it->getLabelList(*buffer_, labels);
1327                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1328                         setCursor(it);
1329                         update();
1330                         return;
1331                 }
1332         }
1333 }
1334
1335
1336 TextMetrics const & BufferView::textMetrics(Text const * t) const
1337 {
1338         return const_cast<BufferView *>(this)->textMetrics(t);
1339 }
1340
1341
1342 TextMetrics & BufferView::textMetrics(Text const * t)
1343 {
1344         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1345         if (tmc_it == text_metrics_.end()) {
1346                 tmc_it = text_metrics_.insert(
1347                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1348         }
1349         return tmc_it->second;
1350 }
1351
1352
1353 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1354                 pit_type pit) const
1355 {
1356         return textMetrics(t).parMetrics(pit);
1357 }
1358
1359
1360 int BufferView::workHeight() const
1361 {
1362         return height_;
1363 }
1364
1365
1366 void BufferView::setCursor(DocIterator const & dit)
1367 {
1368         size_t const n = dit.depth();
1369         for (size_t i = 0; i < n; ++i)
1370                 dit[i].inset().edit(cursor_, true);
1371
1372         cursor_.setCursor(dit);
1373         cursor_.selection() = false;
1374 }
1375
1376
1377 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1378 {
1379         // Would be wrong to delete anything if we have a selection.
1380         if (cur.selection())
1381                 return false;
1382
1383         bool need_anchor_change = false;
1384         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1385                 need_anchor_change);
1386
1387         if (need_anchor_change)
1388                 cur.resetAnchor();
1389
1390         if (!changed)
1391                 return false;
1392
1393         updateLabels(*buffer_);
1394
1395         updateMetrics(false);
1396         buffer_->changed();
1397         return true;
1398 }
1399
1400
1401 bool BufferView::mouseSetCursor(Cursor & cur)
1402 {
1403         BOOST_ASSERT(&cur.bv() == this);
1404
1405         // Has the cursor just left the inset?
1406         bool badcursor = false;
1407         bool leftinset = (&cursor_.inset() != &cur.inset());
1408         if (leftinset)
1409                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1410
1411         // do the dEPM magic if needed
1412         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1413         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1414         // the leftinset bool would not be necessary (badcursor instead).
1415         bool update = leftinset;
1416         if (!badcursor && cursor_.inTexted())
1417                 update |= checkDepm(cur, cursor_);
1418
1419         // if the cursor was in an empty script inset and the new
1420         // position is in the nucleus of the inset, notifyCursorLeaves
1421         // will kill the script inset itself. So we check all the
1422         // elements of the cursor to make sure that they are correct.
1423         // For an example, see bug 2933:
1424         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1425         // The code below could maybe be moved to a DocIterator method.
1426         //lyxerr << "cur before " << cur <<std::endl;
1427         DocIterator dit(cur.inset());
1428         dit.push_back(cur.bottom());
1429         size_t i = 1;
1430         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1431                 dit.push_back(cur[i]);
1432                 ++i;
1433         }
1434         //lyxerr << "5 cur after" << dit <<std::endl;
1435
1436         cursor_.setCursor(dit);
1437         cursor_.boundary(cur.boundary());
1438         cursor_.clearSelection();
1439         finishUndo();
1440         return update;
1441 }
1442
1443
1444 void BufferView::putSelectionAt(DocIterator const & cur,
1445                                 int length, bool backwards)
1446 {
1447         cursor_.clearSelection();
1448
1449         setCursor(cur);
1450
1451         if (length) {
1452                 if (backwards) {
1453                         cursor_.pos() += length;
1454                         cursor_.setSelection(cursor_, -length);
1455                 } else
1456                         cursor_.setSelection(cursor_, length);
1457                 cap::saveSelection(cursor_);
1458         }
1459 }
1460
1461
1462 Cursor & BufferView::cursor()
1463 {
1464         return cursor_;
1465 }
1466
1467
1468 Cursor const & BufferView::cursor() const
1469 {
1470         return cursor_;
1471 }
1472
1473
1474 pit_type BufferView::anchor_ref() const
1475 {
1476         return anchor_ref_;
1477 }
1478
1479
1480 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1481 {
1482         return metrics_info_;
1483 }
1484
1485
1486 // FIXME: We should split-up updateMetrics() for the singlepar case.
1487 void BufferView::updateMetrics(bool singlepar)
1488 {
1489         Text & buftext = buffer_->text();
1490         TextMetrics & tm = textMetrics(&buftext);
1491         pit_type size = int(buftext.paragraphs().size());
1492
1493         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1494                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1495                 offset_ref_ = 0;
1496         }
1497
1498         // If the paragraph metrics has changed, we can not
1499         // use the singlepar optimisation.
1500         if (singlepar
1501                 // In Single Paragraph mode, rebreak only
1502                 // the (main text, not inset!) paragraph containing the cursor.
1503                 // (if this paragraph contains insets etc., rebreaking will
1504                 // recursively descend)
1505                 && tm.redoParagraph(cursor_.bottom().pit()))
1506                 singlepar = false;
1507
1508         pit_type const pit = anchor_ref_;
1509         int pit1 = pit;
1510         int pit2 = pit;
1511         size_t const npit = buftext.paragraphs().size();
1512
1513         // Rebreak anchor paragraph.
1514         if (!singlepar)
1515                 tm.redoParagraph(pit);
1516
1517         // Clear out the position cache in case of full screen redraw.
1518         if (!singlepar)
1519                 coord_cache_.clear();
1520
1521         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1522
1523         // Redo paragraphs above anchor if necessary.
1524         int y1 = y0;
1525         while (y1 > 0 && pit1 > 0) {
1526                 y1 -= tm.parMetrics(pit1).ascent();
1527                 --pit1;
1528                 if (!singlepar)
1529                         tm.redoParagraph(pit1);
1530                 y1 -= tm.parMetrics(pit1).descent();
1531         }
1532
1533
1534         // Take care of ascent of first line
1535         y1 -= tm.parMetrics(pit1).ascent();
1536
1537         // Normalize anchor for next time
1538         anchor_ref_ = pit1;
1539         offset_ref_ = -y1;
1540
1541         // Grey at the beginning is ugly
1542         if (pit1 == 0 && y1 > 0) {
1543                 y0 -= y1;
1544                 y1 = 0;
1545                 anchor_ref_ = 0;
1546         }
1547
1548         // Redo paragraphs below the anchor if necessary.
1549         int y2 = y0;
1550         while (y2 < height_ && pit2 < int(npit) - 1) {
1551                 y2 += tm.parMetrics(pit2).descent();
1552                 ++pit2;
1553                 if (!singlepar)
1554                         tm.redoParagraph(pit2);
1555                 y2 += tm.parMetrics(pit2).ascent();
1556         }
1557
1558         // Take care of descent of last line
1559         y2 += tm.parMetrics(pit2).descent();
1560
1561         // The coordinates of all these paragraphs are correct, cache them
1562         int y = y1;
1563         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1564         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1565                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1566                 y += pm.ascent();
1567                 parPos[pit] = Point(0, y);
1568                 if (singlepar && pit == cursor_.bottom().pit()) {
1569                         // In Single Paragraph mode, collect here the
1570                         // y1 and y2 of the (one) paragraph the cursor is in
1571                         y1 = y - pm.ascent();
1572                         y2 = y + pm.descent();
1573                 }
1574                 y += pm.descent();
1575         }
1576
1577         if (singlepar) {
1578                 // collect cursor paragraph iter bounds
1579                 pit1 = cursor_.bottom().pit();
1580                 pit2 = cursor_.bottom().pit();
1581         }
1582
1583         LYXERR(Debug::DEBUG)
1584                 << BOOST_CURRENT_FUNCTION
1585                 << " y1: " << y1
1586                 << " y2: " << y2
1587                 << " pit1: " << pit1
1588                 << " pit2: " << pit2
1589                 << " npit: " << npit
1590                 << " singlepar: " << singlepar
1591                 << "size: " << size
1592                 << endl;
1593
1594         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1595                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1596
1597         if (lyxerr.debugging(Debug::WORKAREA)) {
1598                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1599                 coord_cache_.dump();
1600         }
1601 }
1602
1603
1604 void BufferView::menuInsertLyXFile(string const & filenm)
1605 {
1606         BOOST_ASSERT(cursor_.inTexted());
1607         string filename = filenm;
1608
1609         if (filename.empty()) {
1610                 // Launch a file browser
1611                 // FIXME UNICODE
1612                 string initpath = lyxrc.document_path;
1613
1614                 if (buffer_) {
1615                         string const trypath = buffer_->filePath();
1616                         // If directory is writeable, use this as default.
1617                         if (isDirWriteable(FileName(trypath)))
1618                                 initpath = trypath;
1619                 }
1620
1621                 // FIXME UNICODE
1622                 FileDialog fileDlg(_("Select LyX document to insert"),
1623                         LFUN_FILE_INSERT,
1624                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1625                         make_pair(_("Examples|#E#e"),
1626                                     from_utf8(addPath(package().system_support().absFilename(),
1627                                     "examples"))));
1628
1629                 FileDialog::Result result =
1630                         fileDlg.open(from_utf8(initpath),
1631                                      FileFilterList(_("LyX Documents (*.lyx)")),
1632                                      docstring());
1633
1634                 if (result.first == FileDialog::Later)
1635                         return;
1636
1637                 // FIXME UNICODE
1638                 filename = to_utf8(result.second);
1639
1640                 // check selected filename
1641                 if (filename.empty()) {
1642                         // emit message signal.
1643                         message(_("Canceled."));
1644                         return;
1645                 }
1646         }
1647
1648         // Get absolute path of file and add ".lyx"
1649         // to the filename if necessary
1650         filename = fileSearch(string(), filename, "lyx").absFilename();
1651
1652         docstring const disp_fn = makeDisplayPath(filename);
1653         // emit message signal.
1654         message(bformat(_("Inserting document %1$s..."), disp_fn));
1655
1656         docstring res;
1657         Buffer buf("", false);
1658         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1659                 ErrorList & el = buffer_->errorList("Parse");
1660                 // Copy the inserted document error list into the current buffer one.
1661                 el = buf.errorList("Parse");
1662                 recordUndo(cursor_);
1663                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1664                                              buf.params().textclass, el);
1665                 res = _("Document %1$s inserted.");
1666         } else
1667                 res = _("Could not insert document %1$s");
1668
1669         // emit message signal.
1670         message(bformat(res, disp_fn));
1671         buffer_->errors("Parse");
1672         resize();
1673 }
1674
1675 } // namespace lyx