3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.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"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Selection.h"
68 #include "graphics/Previews.h"
70 #include "support/convert.h"
71 #include "support/FileFilterList.h"
72 #include "support/filetools.h"
73 #include "support/Package.h"
74 #include "support/types.h"
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
84 using std::istringstream;
88 using std::mem_fun_ref;
95 using support::addPath;
96 using support::bformat;
97 using support::FileFilterList;
98 using support::FileName;
99 using support::fileSearch;
100 using support::isDirWriteable;
101 using support::isFileReadable;
102 using support::makeDisplayPath;
103 using support::package;
105 namespace Alert = frontend::Alert;
109 /// Return an inset of this class if it exists at the current cursor position
111 T * getInsetByCode(Cursor & cur, Inset::Code code)
114 DocIterator it = cur;
115 if (it.nextInset() &&
116 it.nextInset()->lyxCode() == code) {
117 inset = static_cast<T*>(it.nextInset());
125 BufferView::BufferView()
126 : width_(0), height_(0), buffer_(0), wh_(0),
128 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129 intl_(new Intl), last_inset_(0)
131 xsel_cache_.set = false;
132 intl_->initKeyMapper(lyxrc.use_kbmap);
136 BufferView::~BufferView()
141 Buffer * BufferView::buffer() const
147 Buffer * BufferView::setBuffer(Buffer * b)
149 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
150 << "[ b = " << b << "]" << endl;
153 // Save the current selection if any
154 cap::saveSelection(cursor_);
155 // Save the actual cursor position and anchor inside the
156 // buffer so that it can be restored in case we rechange
157 // to this buffer later on.
158 buffer_->saveCursor(cursor_.selectionBegin(),
159 cursor_.selectionEnd());
160 // update bookmark pit of the current buffer before switch
161 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
162 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
163 if (buffer()->fileName() != bm.filename.absFilename())
165 // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
166 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
170 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
171 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
172 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
174 // current buffer is going to be switched-off, save cursor pos
175 // Ideally, the whole cursor stack should be saved, but session
176 // currently can only handle bottom (whole document) level pit and pos.
177 // That is to say, if a cursor is in a nested inset, it will be
178 // restore to the left of the top level inset.
179 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
180 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
183 // If we're quitting lyx, don't bother updating stuff
189 //FIXME Fix for bug 3440 is here.
190 // If we are closing current buffer, switch to the first in
193 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
194 << " No Buffer!" << endl;
195 // We are closing the buffer, use the first buffer as current
197 // if (last_buffer_) buffer_ = last_buffer_;
198 // also check that this is in theBufferList()?
199 buffer_ = theBufferList().first();
202 // last_buffer = buffer_;
203 // Set current buffer
208 cursor_ = Cursor(*this);
215 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
216 << "Buffer addr: " << buffer_ << endl;
217 cursor_.push(buffer_->inset());
218 cursor_.resetAnchor();
219 buffer_->text().setCurrentFont(cursor_);
221 // Update the metrics now that we have a proper Cursor.
222 updateMetrics(false);
224 // FIXME: This code won't be needed once we switch to
225 // "one Buffer" / "one BufferView".
226 if (buffer_->getCursor().size() > 0 &&
227 buffer_->getAnchor().size() > 0)
229 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
230 cursor_.resetAnchor();
231 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
232 cursor_.setSelection();
233 // do not set selection to the new buffer because we
234 // only paste recent selection.
236 // Make sure that the restored cursor is not broken. This can happen for
237 // example if this Buffer has been modified by another view.
238 cursor_.fixIfBroken();
241 // Update the metrics if the cursor new position was off screen.
242 updateMetrics(false);
245 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
246 graphics::Previews::get().generateBufferPreviews(*buffer_);
251 void BufferView::resize()
256 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
258 updateMetrics(false);
262 bool BufferView::fitCursor()
264 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
265 frontend::FontMetrics const & fm =
266 theFontMetrics(cursor_.getFont());
267 int const asc = fm.maxAscent();
268 int const des = fm.maxDescent();
269 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
270 if (p.y_ - asc >= 0 && p.y_ + des < height_)
278 bool BufferView::multiParSel()
280 if (!cursor_.selection())
282 bool ret = multiparsel_cache_;
283 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
284 // Either this, or previous selection spans paragraphs
285 return ret || multiparsel_cache_;
289 bool BufferView::update(Update::flags flags)
291 // last_inset_ points to the last visited inset. This pointer may become
292 // invalid because of keyboard editing. Since all such operations
293 // causes screen update(), I reset last_inset_ to avoid such a problem.
295 // This is close to a hot-path.
297 << BOOST_CURRENT_FUNCTION
298 << "[fitcursor = " << (flags & Update::FitCursor)
299 << ", forceupdate = " << (flags & Update::Force)
300 << ", singlepar = " << (flags & Update::SinglePar)
301 << "] buffer: " << buffer_ << endl;
303 // Check needed to survive LyX startup
307 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
309 // Update macro store
310 if (!(cursor().inMathed() && cursor().inMacroMode()))
311 buffer_->buildMacros();
313 // Now do the first drawing step if needed. This consists on updating
314 // the CoordCache in updateMetrics().
315 // The second drawing step is done in WorkArea::redraw() if needed.
317 // Case when no explicit update is requested.
319 // no need to redraw anything.
320 metrics_info_.update_strategy = NoScreenUpdate;
324 if (flags == Update::Decoration) {
325 metrics_info_.update_strategy = DecorationUpdate;
329 if (flags == Update::FitCursor
330 || flags == (Update::Decoration | Update::FitCursor)) {
331 bool const fit_cursor = fitCursor();
332 // tell the frontend to update the screen if needed.
334 updateMetrics(false);
337 if (flags & Update::Decoration) {
338 metrics_info_.update_strategy = DecorationUpdate;
341 // no screen update is needed.
342 metrics_info_.update_strategy = NoScreenUpdate;
346 bool full_metrics = flags & Update::Force;
347 if (flags & Update::MultiParSel)
348 full_metrics |= multiParSel();
350 bool const single_par = !full_metrics;
351 updateMetrics(single_par);
353 if (flags & Update::FitCursor && fitCursor())
354 updateMetrics(false);
356 // tell the frontend to update the screen.
361 void BufferView::updateScrollbar()
364 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
365 << " no text in updateScrollbar" << endl;
366 scrollbarParameters_.reset();
370 Text & t = buffer_->text();
371 TextMetrics & tm = text_metrics_[&t];
373 int const parsize = int(t.paragraphs().size() - 1);
374 if (anchor_ref_ > parsize) {
375 anchor_ref_ = parsize;
380 << BOOST_CURRENT_FUNCTION
381 << " Updating scrollbar: height: " << t.paragraphs().size()
382 << " curr par: " << cursor_.bottom().pit()
383 << " default height " << defaultRowHeight() << endl;
385 // It would be better to fix the scrollbar to understand
386 // values in [0..1] and divide everything by wh
388 // estimated average paragraph height:
392 int h = tm.parMetrics(anchor_ref_).height();
394 // Normalize anchor/offset (MV):
395 while (offset_ref_ > h && anchor_ref_ < parsize) {
398 h = tm.parMetrics(anchor_ref_).height();
400 // Look at paragraph heights on-screen
403 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
406 int const h2 = tm.parMetrics(pit).height();
412 int const hav = sumh / nh;
413 // More realistic average paragraph height
418 scrollbarParameters_.height = (parsize + 1) * wh_;
419 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
420 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
424 ScrollbarParameters const & BufferView::scrollbarParameters() const
426 return scrollbarParameters_;
430 void BufferView::scrollDocView(int value)
432 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
433 << "[ value = " << value << "]" << endl;
438 Text & t = buffer_->text();
439 TextMetrics & tm = text_metrics_[&t];
441 float const bar = value / float(wh_ * t.paragraphs().size());
443 anchor_ref_ = int(bar * t.paragraphs().size());
444 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
445 anchor_ref_ = int(t.paragraphs().size()) - 1;
447 tm.redoParagraph(anchor_ref_);
448 int const h = tm.parMetrics(anchor_ref_).height();
449 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
450 updateMetrics(false);
454 void BufferView::setCursorFromScrollbar()
459 Text & t = buffer_->text();
461 int const height = 2 * defaultRowHeight();
462 int const first = height;
463 int const last = height_ - height;
464 Cursor & cur = cursor_;
466 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
469 case bv_funcs::CUR_ABOVE:
470 // We reset the cursor because bv_funcs::status() does not
471 // work when the cursor is within mathed.
472 cur.reset(buffer_->inset());
473 t.setCursorFromCoordinates(cur, 0, first);
474 cur.clearSelection();
476 case bv_funcs::CUR_BELOW:
477 // We reset the cursor because bv_funcs::status() does not
478 // work when the cursor is within mathed.
479 cur.reset(buffer_->inset());
480 t.setCursorFromCoordinates(cur, 0, last);
481 cur.clearSelection();
483 case bv_funcs::CUR_INSIDE:
484 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
485 int const newy = min(last, max(y, first));
487 cur.reset(buffer_->inset());
488 t.setCursorFromCoordinates(cur, 0, newy);
494 Change const BufferView::getCurrentChange() const
496 if (!cursor_.selection())
497 return Change(Change::UNCHANGED);
499 DocIterator dit = cursor_.selectionBegin();
500 return dit.paragraph().lookupChange(dit.pos());
504 void BufferView::saveBookmark(unsigned int idx)
506 // tenatively save bookmark, id and pos will be used to
507 // acturately locate a bookmark in a 'live' lyx session.
508 // pit and pos will be updated with bottom level pit/pos
510 LyX::ref().session().bookmarks().save(
511 FileName(buffer_->fileName()),
512 cursor_.bottom().pit(),
513 cursor_.bottom().pos(),
514 cursor_.paragraph().id(),
519 // emit message signal.
520 message(_("Save bookmark"));
524 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
525 int top_id, pos_type top_pos)
527 cursor_.clearSelection();
529 // if a valid par_id is given, try it first
530 // This is the case for a 'live' bookmark when unique paragraph ID
531 // is used to track bookmarks.
533 ParIterator par = buffer_->getParFromID(top_id);
534 if (par != buffer_->par_iterator_end()) {
535 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
536 // Some slices of the iterator may not be
537 // reachable (e.g. closed collapsable inset)
538 // so the dociterator may need to be
539 // shortened. Otherwise, setCursor may crash
540 // lyx when the cursor can not be set to these
542 size_t const n = dit.depth();
543 for (size_t i = 0; i < n; ++i)
544 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
549 // Note: return bottom (document) level pit.
550 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
553 // if top_id == 0, or searching through top_id failed
554 // This is the case for a 'restored' bookmark when only bottom
555 // (document level) pit was saved. Because of this, bookmark
556 // restoration is inaccurate. If a bookmark was within an inset,
557 // it will be restored to the left of the outmost inset that contains
559 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
560 DocIterator it = doc_iterator_begin(buffer_->inset());
561 it.pit() = bottom_pit;
562 it.pos() = min(bottom_pos, it.paragraph().size());
564 return boost::make_tuple(it.pit(), it.pos(),
565 it.paragraph().id());
568 return boost::make_tuple(pit_type(0), pos_type(0), 0);
572 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
574 if (lyxrc.rtl_support) {
575 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
576 if (intl_->keymap == Intl::PRIMARY)
579 if (intl_->keymap == Intl::SECONDARY)
584 intl_->getTransManager().translateAndInsert(c, t, cur);
588 int BufferView::workWidth() const
594 void BufferView::center()
596 CursorSlice & bot = cursor_.bottom();
597 TextMetrics & tm = text_metrics_[bot.text()];
598 pit_type const pit = bot.pit();
599 tm.redoParagraph(pit);
600 ParagraphMetrics const & pm = tm.parMetrics(pit);
602 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
603 + pm.ascent() - height_ / 2;
607 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
611 Cursor & cur = cursor_;
613 switch (cmd.action) {
616 flag.enabled(!buffer_->undostack().empty());
619 flag.enabled(!buffer_->redostack().empty());
621 case LFUN_FILE_INSERT:
622 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
623 case LFUN_FILE_INSERT_PLAINTEXT:
624 case LFUN_BOOKMARK_SAVE:
625 // FIXME: Actually, these LFUNS should be moved to Text
626 flag.enabled(cur.inTexted());
628 case LFUN_FONT_STATE:
629 case LFUN_LABEL_INSERT:
630 case LFUN_PARAGRAPH_GOTO:
631 // FIXME handle non-trivially
632 case LFUN_OUTLINE_UP:
633 case LFUN_OUTLINE_DOWN:
634 case LFUN_OUTLINE_IN:
635 case LFUN_OUTLINE_OUT:
637 case LFUN_REFERENCE_NEXT:
639 case LFUN_WORD_REPLACE:
642 case LFUN_MARK_TOGGLE:
643 case LFUN_SCREEN_RECENTER:
644 case LFUN_BIBTEX_DATABASE_ADD:
645 case LFUN_BIBTEX_DATABASE_DEL:
646 case LFUN_WORDS_COUNT:
647 case LFUN_NEXT_INSET_TOGGLE:
651 case LFUN_LABEL_GOTO: {
652 flag.enabled(!cmd.argument().empty()
653 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
657 case LFUN_CHANGES_TRACK:
659 flag.setOnOff(buffer_->params().trackChanges);
662 case LFUN_CHANGES_OUTPUT:
663 flag.enabled(buffer_);
664 flag.setOnOff(buffer_->params().outputChanges);
667 case LFUN_CHANGES_MERGE:
668 case LFUN_CHANGE_NEXT:
669 case LFUN_ALL_CHANGES_ACCEPT:
670 case LFUN_ALL_CHANGES_REJECT:
671 // TODO: context-sensitive enabling of LFUNs
672 // In principle, these command should only be enabled if there
673 // is a change in the document. However, without proper
674 // optimizations, this will inevitably result in poor performance.
675 flag.enabled(buffer_);
678 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
679 flag.setOnOff(buffer_->params().compressed);
691 Update::flags BufferView::dispatch(FuncRequest const & cmd)
693 //lyxerr << BOOST_CURRENT_FUNCTION
694 // << [ cmd = " << cmd << "]" << endl;
696 // Make sure that the cached BufferView is correct.
697 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
698 << " action[" << cmd.action << ']'
699 << " arg[" << to_utf8(cmd.argument()) << ']'
700 << " x[" << cmd.x << ']'
701 << " y[" << cmd.y << ']'
702 << " button[" << cmd.button() << ']'
705 // FIXME: this should not be possible.
709 Cursor & cur = cursor_;
710 // Default Update flags.
711 Update::flags updateFlags = Update::Force | Update::FitCursor;
713 switch (cmd.action) {
716 cur.message(_("Undo"));
717 cur.clearSelection();
718 if (!textUndo(*this)) {
719 cur.message(_("No further undo information"));
720 updateFlags = Update::None;
725 cur.message(_("Redo"));
726 cur.clearSelection();
727 if (!textRedo(*this)) {
728 cur.message(_("No further redo information"));
729 updateFlags = Update::None;
733 case LFUN_FILE_INSERT:
735 menuInsertLyXFile(to_utf8(cmd.argument()));
738 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
740 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
743 case LFUN_FILE_INSERT_PLAINTEXT:
745 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
748 case LFUN_FONT_STATE:
749 cur.message(cur.currentState());
752 case LFUN_BOOKMARK_SAVE:
753 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
756 case LFUN_LABEL_GOTO: {
757 docstring label = cmd.argument();
760 getInsetByCode<InsetRef>(cursor_,
763 label = inset->getParam("reference");
764 // persistent=false: use temp_bookmark
774 case LFUN_PARAGRAPH_GOTO: {
775 int const id = convert<int>(to_utf8(cmd.argument()));
777 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
778 ParIterator par = b->getParFromID(id);
779 if (par == b->par_iterator_end()) {
781 << "No matching paragraph found! ["
782 << id << "]." << endl;
785 << "Paragraph " << par->id()
786 << " found in buffer `"
787 << b->fileName() << "'." << endl;
791 setCursor(makeDocIterator(par, 0));
793 // Switch to other buffer view and resend cmd
794 theLyXFunc().dispatch(FuncRequest(
795 LFUN_BUFFER_SWITCH, b->fileName()));
796 theLyXFunc().dispatch(cmd);
797 updateFlags = Update::None;
806 case LFUN_OUTLINE_UP:
807 toc::outline(toc::Up, cursor_);
808 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
809 updateLabels(*buffer_);
811 case LFUN_OUTLINE_DOWN:
812 toc::outline(toc::Down, cursor_);
813 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
814 updateLabels(*buffer_);
816 case LFUN_OUTLINE_IN:
817 toc::outline(toc::In, cursor_);
818 updateLabels(*buffer_);
820 case LFUN_OUTLINE_OUT:
821 toc::outline(toc::Out, cursor_);
822 updateLabels(*buffer_);
826 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
829 case LFUN_REFERENCE_NEXT: {
830 vector<Inset_code> tmp;
831 tmp.push_back(Inset::LABEL_CODE);
832 tmp.push_back(Inset::REF_CODE);
833 bv_funcs::gotoInset(this, tmp, true);
837 case LFUN_CHANGES_TRACK:
838 buffer_->params().trackChanges = !buffer_->params().trackChanges;
841 case LFUN_CHANGES_OUTPUT:
842 buffer_->params().outputChanges = !buffer_->params().outputChanges;
843 if (buffer_->params().outputChanges) {
844 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
845 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
846 LaTeXFeatures::isAvailable("xcolor");
848 if (!dvipost && !xcolorsoul) {
849 Alert::warning(_("Changes not shown in LaTeX output"),
850 _("Changes will not be highlighted in LaTeX output, "
851 "because neither dvipost nor xcolor/soul are installed.\n"
852 "Please install these packages or redefine "
853 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
854 } else if (!xcolorsoul) {
855 Alert::warning(_("Changes not shown in LaTeX output"),
856 _("Changes will not be highlighted in LaTeX output "
857 "when using pdflatex, because xcolor and soul are not installed.\n"
858 "Please install both packages or redefine "
859 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
864 case LFUN_CHANGE_NEXT:
865 findNextChange(this);
868 case LFUN_CHANGES_MERGE:
869 if (findNextChange(this))
870 showDialog("changes");
873 case LFUN_ALL_CHANGES_ACCEPT:
874 // select complete document
875 cursor_.reset(buffer_->inset());
876 cursor_.selHandle(true);
877 buffer_->text().cursorBottom(cursor_);
878 // accept everything in a single step to support atomic undo
879 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
882 case LFUN_ALL_CHANGES_REJECT:
883 // select complete document
884 cursor_.reset(buffer_->inset());
885 cursor_.selHandle(true);
886 buffer_->text().cursorBottom(cursor_);
887 // reject everything in a single step to support atomic undo
888 // Note: reject does not work recursively; the user may have to repeat the operation
889 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
896 case LFUN_WORD_REPLACE: {
897 bool has_deleted = false;
898 if (cur.selection()) {
899 DocIterator beg = cur.selectionBegin();
900 DocIterator end = cur.selectionEnd();
901 if (beg.pit() == end.pit()) {
902 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
903 if (cur.paragraph().isDeleted(p))
908 replace(this, cmd, has_deleted);
913 cur.clearSelection();
915 cur.message(from_utf8(N_("Mark off")));
919 cur.clearSelection();
922 cur.message(from_utf8(N_("Mark on")));
925 case LFUN_MARK_TOGGLE:
926 cur.clearSelection();
929 cur.message(from_utf8(N_("Mark removed")));
932 cur.message(from_utf8(N_("Mark set")));
937 case LFUN_SCREEN_RECENTER:
941 case LFUN_BIBTEX_DATABASE_ADD: {
942 Cursor tmpcur = cursor_;
943 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
944 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
947 if (inset->addDatabase(to_utf8(cmd.argument())))
948 buffer_->updateBibfilesCache();
953 case LFUN_BIBTEX_DATABASE_DEL: {
954 Cursor tmpcur = cursor_;
955 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
956 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
959 if (inset->delDatabase(to_utf8(cmd.argument())))
960 buffer_->updateBibfilesCache();
965 case LFUN_WORDS_COUNT: {
966 DocIterator from, to;
967 if (cur.selection()) {
968 from = cur.selectionBegin();
969 to = cur.selectionEnd();
971 from = doc_iterator_begin(buffer_->inset());
972 to = doc_iterator_end(buffer_->inset());
974 int const count = countWords(from, to);
978 message = bformat(_("%1$d words in selection."),
981 message = bformat(_("%1$d words in document."),
986 message = _("One word in selection.");
988 message = _("One word in document.");
991 Alert::information(_("Count words"), message);
995 case LFUN_BUFFER_TOGGLE_COMPRESSION:
996 // turn compression on/off
997 buffer_->params().compressed = !buffer_->params().compressed;
1000 case LFUN_NEXT_INSET_TOGGLE: {
1001 // this is the real function we want to invoke
1002 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1003 // if there is an inset at cursor, see whether it
1005 Inset * inset = cur.nextInset();
1006 if (inset && inset->isActive()) {
1007 Cursor tmpcur = cur;
1008 tmpcur.pushLeft(*inset);
1009 inset->dispatch(tmpcur, tmpcmd);
1010 if (tmpcur.result().dispatched()) {
1014 // if it did not work, try the underlying inset.
1015 if (!cur.result().dispatched())
1016 cur.dispatch(tmpcmd);
1018 if (cur.result().dispatched())
1019 cur.clearSelection();
1025 updateFlags = Update::None;
1032 docstring const BufferView::requestSelection()
1037 Cursor & cur = cursor_;
1039 if (!cur.selection()) {
1040 xsel_cache_.set = false;
1044 if (!xsel_cache_.set ||
1045 cur.top() != xsel_cache_.cursor ||
1046 cur.anchor_.top() != xsel_cache_.anchor)
1048 xsel_cache_.cursor = cur.top();
1049 xsel_cache_.anchor = cur.anchor_.top();
1050 xsel_cache_.set = cur.selection();
1051 return cur.selectionAsString(false);
1057 void BufferView::clearSelection()
1060 cursor_.clearSelection();
1061 // Clear the selection buffer. Otherwise a subsequent
1062 // middle-mouse-button paste would use the selection buffer,
1063 // not the more current external selection.
1064 cap::clearSelection();
1065 xsel_cache_.set = false;
1066 // The buffer did not really change, but this causes the
1067 // redraw we need because we cleared the selection above.
1073 void BufferView::workAreaResize(int width, int height)
1075 // Update from work area
1079 // The complete text metrics will be redone.
1080 text_metrics_.clear();
1087 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1089 pit_type pit = text.getPitNearY(*this, y);
1090 BOOST_ASSERT(pit != -1);
1091 Paragraph const & par = text.getPar(pit);
1093 LYXERR(Debug::DEBUG)
1094 << BOOST_CURRENT_FUNCTION
1099 InsetList::const_iterator iit = par.insetlist.begin();
1100 InsetList::const_iterator iend = par.insetlist.end();
1101 for (; iit != iend; ++iit) {
1102 Inset * const inset = iit->inset;
1103 if (inset->covers(*this, x, y)) {
1104 if (!inset->descendable())
1105 // No need to go further down if the inset is not
1109 size_t cell_number = inset->nargs();
1110 // Check all the inner cell.
1111 for (size_t i = 0; i != cell_number; ++i) {
1112 Text const * inner_text = inset->getText(i);
1115 Inset const * inset_deeper =
1116 getCoveringInset(*inner_text, x, y);
1118 return inset_deeper;
1122 LYXERR(Debug::DEBUG)
1123 << BOOST_CURRENT_FUNCTION
1124 << ": Hit inset: " << inset << endl;
1128 LYXERR(Debug::DEBUG)
1129 << BOOST_CURRENT_FUNCTION
1130 << ": No inset hit. " << endl;
1135 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1137 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1139 // This is only called for mouse related events including
1140 // LFUN_FILE_OPEN generated by drag-and-drop.
1141 FuncRequest cmd = cmd0;
1143 // E.g. Qt mouse press when no buffer
1148 cur.push(buffer_->inset());
1149 cur.selection() = cursor_.selection();
1151 // Either the inset under the cursor or the
1152 // surrounding Text will handle this event.
1154 // make sure we stay within the screen...
1155 cmd.y = min(max(cmd.y, -1), height_);
1157 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1159 // Get inset under mouse, if there is one.
1160 Inset const * covering_inset =
1161 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1162 if (covering_inset == last_inset_)
1163 // Same inset, no need to do anything...
1166 bool need_redraw = false;
1167 // const_cast because of setMouseHover().
1168 Inset * inset = const_cast<Inset *>(covering_inset);
1170 // Remove the hint on the last hovered inset (if any).
1171 need_redraw |= last_inset_->setMouseHover(false);
1173 // Highlighted the newly hovered inset (if any).
1174 need_redraw |= inset->setMouseHover(true);
1175 last_inset_ = inset;
1177 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1178 // not expose the button for redraw. We adjust here the metrics dimension
1179 // to enable a full redraw.
1180 // FIXME: It is possible to redraw only the area around the button!
1182 && metrics_info_.update_strategy == SingleParUpdate) {
1183 // FIXME: It should be possible to redraw only the area around
1184 // the button by doing this:
1186 //metrics_info_.singlepar = false;
1187 //metrics_info_.y1 = ymin of button;
1188 //metrics_info_.y2 = ymax of button;
1190 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1191 // between background updates and text updates. So we use the hammer
1192 // solution for now. We could also avoid the updateMetrics() below
1193 // by using the first and last pit of the CoordCache. Have a look
1194 // at Text::getPitNearY() to see what I mean.
1196 //metrics_info_.pit1 = first pit of CoordCache;
1197 //metrics_info_.pit2 = last pit of CoordCache;
1198 //metrics_info_.singlepar = false;
1199 //metrics_info_.y1 = 0;
1200 //metrics_info_.y2 = height_;
1202 updateMetrics(false);
1205 // This event (moving without mouse click) is not passed further.
1206 // This should be changed if it is further utilized.
1210 // Build temporary cursor.
1211 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1213 // Put anchor at the same position.
1216 // Try to dispatch to an non-editable inset near this position
1217 // via the temp cursor. If the inset wishes to change the real
1218 // cursor it has to do so explicitly by using
1219 // cur.bv().cursor() = cur; (or similar)
1221 inset->dispatch(cur, cmd);
1224 // Now dispatch to the temporary cursor. If the real cursor should
1225 // be modified, the inset's dispatch has to do so explicitly.
1226 if (!cur.result().dispatched())
1229 //Do we have a selection?
1230 theSelection().haveSelection(cursor().selection());
1232 // Redraw if requested and necessary.
1233 if (cur.result().dispatched() && cur.result().update())
1234 return update(cur.result().update());
1240 void BufferView::scroll(int /*lines*/)
1245 // Text const * t = &buffer_->text();
1246 // int const line_height = defaultRowHeight();
1248 // // The new absolute coordinate
1249 // int new_top_y = top_y() + lines * line_height;
1251 // // Restrict to a valid value
1252 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1253 // new_top_y = std::max(0, new_top_y);
1255 // scrollDocView(new_top_y);
1260 void BufferView::setCursorFromRow(int row)
1265 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1267 cursor_.reset(buffer_->inset());
1269 buffer_->text().setCursor(cursor_, 0, 0);
1271 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1275 void BufferView::gotoLabel(docstring const & label)
1277 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1278 vector<docstring> labels;
1279 it->getLabelList(*buffer_, labels);
1280 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1289 TextMetrics const & BufferView::textMetrics(Text const * t) const
1291 return const_cast<BufferView *>(this)->textMetrics(t);
1295 TextMetrics & BufferView::textMetrics(Text const * t)
1297 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1298 if (tmc_it == text_metrics_.end()) {
1299 tmc_it = text_metrics_.insert(
1300 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1302 return tmc_it->second;
1306 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1309 return textMetrics(t).parMetrics(pit);
1313 int BufferView::workHeight() const
1319 void BufferView::setCursor(DocIterator const & dit)
1321 size_t const n = dit.depth();
1322 for (size_t i = 0; i < n; ++i)
1323 dit[i].inset().edit(cursor_, true);
1325 cursor_.setCursor(dit);
1326 cursor_.selection() = false;
1330 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1332 // Would be wrong to delete anything if we have a selection.
1333 if (cur.selection())
1336 bool need_anchor_change = false;
1337 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1338 need_anchor_change);
1340 if (need_anchor_change)
1346 updateLabels(*buffer_);
1348 updateMetrics(false);
1354 bool BufferView::mouseSetCursor(Cursor & cur)
1356 BOOST_ASSERT(&cur.bv() == this);
1358 // this event will clear selection so we save selection for
1359 // persistent selection
1360 cap::saveSelection(cursor());
1362 // Has the cursor just left the inset?
1363 bool badcursor = false;
1364 bool leftinset = (&cursor_.inset() != &cur.inset());
1366 badcursor = notifyCursorLeaves(cursor_, cur);
1368 // do the dEPM magic if needed
1369 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1370 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1371 // the leftinset bool would not be necessary (badcursor instead).
1372 bool update = leftinset;
1373 if (!badcursor && cursor_.inTexted())
1374 update |= checkDepm(cur, cursor_);
1376 // if the cursor was in an empty script inset and the new
1377 // position is in the nucleus of the inset, notifyCursorLeaves
1378 // will kill the script inset itself. So we check all the
1379 // elements of the cursor to make sure that they are correct.
1380 // For an example, see bug 2933:
1381 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1382 // The code below could maybe be moved to a DocIterator method.
1383 //lyxerr << "cur before " << cur <<std::endl;
1384 DocIterator dit(cur.inset());
1385 dit.push_back(cur.bottom());
1387 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1388 dit.push_back(cur[i]);
1391 //lyxerr << "5 cur after" << dit <<std::endl;
1393 cursor_.setCursor(dit);
1394 cursor_.boundary(cur.boundary());
1395 cursor_.clearSelection();
1401 void BufferView::putSelectionAt(DocIterator const & cur,
1402 int length, bool backwards)
1404 cursor_.clearSelection();
1410 cursor_.pos() += length;
1411 cursor_.setSelection(cursor_, -length);
1413 cursor_.setSelection(cursor_, length);
1418 Cursor & BufferView::cursor()
1424 Cursor const & BufferView::cursor() const
1430 pit_type BufferView::anchor_ref() const
1436 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1438 return metrics_info_;
1442 // FIXME: We should split-up updateMetrics() for the singlepar case.
1443 void BufferView::updateMetrics(bool singlepar)
1445 Text & buftext = buffer_->text();
1446 TextMetrics & tm = textMetrics(&buftext);
1447 pit_type size = int(buftext.paragraphs().size());
1449 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1450 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1455 // Clear out the position cache in case of full screen redraw,
1456 coord_cache_.clear();
1458 // Clear out paragraph metrics to avoid having invalid metrics
1459 // in the cache from paragraphs not relayouted below
1463 // If the paragraph metrics has changed, we can not
1464 // use the singlepar optimisation.
1466 // In Single Paragraph mode, rebreak only
1467 // the (main text, not inset!) paragraph containing the cursor.
1468 // (if this paragraph contains insets etc., rebreaking will
1469 // recursively descend)
1470 && tm.redoParagraph(cursor_.bottom().pit()))
1473 pit_type const pit = anchor_ref_;
1476 size_t const npit = buftext.paragraphs().size();
1478 // Rebreak anchor paragraph.
1480 tm.redoParagraph(pit);
1482 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1484 // Redo paragraphs above anchor if necessary.
1486 while (y1 > 0 && pit1 > 0) {
1487 y1 -= tm.parMetrics(pit1).ascent();
1490 tm.redoParagraph(pit1);
1491 y1 -= tm.parMetrics(pit1).descent();
1495 // Take care of ascent of first line
1496 y1 -= tm.parMetrics(pit1).ascent();
1498 // Normalize anchor for next time
1502 // Grey at the beginning is ugly
1503 if (pit1 == 0 && y1 > 0) {
1509 // Redo paragraphs below the anchor if necessary.
1511 while (y2 < height_ && pit2 < int(npit) - 1) {
1512 y2 += tm.parMetrics(pit2).descent();
1515 tm.redoParagraph(pit2);
1516 y2 += tm.parMetrics(pit2).ascent();
1519 // Take care of descent of last line
1520 y2 += tm.parMetrics(pit2).descent();
1522 // The coordinates of all these paragraphs are correct, cache them
1524 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1525 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1526 ParagraphMetrics const & pm = tm.parMetrics(pit);
1528 parPos[pit] = Point(0, y);
1529 if (singlepar && pit == cursor_.bottom().pit()) {
1530 // In Single Paragraph mode, collect here the
1531 // y1 and y2 of the (one) paragraph the cursor is in
1532 y1 = y - pm.ascent();
1533 y2 = y + pm.descent();
1539 // collect cursor paragraph iter bounds
1540 pit1 = cursor_.bottom().pit();
1541 pit2 = cursor_.bottom().pit();
1544 LYXERR(Debug::DEBUG)
1545 << BOOST_CURRENT_FUNCTION
1548 << " pit1: " << pit1
1549 << " pit2: " << pit2
1550 << " npit: " << npit
1551 << " singlepar: " << singlepar
1555 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1556 singlepar? SingleParUpdate: FullScreenUpdate, size);
1558 if (lyxerr.debugging(Debug::WORKAREA)) {
1559 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1560 coord_cache_.dump();
1565 void BufferView::menuInsertLyXFile(string const & filenm)
1567 BOOST_ASSERT(cursor_.inTexted());
1568 string filename = filenm;
1570 if (filename.empty()) {
1571 // Launch a file browser
1573 string initpath = lyxrc.document_path;
1576 string const trypath = buffer_->filePath();
1577 // If directory is writeable, use this as default.
1578 if (isDirWriteable(FileName(trypath)))
1583 FileDialog fileDlg(_("Select LyX document to insert"),
1585 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1586 make_pair(_("Examples|#E#e"),
1587 from_utf8(addPath(package().system_support().absFilename(),
1590 FileDialog::Result result =
1591 fileDlg.open(from_utf8(initpath),
1592 FileFilterList(_("LyX Documents (*.lyx)")),
1595 if (result.first == FileDialog::Later)
1599 filename = to_utf8(result.second);
1601 // check selected filename
1602 if (filename.empty()) {
1603 // emit message signal.
1604 message(_("Canceled."));
1609 // Get absolute path of file and add ".lyx"
1610 // to the filename if necessary
1611 filename = fileSearch(string(), filename, "lyx").absFilename();
1613 docstring const disp_fn = makeDisplayPath(filename);
1614 // emit message signal.
1615 message(bformat(_("Inserting document %1$s..."), disp_fn));
1618 Buffer buf("", false);
1619 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1620 ErrorList & el = buffer_->errorList("Parse");
1621 // Copy the inserted document error list into the current buffer one.
1622 el = buf.errorList("Parse");
1623 recordUndo(cursor_);
1624 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1625 buf.params().textclass, el);
1626 res = _("Document %1$s inserted.");
1628 res = _("Could not insert document %1$s");
1630 // emit message signal.
1631 message(bformat(res, disp_fn));
1632 buffer_->errors("Parse");