]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
EmbeddedObjects.lyx: add hint how to force a rotation direction for rotated floats
[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 }
317
318
319 bool BufferView::fitCursor()
320 {
321         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
322                 frontend::FontMetrics const & fm =
323                         theFontMetrics(cursor_.getFont());
324                 int const asc = fm.maxAscent();
325                 int const des = fm.maxDescent();
326                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
327                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
328                         return false;
329         }
330         center();
331         return true;
332 }
333
334
335 bool BufferView::multiParSel()
336 {
337         if (!cursor_.selection())
338                 return false;
339         bool ret = multiparsel_cache_;
340         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
341         // Either this, or previous selection spans paragraphs
342         return ret || multiparsel_cache_;
343 }
344
345
346 bool BufferView::update(Update::flags flags)
347 {
348         // last_inset_ points to the last visited inset. This pointer may become
349         // invalid because of keyboard editing. Since all such operations
350         // causes screen update(), I reset last_inset_ to avoid such a problem.
351         last_inset_ = 0;
352         // This is close to a hot-path.
353         LYXERR(Debug::DEBUG)
354                 << BOOST_CURRENT_FUNCTION
355                 << "[fitcursor = " << (flags & Update::FitCursor)
356                 << ", forceupdate = " << (flags & Update::Force)
357                 << ", singlepar = " << (flags & Update::SinglePar)
358                 << "]  buffer: " << buffer_ << endl;
359
360         // Check needed to survive LyX startup
361         if (!buffer_)
362                 return false;
363
364         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
365
366         // Update macro store
367         if (!(cursor().inMathed() && cursor().inMacroMode()))
368                 buffer_->buildMacros();
369
370         // Now do the first drawing step if needed. This consists on updating
371         // the CoordCache in updateMetrics().
372         // The second drawing step is done in WorkArea::redraw() if needed.
373
374         // Case when no explicit update is requested.
375         if (!flags) {
376                 // no need to redraw anything.
377                 metrics_info_.update_strategy = NoScreenUpdate;
378                 return false;
379         }
380
381         if (flags == Update::Decoration) {
382                 metrics_info_.update_strategy = DecorationUpdate;
383                 return true;
384         }
385
386         if (flags == Update::FitCursor
387                 || flags == (Update::Decoration | Update::FitCursor)) {
388                 bool const fit_cursor = fitCursor();
389                 // tell the frontend to update the screen if needed.
390                 if (fit_cursor) {
391                         updateMetrics(false);
392                         return true;
393                 }
394                 if (flags & Update::Decoration) {
395                         metrics_info_.update_strategy = DecorationUpdate;
396                         return true;
397                 }
398                 // no screen update is needed.
399                 metrics_info_.update_strategy = NoScreenUpdate;
400                 return false;
401         }
402
403         bool full_metrics = flags & Update::Force;
404         if (flags & Update::MultiParSel)
405                 full_metrics |= multiParSel();
406
407         bool const single_par = !full_metrics;
408         updateMetrics(single_par);
409
410         if (flags & Update::FitCursor && fitCursor())
411                 updateMetrics(false);
412
413         // tell the frontend to update the screen.
414         return true;
415 }
416
417
418 void BufferView::updateScrollbar()
419 {
420         if (!buffer_) {
421                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
422                                      << " no text in updateScrollbar" << endl;
423                 scrollbarParameters_.reset();
424                 return;
425         }
426
427         Text & t = buffer_->text();
428         TextMetrics & tm = text_metrics_[&t];
429
430         int const parsize = int(t.paragraphs().size() - 1);
431         if (anchor_ref_ >  parsize)  {
432                 anchor_ref_ = parsize;
433                 offset_ref_ = 0;
434         }
435
436         LYXERR(Debug::GUI)
437                 << BOOST_CURRENT_FUNCTION
438                 << " Updating scrollbar: height: " << t.paragraphs().size()
439                 << " curr par: " << cursor_.bottom().pit()
440                 << " default height " << defaultRowHeight() << endl;
441
442         // It would be better to fix the scrollbar to understand
443         // values in [0..1] and divide everything by wh
444
445         // estimated average paragraph height:
446         if (wh_ == 0)
447                 wh_ = height_ / 4;
448
449         int h = tm.parMetrics(anchor_ref_).height();
450
451         // Normalize anchor/offset (MV):
452         while (offset_ref_ > h && anchor_ref_ < parsize) {
453                 anchor_ref_++;
454                 offset_ref_ -= h;
455                 h = tm.parMetrics(anchor_ref_).height();
456         }
457         // Look at paragraph heights on-screen
458         int sumh = 0;
459         int nh = 0;
460         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
461                 if (sumh > height_)
462                         break;
463                 int const h2 = tm.parMetrics(pit).height();
464                 sumh += h2;
465                 nh++;
466         }
467
468         BOOST_ASSERT(nh);
469         int const hav = sumh / nh;
470         // More realistic average paragraph height
471         if (hav > wh_)
472                 wh_ = hav;
473
474         BOOST_ASSERT(h);
475         scrollbarParameters_.height = (parsize + 1) * wh_;
476         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
477         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
478 }
479
480
481 ScrollbarParameters const & BufferView::scrollbarParameters() const
482 {
483         return scrollbarParameters_;
484 }
485
486
487 void BufferView::scrollDocView(int value)
488 {
489         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
490                            << "[ value = " << value << "]" << endl;
491
492         if (!buffer_)
493                 return;
494
495         Text & t = buffer_->text();
496         TextMetrics & tm = text_metrics_[&t];
497
498         float const bar = value / float(wh_ * t.paragraphs().size());
499
500         anchor_ref_ = int(bar * t.paragraphs().size());
501         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
502                 anchor_ref_ = int(t.paragraphs().size()) - 1;
503
504         tm.redoParagraph(anchor_ref_);
505         int const h = tm.parMetrics(anchor_ref_).height();
506         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
507         updateMetrics(false);
508 }
509
510
511 void BufferView::setCursorFromScrollbar()
512 {
513         if (!buffer_)
514                 return;
515
516         Text & t = buffer_->text();
517
518         int const height = 2 * defaultRowHeight();
519         int const first = height;
520         int const last = height_ - height;
521         Cursor & cur = cursor_;
522
523         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
524
525         switch (st) {
526         case bv_funcs::CUR_ABOVE:
527                 // We reset the cursor because bv_funcs::status() does not
528                 // work when the cursor is within mathed.
529                 cur.reset(buffer_->inset());
530                 t.setCursorFromCoordinates(cur, 0, first);
531                 cur.clearSelection();
532                 break;
533         case bv_funcs::CUR_BELOW:
534                 // We reset the cursor because bv_funcs::status() does not
535                 // work when the cursor is within mathed.
536                 cur.reset(buffer_->inset());
537                 t.setCursorFromCoordinates(cur, 0, last);
538                 cur.clearSelection();
539                 break;
540         case bv_funcs::CUR_INSIDE:
541                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
542                 int const newy = min(last, max(y, first));
543                 if (y != newy) {
544                         cur.reset(buffer_->inset());
545                         t.setCursorFromCoordinates(cur, 0, newy);
546                 }
547         }
548 }
549
550
551 Change const BufferView::getCurrentChange() const
552 {
553         if (!cursor_.selection())
554                 return Change(Change::UNCHANGED);
555
556         DocIterator dit = cursor_.selectionBegin();
557         return dit.paragraph().lookupChange(dit.pos());
558 }
559
560
561 void BufferView::saveBookmark(unsigned int idx)
562 {
563         // tenatively save bookmark, id and pos will be used to
564         // acturately locate a bookmark in a 'live' lyx session.
565         // pit and pos will be updated with bottom level pit/pos
566         // when lyx exits.
567         LyX::ref().session().bookmarks().save(
568                 FileName(buffer_->fileName()),
569                 cursor_.bottom().pit(),
570                 cursor_.bottom().pos(),
571                 cursor_.paragraph().id(),
572                 cursor_.pos(),
573                 idx
574         );
575         if (idx)
576                 // emit message signal.
577                 message(_("Save bookmark"));
578 }
579
580
581 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
582         int top_id, pos_type top_pos)
583 {
584         cursor_.clearSelection();
585
586         // if a valid par_id is given, try it first
587         // This is the case for a 'live' bookmark when unique paragraph ID
588         // is used to track bookmarks.
589         if (top_id > 0) {
590                 ParIterator par = buffer_->getParFromID(top_id);
591                 if (par != buffer_->par_iterator_end()) {
592                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
593                         // Some slices of the iterator may not be
594                         // reachable (e.g. closed collapsable inset)
595                         // so the dociterator may need to be
596                         // shortened. Otherwise, setCursor may crash
597                         // lyx when the cursor can not be set to these
598                         // insets.
599                         size_t const n = dit.depth();
600                         for (size_t i = 0; i < n; ++i)
601                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
602                                         dit.resize(i);
603                                         break;
604                                 }
605                         setCursor(dit);
606                         // Note: return bottom (document) level pit.
607                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
608                 }
609         }
610         // if top_id == 0, or searching through top_id failed
611         // This is the case for a 'restored' bookmark when only bottom
612         // (document level) pit was saved. Because of this, bookmark
613         // restoration is inaccurate. If a bookmark was within an inset,
614         // it will be restored to the left of the outmost inset that contains
615         // the bookmark.
616         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
617                 DocIterator it = doc_iterator_begin(buffer_->inset());
618                 it.pit() = bottom_pit;
619                 it.pos() = min(bottom_pos, it.paragraph().size());
620                 setCursor(it);
621                 return boost::make_tuple(it.pit(), it.pos(),
622                                          it.paragraph().id());
623         }
624         // both methods fail
625         return boost::make_tuple(pit_type(0), pos_type(0), 0);
626 }
627
628
629 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
630 {
631         if (lyxrc.rtl_support) {
632                 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
633                         if (intl_->keymap == Intl::PRIMARY)
634                                 intl_->keyMapSec();
635                 } else {
636                         if (intl_->keymap == Intl::SECONDARY)
637                                 intl_->keyMapPrim();
638                 }
639         }
640         
641         intl_->getTransManager().translateAndInsert(c, t, cur);
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                 break;
783
784         case LFUN_REDO:
785                 cur.message(_("Redo"));
786                 cur.clearSelection();
787                 if (!textRedo(*this)) {
788                         cur.message(_("No further redo information"));
789                         updateFlags = Update::None;
790                 }
791                 break;
792
793         case LFUN_FILE_INSERT:
794                 // FIXME UNICODE
795                 menuInsertLyXFile(to_utf8(cmd.argument()));
796                 break;
797
798         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
799                 // FIXME UNICODE
800                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
801                 break;
802
803         case LFUN_FILE_INSERT_PLAINTEXT:
804                 // FIXME UNICODE
805                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
806                 break;
807
808         case LFUN_FONT_STATE:
809                 cur.message(cur.currentState());
810                 break;
811
812         case LFUN_BOOKMARK_SAVE:
813                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
814                 break;
815
816         case LFUN_LABEL_GOTO: {
817                 docstring label = cmd.argument();
818                 if (label.empty()) {
819                         InsetRef * inset =
820                                 getInsetByCode<InsetRef>(cursor_,
821                                                          Inset::REF_CODE);
822                         if (inset) {
823                                 label = inset->getParam("reference");
824                                 // persistent=false: use temp_bookmark
825                                 saveBookmark(0);
826                         }
827                 }
828
829                 if (!label.empty())
830                         gotoLabel(label);
831                 break;
832         }
833
834         case LFUN_PARAGRAPH_GOTO: {
835                 int const id = convert<int>(to_utf8(cmd.argument()));
836                 int i = 0;
837                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
838                         ParIterator par = b->getParFromID(id);
839                         if (par == b->par_iterator_end()) {
840                                 LYXERR(Debug::INFO)
841                                         << "No matching paragraph found! ["
842                                         << id << "]." << endl;
843                         } else {
844                                 LYXERR(Debug::INFO)
845                                         << "Paragraph " << par->id()
846                                         << " found in buffer `"
847                                         << b->fileName() << "'." << endl;
848
849                                 if (b == buffer_) {
850                                         // Set the cursor
851                                         setCursor(makeDocIterator(par, 0));
852                                 } else {
853                                         // Switch to other buffer view and resend cmd
854                                         theLyXFunc().dispatch(FuncRequest(
855                                                 LFUN_BUFFER_SWITCH, b->fileName()));
856                                         theLyXFunc().dispatch(cmd);
857                                         updateFlags = Update::None;
858                                 }
859                                 break;
860                         }
861                         ++i;
862                 }
863                 break;
864         }
865
866         case LFUN_OUTLINE_UP:
867                 toc::outline(toc::Up, cursor_);
868                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
869                 updateLabels(*buffer_);
870                 break;
871         case LFUN_OUTLINE_DOWN:
872                 toc::outline(toc::Down, cursor_);
873                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
874                 updateLabels(*buffer_);
875                 break;
876         case LFUN_OUTLINE_IN:
877                 toc::outline(toc::In, cursor_);
878                 updateLabels(*buffer_);
879                 break;
880         case LFUN_OUTLINE_OUT:
881                 toc::outline(toc::Out, cursor_);
882                 updateLabels(*buffer_);
883                 break;
884
885         case LFUN_NOTE_NEXT:
886                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
887                 break;
888
889         case LFUN_REFERENCE_NEXT: {
890                 vector<Inset_code> tmp;
891                 tmp.push_back(Inset::LABEL_CODE);
892                 tmp.push_back(Inset::REF_CODE);
893                 bv_funcs::gotoInset(this, tmp, true);
894                 break;
895         }
896
897         case LFUN_CHANGES_TRACK:
898                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
899                 break;
900
901         case LFUN_CHANGES_OUTPUT:
902                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
903                 if (buffer_->params().outputChanges) {
904                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
905                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
906                                           LaTeXFeatures::isAvailable("xcolor");
907
908                         if (!dvipost && !xcolorsoul) {
909                                 Alert::warning(_("Changes not shown in LaTeX output"),
910                                                _("Changes will not be highlighted in LaTeX output, "
911                                                  "because neither dvipost nor xcolor/soul are installed.\n"
912                                                  "Please install these packages or redefine "
913                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
914                         } else if (!xcolorsoul) {
915                                 Alert::warning(_("Changes not shown in LaTeX output"),
916                                                _("Changes will not be highlighted in LaTeX output "
917                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
918                                                  "Please install both packages or redefine "
919                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
920                         }
921                 }
922                 break;
923
924         case LFUN_CHANGE_NEXT:
925                 findNextChange(this);
926                 break;
927
928         case LFUN_CHANGES_MERGE:
929                 if (findNextChange(this))
930                         showDialog("changes");
931                 break;
932
933         case LFUN_ALL_CHANGES_ACCEPT:
934                 // select complete document
935                 cursor_.reset(buffer_->inset());
936                 cursor_.selHandle(true);
937                 buffer_->text().cursorBottom(cursor_);
938                 // accept everything in a single step to support atomic undo
939                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
940                 break;
941
942         case LFUN_ALL_CHANGES_REJECT:
943                 // select complete document
944                 cursor_.reset(buffer_->inset());
945                 cursor_.selHandle(true);
946                 buffer_->text().cursorBottom(cursor_);
947                 // reject everything in a single step to support atomic undo
948                 // Note: reject does not work recursively; the user may have to repeat the operation
949                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
950                 break;
951
952         case LFUN_WORD_FIND:
953                 find(this, cmd);
954                 break;
955
956         case LFUN_WORD_REPLACE:
957                 replace(this, cmd);
958                 break;
959
960         case LFUN_MARK_OFF:
961                 cur.clearSelection();
962                 cur.resetAnchor();
963                 cur.message(from_utf8(N_("Mark off")));
964                 break;
965
966         case LFUN_MARK_ON:
967                 cur.clearSelection();
968                 cur.mark() = true;
969                 cur.resetAnchor();
970                 cur.message(from_utf8(N_("Mark on")));
971                 break;
972
973         case LFUN_MARK_TOGGLE:
974                 cur.clearSelection();
975                 if (cur.mark()) {
976                         cur.mark() = false;
977                         cur.message(from_utf8(N_("Mark removed")));
978                 } else {
979                         cur.mark() = true;
980                         cur.message(from_utf8(N_("Mark set")));
981                 }
982                 cur.resetAnchor();
983                 break;
984
985         case LFUN_SCREEN_RECENTER:
986                 center();
987                 break;
988
989         case LFUN_BIBTEX_DATABASE_ADD: {
990                 Cursor tmpcur = cursor_;
991                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
992                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
993                                                 Inset::BIBTEX_CODE);
994                 if (inset) {
995                         if (inset->addDatabase(to_utf8(cmd.argument())))
996                                 buffer_->updateBibfilesCache();
997                 }
998                 break;
999         }
1000
1001         case LFUN_BIBTEX_DATABASE_DEL: {
1002                 Cursor tmpcur = cursor_;
1003                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
1004                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1005                                                 Inset::BIBTEX_CODE);
1006                 if (inset) {
1007                         if (inset->delDatabase(to_utf8(cmd.argument())))
1008                                 buffer_->updateBibfilesCache();
1009                 }
1010                 break;
1011         }
1012
1013         case LFUN_WORDS_COUNT: {
1014                 DocIterator from, to;
1015                 if (cur.selection()) {
1016                         from = cur.selectionBegin();
1017                         to = cur.selectionEnd();
1018                 } else {
1019                         from = doc_iterator_begin(buffer_->inset());
1020                         to = doc_iterator_end(buffer_->inset());
1021                 }
1022                 int const count = countWords(from, to);
1023                 docstring message;
1024                 if (count != 1) {
1025                         if (cur.selection())
1026                                 message = bformat(_("%1$d words in selection."),
1027                                           count);
1028                                 else
1029                                         message = bformat(_("%1$d words in document."),
1030                                                           count);
1031                 }
1032                 else {
1033                         if (cur.selection())
1034                                 message = _("One word in selection.");
1035                         else
1036                                 message = _("One word in document.");
1037                 }
1038
1039                 Alert::information(_("Count words"), message);
1040         }
1041                 break;
1042
1043         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1044                 // turn compression on/off
1045                 buffer_->params().compressed = !buffer_->params().compressed;
1046                 break;
1047
1048         case LFUN_NEXT_INSET_TOGGLE: {
1049                 // this is the real function we want to invoke
1050                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1051                 // if there is an inset at cursor, see whether it
1052                 // wants to toggle.
1053                 Inset * inset = cur.nextInset();
1054                 if (inset && inset->isActive()) {
1055                         Cursor tmpcur = cur;
1056                         tmpcur.pushLeft(*inset);
1057                         inset->dispatch(tmpcur, tmpcmd);
1058                         if (tmpcur.result().dispatched()) {
1059                                 cur.dispatched();
1060                         }
1061                 }
1062                 // if it did not work, try the underlying inset.
1063                 if (!cur.result().dispatched())
1064                         cur.dispatch(tmpcmd);
1065
1066                 if (cur.result().dispatched())
1067                         cur.clearSelection();
1068
1069                 break;
1070         }
1071
1072         default:
1073                 updateFlags = Update::None;
1074         }
1075
1076         return updateFlags;
1077 }
1078
1079
1080 docstring const BufferView::requestSelection()
1081 {
1082         if (!buffer_)
1083                 return docstring();
1084
1085         Cursor & cur = cursor_;
1086
1087         if (!cur.selection()) {
1088                 xsel_cache_.set = false;
1089                 return docstring();
1090         }
1091
1092         if (!xsel_cache_.set ||
1093             cur.top() != xsel_cache_.cursor ||
1094             cur.anchor_.top() != xsel_cache_.anchor)
1095         {
1096                 xsel_cache_.cursor = cur.top();
1097                 xsel_cache_.anchor = cur.anchor_.top();
1098                 xsel_cache_.set = cur.selection();
1099                 return cur.selectionAsString(false);
1100         }
1101         return docstring();
1102 }
1103
1104
1105 void BufferView::clearSelection()
1106 {
1107         if (buffer_) {
1108                 cursor_.clearSelection();
1109                 // Clear the selection buffer. Otherwise a subsequent
1110                 // middle-mouse-button paste would use the selection buffer,
1111                 // not the more current external selection.
1112                 cap::clearSelection();
1113                 xsel_cache_.set = false;
1114                 // The buffer did not really change, but this causes the
1115                 // redraw we need because we cleared the selection above.
1116                 buffer_->changed();
1117         }
1118 }
1119
1120
1121 void BufferView::workAreaResize(int width, int height)
1122 {
1123         // Update from work area
1124         width_ = width;
1125         height_ = height;
1126
1127         // The complete text metrics will be redone.
1128         text_metrics_.clear();
1129
1130         if (buffer_)
1131                 resize();
1132 }
1133
1134
1135 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1136 {
1137         pit_type pit = text.getPitNearY(*this, y);
1138         BOOST_ASSERT(pit != -1);
1139         Paragraph const & par = text.getPar(pit);
1140
1141         LYXERR(Debug::DEBUG)
1142                 << BOOST_CURRENT_FUNCTION
1143                 << ": x: " << x
1144                 << " y: " << y
1145                 << "  pit: " << pit
1146                 << endl;
1147         InsetList::const_iterator iit = par.insetlist.begin();
1148         InsetList::const_iterator iend = par.insetlist.end();
1149         for (; iit != iend; ++iit) {
1150                 Inset * const inset = iit->inset;
1151                 if (inset->covers(*this, x, y)) {
1152                         if (!inset->descendable())
1153                                 // No need to go further down if the inset is not
1154                                 // descendable.
1155                                 return inset;
1156
1157                         size_t cell_number = inset->nargs();
1158                         // Check all the inner cell.
1159                         for (size_t i = 0; i != cell_number; ++i) {
1160                                 Text const * inner_text = inset->getText(i);
1161                                 if (inner_text) {
1162                                         // Try deeper.
1163                                         Inset const * inset_deeper =
1164                                                 getCoveringInset(*inner_text, x, y);
1165                                         if (inset_deeper)
1166                                                 return inset_deeper;
1167                                 }
1168                         }
1169
1170                         LYXERR(Debug::DEBUG)
1171                                 << BOOST_CURRENT_FUNCTION
1172                                 << ": Hit inset: " << inset << endl;
1173                         return inset;
1174                 }
1175         }
1176         LYXERR(Debug::DEBUG)
1177                 << BOOST_CURRENT_FUNCTION
1178                 << ": No inset hit. " << endl;
1179         return 0;
1180 }
1181
1182
1183 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1184 {
1185         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1186
1187         // This is only called for mouse related events including
1188         // LFUN_FILE_OPEN generated by drag-and-drop.
1189         FuncRequest cmd = cmd0;
1190
1191         // E.g. Qt mouse press when no buffer
1192         if (!buffer_)
1193                 return false;
1194
1195         Cursor cur(*this);
1196         cur.push(buffer_->inset());
1197         cur.selection() = cursor_.selection();
1198
1199         // Either the inset under the cursor or the
1200         // surrounding Text will handle this event.
1201
1202         // make sure we stay within the screen...
1203         cmd.y = min(max(cmd.y, -1), height_);
1204
1205         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1206
1207                 // Get inset under mouse, if there is one.
1208                 Inset const * covering_inset =
1209                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1210                 if (covering_inset == last_inset_)
1211                         // Same inset, no need to do anything...
1212                         return false;
1213
1214                 bool need_redraw = false;
1215                 // const_cast because of setMouseHover().
1216                 Inset * inset = const_cast<Inset *>(covering_inset);
1217                 if (last_inset_)
1218                         // Remove the hint on the last hovered inset (if any).
1219                         need_redraw |= last_inset_->setMouseHover(false);
1220                 if (inset)
1221                         // Highlighted the newly hovered inset (if any).
1222                         need_redraw |= inset->setMouseHover(true);
1223                 last_inset_ = inset;
1224
1225                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1226                 // not expose the button for redraw. We adjust here the metrics dimension
1227                 // to enable a full redraw.
1228                 // FIXME: It is possible to redraw only the area around the button!
1229                 if (need_redraw
1230                         && metrics_info_.update_strategy == SingleParUpdate) {
1231                         // FIXME: It should be possible to redraw only the area around
1232                         // the button by doing this:
1233                         //
1234                         //metrics_info_.singlepar = false;
1235                         //metrics_info_.y1 = ymin of button;
1236                         //metrics_info_.y2 = ymax of button;
1237                         //
1238                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1239                         // between background updates and text updates. So we use the hammer
1240                         // solution for now. We could also avoid the updateMetrics() below
1241                         // by using the first and last pit of the CoordCache. Have a look
1242                         // at Text::getPitNearY() to see what I mean.
1243                         //
1244                         //metrics_info_.pit1 = first pit of CoordCache;
1245                         //metrics_info_.pit2 = last pit of CoordCache;
1246                         //metrics_info_.singlepar = false;
1247                         //metrics_info_.y1 = 0;
1248                         //metrics_info_.y2 = height_;
1249                         //
1250                         updateMetrics(false);
1251                 }
1252
1253                 // This event (moving without mouse click) is not passed further.
1254                 // This should be changed if it is further utilized.
1255                 return need_redraw;
1256         }
1257
1258         // Build temporary cursor.
1259         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1260
1261         // Put anchor at the same position.
1262         cur.resetAnchor();
1263
1264         // Try to dispatch to an non-editable inset near this position
1265         // via the temp cursor. If the inset wishes to change the real
1266         // cursor it has to do so explicitly by using
1267         //  cur.bv().cursor() = cur;  (or similar)
1268         if (inset) {
1269                 inset->dispatch(cur, cmd);
1270         }
1271
1272         // Now dispatch to the temporary cursor. If the real cursor should
1273         // be modified, the inset's dispatch has to do so explicitly.
1274         if (!cur.result().dispatched())
1275                 cur.dispatch(cmd);
1276
1277         // Redraw if requested and necessary.
1278         if (cur.result().dispatched() && cur.result().update())
1279                 return update(cur.result().update());
1280
1281         return false;
1282 }
1283
1284
1285 void BufferView::scroll(int /*lines*/)
1286 {
1287 //      if (!buffer_)
1288 //              return;
1289 //
1290 //      Text const * t = &buffer_->text();
1291 //      int const line_height = defaultRowHeight();
1292 //
1293 //      // The new absolute coordinate
1294 //      int new_top_y = top_y() + lines * line_height;
1295 //
1296 //      // Restrict to a valid value
1297 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1298 //      new_top_y = std::max(0, new_top_y);
1299 //
1300 //      scrollDocView(new_top_y);
1301 //
1302 }
1303
1304
1305 void BufferView::setCursorFromRow(int row)
1306 {
1307         int tmpid = -1;
1308         int tmppos = -1;
1309
1310         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1311
1312         if (tmpid == -1)
1313                 buffer_->text().setCursor(cursor_, 0, 0);
1314         else
1315                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1316 }
1317
1318
1319 void BufferView::gotoLabel(docstring const & label)
1320 {
1321         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1322                 vector<docstring> labels;
1323                 it->getLabelList(*buffer_, labels);
1324                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1325                         setCursor(it);
1326                         update();
1327                         return;
1328                 }
1329         }
1330 }
1331
1332
1333 TextMetrics const & BufferView::textMetrics(Text const * t) const
1334 {
1335         return const_cast<BufferView *>(this)->textMetrics(t);
1336 }
1337
1338
1339 TextMetrics & BufferView::textMetrics(Text const * t)
1340 {
1341         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1342         if (tmc_it == text_metrics_.end()) {
1343                 tmc_it = text_metrics_.insert(
1344                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1345         }
1346         return tmc_it->second;
1347 }
1348
1349
1350 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1351                 pit_type pit) const
1352 {
1353         return textMetrics(t).parMetrics(pit);
1354 }
1355
1356
1357 int BufferView::workHeight() const
1358 {
1359         return height_;
1360 }
1361
1362
1363 void BufferView::setCursor(DocIterator const & dit)
1364 {
1365         size_t const n = dit.depth();
1366         for (size_t i = 0; i < n; ++i)
1367                 dit[i].inset().edit(cursor_, true);
1368
1369         cursor_.setCursor(dit);
1370         cursor_.selection() = false;
1371 }
1372
1373
1374 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1375 {
1376         // Would be wrong to delete anything if we have a selection.
1377         if (cur.selection())
1378                 return false;
1379
1380         bool need_anchor_change = false;
1381         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1382                 need_anchor_change);
1383
1384         if (need_anchor_change)
1385                 cur.resetAnchor();
1386
1387         if (!changed)
1388                 return false;
1389
1390         updateLabels(*buffer_);
1391
1392         updateMetrics(false);
1393         buffer_->changed();
1394         return true;
1395 }
1396
1397
1398 bool BufferView::mouseSetCursor(Cursor & cur)
1399 {
1400         BOOST_ASSERT(&cur.bv() == this);
1401
1402         // Has the cursor just left the inset?
1403         bool badcursor = false;
1404         bool leftinset = (&cursor_.inset() != &cur.inset());
1405         if (leftinset)
1406                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1407
1408         // do the dEPM magic if needed
1409         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1410         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1411         // the leftinset bool would not be necessary (badcursor instead).
1412         bool update = leftinset;
1413         if (!badcursor && cursor_.inTexted())
1414                 update |= checkDepm(cur, cursor_);
1415
1416         // if the cursor was in an empty script inset and the new
1417         // position is in the nucleus of the inset, notifyCursorLeaves
1418         // will kill the script inset itself. So we check all the
1419         // elements of the cursor to make sure that they are correct.
1420         // For an example, see bug 2933:
1421         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1422         // The code below could maybe be moved to a DocIterator method.
1423         //lyxerr << "cur before " << cur <<std::endl;
1424         DocIterator dit(cur.inset());
1425         dit.push_back(cur.bottom());
1426         size_t i = 1;
1427         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1428                 dit.push_back(cur[i]);
1429                 ++i;
1430         }
1431         //lyxerr << "5 cur after" << dit <<std::endl;
1432
1433         cursor_.setCursor(dit);
1434         cursor_.boundary(cur.boundary());
1435         cursor_.clearSelection();
1436         finishUndo();
1437         return update;
1438 }
1439
1440
1441 void BufferView::putSelectionAt(DocIterator const & cur,
1442                                 int length, bool backwards)
1443 {
1444         cursor_.clearSelection();
1445
1446         setCursor(cur);
1447
1448         if (length) {
1449                 if (backwards) {
1450                         cursor_.pos() += length;
1451                         cursor_.setSelection(cursor_, -length);
1452                 } else
1453                         cursor_.setSelection(cursor_, length);
1454                 cap::saveSelection(cursor_);
1455         }
1456 }
1457
1458
1459 Cursor & BufferView::cursor()
1460 {
1461         return cursor_;
1462 }
1463
1464
1465 Cursor const & BufferView::cursor() const
1466 {
1467         return cursor_;
1468 }
1469
1470
1471 pit_type BufferView::anchor_ref() const
1472 {
1473         return anchor_ref_;
1474 }
1475
1476
1477 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1478 {
1479         return metrics_info_;
1480 }
1481
1482
1483 // FIXME: We should split-up updateMetrics() for the singlepar case.
1484 void BufferView::updateMetrics(bool singlepar)
1485 {
1486         Text & buftext = buffer_->text();
1487         TextMetrics & tm = textMetrics(&buftext);
1488         pit_type size = int(buftext.paragraphs().size());
1489
1490         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1491                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1492                 offset_ref_ = 0;
1493         }
1494
1495         // If the paragraph metrics has changed, we can not
1496         // use the singlepar optimisation.
1497         if (singlepar
1498                 // In Single Paragraph mode, rebreak only
1499                 // the (main text, not inset!) paragraph containing the cursor.
1500                 // (if this paragraph contains insets etc., rebreaking will
1501                 // recursively descend)
1502                 && tm.redoParagraph(cursor_.bottom().pit()))
1503                 singlepar = false;
1504
1505         pit_type const pit = anchor_ref_;
1506         int pit1 = pit;
1507         int pit2 = pit;
1508         size_t const npit = buftext.paragraphs().size();
1509
1510         // Rebreak anchor paragraph.
1511         if (!singlepar)
1512                 tm.redoParagraph(pit);
1513
1514         // Clear out the position cache in case of full screen redraw.
1515         if (!singlepar)
1516                 coord_cache_.clear();
1517
1518         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1519
1520         // Redo paragraphs above anchor if necessary.
1521         int y1 = y0;
1522         while (y1 > 0 && pit1 > 0) {
1523                 y1 -= tm.parMetrics(pit1).ascent();
1524                 --pit1;
1525                 if (!singlepar)
1526                         tm.redoParagraph(pit1);
1527                 y1 -= tm.parMetrics(pit1).descent();
1528         }
1529
1530
1531         // Take care of ascent of first line
1532         y1 -= tm.parMetrics(pit1).ascent();
1533
1534         // Normalize anchor for next time
1535         anchor_ref_ = pit1;
1536         offset_ref_ = -y1;
1537
1538         // Grey at the beginning is ugly
1539         if (pit1 == 0 && y1 > 0) {
1540                 y0 -= y1;
1541                 y1 = 0;
1542                 anchor_ref_ = 0;
1543         }
1544
1545         // Redo paragraphs below the anchor if necessary.
1546         int y2 = y0;
1547         while (y2 < height_ && pit2 < int(npit) - 1) {
1548                 y2 += tm.parMetrics(pit2).descent();
1549                 ++pit2;
1550                 if (!singlepar)
1551                         tm.redoParagraph(pit2);
1552                 y2 += tm.parMetrics(pit2).ascent();
1553         }
1554
1555         // Take care of descent of last line
1556         y2 += tm.parMetrics(pit2).descent();
1557
1558         // The coordinates of all these paragraphs are correct, cache them
1559         int y = y1;
1560         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1561         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1562                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1563                 y += pm.ascent();
1564                 parPos[pit] = Point(0, y);
1565                 if (singlepar && pit == cursor_.bottom().pit()) {
1566                         // In Single Paragraph mode, collect here the
1567                         // y1 and y2 of the (one) paragraph the cursor is in
1568                         y1 = y - pm.ascent();
1569                         y2 = y + pm.descent();
1570                 }
1571                 y += pm.descent();
1572         }
1573
1574         if (singlepar) {
1575                 // collect cursor paragraph iter bounds
1576                 pit1 = cursor_.bottom().pit();
1577                 pit2 = cursor_.bottom().pit();
1578         }
1579
1580         LYXERR(Debug::DEBUG)
1581                 << BOOST_CURRENT_FUNCTION
1582                 << " y1: " << y1
1583                 << " y2: " << y2
1584                 << " pit1: " << pit1
1585                 << " pit2: " << pit2
1586                 << " npit: " << npit
1587                 << " singlepar: " << singlepar
1588                 << "size: " << size
1589                 << endl;
1590
1591         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1592                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1593
1594         if (lyxerr.debugging(Debug::WORKAREA)) {
1595                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1596                 coord_cache_.dump();
1597         }
1598 }
1599
1600
1601 void BufferView::menuInsertLyXFile(string const & filenm)
1602 {
1603         BOOST_ASSERT(cursor_.inTexted());
1604         string filename = filenm;
1605
1606         if (filename.empty()) {
1607                 // Launch a file browser
1608                 // FIXME UNICODE
1609                 string initpath = lyxrc.document_path;
1610
1611                 if (buffer_) {
1612                         string const trypath = buffer_->filePath();
1613                         // If directory is writeable, use this as default.
1614                         if (isDirWriteable(FileName(trypath)))
1615                                 initpath = trypath;
1616                 }
1617
1618                 // FIXME UNICODE
1619                 FileDialog fileDlg(_("Select LyX document to insert"),
1620                         LFUN_FILE_INSERT,
1621                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1622                         make_pair(_("Examples|#E#e"),
1623                                     from_utf8(addPath(package().system_support().absFilename(),
1624                                     "examples"))));
1625
1626                 FileDialog::Result result =
1627                         fileDlg.open(from_utf8(initpath),
1628                                      FileFilterList(_("LyX Documents (*.lyx)")),
1629                                      docstring());
1630
1631                 if (result.first == FileDialog::Later)
1632                         return;
1633
1634                 // FIXME UNICODE
1635                 filename = to_utf8(result.second);
1636
1637                 // check selected filename
1638                 if (filename.empty()) {
1639                         // emit message signal.
1640                         message(_("Canceled."));
1641                         return;
1642                 }
1643         }
1644
1645         // Get absolute path of file and add ".lyx"
1646         // to the filename if necessary
1647         filename = fileSearch(string(), filename, "lyx").absFilename();
1648
1649         docstring const disp_fn = makeDisplayPath(filename);
1650         // emit message signal.
1651         message(bformat(_("Inserting document %1$s..."), disp_fn));
1652
1653         docstring res;
1654         Buffer buf("", false);
1655         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1656                 ErrorList & el = buffer_->errorList("Parse");
1657                 // Copy the inserted document error list into the current buffer one.
1658                 el = buf.errorList("Parse");
1659                 recordUndo(cursor_);
1660                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1661                                              buf.params().textclass, el);
1662                 res = _("Document %1$s inserted.");
1663         } else
1664                 res = _("Could not insert document %1$s");
1665
1666         // emit message signal.
1667         message(bformat(res, disp_fn));
1668         buffer_->errors("Parse");
1669         resize();
1670 }
1671
1672 } // namespace lyx