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 "lyx_cb.h" // added for Dispatch functions
42 #include "lyxlayout.h"
44 #include "lyxtextclass.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>
85 using support::addPath;
86 using support::bformat;
87 using support::FileFilterList;
88 using support::FileName;
89 using support::fileSearch;
90 using support::isDirWriteable;
91 using support::isFileReadable;
92 using support::makeDisplayPath;
93 using support::package;
97 using std::istringstream;
101 using std::mem_fun_ref;
105 namespace Alert = frontend::Alert;
109 /// Return an inset of this class if it exists at the current cursor position
111 T * getInsetByCode(LCursor & cur, InsetBase::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 void BufferView::setBuffer(Buffer * b)
149 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
150 << "[ b = " << b << "]" << endl;
153 // Save the actual cursor position and anchor inside the
154 // buffer so that it can be restored in case we rechange
155 // to this buffer later on.
156 buffer_->saveCursor(cursor_.selectionBegin(),
157 cursor_.selectionEnd());
158 // current buffer is going to be switched-off, save cursor pos
159 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
160 boost::tie(cursor_.pit(), cursor_.pos()) );
163 // If we're quitting lyx, don't bother updating stuff
169 // If we are closing current buffer, switch to the first in
172 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
173 << " No Buffer!" << endl;
174 // We are closing the buffer, use the first buffer as current
175 buffer_ = theBufferList().first();
177 // Set current buffer
182 cursor_ = LCursor(*this);
187 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
188 << "Buffer addr: " << buffer_ << endl;
189 cursor_.push(buffer_->inset());
190 cursor_.resetAnchor();
191 buffer_->text().setCurrentFont(cursor_);
192 if (buffer_->getCursor().size() > 0 &&
193 buffer_->getAnchor().size() > 0)
195 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
196 cursor_.resetAnchor();
197 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
198 cursor_.setSelection();
199 theSelection().haveSelection(cursor_.selection());
204 updateMetrics(false);
206 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
207 graphics::Previews::get().generateBufferPreviews(*buffer_);
211 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
213 // File already open?
214 if (theBufferList().exists(filename.absFilename())) {
215 docstring const file = makeDisplayPath(filename.absFilename(), 20);
216 docstring text = bformat(_("The document %1$s is already "
217 "loaded.\n\nDo you want to revert "
218 "to the saved version?"), file);
219 int const ret = Alert::prompt(_("Revert to saved document?"),
220 text, 0, 1, _("&Revert"), _("&Switch to document"));
223 setBuffer(theBufferList().getBuffer(filename.absFilename()));
226 // FIXME: should be LFUN_REVERT
227 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
229 // Fall through to new load. (Asger)
235 if (isFileReadable(filename)) {
236 b = theBufferList().newBuffer(filename.absFilename());
237 if (!lyx::loadLyXFile(b, filename)) {
238 theBufferList().release(b);
242 docstring text = bformat(_("The document %1$s does not yet "
243 "exist.\n\nDo you want to create "
244 "a new document?"), from_utf8(filename.absFilename()));
245 int const ret = Alert::prompt(_("Create new document?"),
246 text, 0, 1, _("&Create"), _("Cancel"));
249 b = newFile(filename.absFilename(), string(), true);
257 // Send the "errors" signal in case of parsing errors
260 // Update the labels and section numbering.
261 updateLabels(*buffer_);
262 // scroll to the position when the file was last closed
263 if (lyxrc.use_lastfilepos) {
266 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
267 // if successfully move to pit (returned par_id is not zero), update metrics
268 if (moveToPosition(pit, 0, pos).get<1>()) {
270 updateMetrics(false);
275 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
281 void BufferView::resize()
286 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
288 updateMetrics(false);
293 bool BufferView::fitCursor()
295 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
296 frontend::FontMetrics const & fm =
297 theFontMetrics(cursor_.getFont());
298 int const asc = fm.maxAscent();
299 int const des = fm.maxDescent();
300 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
301 if (p.y_ - asc >= 0 && p.y_ + des < height_)
309 bool BufferView::multiParSel()
311 if (!cursor_.selection())
313 bool ret = multiparsel_cache_;
314 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
315 // Either this, or previous selection spans paragraphs
316 return ret || multiparsel_cache_;
320 bool BufferView::update(Update::flags flags)
322 // last_inset_ points to the last visited inset. This pointer may become
323 // invalid because of keyboard editing. Since all such operations
324 // causes screen update(), I reset last_inset_ to avoid such a problem.
326 // This is close to a hot-path.
327 if (lyxerr.debugging(Debug::DEBUG)) {
329 << BOOST_CURRENT_FUNCTION
330 << "[fitcursor = " << (flags & Update::FitCursor)
331 << ", forceupdate = " << (flags & Update::Force)
332 << ", singlepar = " << (flags & Update::SinglePar)
333 << "] buffer: " << buffer_ << endl;
336 // Check needed to survive LyX startup
340 if (lyxerr.debugging(Debug::WORKAREA)) {
341 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
344 // Update macro store
345 buffer_->buildMacros();
347 // Now do the first drawing step if needed. This consists on updating
348 // the CoordCache in updateMetrics().
349 // The second drawing step is done in WorkArea::redraw() if needed.
351 // Case when no explicit update is requested.
353 // no need to redraw anything.
354 metrics_info_.update_strategy = NoScreenUpdate;
358 if (flags == Update::Decoration) {
359 metrics_info_.update_strategy = DecorationUpdate;
363 if (flags == Update::FitCursor
364 || flags == (Update::Decoration | Update::FitCursor)) {
365 bool const fit_cursor = fitCursor();
366 // tell the frontend to update the screen if needed.
368 updateMetrics(false);
371 if (flags & Update::Decoration) {
372 metrics_info_.update_strategy = DecorationUpdate;
375 // no screen update is needed.
376 metrics_info_.update_strategy = NoScreenUpdate;
380 bool full_metrics = flags & Update::Force;
381 if (flags & Update::MultiParSel)
382 full_metrics |= multiParSel();
384 bool const single_par = !full_metrics;
385 updateMetrics(single_par);
387 if (flags & Update::FitCursor && fitCursor())
388 updateMetrics(false);
390 // tell the frontend to update the screen.
395 void BufferView::updateScrollbar()
398 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
399 << " no text in updateScrollbar" << endl;
400 scrollbarParameters_.reset();
404 LyXText & t = buffer_->text();
405 TextMetrics & tm = text_metrics_[&t];
407 int const parsize = int(t.paragraphs().size() - 1);
408 if (anchor_ref_ > parsize) {
409 anchor_ref_ = parsize;
413 if (lyxerr.debugging(Debug::GUI)) {
415 << BOOST_CURRENT_FUNCTION
416 << " Updating scrollbar: height: " << t.paragraphs().size()
417 << " curr par: " << cursor_.bottom().pit()
418 << " default height " << defaultRowHeight() << endl;
421 // It would be better to fix the scrollbar to understand
422 // values in [0..1] and divide everything by wh
424 // estimated average paragraph height:
428 int h = tm.parMetrics(anchor_ref_).height();
430 // Normalize anchor/offset (MV):
431 while (offset_ref_ > h && anchor_ref_ < parsize) {
434 h = tm.parMetrics(anchor_ref_).height();
436 // Look at paragraph heights on-screen
439 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
442 int const h2 = tm.parMetrics(pit).height();
448 int const hav = sumh / nh;
449 // More realistic average paragraph height
454 scrollbarParameters_.height = (parsize + 1) * wh_;
455 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
456 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
460 ScrollbarParameters const & BufferView::scrollbarParameters() const
462 return scrollbarParameters_;
466 void BufferView::scrollDocView(int value)
468 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
469 << "[ value = " << value << "]" << endl;
474 LyXText & t = buffer_->text();
475 TextMetrics & tm = text_metrics_[&t];
477 float const bar = value / float(wh_ * t.paragraphs().size());
479 anchor_ref_ = int(bar * t.paragraphs().size());
480 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
481 anchor_ref_ = int(t.paragraphs().size()) - 1;
483 tm.redoParagraph(anchor_ref_);
484 int const h = tm.parMetrics(anchor_ref_).height();
485 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
486 updateMetrics(false);
490 void BufferView::setCursorFromScrollbar()
492 LyXText & t = buffer_->text();
494 int const height = 2 * defaultRowHeight();
495 int const first = height;
496 int const last = height_ - height;
497 LCursor & cur = cursor_;
499 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
502 case bv_funcs::CUR_ABOVE:
503 t.setCursorFromCoordinates(cur, 0, first);
504 cur.clearSelection();
506 case bv_funcs::CUR_BELOW:
507 t.setCursorFromCoordinates(cur, 0, last);
508 cur.clearSelection();
510 case bv_funcs::CUR_INSIDE:
511 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
512 int const newy = min(last, max(y, first));
514 cur.reset(buffer_->inset());
515 t.setCursorFromCoordinates(cur, 0, newy);
521 Change const BufferView::getCurrentChange() const
523 if (!cursor_.selection())
524 return Change(Change::UNCHANGED);
526 DocIterator dit = cursor_.selectionBegin();
527 return dit.paragraph().lookupChange(dit.pos());
531 void BufferView::saveBookmark(bool persistent)
533 LyX::ref().session().bookmarks().save(
534 FileName(buffer_->fileName()),
536 cursor_.paragraph().id(),
541 // emit message signal.
542 message(_("Save bookmark"));
546 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
548 cursor_.clearSelection();
550 // if a valid par_id is given, try it first
552 ParIterator par = buffer_->getParFromID(par_id);
553 if (par != buffer_->par_iterator_end()) {
554 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
555 return boost::make_tuple(cursor_.pit(), par_id);
558 // if par_id == 0, or searching through par_id failed
559 if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
560 ParIterator it = buffer_->par_iterator_begin();
561 ParIterator const end = buffer_->par_iterator_end();
562 for (; it != end; ++it)
563 if (it.pit() == par_pit) {
564 // restored pos may be bigger than it->size
565 setCursor(makeDocIterator(it, min(par_pos, it->size())));
566 return boost::make_tuple(par_pit, it->id());
570 return boost::make_tuple(pit_type(0), 0);
574 void BufferView::switchKeyMap()
576 if (!lyxrc.rtl_support)
579 if (getLyXText()->real_current_font.isRightToLeft()) {
580 if (intl_->keymap == Intl::PRIMARY)
583 if (intl_->keymap == Intl::SECONDARY)
589 int BufferView::workWidth() const
595 void BufferView::center()
597 CursorSlice & bot = cursor_.bottom();
598 TextMetrics & tm = text_metrics_[bot.text()];
599 pit_type const pit = bot.pit();
600 tm.redoParagraph(pit);
601 ParagraphMetrics const & pm = tm.parMetrics(pit);
603 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
604 + pm.ascent() - height_ / 2;
608 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
612 switch (cmd.action) {
615 flag.enabled(!buffer_->undostack().empty());
618 flag.enabled(!buffer_->redostack().empty());
620 case LFUN_FILE_INSERT:
621 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
622 case LFUN_FILE_INSERT_PLAINTEXT:
623 case LFUN_BOOKMARK_SAVE:
624 // FIXME: Actually, these LFUNS should be moved to LyXText
625 flag.enabled(cursor_.inTexted());
627 case LFUN_FONT_STATE:
628 case LFUN_LABEL_INSERT:
629 case LFUN_PARAGRAPH_GOTO:
630 // FIXME handle non-trivially
631 case LFUN_OUTLINE_UP:
632 case LFUN_OUTLINE_DOWN:
633 case LFUN_OUTLINE_IN:
634 case LFUN_OUTLINE_OUT:
636 case LFUN_REFERENCE_NEXT:
638 case LFUN_WORD_REPLACE:
641 case LFUN_MARK_TOGGLE:
642 case LFUN_SCREEN_RECENTER:
643 case LFUN_BIBTEX_DATABASE_ADD:
644 case LFUN_BIBTEX_DATABASE_DEL:
645 case LFUN_WORDS_COUNT:
646 case LFUN_NEXT_INSET_TOGGLE:
650 case LFUN_LABEL_GOTO: {
651 flag.enabled(!cmd.argument().empty()
652 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
656 case LFUN_CHANGES_TRACK:
658 flag.setOnOff(buffer_->params().trackChanges);
661 case LFUN_CHANGES_OUTPUT: {
662 OutputParams runparams;
663 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
664 flag.enabled(buffer_ && features.isAvailable("dvipost"));
665 flag.setOnOff(buffer_->params().outputChanges);
669 case LFUN_CHANGES_MERGE:
670 case LFUN_CHANGE_NEXT:
671 case LFUN_ALL_CHANGES_ACCEPT:
672 case LFUN_ALL_CHANGES_REJECT:
673 // TODO: context-sensitive enabling of LFUNs
674 // In principle, these command should only be enabled if there
675 // is a change in the document. However, without proper
676 // optimizations, this will inevitably result in poor performance.
677 flag.enabled(buffer_);
680 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
681 flag.setOnOff(buffer_->params().compressed);
693 bool BufferView::dispatch(FuncRequest const & cmd)
695 //lyxerr << BOOST_CURRENT_FUNCTION
696 // << [ cmd = " << cmd << "]" << endl;
698 // Make sure that the cached BufferView is correct.
699 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
700 << " action[" << cmd.action << ']'
701 << " arg[" << to_utf8(cmd.argument()) << ']'
702 << " x[" << cmd.x << ']'
703 << " y[" << cmd.y << ']'
704 << " button[" << cmd.button() << ']'
707 LCursor & cur = cursor_;
709 switch (cmd.action) {
713 cur.message(_("Undo"));
714 cur.clearSelection();
715 if (!textUndo(*this))
716 cur.message(_("No further undo information"));
724 cur.message(_("Redo"));
725 cur.clearSelection();
726 if (!textRedo(*this))
727 cur.message(_("No further redo information"));
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_,
761 InsetBase::REF_CODE);
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));
795 // Switch to other buffer view and resend cmd
796 theLyXFunc().dispatch(FuncRequest(
797 LFUN_BUFFER_SWITCH, b->fileName()));
798 theLyXFunc().dispatch(cmd);
807 case LFUN_OUTLINE_UP:
808 toc::outline(toc::Up, cursor_);
809 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
810 updateLabels(*buffer_);
812 case LFUN_OUTLINE_DOWN:
813 toc::outline(toc::Down, cursor_);
814 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
815 updateLabels(*buffer_);
817 case LFUN_OUTLINE_IN:
818 toc::outline(toc::In, cursor_);
819 updateLabels(*buffer_);
821 case LFUN_OUTLINE_OUT:
822 toc::outline(toc::Out, cursor_);
823 updateLabels(*buffer_);
827 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
830 case LFUN_REFERENCE_NEXT: {
831 vector<InsetBase_code> tmp;
832 tmp.push_back(InsetBase::LABEL_CODE);
833 tmp.push_back(InsetBase::REF_CODE);
834 bv_funcs::gotoInset(this, tmp, true);
838 case LFUN_CHANGES_TRACK:
839 buffer_->params().trackChanges = !buffer_->params().trackChanges;
842 case LFUN_CHANGES_OUTPUT: {
843 buffer_->params().outputChanges = !buffer_->params().outputChanges;
847 case LFUN_CHANGE_NEXT:
848 findNextChange(this);
851 case LFUN_CHANGES_MERGE:
852 if (findNextChange(this))
853 showDialog("changes");
856 case LFUN_ALL_CHANGES_ACCEPT: {
857 cursor_.reset(buffer_->inset());
859 #warning FIXME changes
861 while (findNextChange(this))
862 getLyXText()->acceptOrRejectChange(cursor_, true);
867 case LFUN_ALL_CHANGES_REJECT: {
868 cursor_.reset(buffer_->inset());
870 #warning FIXME changes
872 while (findNextChange(this))
873 getLyXText()->acceptOrRejectChange(cursor_, false);
881 case LFUN_WORD_REPLACE:
886 cur.clearSelection();
888 cur.message(from_utf8(N_("Mark off")));
892 cur.clearSelection();
895 cur.message(from_utf8(N_("Mark on")));
898 case LFUN_MARK_TOGGLE:
899 cur.clearSelection();
902 cur.message(from_utf8(N_("Mark removed")));
905 cur.message(from_utf8(N_("Mark set")));
910 case LFUN_SCREEN_RECENTER:
914 case LFUN_BIBTEX_DATABASE_ADD: {
915 LCursor tmpcur = cursor_;
916 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
917 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
918 InsetBase::BIBTEX_CODE);
920 if (inset->addDatabase(to_utf8(cmd.argument())))
921 buffer_->updateBibfilesCache();
926 case LFUN_BIBTEX_DATABASE_DEL: {
927 LCursor tmpcur = cursor_;
928 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
929 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
930 InsetBase::BIBTEX_CODE);
932 if (inset->delDatabase(to_utf8(cmd.argument())))
933 buffer_->updateBibfilesCache();
938 case LFUN_WORDS_COUNT: {
939 DocIterator from, to;
940 if (cur.selection()) {
941 from = cur.selectionBegin();
942 to = cur.selectionEnd();
944 from = doc_iterator_begin(buffer_->inset());
945 to = doc_iterator_end(buffer_->inset());
947 int const count = countWords(from, to);
951 message = bformat(_("%1$d words in selection."),
954 message = bformat(_("%1$d words in document."),
959 message = _("One word in selection.");
961 message = _("One word in document.");
964 Alert::information(_("Count words"), message);
968 case LFUN_BUFFER_TOGGLE_COMPRESSION:
969 // turn compression on/off
970 buffer_->params().compressed = !buffer_->params().compressed;
973 case LFUN_NEXT_INSET_TOGGLE: {
974 // this is the real function we want to invoke
975 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
976 // if there is an inset at cursor, see whether it
978 InsetBase * inset = cur.nextInset();
979 if (inset && inset->isActive()) {
980 LCursor tmpcur = cur;
981 tmpcur.pushLeft(*inset);
982 inset->dispatch(tmpcur, tmpcmd);
983 if (tmpcur.result().dispatched()) {
987 // if it did not work, try the underlying inset.
988 if (!cur.result().dispatched())
989 cur.dispatch(tmpcmd);
991 if (cur.result().dispatched())
992 cur.clearSelection();
1005 docstring const BufferView::requestSelection()
1010 LCursor & cur = cursor_;
1012 if (!cur.selection()) {
1013 xsel_cache_.set = false;
1017 if (!xsel_cache_.set ||
1018 cur.top() != xsel_cache_.cursor ||
1019 cur.anchor_.top() != xsel_cache_.anchor)
1021 xsel_cache_.cursor = cur.top();
1022 xsel_cache_.anchor = cur.anchor_.top();
1023 xsel_cache_.set = cur.selection();
1024 return cur.selectionAsString(false);
1030 void BufferView::clearSelection()
1033 cursor_.clearSelection();
1034 xsel_cache_.set = false;
1035 // The buffer did not really change, but this causes the
1036 // redraw we need because we cleared the selection above.
1042 void BufferView::workAreaResize(int width, int height)
1044 // Update from work area
1048 // The complete text metrics will be redone.
1049 text_metrics_.clear();
1056 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1058 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1060 // This is only called for mouse related events including
1061 // LFUN_FILE_OPEN generated by drag-and-drop.
1062 FuncRequest cmd = cmd0;
1064 // E.g. Qt mouse press when no buffer
1069 cur.push(buffer_->inset());
1070 cur.selection() = cursor_.selection();
1072 // Either the inset under the cursor or the
1073 // surrounding LyXText will handle this event.
1075 // Build temporary cursor.
1076 cmd.y = min(max(cmd.y, -1), height_);
1077 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1079 //lyxerr << BOOST_CURRENT_FUNCTION
1080 // << " * hit inset at tip: " << inset << endl;
1081 //lyxerr << BOOST_CURRENT_FUNCTION
1082 // << " * created temp cursor:" << cur << endl;
1084 // NOTE: editXY returns the top level inset of nested insets. If you happen
1085 // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1086 // footnote inset, again inset=0), that inset will not be redrawn.
1087 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1088 bool need_redraw = false;
1090 if (inset != last_inset_) {
1092 need_redraw |= last_inset_->setMouseHover(false);
1094 need_redraw |= inset->setMouseHover(true);
1095 last_inset_ = inset;
1098 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1099 // not expose the button for redraw. We adjust here the metrics dimension
1100 // to enable a full redraw.
1101 // FIXME: It is possible to redraw only the area around the button!
1103 && metrics_info_.update_strategy == SingleParUpdate) {
1104 // FIXME: It should be possible to redraw only the area around
1105 // the button by doing this:
1107 //metrics_info_.singlepar = false;
1108 //metrics_info_.y1 = ymin of button;
1109 //metrics_info_.y2 = ymax of button;
1111 // Unfortunately, rowpainter.C:paintText() does not distinguish
1112 // between background updates and text updates. So we use the hammer
1113 // solution for now. We could also avoid the updateMetrics() below
1114 // by using the first and last pit of the CoordCache. Have a look
1115 // at LyXText::getPitNearY() to see what I mean.
1117 //metrics_info_.pit1 = first pit of CoordCache;
1118 //metrics_info_.pit2 = last pit of CoordCache;
1119 //metrics_info_.singlepar = false;
1120 //metrics_info_.y1 = 0;
1121 //metrics_info_.y2 = height_;
1123 updateMetrics(false);
1126 // This event (moving without mouse click) is not passed further.
1127 // This should be changed if it is further utilized.
1131 // Put anchor at the same position.
1134 // Try to dispatch to an non-editable inset near this position
1135 // via the temp cursor. If the inset wishes to change the real
1136 // cursor it has to do so explicitly by using
1137 // cur.bv().cursor() = cur; (or similar)
1139 inset->dispatch(cur, cmd);
1142 // Now dispatch to the temporary cursor. If the real cursor should
1143 // be modified, the inset's dispatch has to do so explicitly.
1144 if (!cur.result().dispatched())
1147 // Redraw if requested and necessary.
1148 if (cur.result().dispatched() && cur.result().update())
1149 return update(cur.result().update());
1155 void BufferView::scroll(int /*lines*/)
1160 // LyXText const * t = &buffer_->text();
1161 // int const line_height = defaultRowHeight();
1163 // // The new absolute coordinate
1164 // int new_top_y = top_y() + lines * line_height;
1166 // // Restrict to a valid value
1167 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1168 // new_top_y = std::max(0, new_top_y);
1170 // scrollDocView(new_top_y);
1175 void BufferView::setCursorFromRow(int row)
1180 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1183 buffer_->text().setCursor(cursor_, 0, 0);
1185 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1189 void BufferView::gotoLabel(docstring const & label)
1191 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1192 vector<docstring> labels;
1193 it->getLabelList(*buffer_, labels);
1194 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1203 LyXText * BufferView::getLyXText()
1205 LyXText * text = cursor_.innerText();
1211 LyXText const * BufferView::getLyXText() const
1213 LyXText const * text = cursor_.innerText();
1219 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1221 return const_cast<BufferView *>(this)->textMetrics(t);
1225 TextMetrics & BufferView::textMetrics(LyXText const * t)
1227 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1228 if (tmc_it == text_metrics_.end()) {
1229 tmc_it = text_metrics_.insert(
1230 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1232 return tmc_it->second;
1236 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1239 return textMetrics(t).parMetrics(pit);
1243 int BufferView::workHeight() const
1249 void BufferView::setCursor(DocIterator const & dit)
1251 size_t const n = dit.depth();
1252 for (size_t i = 0; i < n; ++i)
1253 dit[i].inset().edit(cursor_, true);
1255 cursor_.setCursor(dit);
1256 cursor_.selection() = false;
1260 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1262 // Would be wrong to delete anything if we have a selection.
1263 if (cur.selection())
1266 bool need_anchor_change = false;
1267 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1268 need_anchor_change);
1270 if (need_anchor_change)
1276 updateMetrics(false);
1282 bool BufferView::mouseSetCursor(LCursor & cur)
1284 BOOST_ASSERT(&cur.bv() == this);
1286 // Has the cursor just left the inset?
1287 bool badcursor = false;
1288 if (&cursor_.inset() != &cur.inset())
1289 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1291 // do the dEPM magic if needed
1292 // FIXME: move this to InsetText::notifyCursorLeaves?
1293 bool update = false;
1294 if (!badcursor && cursor_.inTexted())
1295 checkDepm(cur, cursor_);
1297 // if the cursor was in an empty script inset and the new
1298 // position is in the nucleus of the inset, notifyCursorLeaves
1299 // will kill the script inset itself. So we check all the
1300 // elements of the cursor to make sure that they are correct.
1301 // For an example, see bug 2933:
1302 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1303 // The code below could maybe be moved to a DocIterator method.
1304 //lyxerr << "cur before " << cur <<std::endl;
1305 DocIterator dit(cur.inset());
1306 dit.push_back(cur.bottom());
1308 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1309 dit.push_back(cur[i]);
1312 //lyxerr << "5 cur after" << dit <<std::endl;
1314 cursor_.setCursor(dit);
1315 cursor_.clearSelection();
1316 // remember new position.
1317 cursor_.setTargetX();
1323 void BufferView::putSelectionAt(DocIterator const & cur,
1324 int length, bool backwards)
1326 cursor_.clearSelection();
1332 cursor_.pos() += length;
1333 cursor_.setSelection(cursor_, -length);
1335 cursor_.setSelection(cursor_, length);
1336 theSelection().haveSelection(cursor_.selection());
1341 LCursor & BufferView::cursor()
1347 LCursor const & BufferView::cursor() const
1353 pit_type BufferView::anchor_ref() const
1359 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1361 return metrics_info_;
1365 // FIXME: We should split-up updateMetrics() for the singlepar case.
1366 void BufferView::updateMetrics(bool singlepar)
1368 LyXText & buftext = buffer_->text();
1369 TextMetrics & tm = textMetrics(&buftext);
1370 pit_type size = int(buftext.paragraphs().size());
1372 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1373 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1377 // If the paragraph metrics has changed, we can not
1378 // use the singlepar optimisation.
1380 // In Single Paragraph mode, rebreak only
1381 // the (main text, not inset!) paragraph containing the cursor.
1382 // (if this paragraph contains insets etc., rebreaking will
1383 // recursively descend)
1384 && tm.redoParagraph(cursor_.bottom().pit()))
1387 pit_type const pit = anchor_ref_;
1390 size_t const npit = buftext.paragraphs().size();
1392 // Rebreak anchor paragraph.
1394 tm.redoParagraph(pit);
1396 // Clear out the position cache in case of full screen redraw.
1398 coord_cache_.clear();
1400 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1402 // Redo paragraphs above anchor if necessary.
1404 while (y1 > 0 && pit1 > 0) {
1405 y1 -= tm.parMetrics(pit1).ascent();
1408 tm.redoParagraph(pit1);
1409 y1 -= tm.parMetrics(pit1).descent();
1413 // Take care of ascent of first line
1414 y1 -= tm.parMetrics(pit1).ascent();
1416 // Normalize anchor for next time
1420 // Grey at the beginning is ugly
1421 if (pit1 == 0 && y1 > 0) {
1427 // Redo paragraphs below the anchor if necessary.
1429 while (y2 < height_ && pit2 < int(npit) - 1) {
1430 y2 += tm.parMetrics(pit2).descent();
1433 tm.redoParagraph(pit2);
1434 y2 += tm.parMetrics(pit2).ascent();
1437 // Take care of descent of last line
1438 y2 += tm.parMetrics(pit2).descent();
1440 // The coordinates of all these paragraphs are correct, cache them
1442 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1443 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1444 ParagraphMetrics const & pm = tm.parMetrics(pit);
1446 parPos[pit] = Point(0, y);
1447 if (singlepar && pit == cursor_.bottom().pit()) {
1448 // In Single Paragraph mode, collect here the
1449 // y1 and y2 of the (one) paragraph the cursor is in
1450 y1 = y - pm.ascent();
1451 y2 = y + pm.descent();
1457 // collect cursor paragraph iter bounds
1458 pit1 = cursor_.bottom().pit();
1459 pit2 = cursor_.bottom().pit();
1462 lyxerr[Debug::DEBUG]
1463 << BOOST_CURRENT_FUNCTION
1466 << " pit1: " << pit1
1467 << " pit2: " << pit2
1468 << " npit: " << npit
1469 << " singlepar: " << singlepar
1473 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1474 singlepar? SingleParUpdate: FullScreenUpdate, size);
1476 if (lyxerr.debugging(Debug::WORKAREA)) {
1477 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1478 coord_cache_.dump();
1483 void BufferView::menuInsertLyXFile(string const & filenm)
1485 BOOST_ASSERT(cursor_.inTexted());
1486 string filename = filenm;
1488 if (filename.empty()) {
1489 // Launch a file browser
1491 string initpath = lyxrc.document_path;
1494 string const trypath = buffer_->filePath();
1495 // If directory is writeable, use this as default.
1496 if (isDirWriteable(FileName(trypath)))
1501 FileDialog fileDlg(_("Select LyX document to insert"),
1503 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1504 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1506 FileDialog::Result result =
1507 fileDlg.open(from_utf8(initpath),
1508 FileFilterList(_("LyX Documents (*.lyx)")),
1511 if (result.first == FileDialog::Later)
1515 filename = to_utf8(result.second);
1517 // check selected filename
1518 if (filename.empty()) {
1519 // emit message signal.
1520 message(_("Canceled."));
1525 // Get absolute path of file and add ".lyx"
1526 // to the filename if necessary
1527 filename = fileSearch(string(), filename, "lyx").absFilename();
1529 docstring const disp_fn = makeDisplayPath(filename);
1530 // emit message signal.
1531 message(bformat(_("Inserting document %1$s..."), disp_fn));
1534 Buffer buf("", false);
1535 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1536 ErrorList & el = buffer_->errorList("Parse");
1537 // Copy the inserted document error list into the current buffer one.
1538 el = buf.errorList("Parse");
1539 recordUndo(cursor_);
1540 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1541 buf.params().textclass, el);
1542 res = _("Document %1$s inserted.");
1544 res = _("Could not insert document %1$s");
1546 // emit message signal.
1547 message(bformat(res, disp_fn));
1548 buffer_->errors("Parse");