3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "DispatchResult.h"
29 #include "DocIterator.h"
31 #include "ErrorList.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "IndicesList.h"
37 #include "InsetIterator.h"
38 #include "InsetList.h"
40 #include "LaTeXFeatures.h"
44 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
120 using namespace lyx::support;
121 using namespace lyx::graphics;
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
153 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
157 delete preview_loader_;
165 /// search for macro in local (buffer) table or in children
166 MacroData const * getBufferMacro(docstring const & name,
167 DocIterator const & pos) const;
169 /// Update macro table starting with position of it \param it in some
171 void updateMacros(DocIterator & it, DocIterator & scope);
173 void setLabel(ParIterator & it, UpdateType utype) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this an unnamed file (New...)?
199 /// is this an internal bufffer?
200 bool internal_buffer;
205 /// name of the file the buffer is associated with.
208 /** Set to true only when the file is fully loaded.
209 * Used to prevent the premature generation of previews
210 * and by the citation inset.
212 bool file_fully_loaded;
215 mutable TocBackend toc_backend;
218 typedef pair<DocIterator, MacroData> ScopeMacro;
219 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
220 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
221 /// map from the macro name to the position map,
222 /// which maps the macro definition position to the scope and the MacroData.
223 NamePositionScopeMacroMap macros;
224 /// This seem to change the way Buffer::getMacro() works
225 mutable bool macro_lock;
227 /// positions of child buffers in the buffer
228 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
229 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
230 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
231 /// position of children buffers in this buffer
232 BufferPositionMap children_positions;
233 /// map from children inclusion positions to their scope and their buffer
234 PositionScopeBufferMap position_to_children;
236 /// Container for all sort of Buffer dependant errors.
237 map<string, ErrorList> errorLists;
239 /// timestamp and checksum used to test if the file has been externally
240 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
242 unsigned long checksum_;
245 frontend::WorkAreaManager * wa_;
247 frontend::GuiBufferDelegate * gui_;
252 /// A cache for the bibfiles (including bibfiles of loaded child
253 /// documents), needed for appropriate update of natbib labels.
254 mutable support::FileNameList bibfiles_cache_;
256 // FIXME The caching mechanism could be improved. At present, we have a
257 // cache for each Buffer, that caches all the bibliography info for that
258 // Buffer. A more efficient solution would be to have a global cache per
259 // file, and then to construct the Buffer's bibinfo from that.
260 /// A cache for bibliography info
261 mutable BiblioInfo bibinfo_;
262 /// whether the bibinfo cache is valid
263 mutable bool bibinfo_cache_valid_;
264 /// whether the bibfile cache is valid
265 mutable bool bibfile_cache_valid_;
266 /// Cache of timestamps of .bib files
267 map<FileName, time_t> bibfile_status_;
268 /// Indicates whether the bibinfo has changed since the last time
269 /// we ran updateBuffer(), i.e., whether citation labels may need
271 mutable bool cite_labels_valid_;
273 mutable RefCache ref_cache_;
275 /// our Text that should be wrapped in an InsetText
279 PreviewLoader * preview_loader_;
281 /// This is here to force the test to be done whenever parent_buffer
283 Buffer const * parent() const {
284 // if parent_buffer is not loaded, then it has been unloaded,
285 // which means that parent_buffer is an invalid pointer. So we
286 // set it to null in that case.
287 // however, the BufferList doesn't know about cloned buffers, so
288 // they will always be regarded as unloaded. in that case, we hope
290 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
292 return parent_buffer;
296 void setParent(Buffer const * pb) {
297 if (parent_buffer == pb)
300 if (!cloned_buffer_ && parent_buffer && pb)
301 LYXERR0("Warning: a buffer should not have two parents!");
303 if (!cloned_buffer_ && parent_buffer) {
304 parent_buffer->invalidateBibfileCache();
305 parent_buffer->invalidateBibinfoCache();
309 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
310 /// This one is useful for preview detached in a thread.
311 Buffer const * cloned_buffer_;
313 CloneList * clone_list_;
314 /// are we in the process of exporting this buffer?
315 mutable bool doing_export;
317 /// compute statistics
318 /// \p from initial position
319 /// \p to points to the end position
320 void updateStatistics(DocIterator & from, DocIterator & to,
321 bool skipNoOutput = true);
322 /// statistics accessor functions
323 int wordCount() const { return word_count_; }
324 int charCount(bool with_blanks) const {
326 + (with_blanks ? blank_count_ : 0);
330 /// So we can force access via the accessors.
331 mutable Buffer const * parent_buffer;
340 /// Creates the per buffer temporary directory
341 static FileName createBufferTmpDir()
344 // We are in our own directory. Why bother to mangle name?
345 // In fact I wrote this code to circumvent a problematic behaviour
346 // (bug?) of EMX mkstemp().
347 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
348 convert<string>(count++));
350 if (!tmpfl.createDirectory(0777)) {
351 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
352 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
353 from_utf8(tmpfl.absFileName())));
359 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
360 Buffer const * cloned_buffer)
361 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
362 internal_buffer(false), read_only(readonly_), filename(file),
363 file_fully_loaded(false), toc_backend(owner), macro_lock(false),
364 timestamp_(0), checksum_(0), wa_(0), gui_(0), undo_(*owner),
365 bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
366 cite_labels_valid_(false), preview_loader_(0),
367 cloned_buffer_(cloned_buffer), clone_list_(0),
368 doing_export(false), parent_buffer(0)
370 if (!cloned_buffer_) {
371 temppath = createBufferTmpDir();
372 lyxvc.setBuffer(owner_);
374 wa_ = new frontend::WorkAreaManager;
377 temppath = cloned_buffer_->d->temppath;
378 file_fully_loaded = true;
379 params = cloned_buffer_->d->params;
380 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
381 bibinfo_ = cloned_buffer_->d->bibinfo_;
382 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
383 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
384 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
385 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
386 unnamed = cloned_buffer_->d->unnamed;
387 internal_buffer = cloned_buffer_->d->internal_buffer;
391 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
392 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
394 LYXERR(Debug::INFO, "Buffer::Buffer()");
396 d->inset = new InsetText(*cloned_buffer->d->inset);
397 d->inset->setBuffer(*this);
398 // FIXME: optimize this loop somewhat, maybe by creating a new
399 // general recursive Inset::setId().
400 DocIterator it = doc_iterator_begin(this);
401 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
402 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
403 it.paragraph().setId(cloned_it.paragraph().id());
405 d->inset = new InsetText(this);
406 d->inset->setAutoBreakRows(true);
407 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
413 LYXERR(Debug::INFO, "Buffer::~Buffer()");
414 // here the buffer should take care that it is
415 // saved properly, before it goes into the void.
417 // GuiView already destroyed
421 // No need to do additional cleanups for internal buffer.
427 // this is in case of recursive includes: we won't try to delete
428 // ourselves as a child.
429 d->clone_list_->erase(this);
430 // loop over children
431 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
432 Impl::BufferPositionMap::iterator end = d->children_positions.end();
433 for (; it != end; ++it) {
434 Buffer * child = const_cast<Buffer *>(it->first);
435 if (d->clone_list_->erase(child))
438 // if we're the master buffer, then we should get rid of the list
441 // if this is not empty, we have leaked something. worse, one of the
442 // children still has a reference to this list.
443 LASSERT(d->clone_list_->empty(), /* */);
444 list<CloneList *>::iterator it =
445 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
446 LASSERT(it != cloned_buffers.end(), /* */);
447 cloned_buffers.erase(it);
448 delete d->clone_list_;
450 // FIXME Do we really need to do this right before we delete d?
451 // clear references to children in macro tables
452 d->children_positions.clear();
453 d->position_to_children.clear();
455 // loop over children
456 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
457 Impl::BufferPositionMap::iterator end = d->children_positions.end();
458 for (; it != end; ++it) {
459 Buffer * child = const_cast<Buffer *>(it->first);
460 if (theBufferList().isLoaded(child))
461 theBufferList().releaseChild(this, child);
465 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
466 msg += emergencyWrite();
467 Alert::warning(_("Attempting to close changed document!"), msg);
470 // FIXME Do we really need to do this right before we delete d?
471 // clear references to children in macro tables
472 d->children_positions.clear();
473 d->position_to_children.clear();
475 if (!d->temppath.destroyDirectory()) {
476 Alert::warning(_("Could not remove temporary directory"),
477 bformat(_("Could not remove the temporary directory %1$s"),
478 from_utf8(d->temppath.absFileName())));
487 Buffer * Buffer::cloneFromMaster() const
490 cloned_buffers.push_back(new CloneList());
491 CloneList * clones = cloned_buffers.back();
493 masterBuffer()->cloneWithChildren(bufmap, clones);
495 // make sure we got cloned
496 BufferMap::const_iterator bit = bufmap.find(this);
497 LASSERT(bit != bufmap.end(), return 0);
498 Buffer * cloned_buffer = bit->second;
500 return cloned_buffer;
504 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
506 // have we already been cloned?
507 if (bufmap.find(this) != bufmap.end())
510 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
511 bufmap[this] = buffer_clone;
512 clones->insert(buffer_clone);
513 buffer_clone->d->clone_list_ = clones;
514 buffer_clone->d->macro_lock = true;
515 buffer_clone->d->children_positions.clear();
516 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
517 // math macro caches need to be rethought and simplified.
518 // I am not sure wether we should handle Buffer cloning here or in BufferList.
519 // Right now BufferList knows nothing about buffer clones.
520 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
521 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
522 for (; it != end; ++it) {
523 DocIterator dit = it->first.clone(buffer_clone);
524 dit.setBuffer(buffer_clone);
525 Buffer * child = const_cast<Buffer *>(it->second.second);
527 child->cloneWithChildren(bufmap, clones);
528 BufferMap::iterator const bit = bufmap.find(child);
529 LASSERT(bit != bufmap.end(), continue);
530 Buffer * child_clone = bit->second;
532 Inset * inset = dit.nextInset();
533 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
534 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
535 inset_inc->setChildBuffer(child_clone);
536 child_clone->d->setParent(buffer_clone);
537 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
538 buffer_clone->setChild(dit, child_clone);
540 buffer_clone->d->macro_lock = false;
545 Buffer * Buffer::cloneBufferOnly() const {
546 cloned_buffers.push_back(new CloneList());
547 CloneList * clones = cloned_buffers.back();
548 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
549 clones->insert(buffer_clone);
550 buffer_clone->d->clone_list_ = clones;
551 // we won't be cloning the children
552 buffer_clone->d->children_positions.clear();
557 bool Buffer::isClone() const
559 return d->cloned_buffer_;
563 void Buffer::changed(bool update_metrics) const
566 d->wa_->redrawAll(update_metrics);
570 frontend::WorkAreaManager & Buffer::workAreaManager() const
572 LASSERT(d->wa_, /**/);
577 Text & Buffer::text() const
579 return d->inset->text();
583 Inset & Buffer::inset() const
589 BufferParams & Buffer::params()
595 BufferParams const & Buffer::params() const
601 ParagraphList & Buffer::paragraphs()
603 return text().paragraphs();
607 ParagraphList const & Buffer::paragraphs() const
609 return text().paragraphs();
613 LyXVC & Buffer::lyxvc()
619 LyXVC const & Buffer::lyxvc() const
625 string const Buffer::temppath() const
627 return d->temppath.absFileName();
631 TexRow & Buffer::texrow()
637 TexRow const & Buffer::texrow() const
643 TocBackend & Buffer::tocBackend() const
645 return d->toc_backend;
649 Undo & Buffer::undo()
655 void Buffer::setChild(DocIterator const & dit, Buffer * child)
657 d->children_positions[child] = dit;
661 string Buffer::latexName(bool const no_path) const
663 FileName latex_name =
664 makeLatexName(d->exportFileName());
665 return no_path ? latex_name.onlyFileName()
666 : latex_name.absFileName();
670 FileName Buffer::Impl::exportFileName() const
672 docstring const branch_suffix =
673 params.branchlist().getFileNameSuffix();
674 if (branch_suffix.empty())
677 string const name = filename.onlyFileNameWithoutExt()
678 + to_utf8(branch_suffix);
679 FileName res(filename.onlyPath().absFileName() + "/" + name);
680 res.changeExtension(filename.extension());
686 string Buffer::logName(LogType * type) const
688 string const filename = latexName(false);
690 if (filename.empty()) {
696 string const path = temppath();
698 FileName const fname(addName(temppath(),
699 onlyFileName(changeExtension(filename,
702 // FIXME: how do we know this is the name of the build log?
703 FileName const bname(
704 addName(path, onlyFileName(
705 changeExtension(filename,
706 formats.extension(params().bufferFormat()) + ".out"))));
708 // Also consider the master buffer log file
709 FileName masterfname = fname;
711 if (masterBuffer() != this) {
712 string const mlogfile = masterBuffer()->logName(&mtype);
713 masterfname = FileName(mlogfile);
716 // If no Latex log or Build log is newer, show Build log
717 if (bname.exists() &&
718 ((!fname.exists() && !masterfname.exists())
719 || (fname.lastModified() < bname.lastModified()
720 && masterfname.lastModified() < bname.lastModified()))) {
721 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
724 return bname.absFileName();
725 // If we have a newer master file log or only a master log, show this
726 } else if (fname != masterfname
727 && (!fname.exists() && (masterfname.exists()
728 || fname.lastModified() < masterfname.lastModified()))) {
729 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
732 return masterfname.absFileName();
734 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
737 return fname.absFileName();
741 void Buffer::setReadonly(bool const flag)
743 if (d->read_only != flag) {
750 void Buffer::setFileName(FileName const & fname)
753 setReadonly(d->filename.isReadOnly());
759 int Buffer::readHeader(Lexer & lex)
761 int unknown_tokens = 0;
763 int begin_header_line = -1;
765 // Initialize parameters that may be/go lacking in header:
766 params().branchlist().clear();
767 params().preamble.erase();
768 params().options.erase();
769 params().master.erase();
770 params().float_placement.erase();
771 params().paperwidth.erase();
772 params().paperheight.erase();
773 params().leftmargin.erase();
774 params().rightmargin.erase();
775 params().topmargin.erase();
776 params().bottommargin.erase();
777 params().headheight.erase();
778 params().headsep.erase();
779 params().footskip.erase();
780 params().columnsep.erase();
781 params().fonts_cjk.erase();
782 params().listings_params.clear();
783 params().clearLayoutModules();
784 params().clearRemovedModules();
785 params().clearIncludedChildren();
786 params().pdfoptions().clear();
787 params().indiceslist().clear();
788 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
789 params().isbackgroundcolor = false;
790 params().fontcolor = RGBColor(0, 0, 0);
791 params().isfontcolor = false;
792 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
793 params().boxbgcolor = RGBColor(0xFF, 0, 0);
794 params().html_latex_start.clear();
795 params().html_latex_end.clear();
796 params().html_math_img_scale = 1.0;
797 params().output_sync_macro.erase();
798 params().local_layout.clear();
800 for (int i = 0; i < 4; ++i) {
801 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
802 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
805 ErrorList & errorList = d->errorLists["Parse"];
814 if (token == "\\end_header")
818 if (token == "\\begin_header") {
819 begin_header_line = line;
823 LYXERR(Debug::PARSER, "Handling document header token: `"
826 string unknown = params().readToken(lex, token, d->filename.onlyPath());
827 if (!unknown.empty()) {
828 if (unknown[0] != '\\' && token == "\\textclass") {
829 Alert::warning(_("Unknown document class"),
830 bformat(_("Using the default document class, because the "
831 "class %1$s is unknown."), from_utf8(unknown)));
834 docstring const s = bformat(_("Unknown token: "
838 errorList.push_back(ErrorItem(_("Document header error"),
843 if (begin_header_line) {
844 docstring const s = _("\\begin_header is missing");
845 errorList.push_back(ErrorItem(_("Document header error"),
849 params().makeDocumentClass();
851 return unknown_tokens;
856 // changed to be public and have one parameter
857 // Returns true if "\end_document" is not read (Asger)
858 bool Buffer::readDocument(Lexer & lex)
860 ErrorList & errorList = d->errorLists["Parse"];
863 // remove dummy empty par
864 paragraphs().clear();
866 if (!lex.checkFor("\\begin_document")) {
867 docstring const s = _("\\begin_document is missing");
868 errorList.push_back(ErrorItem(_("Document header error"),
874 if (params().outputChanges) {
875 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
876 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
877 LaTeXFeatures::isAvailable("xcolor");
879 if (!dvipost && !xcolorulem) {
880 Alert::warning(_("Changes not shown in LaTeX output"),
881 _("Changes will not be highlighted in LaTeX output, "
882 "because neither dvipost nor xcolor/ulem are installed.\n"
883 "Please install these packages or redefine "
884 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
885 } else if (!xcolorulem) {
886 Alert::warning(_("Changes not shown in LaTeX output"),
887 _("Changes will not be highlighted in LaTeX output "
888 "when using pdflatex, because xcolor and ulem are not installed.\n"
889 "Please install both packages or redefine "
890 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
894 if (!params().master.empty()) {
895 FileName const master_file = makeAbsPath(params().master,
896 onlyPath(absFileName()));
897 if (isLyXFileName(master_file.absFileName())) {
899 checkAndLoadLyXFile(master_file, true);
901 // necessary e.g. after a reload
902 // to re-register the child (bug 5873)
903 // FIXME: clean up updateMacros (here, only
904 // child registering is needed).
905 master->updateMacros();
906 // set master as master buffer, but only
907 // if we are a real child
908 if (master->isChild(this))
910 // if the master is not fully loaded
911 // it is probably just loading this
912 // child. No warning needed then.
913 else if (master->isFullyLoaded())
914 LYXERR0("The master '"
916 << "' assigned to this document ("
918 << ") does not include "
919 "this document. Ignoring the master assignment.");
924 // assure we have a default index
925 params().indiceslist().addDefault(B_("Index"));
928 bool const res = text().read(lex, errorList, d->inset);
930 // inform parent buffer about local macros
932 Buffer const * pbuf = parent();
933 UserMacroSet::const_iterator cit = usermacros.begin();
934 UserMacroSet::const_iterator end = usermacros.end();
935 for (; cit != end; ++cit)
936 pbuf->usermacros.insert(*cit);
940 updateMacroInstances(InternalUpdate);
945 bool Buffer::readString(string const & s)
947 params().compressed = false;
952 FileName const fn = FileName::tempName("Buffer_readString");
955 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
956 if (ret_plf != ReadSuccess)
959 if (file_format != LYX_FORMAT) {
960 // We need to call lyx2lyx, so write the input to a file
961 ofstream os(fn.toFilesystemEncoding().c_str());
965 return readFile(fn) == ReadSuccess;
968 if (readDocument(lex))
974 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
978 if (!lex.setFile(fname)) {
979 Alert::error(_("File Not Found"),
980 bformat(_("Unable to open file `%1$s'."),
981 from_utf8(fn.absFileName())));
982 return ReadFileNotFound;
986 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
987 if (ret_plf != ReadSuccess)
990 if (file_format != LYX_FORMAT) {
992 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
993 if (ret_clf != ReadSuccess)
995 return readFile(tmpFile);
998 // FIXME: InsetInfo needs to know whether the file is under VCS
999 // during the parse process, so this has to be done before.
1000 lyxvc().file_found_hook(d->filename);
1002 if (readDocument(lex)) {
1003 Alert::error(_("Document format failure"),
1004 bformat(_("%1$s ended unexpectedly, which means"
1005 " that it is probably corrupted."),
1006 from_utf8(fn.absFileName())));
1007 return ReadDocumentFailure;
1010 d->file_fully_loaded = true;
1011 d->read_only = !d->filename.isWritable();
1012 params().compressed = formats.isZippedFile(d->filename);
1018 bool Buffer::isFullyLoaded() const
1020 return d->file_fully_loaded;
1024 void Buffer::setFullyLoaded(bool value)
1026 d->file_fully_loaded = value;
1030 PreviewLoader * Buffer::loader() const
1032 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1034 if (!d->preview_loader_)
1035 d->preview_loader_ = new PreviewLoader(*this);
1036 return d->preview_loader_;
1040 void Buffer::removePreviews() const
1042 delete d->preview_loader_;
1043 d->preview_loader_ = 0;
1047 void Buffer::updatePreviews() const
1049 PreviewLoader * ploader = loader();
1053 InsetIterator it = inset_iterator_begin(*d->inset);
1054 InsetIterator const end = inset_iterator_end(*d->inset);
1055 for (; it != end; ++it)
1056 it->addPreview(it, *ploader);
1058 ploader->startLoading();
1062 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1063 FileName const & fn, int & file_format) const
1065 if(!lex.checkFor("\\lyxformat")) {
1066 Alert::error(_("Document format failure"),
1067 bformat(_("%1$s is not a readable LyX document."),
1068 from_utf8(fn.absFileName())));
1069 return ReadNoLyXFormat;
1075 // LyX formats 217 and earlier were written as 2.17. This corresponds
1076 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1077 // these cases. See also: www.lyx.org/trac/changeset/1313.
1078 size_t dot = tmp_format.find_first_of(".,");
1079 if (dot != string::npos)
1080 tmp_format.erase(dot, 1);
1082 file_format = convert<int>(tmp_format);
1087 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1088 FileName & tmpfile, int from_format)
1090 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1091 if(tmpfile.empty()) {
1092 Alert::error(_("Conversion failed"),
1093 bformat(_("%1$s is from a different"
1094 " version of LyX, but a temporary"
1095 " file for converting it could"
1096 " not be created."),
1097 from_utf8(fn.absFileName())));
1098 return LyX2LyXNoTempFile;
1101 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1102 if (lyx2lyx.empty()) {
1103 Alert::error(_("Conversion script not found"),
1104 bformat(_("%1$s is from a different"
1105 " version of LyX, but the"
1106 " conversion script lyx2lyx"
1107 " could not be found."),
1108 from_utf8(fn.absFileName())));
1109 return LyX2LyXNotFound;
1113 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1114 ostringstream command;
1115 command << os::python()
1116 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1117 << " -t " << convert<string>(LYX_FORMAT)
1118 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1119 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1120 string const command_str = command.str();
1122 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1124 cmd_ret const ret = runCommand(command_str);
1125 if (ret.first != 0) {
1126 if (from_format < LYX_FORMAT) {
1127 Alert::error(_("Conversion script failed"),
1128 bformat(_("%1$s is from an older version"
1129 " of LyX and the lyx2lyx script"
1130 " failed to convert it."),
1131 from_utf8(fn.absFileName())));
1132 return LyX2LyXOlderFormat;
1134 Alert::error(_("Conversion script failed"),
1135 bformat(_("%1$s is from a newer version"
1136 " of LyX and the lyx2lyx script"
1137 " failed to convert it."),
1138 from_utf8(fn.absFileName())));
1139 return LyX2LyXNewerFormat;
1146 // Should probably be moved to somewhere else: BufferView? GuiView?
1147 bool Buffer::save() const
1149 docstring const file = makeDisplayPath(absFileName(), 20);
1150 d->filename.refresh();
1152 // check the read-only status before moving the file as a backup
1153 if (d->filename.exists()) {
1154 bool const read_only = !d->filename.isWritable();
1156 Alert::warning(_("File is read-only"),
1157 bformat(_("The file %1$s cannot be written because it "
1158 "is marked as read-only."), file));
1163 // ask if the disk file has been externally modified (use checksum method)
1164 if (fileName().exists() && isExternallyModified(checksum_method)) {
1166 bformat(_("Document %1$s has been externally modified. "
1167 "Are you sure you want to overwrite this file?"), file);
1168 int const ret = Alert::prompt(_("Overwrite modified file?"),
1169 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1174 // We don't need autosaves in the immediate future. (Asger)
1175 resetAutosaveTimers();
1177 FileName backupName;
1178 bool madeBackup = false;
1180 // make a backup if the file already exists
1181 if (lyxrc.make_backup && fileName().exists()) {
1182 backupName = FileName(absFileName() + '~');
1183 if (!lyxrc.backupdir_path.empty()) {
1184 string const mangledName =
1185 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1186 backupName = FileName(addName(lyxrc.backupdir_path,
1190 // Except file is symlink do not copy because of #6587.
1191 // Hard links have bad luck.
1192 if (fileName().isSymLink())
1193 madeBackup = fileName().copyTo(backupName);
1195 madeBackup = fileName().moveTo(backupName);
1198 Alert::error(_("Backup failure"),
1199 bformat(_("Cannot create backup file %1$s.\n"
1200 "Please check whether the directory exists and is writable."),
1201 from_utf8(backupName.absFileName())));
1202 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1206 if (writeFile(d->filename)) {
1210 // Saving failed, so backup is not backup
1212 backupName.moveTo(d->filename);
1218 bool Buffer::writeFile(FileName const & fname) const
1220 // FIXME Do we need to do these here? I don't think writing
1221 // the LyX file depends upon it. (RGH)
1223 // updateMacroInstances();
1225 if (d->read_only && fname == d->filename)
1228 bool retval = false;
1230 docstring const str = bformat(_("Saving document %1$s..."),
1231 makeDisplayPath(fname.absFileName()));
1234 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1236 if (params().compressed) {
1237 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1238 retval = ofs && write(ofs);
1240 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1241 retval = ofs && write(ofs);
1245 message(str + _(" could not write file!"));
1250 // removeAutosaveFile();
1253 message(str + _(" done."));
1259 docstring Buffer::emergencyWrite()
1261 // No need to save if the buffer has not changed.
1265 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1267 docstring user_message = bformat(
1268 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1270 // We try to save three places:
1271 // 1) Same place as document. Unless it is an unnamed doc.
1273 string s = absFileName();
1276 if (writeFile(FileName(s))) {
1278 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1279 return user_message;
1281 user_message += " " + _("Save failed! Trying again...\n");
1285 // 2) In HOME directory.
1286 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1288 lyxerr << ' ' << s << endl;
1289 if (writeFile(FileName(s))) {
1291 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1292 return user_message;
1295 user_message += " " + _("Save failed! Trying yet again...\n");
1297 // 3) In "/tmp" directory.
1298 // MakeAbsPath to prepend the current
1299 // drive letter on OS/2
1300 s = addName(package().temp_dir().absFileName(), absFileName());
1302 lyxerr << ' ' << s << endl;
1303 if (writeFile(FileName(s))) {
1305 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1306 return user_message;
1309 user_message += " " + _("Save failed! Bummer. Document is lost.");
1312 return user_message;
1316 bool Buffer::write(ostream & ofs) const
1319 // Use the standard "C" locale for file output.
1320 ofs.imbue(locale::classic());
1323 // The top of the file should not be written by params().
1325 // write out a comment in the top of the file
1326 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1327 << " created this file. For more info see http://www.lyx.org/\n"
1328 << "\\lyxformat " << LYX_FORMAT << "\n"
1329 << "\\begin_document\n";
1331 /// For each author, set 'used' to true if there is a change
1332 /// by this author in the document; otherwise set it to 'false'.
1333 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1334 AuthorList::Authors::const_iterator a_end = params().authors().end();
1335 for (; a_it != a_end; ++a_it)
1336 a_it->setUsed(false);
1338 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1339 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1340 for ( ; it != end; ++it)
1341 it->checkAuthors(params().authors());
1343 // now write out the buffer parameters.
1344 ofs << "\\begin_header\n";
1345 params().writeFile(ofs);
1346 ofs << "\\end_header\n";
1349 ofs << "\n\\begin_body\n";
1351 ofs << "\n\\end_body\n";
1353 // Write marker that shows file is complete
1354 ofs << "\\end_document" << endl;
1356 // Shouldn't really be needed....
1359 // how to check if close went ok?
1360 // Following is an attempt... (BE 20001011)
1362 // good() returns false if any error occured, including some
1363 // formatting error.
1364 // bad() returns true if something bad happened in the buffer,
1365 // which should include file system full errors.
1370 lyxerr << "File was not closed properly." << endl;
1377 bool Buffer::makeLaTeXFile(FileName const & fname,
1378 string const & original_path,
1379 OutputParams const & runparams_in,
1380 OutputWhat output) const
1382 OutputParams runparams = runparams_in;
1384 // This is necessary for LuaTeX/XeTeX with tex fonts.
1385 // See FIXME in BufferParams::encoding()
1386 if (runparams.isFullUnicode())
1387 runparams.encoding = encodings.fromLyXName("utf8-plain");
1389 string const encoding = runparams.encoding->iconvName();
1390 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1393 try { ofs.reset(encoding); }
1394 catch (iconv_codecvt_facet_exception & e) {
1395 lyxerr << "Caught iconv exception: " << e.what() << endl;
1396 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1397 "verify that the support software for your encoding (%1$s) is "
1398 "properly installed"), from_ascii(encoding)));
1401 if (!openFileWrite(ofs, fname))
1404 //TexStream ts(ofs.rdbuf(), &texrow());
1405 ErrorList & errorList = d->errorLists["Export"];
1407 bool failed_export = false;
1408 otexstream os(ofs, d->texrow);
1410 // make sure we are ready to export
1411 // this needs to be done before we validate
1412 // FIXME Do we need to do this all the time? I.e., in children
1413 // of a master we are exporting?
1415 updateMacroInstances(OutputUpdate);
1418 os.texrow().reset();
1419 writeLaTeXSource(os, original_path, runparams, output);
1421 catch (EncodingException & e) {
1422 odocstringstream ods;
1423 ods.put(e.failed_char);
1425 oss << "0x" << hex << e.failed_char << dec;
1426 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1427 " (code point %2$s)"),
1428 ods.str(), from_utf8(oss.str()));
1429 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1430 "representable in the chosen encoding.\n"
1431 "Changing the document encoding to utf8 could help."),
1432 e.par_id, e.pos, e.pos + 1));
1433 failed_export = true;
1435 catch (iconv_codecvt_facet_exception & e) {
1436 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1437 _(e.what()), -1, 0, 0));
1438 failed_export = true;
1440 catch (exception const & e) {
1441 errorList.push_back(ErrorItem(_("conversion failed"),
1442 _(e.what()), -1, 0, 0));
1443 failed_export = true;
1446 lyxerr << "Caught some really weird exception..." << endl;
1452 failed_export = true;
1453 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1457 return !failed_export;
1461 void Buffer::writeLaTeXSource(otexstream & os,
1462 string const & original_path,
1463 OutputParams const & runparams_in,
1464 OutputWhat output) const
1466 // The child documents, if any, shall be already loaded at this point.
1468 OutputParams runparams = runparams_in;
1470 // Classify the unicode characters appearing in math insets
1471 Encodings::initUnicodeMath(*this);
1473 // validate the buffer.
1474 LYXERR(Debug::LATEX, " Validating buffer...");
1475 LaTeXFeatures features(*this, params(), runparams);
1477 runparams.use_polyglossia = features.usePolyglossia();
1478 LYXERR(Debug::LATEX, " Buffer validation done.");
1480 bool const output_preamble =
1481 output == FullSource || output == OnlyPreamble;
1482 bool const output_body =
1483 output == FullSource || output == OnlyBody;
1485 // The starting paragraph of the coming rows is the
1486 // first paragraph of the document. (Asger)
1487 if (output_preamble && runparams.nice) {
1488 os << "%% LyX " << lyx_version << " created this file. "
1489 "For more info, see http://www.lyx.org/.\n"
1490 "%% Do not edit unless you really know what "
1493 LYXERR(Debug::INFO, "lyx document header finished");
1495 // There are a few differences between nice LaTeX and usual files:
1496 // usual files have \batchmode and special input@path to allow
1497 // inclusion of figures specified by an explicitly relative path
1498 // (i.e., a path starting with './' or '../') with either \input or
1499 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1500 // input@path is set when the actual parameter original_path is set.
1501 // This is done for usual tex-file, but not for nice-latex-file.
1502 // (Matthias 250696)
1503 // Note that input@path is only needed for something the user does
1504 // in the preamble, included .tex files or ERT, files included by
1505 // LyX work without it.
1506 if (output_preamble) {
1507 if (!runparams.nice) {
1508 // code for usual, NOT nice-latex-file
1509 os << "\\batchmode\n"; // changed from \nonstopmode
1511 if (!original_path.empty()) {
1513 // We don't know the encoding of inputpath
1514 docstring const inputpath = from_utf8(original_path);
1515 docstring uncodable_glyphs;
1516 Encoding const * const enc = runparams.encoding;
1518 for (size_t n = 0; n < inputpath.size(); ++n) {
1519 if (!enc->encodable(inputpath[n])) {
1520 docstring const glyph(1, inputpath[n]);
1521 LYXERR0("Uncodable character '"
1523 << "' in input path!");
1524 uncodable_glyphs += glyph;
1529 // warn user if we found uncodable glyphs.
1530 if (!uncodable_glyphs.empty()) {
1531 frontend::Alert::warning(
1532 _("Uncodable character in file path"),
1534 _("The path of your document\n"
1536 "contains glyphs that are unknown "
1537 "in the current document encoding "
1538 "(namely %2$s). This may result in "
1539 "incomplete output, unless "
1540 "TEXINPUTS contains the document "
1541 "directory and you don't use "
1542 "explicitly relative paths (i.e., "
1543 "paths starting with './' or "
1544 "'../') in the preamble or in ERT."
1545 "\n\nIn case of problems, choose "
1546 "an appropriate document encoding\n"
1547 "(such as utf8) or change the "
1549 inputpath, uncodable_glyphs));
1552 support::latex_path(original_path);
1553 if (contains(docdir, '#')) {
1554 docdir = subst(docdir, "#", "\\#");
1555 os << "\\catcode`\\#=11"
1556 "\\def\\#{#}\\catcode`\\#=6\n";
1558 if (contains(docdir, '%')) {
1559 docdir = subst(docdir, "%", "\\%");
1560 os << "\\catcode`\\%=11"
1561 "\\def\\%{%}\\catcode`\\%=14\n";
1563 os << "\\makeatletter\n"
1564 << "\\def\\input@path{{"
1565 << docdir << "/}}\n"
1566 << "\\makeatother\n";
1570 // get parent macros (if this buffer has a parent) which will be
1571 // written at the document begin further down.
1572 MacroSet parentMacros;
1573 listParentMacros(parentMacros, features);
1575 // Write the preamble
1576 runparams.use_babel = params().writeLaTeX(os, features,
1577 d->filename.onlyPath());
1579 runparams.use_japanese = features.isRequired("japanese");
1585 os << "\\begin{document}\n";
1587 // output the parent macros
1588 MacroSet::iterator it = parentMacros.begin();
1589 MacroSet::iterator end = parentMacros.end();
1590 for (; it != end; ++it) {
1591 int num_lines = (*it)->write(os.os(), true);
1592 os.texrow().newlines(num_lines);
1595 } // output_preamble
1597 os.texrow().start(paragraphs().begin()->id(), 0);
1599 LYXERR(Debug::INFO, "preamble finished, now the body.");
1601 // if we are doing a real file with body, even if this is the
1602 // child of some other buffer, let's cut the link here.
1603 // This happens for example if only a child document is printed.
1604 Buffer const * save_parent = 0;
1605 if (output_preamble) {
1606 save_parent = d->parent();
1611 latexParagraphs(*this, text(), os, runparams);
1613 // Restore the parenthood if needed
1614 if (output_preamble)
1615 d->setParent(save_parent);
1617 // add this just in case after all the paragraphs
1620 if (output_preamble) {
1621 os << "\\end{document}\n";
1622 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1624 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1626 runparams_in.encoding = runparams.encoding;
1628 // Just to be sure. (Asger)
1629 os.texrow().newline();
1631 //for (int i = 0; i<d->texrow.rows(); i++) {
1633 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1634 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1637 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1638 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1642 void Buffer::makeDocBookFile(FileName const & fname,
1643 OutputParams const & runparams,
1644 OutputWhat output) const
1646 LYXERR(Debug::LATEX, "makeDocBookFile...");
1649 if (!openFileWrite(ofs, fname))
1652 // make sure we are ready to export
1653 // this needs to be done before we validate
1655 updateMacroInstances(OutputUpdate);
1657 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1661 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1665 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1666 OutputParams const & runparams,
1667 OutputWhat output) const
1669 LaTeXFeatures features(*this, params(), runparams);
1674 DocumentClass const & tclass = params().documentClass();
1675 string const top_element = tclass.latexname();
1677 bool const output_preamble =
1678 output == FullSource || output == OnlyPreamble;
1679 bool const output_body =
1680 output == FullSource || output == OnlyBody;
1682 if (output_preamble) {
1683 if (runparams.flavor == OutputParams::XML)
1684 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1687 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1690 if (! tclass.class_header().empty())
1691 os << from_ascii(tclass.class_header());
1692 else if (runparams.flavor == OutputParams::XML)
1693 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1694 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1696 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1698 docstring preamble = from_utf8(params().preamble);
1699 if (runparams.flavor != OutputParams::XML ) {
1700 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1701 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1702 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1703 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1706 string const name = runparams.nice
1707 ? changeExtension(absFileName(), ".sgml") : fname;
1708 preamble += features.getIncludedFiles(name);
1709 preamble += features.getLyXSGMLEntities();
1711 if (!preamble.empty()) {
1712 os << "\n [ " << preamble << " ]";
1718 string top = top_element;
1720 if (runparams.flavor == OutputParams::XML)
1721 top += params().language->code();
1723 top += params().language->code().substr(0, 2);
1726 if (!params().options.empty()) {
1728 top += params().options;
1731 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1732 << " file was created by LyX " << lyx_version
1733 << "\n See http://www.lyx.org/ for more information -->\n";
1735 params().documentClass().counters().reset();
1737 sgml::openTag(os, top);
1739 docbookParagraphs(text(), *this, os, runparams);
1740 sgml::closeTag(os, top_element);
1745 void Buffer::makeLyXHTMLFile(FileName const & fname,
1746 OutputParams const & runparams) const
1748 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1751 if (!openFileWrite(ofs, fname))
1754 // make sure we are ready to export
1755 // this has to be done before we validate
1756 updateBuffer(UpdateMaster, OutputUpdate);
1757 updateMacroInstances(OutputUpdate);
1759 writeLyXHTMLSource(ofs, runparams, FullSource);
1763 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1767 void Buffer::writeLyXHTMLSource(odocstream & os,
1768 OutputParams const & runparams,
1769 OutputWhat output) const
1771 LaTeXFeatures features(*this, params(), runparams);
1773 d->bibinfo_.makeCitationLabels(*this);
1775 bool const output_preamble =
1776 output == FullSource || output == OnlyPreamble;
1777 bool const output_body =
1778 output == FullSource || output == OnlyBody || output == IncludedFile;
1780 if (output_preamble) {
1781 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1782 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/2001/REC-MathML2-20010221/dtd/xhtml-math11-f.dtd\">\n"
1783 // FIXME Language should be set properly.
1784 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1786 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1787 // FIXME Presumably need to set this right
1788 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1790 docstring const & doctitle = features.htmlTitle();
1792 << (doctitle.empty() ?
1793 from_ascii("LyX Document") :
1794 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1797 docstring styles = features.getTClassHTMLPreamble();
1798 if (!styles.empty())
1799 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1801 styles = from_utf8(features.getPreambleSnippets());
1802 if (!styles.empty())
1803 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1805 // we will collect CSS information in a stream, and then output it
1806 // either here, as part of the header, or else in a separate file.
1807 odocstringstream css;
1808 styles = from_utf8(features.getCSSSnippets());
1809 if (!styles.empty())
1810 css << "/* LyX Provided Styles */\n" << styles << '\n';
1812 styles = features.getTClassHTMLStyles();
1813 if (!styles.empty())
1814 css << "/* Layout-provided Styles */\n" << styles << '\n';
1816 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1817 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1818 if (needfg || needbg) {
1819 css << "\nbody {\n";
1822 << from_ascii(X11hexname(params().fontcolor))
1825 css << " background-color: "
1826 << from_ascii(X11hexname(params().backgroundcolor))
1831 docstring const dstyles = css.str();
1832 if (!dstyles.empty()) {
1833 bool written = false;
1834 if (params().html_css_as_file) {
1835 // open a file for CSS info
1837 string const fcssname = addName(temppath(), "docstyle.css");
1838 FileName const fcssfile = FileName(fcssname);
1839 if (openFileWrite(ocss, fcssfile)) {
1843 // write link to header
1844 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1846 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1849 // we are here if the CSS is supposed to be written to the header
1850 // or if we failed to write it to an external file.
1852 os << "<style type='text/css'>\n"
1861 bool const output_body_tag = (output != IncludedFile);
1862 if (output_body_tag)
1865 params().documentClass().counters().reset();
1866 xhtmlParagraphs(text(), *this, xs, runparams);
1867 if (output_body_tag)
1871 if (output_preamble)
1876 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1877 // Other flags: -wall -v0 -x
1878 int Buffer::runChktex()
1882 // get LaTeX-Filename
1883 FileName const path(temppath());
1884 string const name = addName(path.absFileName(), latexName());
1885 string const org_path = filePath();
1887 PathChanger p(path); // path to LaTeX file
1888 message(_("Running chktex..."));
1890 // Generate the LaTeX file if neccessary
1891 OutputParams runparams(¶ms().encoding());
1892 runparams.flavor = OutputParams::LATEX;
1893 runparams.nice = false;
1894 runparams.linelen = lyxrc.plaintext_linelen;
1895 makeLaTeXFile(FileName(name), org_path, runparams);
1898 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1899 int const res = chktex.run(terr); // run chktex
1902 Alert::error(_("chktex failure"),
1903 _("Could not run chktex successfully."));
1904 } else if (res > 0) {
1905 ErrorList & errlist = d->errorLists["ChkTeX"];
1907 bufferErrors(terr, errlist);
1918 void Buffer::validate(LaTeXFeatures & features) const
1920 params().validate(features);
1922 for_each(paragraphs().begin(), paragraphs().end(),
1923 bind(&Paragraph::validate, _1, ref(features)));
1925 if (lyxerr.debugging(Debug::LATEX)) {
1926 features.showStruct();
1931 void Buffer::getLabelList(vector<docstring> & list) const
1933 // If this is a child document, use the master's list instead.
1935 masterBuffer()->getLabelList(list);
1940 Toc & toc = d->toc_backend.toc("label");
1941 TocIterator toc_it = toc.begin();
1942 TocIterator end = toc.end();
1943 for (; toc_it != end; ++toc_it) {
1944 if (toc_it->depth() == 0)
1945 list.push_back(toc_it->str());
1950 void Buffer::updateBibfilesCache(UpdateScope scope) const
1952 // FIXME This is probably unnecssary, given where we call this.
1953 // If this is a child document, use the parent's cache instead.
1954 if (parent() && scope != UpdateChildOnly) {
1955 masterBuffer()->updateBibfilesCache();
1959 d->bibfiles_cache_.clear();
1960 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1961 if (it->lyxCode() == BIBTEX_CODE) {
1962 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1963 support::FileNameList const bibfiles = inset.getBibFiles();
1964 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1967 } else if (it->lyxCode() == INCLUDE_CODE) {
1968 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1969 Buffer const * const incbuf = inset.getChildBuffer();
1972 support::FileNameList const & bibfiles =
1973 incbuf->getBibfilesCache(UpdateChildOnly);
1974 if (!bibfiles.empty()) {
1975 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1981 d->bibfile_cache_valid_ = true;
1982 d->bibinfo_cache_valid_ = false;
1983 d->cite_labels_valid_ = false;
1987 void Buffer::invalidateBibinfoCache() const
1989 d->bibinfo_cache_valid_ = false;
1990 d->cite_labels_valid_ = false;
1991 // also invalidate the cache for the parent buffer
1992 Buffer const * const pbuf = d->parent();
1994 pbuf->invalidateBibinfoCache();
1998 void Buffer::invalidateBibfileCache() const
2000 d->bibfile_cache_valid_ = false;
2001 d->bibinfo_cache_valid_ = false;
2002 d->cite_labels_valid_ = false;
2003 // also invalidate the cache for the parent buffer
2004 Buffer const * const pbuf = d->parent();
2006 pbuf->invalidateBibfileCache();
2010 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2012 // FIXME This is probably unnecessary, given where we call this.
2013 // If this is a child document, use the master's cache instead.
2014 Buffer const * const pbuf = masterBuffer();
2015 if (pbuf != this && scope != UpdateChildOnly)
2016 return pbuf->getBibfilesCache();
2018 if (!d->bibfile_cache_valid_)
2019 this->updateBibfilesCache(scope);
2021 return d->bibfiles_cache_;
2025 BiblioInfo const & Buffer::masterBibInfo() const
2027 Buffer const * const tmp = masterBuffer();
2029 return tmp->masterBibInfo();
2034 void Buffer::checkIfBibInfoCacheIsValid() const
2036 // use the master's cache
2037 Buffer const * const tmp = masterBuffer();
2039 tmp->checkIfBibInfoCacheIsValid();
2043 // compare the cached timestamps with the actual ones.
2044 FileNameList const & bibfiles_cache = getBibfilesCache();
2045 FileNameList::const_iterator ei = bibfiles_cache.begin();
2046 FileNameList::const_iterator en = bibfiles_cache.end();
2047 for (; ei != en; ++ ei) {
2048 time_t lastw = ei->lastModified();
2049 time_t prevw = d->bibfile_status_[*ei];
2050 if (lastw != prevw) {
2051 d->bibinfo_cache_valid_ = false;
2052 d->cite_labels_valid_ = false;
2053 d->bibfile_status_[*ei] = lastw;
2059 void Buffer::reloadBibInfoCache() const
2061 // use the master's cache
2062 Buffer const * const tmp = masterBuffer();
2064 tmp->reloadBibInfoCache();
2068 checkIfBibInfoCacheIsValid();
2069 if (d->bibinfo_cache_valid_)
2072 d->bibinfo_.clear();
2074 d->bibinfo_cache_valid_ = true;
2078 void Buffer::collectBibKeys() const
2080 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2081 it->collectBibKeys(it);
2085 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2087 Buffer const * tmp = masterBuffer();
2088 BiblioInfo & masterbi = (tmp == this) ?
2089 d->bibinfo_ : tmp->d->bibinfo_;
2090 masterbi.mergeBiblioInfo(bi);
2094 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2096 Buffer const * tmp = masterBuffer();
2097 BiblioInfo & masterbi = (tmp == this) ?
2098 d->bibinfo_ : tmp->d->bibinfo_;
2103 bool Buffer::citeLabelsValid() const
2105 return masterBuffer()->d->cite_labels_valid_;
2109 void Buffer::removeBiblioTempFiles() const
2111 // We remove files that contain LaTeX commands specific to the
2112 // particular bibliographic style being used, in order to avoid
2113 // LaTeX errors when we switch style.
2114 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2115 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2116 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2117 aux_file.removeFile();
2118 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2119 bbl_file.removeFile();
2120 // Also for the parent buffer
2121 Buffer const * const pbuf = parent();
2123 pbuf->removeBiblioTempFiles();
2127 bool Buffer::isDepClean(string const & name) const
2129 DepClean::const_iterator const it = d->dep_clean.find(name);
2130 if (it == d->dep_clean.end())
2136 void Buffer::markDepClean(string const & name)
2138 d->dep_clean[name] = true;
2142 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2145 // FIXME? if there is an Buffer LFUN that can be dispatched even
2146 // if internal, put a switch '(cmd.action)' here.
2152 switch (cmd.action()) {
2154 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2155 flag.setOnOff(isReadonly());
2158 // FIXME: There is need for a command-line import.
2159 //case LFUN_BUFFER_IMPORT:
2161 case LFUN_BUFFER_AUTO_SAVE:
2164 case LFUN_BUFFER_EXPORT_CUSTOM:
2165 // FIXME: Nothing to check here?
2168 case LFUN_BUFFER_EXPORT: {
2169 docstring const arg = cmd.argument();
2170 if (arg == "custom") {
2174 string format = to_utf8(arg);
2175 size_t pos = format.find(' ');
2176 if (pos != string::npos)
2177 format = format.substr(0, pos);
2178 enable = params().isExportable(format);
2180 flag.message(bformat(
2181 _("Don't know how to export to format: %1$s"), arg));
2185 case LFUN_BUFFER_CHKTEX:
2186 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2189 case LFUN_BUILD_PROGRAM:
2190 enable = params().isExportable("program");
2193 case LFUN_BRANCH_ADD:
2194 case LFUN_BRANCHES_RENAME:
2195 case LFUN_BUFFER_PRINT:
2196 // if no Buffer is present, then of course we won't be called!
2199 case LFUN_BUFFER_LANGUAGE:
2200 enable = !isReadonly();
2206 flag.setEnabled(enable);
2211 void Buffer::dispatch(string const & command, DispatchResult & result)
2213 return dispatch(lyxaction.lookupFunc(command), result);
2217 // NOTE We can end up here even if we have no GUI, because we are called
2218 // by LyX::exec to handled command-line requests. So we may need to check
2219 // whether we have a GUI or not. The boolean use_gui holds this information.
2220 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2223 // FIXME? if there is an Buffer LFUN that can be dispatched even
2224 // if internal, put a switch '(cmd.action())' here.
2225 dr.dispatched(false);
2228 string const argument = to_utf8(func.argument());
2229 // We'll set this back to false if need be.
2230 bool dispatched = true;
2231 undo().beginUndoGroup();
2233 switch (func.action()) {
2234 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2235 if (lyxvc().inUse())
2236 lyxvc().toggleReadOnly();
2238 setReadonly(!isReadonly());
2241 case LFUN_BUFFER_EXPORT: {
2242 ExportStatus const status = doExport(argument, false);
2243 dr.setError(status != ExportSuccess);
2244 if (status != ExportSuccess)
2245 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2250 case LFUN_BUILD_PROGRAM:
2251 doExport("program", true);
2254 case LFUN_BUFFER_CHKTEX:
2258 case LFUN_BUFFER_EXPORT_CUSTOM: {
2260 string command = split(argument, format_name, ' ');
2261 Format const * format = formats.getFormat(format_name);
2263 lyxerr << "Format \"" << format_name
2264 << "\" not recognized!"
2269 // The name of the file created by the conversion process
2272 // Output to filename
2273 if (format->name() == "lyx") {
2274 string const latexname = latexName(false);
2275 filename = changeExtension(latexname,
2276 format->extension());
2277 filename = addName(temppath(), filename);
2279 if (!writeFile(FileName(filename)))
2283 doExport(format_name, true, filename);
2286 // Substitute $$FName for filename
2287 if (!contains(command, "$$FName"))
2288 command = "( " + command + " ) < $$FName";
2289 command = subst(command, "$$FName", filename);
2291 // Execute the command in the background
2293 call.startscript(Systemcall::DontWait, command, filePath());
2297 // FIXME: There is need for a command-line import.
2299 case LFUN_BUFFER_IMPORT:
2304 case LFUN_BUFFER_AUTO_SAVE:
2306 resetAutosaveTimers();
2309 case LFUN_BRANCH_ADD: {
2310 docstring branch_name = func.argument();
2311 if (branch_name.empty()) {
2315 BranchList & branch_list = params().branchlist();
2316 vector<docstring> const branches =
2317 getVectorFromString(branch_name, branch_list.separator());
2319 for (vector<docstring>::const_iterator it = branches.begin();
2320 it != branches.end(); ++it) {
2322 Branch * branch = branch_list.find(branch_name);
2324 LYXERR0("Branch " << branch_name << " already exists.");
2328 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2330 branch_list.add(branch_name);
2331 branch = branch_list.find(branch_name);
2332 string const x11hexname = X11hexname(branch->color());
2333 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2334 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2336 dr.screenUpdate(Update::Force);
2344 case LFUN_BRANCHES_RENAME: {
2345 if (func.argument().empty())
2348 docstring const oldname = from_utf8(func.getArg(0));
2349 docstring const newname = from_utf8(func.getArg(1));
2350 InsetIterator it = inset_iterator_begin(inset());
2351 InsetIterator const end = inset_iterator_end(inset());
2352 bool success = false;
2353 for (; it != end; ++it) {
2354 if (it->lyxCode() == BRANCH_CODE) {
2355 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2356 if (ins.branch() == oldname) {
2357 undo().recordUndo(CursorData(it));
2358 ins.rename(newname);
2363 if (it->lyxCode() == INCLUDE_CODE) {
2364 // get buffer of external file
2365 InsetInclude const & ins =
2366 static_cast<InsetInclude const &>(*it);
2367 Buffer * child = ins.getChildBuffer();
2370 child->dispatch(func, dr);
2375 dr.screenUpdate(Update::Force);
2376 dr.forceBufferUpdate();
2381 case LFUN_BUFFER_PRINT: {
2382 // we'll assume there's a problem until we succeed
2384 string target = func.getArg(0);
2385 string target_name = func.getArg(1);
2386 string command = func.getArg(2);
2389 || target_name.empty()
2390 || command.empty()) {
2391 LYXERR0("Unable to parse " << func.argument());
2392 docstring const msg =
2393 bformat(_("Unable to parse \"%1$s\""), func.argument());
2397 if (target != "printer" && target != "file") {
2398 LYXERR0("Unrecognized target \"" << target << '"');
2399 docstring const msg =
2400 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2405 if (!doExport("dvi", true)) {
2406 showPrintError(absFileName());
2407 dr.setMessage(_("Error exporting to DVI."));
2411 // Push directory path.
2412 string const path = temppath();
2413 // Prevent the compiler from optimizing away p
2417 // there are three cases here:
2418 // 1. we print to a file
2419 // 2. we print directly to a printer
2420 // 3. we print using a spool command (print to file first)
2423 string const dviname = changeExtension(latexName(true), "dvi");
2425 if (target == "printer") {
2426 if (!lyxrc.print_spool_command.empty()) {
2427 // case 3: print using a spool
2428 string const psname = changeExtension(dviname,".ps");
2429 command += ' ' + lyxrc.print_to_file
2432 + quoteName(dviname);
2434 string command2 = lyxrc.print_spool_command + ' ';
2435 if (target_name != "default") {
2436 command2 += lyxrc.print_spool_printerprefix
2440 command2 += quoteName(psname);
2442 // If successful, then spool command
2443 res = one.startscript(Systemcall::Wait, command,
2447 // If there's no GUI, we have to wait on this command. Otherwise,
2448 // LyX deletes the temporary directory, and with it the spooled
2449 // file, before it can be printed!!
2450 Systemcall::Starttype stype = use_gui ?
2451 Systemcall::DontWait : Systemcall::Wait;
2452 res = one.startscript(stype, command2,
2456 // case 2: print directly to a printer
2457 if (target_name != "default")
2458 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2460 Systemcall::Starttype stype = use_gui ?
2461 Systemcall::DontWait : Systemcall::Wait;
2462 res = one.startscript(stype, command +
2463 quoteName(dviname), filePath());
2467 // case 1: print to a file
2468 FileName const filename(makeAbsPath(target_name, filePath()));
2469 FileName const dvifile(makeAbsPath(dviname, path));
2470 if (filename.exists()) {
2471 docstring text = bformat(
2472 _("The file %1$s already exists.\n\n"
2473 "Do you want to overwrite that file?"),
2474 makeDisplayPath(filename.absFileName()));
2475 if (Alert::prompt(_("Overwrite file?"),
2476 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2479 command += ' ' + lyxrc.print_to_file
2480 + quoteName(filename.toFilesystemEncoding())
2482 + quoteName(dvifile.toFilesystemEncoding());
2484 Systemcall::Starttype stype = use_gui ?
2485 Systemcall::DontWait : Systemcall::Wait;
2486 res = one.startscript(stype, command, filePath());
2492 dr.setMessage(_("Error running external commands."));
2493 showPrintError(absFileName());
2502 dr.dispatched(dispatched);
2503 undo().endUndoGroup();
2507 void Buffer::changeLanguage(Language const * from, Language const * to)
2509 LASSERT(from, /**/);
2512 for_each(par_iterator_begin(),
2514 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2518 bool Buffer::isMultiLingual() const
2520 ParConstIterator end = par_iterator_end();
2521 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2522 if (it->isMultiLingual(params()))
2529 std::set<Language const *> Buffer::getLanguages() const
2531 std::set<Language const *> languages;
2532 getLanguages(languages);
2537 void Buffer::getLanguages(std::set<Language const *> & languages) const
2539 ParConstIterator end = par_iterator_end();
2540 // add the buffer language, even if it's not actively used
2541 languages.insert(language());
2542 // iterate over the paragraphs
2543 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2544 it->getLanguages(languages);
2546 ListOfBuffers clist = getDescendents();
2547 ListOfBuffers::const_iterator cit = clist.begin();
2548 ListOfBuffers::const_iterator const cen = clist.end();
2549 for (; cit != cen; ++cit)
2550 (*cit)->getLanguages(languages);
2554 DocIterator Buffer::getParFromID(int const id) const
2556 Buffer * buf = const_cast<Buffer *>(this);
2558 // John says this is called with id == -1 from undo
2559 lyxerr << "getParFromID(), id: " << id << endl;
2560 return doc_iterator_end(buf);
2563 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2564 if (it.paragraph().id() == id)
2567 return doc_iterator_end(buf);
2571 bool Buffer::hasParWithID(int const id) const
2573 return !getParFromID(id).atEnd();
2577 ParIterator Buffer::par_iterator_begin()
2579 return ParIterator(doc_iterator_begin(this));
2583 ParIterator Buffer::par_iterator_end()
2585 return ParIterator(doc_iterator_end(this));
2589 ParConstIterator Buffer::par_iterator_begin() const
2591 return ParConstIterator(doc_iterator_begin(this));
2595 ParConstIterator Buffer::par_iterator_end() const
2597 return ParConstIterator(doc_iterator_end(this));
2601 Language const * Buffer::language() const
2603 return params().language;
2607 docstring const Buffer::B_(string const & l10n) const
2609 return params().B_(l10n);
2613 bool Buffer::isClean() const
2615 return d->lyx_clean;
2619 bool Buffer::isExternallyModified(CheckMethod method) const
2621 LASSERT(d->filename.exists(), /**/);
2622 // if method == timestamp, check timestamp before checksum
2623 return (method == checksum_method
2624 || d->timestamp_ != d->filename.lastModified())
2625 && d->checksum_ != d->filename.checksum();
2629 void Buffer::saveCheckSum() const
2631 FileName const & file = d->filename;
2634 if (file.exists()) {
2635 d->timestamp_ = file.lastModified();
2636 d->checksum_ = file.checksum();
2638 // in the case of save to a new file.
2645 void Buffer::markClean() const
2647 if (!d->lyx_clean) {
2648 d->lyx_clean = true;
2651 // if the .lyx file has been saved, we don't need an
2653 d->bak_clean = true;
2654 d->undo_.markDirty();
2658 void Buffer::setUnnamed(bool flag)
2664 bool Buffer::isUnnamed() const
2671 /// Don't check unnamed, here: isInternal() is used in
2672 /// newBuffer(), where the unnamed flag has not been set by anyone
2673 /// yet. Also, for an internal buffer, there should be no need for
2674 /// retrieving fileName() nor for checking if it is unnamed or not.
2675 bool Buffer::isInternal() const
2677 return d->internal_buffer;
2681 void Buffer::setInternal(bool flag)
2683 d->internal_buffer = flag;
2687 void Buffer::markDirty()
2690 d->lyx_clean = false;
2693 d->bak_clean = false;
2695 DepClean::iterator it = d->dep_clean.begin();
2696 DepClean::const_iterator const end = d->dep_clean.end();
2698 for (; it != end; ++it)
2703 FileName Buffer::fileName() const
2709 string Buffer::absFileName() const
2711 return d->filename.absFileName();
2715 string Buffer::filePath() const
2717 int last = d->filename.onlyPath().absFileName().length() - 1;
2719 return d->filename.onlyPath().absFileName()[last] == '/'
2720 ? d->filename.onlyPath().absFileName()
2721 : d->filename.onlyPath().absFileName() + "/";
2725 bool Buffer::isReadonly() const
2727 return d->read_only;
2731 void Buffer::setParent(Buffer const * buffer)
2733 // Avoids recursive include.
2734 d->setParent(buffer == this ? 0 : buffer);
2739 Buffer const * Buffer::parent() const
2745 ListOfBuffers Buffer::allRelatives() const
2747 ListOfBuffers lb = masterBuffer()->getDescendents();
2748 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2753 Buffer const * Buffer::masterBuffer() const
2755 // FIXME Should be make sure we are not in some kind
2756 // of recursive include? A -> B -> A will crash this.
2757 Buffer const * const pbuf = d->parent();
2761 return pbuf->masterBuffer();
2765 bool Buffer::isChild(Buffer * child) const
2767 return d->children_positions.find(child) != d->children_positions.end();
2771 DocIterator Buffer::firstChildPosition(Buffer const * child)
2773 Impl::BufferPositionMap::iterator it;
2774 it = d->children_positions.find(child);
2775 if (it == d->children_positions.end())
2776 return DocIterator(this);
2781 bool Buffer::hasChildren() const
2783 return !d->children_positions.empty();
2787 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2789 // loop over children
2790 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2791 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2792 for (; it != end; ++it) {
2793 Buffer * child = const_cast<Buffer *>(it->first);
2795 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2796 if (bit != clist.end())
2798 clist.push_back(child);
2800 // there might be grandchildren
2801 child->collectChildren(clist, true);
2806 ListOfBuffers Buffer::getChildren() const
2809 collectChildren(v, false);
2810 // Make sure we have not included ourselves.
2811 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2812 if (bit != v.end()) {
2813 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2820 ListOfBuffers Buffer::getDescendents() const
2823 collectChildren(v, true);
2824 // Make sure we have not included ourselves.
2825 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2826 if (bit != v.end()) {
2827 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2834 template<typename M>
2835 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2840 typename M::const_iterator it = m.lower_bound(x);
2841 if (it == m.begin())
2849 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2850 DocIterator const & pos) const
2852 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2854 // if paragraphs have no macro context set, pos will be empty
2858 // we haven't found anything yet
2859 DocIterator bestPos = owner_->par_iterator_begin();
2860 MacroData const * bestData = 0;
2862 // find macro definitions for name
2863 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2864 if (nameIt != macros.end()) {
2865 // find last definition in front of pos or at pos itself
2866 PositionScopeMacroMap::const_iterator it
2867 = greatest_below(nameIt->second, pos);
2868 if (it != nameIt->second.end()) {
2870 // scope ends behind pos?
2871 if (pos < it->second.first) {
2872 // Looks good, remember this. If there
2873 // is no external macro behind this,
2874 // we found the right one already.
2875 bestPos = it->first;
2876 bestData = &it->second.second;
2880 // try previous macro if there is one
2881 if (it == nameIt->second.begin())
2888 // find macros in included files
2889 PositionScopeBufferMap::const_iterator it
2890 = greatest_below(position_to_children, pos);
2891 if (it == position_to_children.end())
2892 // no children before
2896 // do we know something better (i.e. later) already?
2897 if (it->first < bestPos )
2900 // scope ends behind pos?
2901 if (pos < it->second.first
2902 && (cloned_buffer_ ||
2903 theBufferList().isLoaded(it->second.second))) {
2904 // look for macro in external file
2906 MacroData const * data
2907 = it->second.second->getMacro(name, false);
2910 bestPos = it->first;
2916 // try previous file if there is one
2917 if (it == position_to_children.begin())
2922 // return the best macro we have found
2927 MacroData const * Buffer::getMacro(docstring const & name,
2928 DocIterator const & pos, bool global) const
2933 // query buffer macros
2934 MacroData const * data = d->getBufferMacro(name, pos);
2938 // If there is a master buffer, query that
2939 Buffer const * const pbuf = d->parent();
2941 d->macro_lock = true;
2942 MacroData const * macro = pbuf->getMacro(
2943 name, *this, false);
2944 d->macro_lock = false;
2950 data = MacroTable::globalMacros().get(name);
2959 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2961 // set scope end behind the last paragraph
2962 DocIterator scope = par_iterator_begin();
2963 scope.pit() = scope.lastpit() + 1;
2965 return getMacro(name, scope, global);
2969 MacroData const * Buffer::getMacro(docstring const & name,
2970 Buffer const & child, bool global) const
2972 // look where the child buffer is included first
2973 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2974 if (it == d->children_positions.end())
2977 // check for macros at the inclusion position
2978 return getMacro(name, it->second, global);
2982 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2984 pit_type const lastpit = it.lastpit();
2986 // look for macros in each paragraph
2987 while (it.pit() <= lastpit) {
2988 Paragraph & par = it.paragraph();
2990 // iterate over the insets of the current paragraph
2991 InsetList const & insets = par.insetList();
2992 InsetList::const_iterator iit = insets.begin();
2993 InsetList::const_iterator end = insets.end();
2994 for (; iit != end; ++iit) {
2995 it.pos() = iit->pos;
2997 // is it a nested text inset?
2998 if (iit->inset->asInsetText()) {
2999 // Inset needs its own scope?
3000 InsetText const * itext = iit->inset->asInsetText();
3001 bool newScope = itext->isMacroScope();
3003 // scope which ends just behind the inset
3004 DocIterator insetScope = it;
3007 // collect macros in inset
3008 it.push_back(CursorSlice(*iit->inset));
3009 updateMacros(it, newScope ? insetScope : scope);
3014 if (iit->inset->asInsetTabular()) {
3015 CursorSlice slice(*iit->inset);
3016 size_t const numcells = slice.nargs();
3017 for (; slice.idx() < numcells; slice.forwardIdx()) {
3018 it.push_back(slice);
3019 updateMacros(it, scope);
3025 // is it an external file?
3026 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3027 // get buffer of external file
3028 InsetInclude const & inset =
3029 static_cast<InsetInclude const &>(*iit->inset);
3031 Buffer * child = inset.getChildBuffer();
3036 // register its position, but only when it is
3037 // included first in the buffer
3038 if (children_positions.find(child) ==
3039 children_positions.end())
3040 children_positions[child] = it;
3042 // register child with its scope
3043 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3047 InsetMath * im = iit->inset->asInsetMath();
3048 if (doing_export && im) {
3049 InsetMathHull * hull = im->asHullInset();
3051 hull->recordLocation(it);
3054 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3058 MathMacroTemplate & macroTemplate =
3059 *iit->inset->asInsetMath()->asMacroTemplate();
3060 MacroContext mc(owner_, it);
3061 macroTemplate.updateToContext(mc);
3064 bool valid = macroTemplate.validMacro();
3065 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3066 // then the BufferView's cursor will be invalid in
3067 // some cases which leads to crashes.
3072 // FIXME (Abdel), I don't understandt why we pass 'it' here
3073 // instead of 'macroTemplate' defined above... is this correct?
3074 macros[macroTemplate.name()][it] =
3075 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3085 void Buffer::updateMacros() const
3090 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3092 // start with empty table
3094 d->children_positions.clear();
3095 d->position_to_children.clear();
3097 // Iterate over buffer, starting with first paragraph
3098 // The scope must be bigger than any lookup DocIterator
3099 // later. For the global lookup, lastpit+1 is used, hence
3100 // we use lastpit+2 here.
3101 DocIterator it = par_iterator_begin();
3102 DocIterator outerScope = it;
3103 outerScope.pit() = outerScope.lastpit() + 2;
3104 d->updateMacros(it, outerScope);
3108 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3110 InsetIterator it = inset_iterator_begin(inset());
3111 InsetIterator const end = inset_iterator_end(inset());
3112 for (; it != end; ++it) {
3113 if (it->lyxCode() == BRANCH_CODE) {
3114 InsetBranch & br = static_cast<InsetBranch &>(*it);
3115 docstring const name = br.branch();
3116 if (!from_master && !params().branchlist().find(name))
3117 result.push_back(name);
3118 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3119 result.push_back(name);
3122 if (it->lyxCode() == INCLUDE_CODE) {
3123 // get buffer of external file
3124 InsetInclude const & ins =
3125 static_cast<InsetInclude const &>(*it);
3126 Buffer * child = ins.getChildBuffer();
3129 child->getUsedBranches(result, true);
3132 // remove duplicates
3137 void Buffer::updateMacroInstances(UpdateType utype) const
3139 LYXERR(Debug::MACROS, "updateMacroInstances for "
3140 << d->filename.onlyFileName());
3141 DocIterator it = doc_iterator_begin(this);
3143 DocIterator const end = doc_iterator_end(this);
3144 for (; it != end; it.forwardInset()) {
3145 // look for MathData cells in InsetMathNest insets
3146 InsetMath * minset = it.nextInset()->asInsetMath();
3150 // update macro in all cells of the InsetMathNest
3151 DocIterator::idx_type n = minset->nargs();
3152 MacroContext mc = MacroContext(this, it);
3153 for (DocIterator::idx_type i = 0; i < n; ++i) {
3154 MathData & data = minset->cell(i);
3155 data.updateMacros(0, mc, utype);
3161 void Buffer::listMacroNames(MacroNameSet & macros) const
3166 d->macro_lock = true;
3168 // loop over macro names
3169 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3170 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3171 for (; nameIt != nameEnd; ++nameIt)
3172 macros.insert(nameIt->first);
3174 // loop over children
3175 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3176 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3177 for (; it != end; ++it)
3178 it->first->listMacroNames(macros);
3181 Buffer const * const pbuf = d->parent();
3183 pbuf->listMacroNames(macros);
3185 d->macro_lock = false;
3189 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3191 Buffer const * const pbuf = d->parent();
3196 pbuf->listMacroNames(names);
3199 MacroNameSet::iterator it = names.begin();
3200 MacroNameSet::iterator end = names.end();
3201 for (; it != end; ++it) {
3203 MacroData const * data =
3204 pbuf->getMacro(*it, *this, false);
3206 macros.insert(data);
3208 // we cannot access the original MathMacroTemplate anymore
3209 // here to calls validate method. So we do its work here manually.
3210 // FIXME: somehow make the template accessible here.
3211 if (data->optionals() > 0)
3212 features.require("xargs");
3218 Buffer::References & Buffer::references(docstring const & label)
3221 return const_cast<Buffer *>(masterBuffer())->references(label);
3223 RefCache::iterator it = d->ref_cache_.find(label);
3224 if (it != d->ref_cache_.end())
3225 return it->second.second;
3227 static InsetLabel const * dummy_il = 0;
3228 static References const dummy_refs;
3229 it = d->ref_cache_.insert(
3230 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3231 return it->second.second;
3235 Buffer::References const & Buffer::references(docstring const & label) const
3237 return const_cast<Buffer *>(this)->references(label);
3241 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3243 masterBuffer()->d->ref_cache_[label].first = il;
3247 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3249 return masterBuffer()->d->ref_cache_[label].first;
3253 void Buffer::clearReferenceCache() const
3256 d->ref_cache_.clear();
3260 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3263 //FIXME: This does not work for child documents yet.
3264 LASSERT(code == CITE_CODE, /**/);
3266 reloadBibInfoCache();
3268 // Check if the label 'from' appears more than once
3269 BiblioInfo const & keys = masterBibInfo();
3270 BiblioInfo::const_iterator bit = keys.begin();
3271 BiblioInfo::const_iterator bend = keys.end();
3272 vector<docstring> labels;
3274 for (; bit != bend; ++bit)
3276 labels.push_back(bit->first);
3278 if (count(labels.begin(), labels.end(), from) > 1)
3281 string const paramName = "key";
3282 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3283 if (it->lyxCode() == code) {
3284 InsetCommand * inset = it->asInsetCommand();
3287 docstring const oldValue = inset->getParam(paramName);
3288 if (oldValue == from)
3289 inset->setParam(paramName, to);
3295 void Buffer::getSourceCode(odocstream & os, string const format,
3296 pit_type par_begin, pit_type par_end,
3297 OutputWhat output) const
3299 OutputParams runparams(¶ms().encoding());
3300 runparams.nice = true;
3301 runparams.flavor = params().getOutputFlavor(format);
3302 runparams.linelen = lyxrc.plaintext_linelen;
3303 // No side effect of file copying and image conversion
3304 runparams.dryrun = true;
3306 if (output == CurrentParagraph) {
3307 runparams.par_begin = par_begin;
3308 runparams.par_end = par_end;
3309 if (par_begin + 1 == par_end) {
3311 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3315 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3316 convert<docstring>(par_begin),
3317 convert<docstring>(par_end - 1))
3320 // output paragraphs
3321 if (runparams.flavor == OutputParams::LYX) {
3322 Paragraph const & par = text().paragraphs()[par_begin];
3324 depth_type dt = par.getDepth();
3325 par.write(ods, params(), dt);
3326 os << from_utf8(ods.str());
3327 } else if (runparams.flavor == OutputParams::HTML) {
3329 setMathFlavor(runparams);
3330 xhtmlParagraphs(text(), *this, xs, runparams);
3331 } else if (runparams.flavor == OutputParams::TEXT) {
3333 // FIXME Handles only one paragraph, unlike the others.
3334 // Probably should have some routine with a signature like them.
3335 writePlaintextParagraph(*this,
3336 text().paragraphs()[par_begin], os, runparams, dummy);
3337 } else if (params().isDocBook()) {
3338 docbookParagraphs(text(), *this, os, runparams);
3340 // We need to validate the Buffer params' features here
3341 // in order to know if we should output polyglossia
3342 // macros (instead of babel macros)
3343 LaTeXFeatures features(*this, params(), runparams);
3344 params().validate(features);
3345 runparams.use_polyglossia = features.usePolyglossia();
3350 // latex or literate
3351 otexstream ots(os, texrow);
3352 latexParagraphs(*this, text(), ots, runparams);
3356 if (output == FullSource)
3357 os << _("Preview source code");
3358 else if (output == OnlyPreamble)
3359 os << _("Preview preamble");
3360 else if (output == OnlyBody)
3361 os << _("Preview body");
3363 if (runparams.flavor == OutputParams::LYX) {
3365 if (output == FullSource)
3367 else if (output == OnlyPreamble)
3368 params().writeFile(ods);
3369 else if (output == OnlyBody)
3371 os << from_utf8(ods.str());
3372 } else if (runparams.flavor == OutputParams::HTML) {
3373 writeLyXHTMLSource(os, runparams, output);
3374 } else if (runparams.flavor == OutputParams::TEXT) {
3375 if (output == OnlyPreamble) {
3376 os << _("% Plaintext does not have a preamble.");
3378 writePlaintextFile(*this, os, runparams);
3379 } else if (params().isDocBook()) {
3380 writeDocBookSource(os, absFileName(), runparams, output);
3382 // latex or literate
3384 d->texrow.newline();
3385 d->texrow.newline();
3386 otexstream ots(os, d->texrow);
3387 writeLaTeXSource(ots, string(), runparams, output);
3393 ErrorList & Buffer::errorList(string const & type) const
3395 return d->errorLists[type];
3399 void Buffer::updateTocItem(std::string const & type,
3400 DocIterator const & dit) const
3403 d->gui_->updateTocItem(type, dit);
3407 void Buffer::structureChanged() const
3410 d->gui_->structureChanged();
3414 void Buffer::errors(string const & err, bool from_master) const
3417 d->gui_->errors(err, from_master);
3421 void Buffer::message(docstring const & msg) const
3424 d->gui_->message(msg);
3428 void Buffer::setBusy(bool on) const
3431 d->gui_->setBusy(on);
3435 void Buffer::updateTitles() const
3438 d->wa_->updateTitles();
3442 void Buffer::resetAutosaveTimers() const
3445 d->gui_->resetAutosaveTimers();
3449 bool Buffer::hasGuiDelegate() const
3455 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3464 class AutoSaveBuffer : public ForkedProcess {
3467 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3468 : buffer_(buffer), fname_(fname) {}
3470 virtual shared_ptr<ForkedProcess> clone() const
3472 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3477 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3478 from_utf8(fname_.absFileName())));
3479 return run(DontWait);
3483 virtual int generateChild();
3485 Buffer const & buffer_;
3490 int AutoSaveBuffer::generateChild()
3492 #if defined(__APPLE__)
3493 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3494 * We should use something else like threads.
3496 * Since I do not know how to determine at run time what is the OS X
3497 * version, I just disable forking altogether for now (JMarc)
3499 pid_t const pid = -1;
3501 // tmp_ret will be located (usually) in /tmp
3502 // will that be a problem?
3503 // Note that this calls ForkedCalls::fork(), so it's
3504 // ok cross-platform.
3505 pid_t const pid = fork();
3506 // If you want to debug the autosave
3507 // you should set pid to -1, and comment out the fork.
3508 if (pid != 0 && pid != -1)
3512 // pid = -1 signifies that lyx was unable
3513 // to fork. But we will do the save
3515 bool failed = false;
3516 FileName const tmp_ret = FileName::tempName("lyxauto");
3517 if (!tmp_ret.empty()) {
3518 buffer_.writeFile(tmp_ret);
3519 // assume successful write of tmp_ret
3520 if (!tmp_ret.moveTo(fname_))
3526 // failed to write/rename tmp_ret so try writing direct
3527 if (!buffer_.writeFile(fname_)) {
3528 // It is dangerous to do this in the child,
3529 // but safe in the parent, so...
3530 if (pid == -1) // emit message signal.
3531 buffer_.message(_("Autosave failed!"));
3535 if (pid == 0) // we are the child so...
3544 FileName Buffer::getEmergencyFileName() const
3546 return FileName(d->filename.absFileName() + ".emergency");
3550 FileName Buffer::getAutosaveFileName() const
3552 // if the document is unnamed try to save in the backup dir, else
3553 // in the default document path, and as a last try in the filePath,
3554 // which will most often be the temporary directory
3557 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3558 : lyxrc.backupdir_path;
3559 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3562 string const fname = "#" + d->filename.onlyFileName() + "#";
3564 return makeAbsPath(fname, fpath);
3568 void Buffer::removeAutosaveFile() const
3570 FileName const f = getAutosaveFileName();
3576 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3578 FileName const newauto = getAutosaveFileName();
3580 if (newauto != oldauto && oldauto.exists())
3581 if (!oldauto.moveTo(newauto))
3582 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3586 bool Buffer::autoSave() const
3588 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3589 if (buf->d->bak_clean || isReadonly())
3592 message(_("Autosaving current document..."));
3593 buf->d->bak_clean = true;
3595 FileName const fname = getAutosaveFileName();
3596 if (d->cloned_buffer_) {
3597 // If this buffer is cloned, we assume that
3598 // we are running in a separate thread already.
3599 FileName const tmp_ret = FileName::tempName("lyxauto");
3600 if (!tmp_ret.empty()) {
3602 // assume successful write of tmp_ret
3603 if (tmp_ret.moveTo(fname))
3606 // failed to write/rename tmp_ret so try writing direct
3607 return writeFile(fname);
3609 /// This function is deprecated as the frontend needs to take care
3610 /// of cloning the buffer and autosaving it in another thread. It
3611 /// is still here to allow (QT_VERSION < 0x040400).
3612 AutoSaveBuffer autosave(*this, fname);
3619 // helper class, to guarantee this gets reset properly
3620 class Buffer::MarkAsExporting {
3622 MarkAsExporting(Buffer const * buf) : buf_(buf)
3624 LASSERT(buf_, /* */);
3625 buf_->setExportStatus(true);
3629 buf_->setExportStatus(false);
3632 Buffer const * const buf_;
3637 void Buffer::setExportStatus(bool e) const
3639 d->doing_export = e;
3640 ListOfBuffers clist = getDescendents();
3641 ListOfBuffers::const_iterator cit = clist.begin();
3642 ListOfBuffers::const_iterator const cen = clist.end();
3643 for (; cit != cen; ++cit)
3644 (*cit)->d->doing_export = e;
3648 bool Buffer::isExporting() const
3650 return d->doing_export;
3654 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3658 return doExport(target, put_in_tempdir, result_file);
3661 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3662 string & result_file) const
3664 bool const update_unincluded =
3665 params().maintain_unincluded_children
3666 && !params().getIncludedChildren().empty();
3668 // (1) export with all included children (omit \includeonly)
3669 if (update_unincluded) {
3670 ExportStatus const status =
3671 doExport(target, put_in_tempdir, true, result_file);
3672 if (status != ExportSuccess)
3675 // (2) export with included children only
3676 return doExport(target, put_in_tempdir, false, result_file);
3680 void Buffer::setMathFlavor(OutputParams & op) const
3682 switch (params().html_math_output) {
3683 case BufferParams::MathML:
3684 op.math_flavor = OutputParams::MathAsMathML;
3686 case BufferParams::HTML:
3687 op.math_flavor = OutputParams::MathAsHTML;
3689 case BufferParams::Images:
3690 op.math_flavor = OutputParams::MathAsImages;
3692 case BufferParams::LaTeX:
3693 op.math_flavor = OutputParams::MathAsLaTeX;
3699 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3700 bool includeall, string & result_file) const
3702 LYXERR(Debug::FILES, "target=" << target);
3703 OutputParams runparams(¶ms().encoding());
3704 string format = target;
3705 string dest_filename;
3706 size_t pos = target.find(' ');
3707 if (pos != string::npos) {
3708 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3709 format = target.substr(0, pos);
3710 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3711 FileName(dest_filename).onlyPath().createPath();
3712 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3714 MarkAsExporting exporting(this);
3715 string backend_format;
3716 runparams.flavor = OutputParams::LATEX;
3717 runparams.linelen = lyxrc.plaintext_linelen;
3718 runparams.includeall = includeall;
3719 vector<string> backs = params().backends();
3720 Converters converters = theConverters();
3721 bool need_nice_file = false;
3722 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3723 // Get shortest path to format
3724 converters.buildGraph();
3725 Graph::EdgePath path;
3726 for (vector<string>::const_iterator it = backs.begin();
3727 it != backs.end(); ++it) {
3728 Graph::EdgePath p = converters.getPath(*it, format);
3729 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3730 backend_format = *it;
3735 if (!put_in_tempdir) {
3736 // Only show this alert if this is an export to a non-temporary
3737 // file (not for previewing).
3738 Alert::error(_("Couldn't export file"), bformat(
3739 _("No information for exporting the format %1$s."),
3740 formats.prettyName(format)));
3742 return ExportNoPathToFormat;
3744 runparams.flavor = converters.getFlavor(path, this);
3745 Graph::EdgePath::const_iterator it = path.begin();
3746 Graph::EdgePath::const_iterator en = path.end();
3747 for (; it != en; ++it)
3748 if (theConverters().get(*it).nice) {
3749 need_nice_file = true;
3754 backend_format = format;
3755 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3756 // FIXME: Don't hardcode format names here, but use a flag
3757 if (backend_format == "pdflatex")
3758 runparams.flavor = OutputParams::PDFLATEX;
3759 else if (backend_format == "luatex")
3760 runparams.flavor = OutputParams::LUATEX;
3761 else if (backend_format == "dviluatex")
3762 runparams.flavor = OutputParams::DVILUATEX;
3763 else if (backend_format == "xetex")
3764 runparams.flavor = OutputParams::XETEX;
3767 string filename = latexName(false);
3768 filename = addName(temppath(), filename);
3769 filename = changeExtension(filename,
3770 formats.extension(backend_format));
3771 LYXERR(Debug::FILES, "filename=" << filename);
3773 // Plain text backend
3774 if (backend_format == "text") {
3775 runparams.flavor = OutputParams::TEXT;
3776 writePlaintextFile(*this, FileName(filename), runparams);
3779 else if (backend_format == "xhtml") {
3780 runparams.flavor = OutputParams::HTML;
3781 setMathFlavor(runparams);
3782 makeLyXHTMLFile(FileName(filename), runparams);
3783 } else if (backend_format == "lyx")
3784 writeFile(FileName(filename));
3786 else if (params().isDocBook()) {
3787 runparams.nice = !put_in_tempdir;
3788 makeDocBookFile(FileName(filename), runparams);
3791 else if (backend_format == format || need_nice_file) {
3792 runparams.nice = true;
3793 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3794 if (d->cloned_buffer_)
3795 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3798 } else if (!lyxrc.tex_allows_spaces
3799 && contains(filePath(), ' ')) {
3800 Alert::error(_("File name error"),
3801 _("The directory path to the document cannot contain spaces."));
3802 return ExportTexPathHasSpaces;
3804 runparams.nice = false;
3805 bool const success = makeLaTeXFile(
3806 FileName(filename), filePath(), runparams);
3807 if (d->cloned_buffer_)
3808 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3813 string const error_type = (format == "program")
3814 ? "Build" : params().bufferFormat();
3815 ErrorList & error_list = d->errorLists[error_type];
3816 string const ext = formats.extension(format);
3817 FileName const tmp_result_file(changeExtension(filename, ext));
3818 bool const success = converters.convert(this, FileName(filename),
3819 tmp_result_file, FileName(absFileName()), backend_format, format,
3822 // Emit the signal to show the error list or copy it back to the
3823 // cloned Buffer so that it can be emitted afterwards.
3824 if (format != backend_format) {
3825 if (d->cloned_buffer_) {
3826 d->cloned_buffer_->d->errorLists[error_type] =
3827 d->errorLists[error_type];
3830 // also to the children, in case of master-buffer-view
3831 ListOfBuffers clist = getDescendents();
3832 ListOfBuffers::const_iterator cit = clist.begin();
3833 ListOfBuffers::const_iterator const cen = clist.end();
3834 for (; cit != cen; ++cit) {
3835 if (d->cloned_buffer_) {
3836 // Enable reverse search by copying back the
3837 // texrow object to the cloned buffer.
3838 // FIXME: this is not thread safe.
3839 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3840 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3841 (*cit)->d->errorLists[error_type];
3843 (*cit)->errors(error_type, true);
3847 if (d->cloned_buffer_) {
3848 // Enable reverse dvi or pdf to work by copying back the texrow
3849 // object to the cloned buffer.
3850 // FIXME: There is a possibility of concurrent access to texrow
3851 // here from the main GUI thread that should be securized.
3852 d->cloned_buffer_->d->texrow = d->texrow;
3853 string const error_type = params().bufferFormat();
3854 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3858 return ExportConverterError;
3860 if (put_in_tempdir) {
3861 result_file = tmp_result_file.absFileName();
3862 return ExportSuccess;
3865 if (dest_filename.empty())
3866 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3868 result_file = dest_filename;
3869 // We need to copy referenced files (e. g. included graphics
3870 // if format == "dvi") to the result dir.
3871 vector<ExportedFile> const files =
3872 runparams.exportdata->externalFiles(format);
3873 string const dest = runparams.export_folder.empty() ?
3874 onlyPath(result_file) : runparams.export_folder;
3875 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3876 : force_overwrite == ALL_FILES;
3877 CopyStatus status = use_force ? FORCE : SUCCESS;
3879 vector<ExportedFile>::const_iterator it = files.begin();
3880 vector<ExportedFile>::const_iterator const en = files.end();
3881 for (; it != en && status != CANCEL; ++it) {
3882 string const fmt = formats.getFormatFromFile(it->sourceName);
3883 string fixedName = it->exportName;
3884 if (!runparams.export_folder.empty()) {
3885 // Relative pathnames starting with ../ will be sanitized
3886 // if exporting to a different folder
3887 while (fixedName.substr(0, 3) == "../")
3888 fixedName = fixedName.substr(3, fixedName.length() - 3);
3890 FileName fixedFileName = makeAbsPath(fixedName, dest);
3891 fixedFileName.onlyPath().createPath();
3892 status = copyFile(fmt, it->sourceName,
3894 it->exportName, status == FORCE,
3895 runparams.export_folder.empty());
3898 if (status == CANCEL) {
3899 message(_("Document export cancelled."));
3900 return ExportCancel;
3903 if (tmp_result_file.exists()) {
3904 // Finally copy the main file
3905 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3906 : force_overwrite != NO_FILES;
3907 if (status == SUCCESS && use_force)
3909 status = copyFile(format, tmp_result_file,
3910 FileName(result_file), result_file,
3912 if (status == CANCEL) {
3913 message(_("Document export cancelled."));
3914 return ExportCancel;
3916 message(bformat(_("Document exported as %1$s "
3918 formats.prettyName(format),
3919 makeDisplayPath(result_file)));
3922 // This must be a dummy converter like fax (bug 1888)
3923 message(bformat(_("Document exported as %1$s"),
3924 formats.prettyName(format)));
3927 return ExportSuccess;
3931 Buffer::ExportStatus Buffer::preview(string const & format) const
3933 bool const update_unincluded =
3934 params().maintain_unincluded_children
3935 && !params().getIncludedChildren().empty();
3936 return preview(format, update_unincluded);
3939 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3941 MarkAsExporting exporting(this);
3943 // (1) export with all included children (omit \includeonly)
3945 ExportStatus const status = doExport(format, true, true, result_file);
3946 if (status != ExportSuccess)
3949 // (2) export with included children only
3950 ExportStatus const status = doExport(format, true, false, result_file);
3951 if (status != ExportSuccess)
3953 if (!formats.view(*this, FileName(result_file), format))
3954 return PreviewError;
3955 return PreviewSuccess;
3959 Buffer::ReadStatus Buffer::extractFromVC()
3961 bool const found = LyXVC::file_not_found_hook(d->filename);
3963 return ReadFileNotFound;
3964 if (!d->filename.isReadableFile())
3970 Buffer::ReadStatus Buffer::loadEmergency()
3972 FileName const emergencyFile = getEmergencyFileName();
3973 if (!emergencyFile.exists()
3974 || emergencyFile.lastModified() <= d->filename.lastModified())
3975 return ReadFileNotFound;
3977 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3978 docstring const text = bformat(_("An emergency save of the document "
3979 "%1$s exists.\n\nRecover emergency save?"), file);
3981 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3982 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3988 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3989 bool const success = (ret_llf == ReadSuccess);
3992 Alert::warning(_("File is read-only"),
3993 bformat(_("An emergency file is successfully loaded, "
3994 "but the original file %1$s is marked read-only. "
3995 "Please make sure to save the document as a different "
3996 "file."), from_utf8(d->filename.absFileName())));
3999 str = _("Document was successfully recovered.");
4001 str = _("Document was NOT successfully recovered.");
4002 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4003 makeDisplayPath(emergencyFile.absFileName()));
4005 int const del_emerg =
4006 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4007 _("&Remove"), _("&Keep"));
4008 if (del_emerg == 0) {
4009 emergencyFile.removeFile();
4011 Alert::warning(_("Emergency file deleted"),
4012 _("Do not forget to save your file now!"), true);
4014 return success ? ReadSuccess : ReadEmergencyFailure;
4017 int const del_emerg =
4018 Alert::prompt(_("Delete emergency file?"),
4019 _("Remove emergency file now?"), 1, 1,
4020 _("&Remove"), _("&Keep"));
4022 emergencyFile.removeFile();
4023 return ReadOriginal;
4033 Buffer::ReadStatus Buffer::loadAutosave()
4035 // Now check if autosave file is newer.
4036 FileName const autosaveFile = getAutosaveFileName();
4037 if (!autosaveFile.exists()
4038 || autosaveFile.lastModified() <= d->filename.lastModified())
4039 return ReadFileNotFound;
4041 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4042 docstring const text = bformat(_("The backup of the document %1$s "
4043 "is newer.\n\nLoad the backup instead?"), file);
4044 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4045 _("&Load backup"), _("Load &original"), _("&Cancel"));
4050 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4051 // the file is not saved if we load the autosave file.
4052 if (ret_llf == ReadSuccess) {
4054 Alert::warning(_("File is read-only"),
4055 bformat(_("A backup file is successfully loaded, "
4056 "but the original file %1$s is marked read-only. "
4057 "Please make sure to save the document as a "
4059 from_utf8(d->filename.absFileName())));
4064 return ReadAutosaveFailure;
4067 // Here we delete the autosave
4068 autosaveFile.removeFile();
4069 return ReadOriginal;
4077 Buffer::ReadStatus Buffer::loadLyXFile()
4079 if (!d->filename.isReadableFile()) {
4080 ReadStatus const ret_rvc = extractFromVC();
4081 if (ret_rvc != ReadSuccess)
4085 ReadStatus const ret_re = loadEmergency();
4086 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4089 ReadStatus const ret_ra = loadAutosave();
4090 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4093 return loadThisLyXFile(d->filename);
4097 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4099 return readFile(fn);
4103 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4105 TeXErrors::Errors::const_iterator it = terr.begin();
4106 TeXErrors::Errors::const_iterator end = terr.end();
4107 ListOfBuffers clist = getDescendents();
4108 ListOfBuffers::const_iterator cen = clist.end();
4110 for (; it != end; ++it) {
4113 int errorRow = it->error_in_line;
4114 Buffer const * buf = 0;
4116 if (it->child_name.empty())
4117 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4119 // The error occurred in a child
4120 ListOfBuffers::const_iterator cit = clist.begin();
4121 for (; cit != cen; ++cit) {
4122 string const child_name =
4123 DocFileName(changeExtension(
4124 (*cit)->absFileName(), "tex")).
4126 if (it->child_name != child_name)
4128 (*cit)->d->texrow.getIdFromRow(errorRow,
4129 id_start, pos_start);
4130 if (id_start != -1) {
4131 buf = d->cloned_buffer_
4132 ? (*cit)->d->cloned_buffer_->d->owner_
4133 : (*cit)->d->owner_;
4144 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4145 } while (found && id_start == id_end && pos_start == pos_end);
4147 if (id_start != id_end) {
4148 // Next registered position is outside the inset where
4149 // the error occurred, so signal end-of-paragraph
4153 errorList.push_back(ErrorItem(it->error_desc,
4154 it->error_text, id_start, pos_start, pos_end, buf));
4159 void Buffer::setBuffersForInsets() const
4161 inset().setBuffer(const_cast<Buffer &>(*this));
4165 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4167 // Use the master text class also for child documents
4168 Buffer const * const master = masterBuffer();
4169 DocumentClass const & textclass = master->params().documentClass();
4171 // do this only if we are the top-level Buffer
4173 reloadBibInfoCache();
4175 // keep the buffers to be children in this set. If the call from the
4176 // master comes back we can see which of them were actually seen (i.e.
4177 // via an InsetInclude). The remaining ones in the set need still be updated.
4178 static std::set<Buffer const *> bufToUpdate;
4179 if (scope == UpdateMaster) {
4180 // If this is a child document start with the master
4181 if (master != this) {
4182 bufToUpdate.insert(this);
4183 master->updateBuffer(UpdateMaster, utype);
4184 // Do this here in case the master has no gui associated with it. Then,
4185 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4186 if (!master->d->gui_)
4189 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4190 if (bufToUpdate.find(this) == bufToUpdate.end())
4194 // start over the counters in the master
4195 textclass.counters().reset();
4198 // update will be done below for this buffer
4199 bufToUpdate.erase(this);
4201 // update all caches
4202 clearReferenceCache();
4205 Buffer & cbuf = const_cast<Buffer &>(*this);
4207 LASSERT(!text().paragraphs().empty(), /**/);
4210 ParIterator parit = cbuf.par_iterator_begin();
4211 updateBuffer(parit, utype);
4214 // TocBackend update will be done later.
4217 d->bibinfo_cache_valid_ = true;
4218 d->cite_labels_valid_ = true;
4219 cbuf.tocBackend().update();
4220 if (scope == UpdateMaster)
4221 cbuf.structureChanged();
4225 static depth_type getDepth(DocIterator const & it)
4227 depth_type depth = 0;
4228 for (size_t i = 0 ; i < it.depth() ; ++i)
4229 if (!it[i].inset().inMathed())
4230 depth += it[i].paragraph().getDepth() + 1;
4231 // remove 1 since the outer inset does not count
4235 static depth_type getItemDepth(ParIterator const & it)
4237 Paragraph const & par = *it;
4238 LabelType const labeltype = par.layout().labeltype;
4240 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4243 // this will hold the lowest depth encountered up to now.
4244 depth_type min_depth = getDepth(it);
4245 ParIterator prev_it = it;
4248 --prev_it.top().pit();
4250 // start of nested inset: go to outer par
4252 if (prev_it.empty()) {
4253 // start of document: nothing to do
4258 // We search for the first paragraph with same label
4259 // that is not more deeply nested.
4260 Paragraph & prev_par = *prev_it;
4261 depth_type const prev_depth = getDepth(prev_it);
4262 if (labeltype == prev_par.layout().labeltype) {
4263 if (prev_depth < min_depth)
4264 return prev_par.itemdepth + 1;
4265 if (prev_depth == min_depth)
4266 return prev_par.itemdepth;
4268 min_depth = min(min_depth, prev_depth);
4269 // small optimization: if we are at depth 0, we won't
4270 // find anything else
4271 if (prev_depth == 0)
4277 static bool needEnumCounterReset(ParIterator const & it)
4279 Paragraph const & par = *it;
4280 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4281 depth_type const cur_depth = par.getDepth();
4282 ParIterator prev_it = it;
4283 while (prev_it.pit()) {
4284 --prev_it.top().pit();
4285 Paragraph const & prev_par = *prev_it;
4286 if (prev_par.getDepth() <= cur_depth)
4287 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4289 // start of nested inset: reset
4294 // set the label of a paragraph. This includes the counters.
4295 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4297 BufferParams const & bp = owner_->masterBuffer()->params();
4298 DocumentClass const & textclass = bp.documentClass();
4299 Paragraph & par = it.paragraph();
4300 Layout const & layout = par.layout();
4301 Counters & counters = textclass.counters();
4303 if (par.params().startOfAppendix()) {
4304 // FIXME: only the counter corresponding to toplevel
4305 // sectioning should be reset
4307 counters.appendix(true);
4309 par.params().appendix(counters.appendix());
4311 // Compute the item depth of the paragraph
4312 par.itemdepth = getItemDepth(it);
4314 if (layout.margintype == MARGIN_MANUAL) {
4315 if (par.params().labelWidthString().empty())
4316 par.params().labelWidthString(par.expandLabel(layout, bp));
4317 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4318 // we do not need to do anything here, since the empty case is
4319 // handled during export.
4321 par.params().labelWidthString(docstring());
4324 switch(layout.labeltype) {
4326 if (layout.toclevel <= bp.secnumdepth
4327 && (layout.latextype != LATEX_ENVIRONMENT
4328 || it.text()->isFirstInSequence(it.pit()))) {
4329 if (counters.hasCounter(layout.counter))
4330 counters.step(layout.counter, utype);
4331 par.params().labelString(par.expandLabel(layout, bp));
4333 par.params().labelString(docstring());
4336 case LABEL_ITEMIZE: {
4337 // At some point of time we should do something more
4338 // clever here, like:
4339 // par.params().labelString(
4340 // bp.user_defined_bullet(par.itemdepth).getText());
4341 // for now, use a simple hardcoded label
4342 docstring itemlabel;
4343 switch (par.itemdepth) {
4345 itemlabel = char_type(0x2022);
4348 itemlabel = char_type(0x2013);
4351 itemlabel = char_type(0x2217);
4354 itemlabel = char_type(0x2219); // or 0x00b7
4357 par.params().labelString(itemlabel);
4361 case LABEL_ENUMERATE: {
4362 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4364 switch (par.itemdepth) {
4373 enumcounter += "iv";
4376 // not a valid enumdepth...
4380 // Maybe we have to reset the enumeration counter.
4381 if (needEnumCounterReset(it))
4382 counters.reset(enumcounter);
4383 counters.step(enumcounter, utype);
4385 string const & lang = par.getParLanguage(bp)->code();
4386 par.params().labelString(counters.theCounter(enumcounter, lang));
4391 case LABEL_SENSITIVE: {
4392 string const & type = counters.current_float();
4393 docstring full_label;
4395 full_label = owner_->B_("Senseless!!! ");
4397 docstring name = owner_->B_(textclass.floats().getType(type).name());
4398 if (counters.hasCounter(from_utf8(type))) {
4399 string const & lang = par.getParLanguage(bp)->code();
4400 counters.step(from_utf8(type), utype);
4401 full_label = bformat(from_ascii("%1$s %2$s:"),
4403 counters.theCounter(from_utf8(type), lang));
4405 full_label = bformat(from_ascii("%1$s #:"), name);
4407 par.params().labelString(full_label);
4411 case LABEL_NO_LABEL:
4412 par.params().labelString(docstring());
4416 case LABEL_TOP_ENVIRONMENT:
4417 case LABEL_CENTERED_TOP_ENVIRONMENT:
4420 par.params().labelString(par.expandLabel(layout, bp));
4426 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4428 LASSERT(parit.pit() == 0, /**/);
4430 // Set the position of the text in the buffer to be able
4431 // to resolve macros in it.
4432 parit.text()->setMacrocontextPosition(parit);
4434 depth_type maxdepth = 0;
4435 pit_type const lastpit = parit.lastpit();
4436 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4437 // reduce depth if necessary
4438 if (parit->params().depth() > maxdepth) {
4439 /** FIXME: this function is const, but
4440 * nevertheless it modifies the buffer. To be
4441 * cleaner, one should modify the buffer in
4442 * another function, which is actually
4443 * non-const. This would however be costly in
4444 * terms of code duplication.
4446 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4447 parit->params().depth(maxdepth);
4449 maxdepth = parit->getMaxDepthAfter();
4451 if (utype == OutputUpdate) {
4452 // track the active counters
4453 // we have to do this for the master buffer, since the local
4454 // buffer isn't tracking anything.
4455 masterBuffer()->params().documentClass().counters().
4456 setActiveLayout(parit->layout());
4459 // set the counter for this paragraph
4460 d->setLabel(parit, utype);
4463 InsetList::const_iterator iit = parit->insetList().begin();
4464 InsetList::const_iterator end = parit->insetList().end();
4465 for (; iit != end; ++iit) {
4466 parit.pos() = iit->pos;
4467 iit->inset->updateBuffer(parit, utype);
4473 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4474 WordLangTuple & word_lang, docstring_list & suggestions) const
4478 suggestions.clear();
4479 word_lang = WordLangTuple();
4480 bool const to_end = to.empty();
4481 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4482 // OK, we start from here.
4483 for (; from != end; from.forwardPos()) {
4484 // We are only interested in text so remove the math CursorSlice.
4485 while (from.inMathed()) {
4489 // If from is at the end of the document (which is possible
4490 // when leaving the mathed) LyX will crash later otherwise.
4491 if (from.atEnd() || (!to_end && from >= end))
4494 from.paragraph().spellCheck();
4495 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4496 if (SpellChecker::misspelled(res)) {
4501 // Do not increase progress when from == to, otherwise the word
4502 // count will be wrong.
4512 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4514 bool inword = false;
4519 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4520 if (!dit.inTexted()) {
4525 Paragraph const & par = dit.paragraph();
4526 pos_type const pos = dit.pos();
4528 // Copied and adapted from isWordSeparator() in Paragraph
4529 if (pos == dit.lastpos()) {
4532 Inset const * ins = par.getInset(pos);
4533 if (ins && skipNoOutput && !ins->producesOutput()) {
4536 // stop if end of range was skipped
4537 if (!to.atEnd() && dit >= to)
4540 } else if (!par.isDeleted(pos)) {
4541 if (par.isWordSeparator(pos))
4547 if (ins && ins->isLetter())
4549 else if (ins && ins->isSpace())
4552 char_type const c = par.getChar(pos);
4553 if (isPrintableNonspace(c))
4555 else if (isSpace(c))
4565 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4567 d->updateStatistics(from, to, skipNoOutput);
4571 int Buffer::wordCount() const
4573 return d->wordCount();
4577 int Buffer::charCount(bool with_blanks) const
4579 return d->charCount(with_blanks);
4583 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4586 // c.f. bug http://www.lyx.org/trac/ticket/6587
4587 removeAutosaveFile();
4588 // e.g., read-only status could have changed due to version control
4589 d->filename.refresh();
4590 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4592 // clear parent. this will get reset if need be.
4594 ReadStatus const status = loadLyXFile();
4595 if (status == ReadSuccess) {
4600 message(bformat(_("Document %1$s reloaded."), disp_fn));
4604 message(bformat(_("Could not reload document %1$s."), disp_fn));
4614 bool Buffer::saveAs(FileName const & fn)
4616 FileName const old_name = fileName();
4617 FileName const old_auto = getAutosaveFileName();
4618 bool const old_unnamed = isUnnamed();
4625 // bring the autosave file with us, just in case.
4626 moveAutosaveFile(old_auto);
4627 // validate version control data and
4628 // correct buffer title
4629 lyxvc().file_found_hook(fileName());
4631 // the file has now been saved to the new location.
4632 // we need to check that the locations of child buffers
4634 checkChildBuffers();
4635 checkMasterBuffer();
4639 // reset the old filename and unnamed state
4640 setFileName(old_name);
4641 setUnnamed(old_unnamed);
4647 // FIXME We could do better here, but it is complicated. What would be
4648 // nice is to offer either (a) to save the child buffer to an appropriate
4649 // location, so that it would "move with the master", or else (b) to update
4650 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4651 // complicated, because the code for this lives in GuiView.
4652 void Buffer::checkChildBuffers()
4654 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4655 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4656 for (; it != en; ++it) {
4657 DocIterator dit = it->second;
4658 Buffer * cbuf = const_cast<Buffer *>(it->first);
4659 if (!cbuf || !theBufferList().isLoaded(cbuf))
4661 Inset * inset = dit.nextInset();
4662 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4663 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4664 docstring const & incfile = inset_inc->getParam("filename");
4665 string oldloc = cbuf->absFileName();
4666 string newloc = makeAbsPath(to_utf8(incfile),
4667 onlyPath(absFileName())).absFileName();
4668 if (oldloc == newloc)
4670 // the location of the child file is incorrect.
4671 Alert::warning(_("Included File Invalid"),
4672 bformat(_("Saving this document to a new location has made the file:\n"
4674 "inaccessible. You will need to update the included filename."),
4675 from_utf8(oldloc)));
4677 inset_inc->setChildBuffer(0);
4679 // invalidate cache of children
4680 d->children_positions.clear();
4681 d->position_to_children.clear();
4685 // If a child has been saved under a different name/path, it might have been
4686 // orphaned. Therefore the master needs to be reset (bug 8161).
4687 void Buffer::checkMasterBuffer()
4689 Buffer const * const master = masterBuffer();
4693 // necessary to re-register the child (bug 5873)
4694 // FIXME: clean up updateMacros (here, only
4695 // child registering is needed).
4696 master->updateMacros();
4697 // (re)set master as master buffer, but only
4698 // if we are a real child
4699 if (master->isChild(this))