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"
119 using namespace lyx::support;
120 using namespace lyx::graphics;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 int const LYX_FORMAT = LYX_FORMAT_LYX;
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
145 // A storehouse for the cloned buffers.
146 list<CloneList *> cloned_buffers;
152 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
156 delete preview_loader_;
164 /// search for macro in local (buffer) table or in children
165 MacroData const * getBufferMacro(docstring const & name,
166 DocIterator const & pos) const;
168 /// Update macro table starting with position of it \param it in some
170 void updateMacros(DocIterator & it, DocIterator & scope);
172 void setLabel(ParIterator & it, UpdateType utype) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this an unnamed file (New...)?
198 /// is this an internal bufffer?
199 bool internal_buffer;
204 /// name of the file the buffer is associated with.
207 /** Set to true only when the file is fully loaded.
208 * Used to prevent the premature generation of previews
209 * and by the citation inset.
211 bool file_fully_loaded;
213 /// Ignore the parent (e.g. when exporting a child standalone)?
217 mutable TocBackend toc_backend;
220 typedef pair<DocIterator, MacroData> ScopeMacro;
221 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
222 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
223 /// map from the macro name to the position map,
224 /// which maps the macro definition position to the scope and the MacroData.
225 NamePositionScopeMacroMap macros;
226 /// This seem to change the way Buffer::getMacro() works
227 mutable bool macro_lock;
229 /// positions of child buffers in the buffer
230 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
231 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
232 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
233 /// position of children buffers in this buffer
234 BufferPositionMap children_positions;
235 /// map from children inclusion positions to their scope and their buffer
236 PositionScopeBufferMap position_to_children;
238 /// Container for all sort of Buffer dependant errors.
239 map<string, ErrorList> errorLists;
241 /// timestamp and checksum used to test if the file has been externally
242 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
244 unsigned long checksum_;
247 frontend::WorkAreaManager * wa_;
249 frontend::GuiBufferDelegate * gui_;
254 /// A cache for the bibfiles (including bibfiles of loaded child
255 /// documents), needed for appropriate update of natbib labels.
256 mutable support::FileNameList bibfiles_cache_;
258 // FIXME The caching mechanism could be improved. At present, we have a
259 // cache for each Buffer, that caches all the bibliography info for that
260 // Buffer. A more efficient solution would be to have a global cache per
261 // file, and then to construct the Buffer's bibinfo from that.
262 /// A cache for bibliography info
263 mutable BiblioInfo bibinfo_;
264 /// whether the bibinfo cache is valid
265 mutable bool bibinfo_cache_valid_;
266 /// whether the bibfile cache is valid
267 mutable bool bibfile_cache_valid_;
268 /// Cache of timestamps of .bib files
269 map<FileName, time_t> bibfile_status_;
270 /// Indicates whether the bibinfo has changed since the last time
271 /// we ran updateBuffer(), i.e., whether citation labels may need
273 mutable bool cite_labels_valid_;
275 mutable RefCache ref_cache_;
277 /// our Text that should be wrapped in an InsetText
281 PreviewLoader * preview_loader_;
283 /// This is here to force the test to be done whenever parent_buffer
285 Buffer const * parent() const {
286 // ignore_parent temporarily "orphans" a buffer
287 // (e.g. if a child is compiled standalone)
290 // if parent_buffer is not loaded, then it has been unloaded,
291 // which means that parent_buffer is an invalid pointer. So we
292 // set it to null in that case.
293 // however, the BufferList doesn't know about cloned buffers, so
294 // they will always be regarded as unloaded. in that case, we hope
296 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
298 return parent_buffer;
302 void setParent(Buffer const * pb) {
303 if (parent_buffer == pb)
306 if (!cloned_buffer_ && parent_buffer && pb)
307 LYXERR0("Warning: a buffer should not have two parents!");
309 if (!cloned_buffer_ && parent_buffer) {
310 parent_buffer->invalidateBibfileCache();
311 parent_buffer->invalidateBibinfoCache();
315 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
316 /// This one is useful for preview detached in a thread.
317 Buffer const * cloned_buffer_;
319 CloneList * clone_list_;
320 /// are we in the process of exporting this buffer?
321 mutable bool doing_export;
323 /// compute statistics
324 /// \p from initial position
325 /// \p to points to the end position
326 void updateStatistics(DocIterator & from, DocIterator & to,
327 bool skipNoOutput = true);
328 /// statistics accessor functions
329 int wordCount() const { return word_count_; }
330 int charCount(bool with_blanks) const {
332 + (with_blanks ? blank_count_ : 0);
336 /// So we can force access via the accessors.
337 mutable Buffer const * parent_buffer;
346 /// Creates the per buffer temporary directory
347 static FileName createBufferTmpDir()
350 // We are in our own directory. Why bother to mangle name?
351 // In fact I wrote this code to circumvent a problematic behaviour
352 // (bug?) of EMX mkstemp().
353 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
354 convert<string>(count++));
356 if (!tmpfl.createDirectory(0777)) {
357 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
358 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
359 from_utf8(tmpfl.absFileName())));
365 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
366 Buffer const * cloned_buffer)
367 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
368 internal_buffer(false), read_only(readonly_), filename(file),
369 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
370 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
371 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
372 cite_labels_valid_(false), preview_loader_(0),
373 cloned_buffer_(cloned_buffer), clone_list_(0),
374 doing_export(false), parent_buffer(0)
376 if (!cloned_buffer_) {
377 temppath = createBufferTmpDir();
378 lyxvc.setBuffer(owner_);
380 wa_ = new frontend::WorkAreaManager;
383 temppath = cloned_buffer_->d->temppath;
384 file_fully_loaded = true;
385 params = cloned_buffer_->d->params;
386 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
387 bibinfo_ = cloned_buffer_->d->bibinfo_;
388 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
389 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
390 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
391 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
392 unnamed = cloned_buffer_->d->unnamed;
393 internal_buffer = cloned_buffer_->d->internal_buffer;
397 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
398 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
400 LYXERR(Debug::INFO, "Buffer::Buffer()");
402 d->inset = new InsetText(*cloned_buffer->d->inset);
403 d->inset->setBuffer(*this);
404 // FIXME: optimize this loop somewhat, maybe by creating a new
405 // general recursive Inset::setId().
406 DocIterator it = doc_iterator_begin(this);
407 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
408 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
409 it.paragraph().setId(cloned_it.paragraph().id());
411 d->inset = new InsetText(this);
412 d->inset->setAutoBreakRows(true);
413 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
419 LYXERR(Debug::INFO, "Buffer::~Buffer()");
420 // here the buffer should take care that it is
421 // saved properly, before it goes into the void.
423 // GuiView already destroyed
427 // No need to do additional cleanups for internal buffer.
433 // this is in case of recursive includes: we won't try to delete
434 // ourselves as a child.
435 d->clone_list_->erase(this);
436 // loop over children
437 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
438 Impl::BufferPositionMap::iterator end = d->children_positions.end();
439 for (; it != end; ++it) {
440 Buffer * child = const_cast<Buffer *>(it->first);
441 if (d->clone_list_->erase(child))
444 // if we're the master buffer, then we should get rid of the list
447 // if this is not empty, we have leaked something. worse, one of the
448 // children still has a reference to this list.
449 LASSERT(d->clone_list_->empty(), /* */);
450 list<CloneList *>::iterator it =
451 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
452 LASSERT(it != cloned_buffers.end(), /* */);
453 cloned_buffers.erase(it);
454 delete d->clone_list_;
456 // FIXME Do we really need to do this right before we delete d?
457 // clear references to children in macro tables
458 d->children_positions.clear();
459 d->position_to_children.clear();
461 // loop over children
462 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
463 Impl::BufferPositionMap::iterator end = d->children_positions.end();
464 for (; it != end; ++it) {
465 Buffer * child = const_cast<Buffer *>(it->first);
466 if (theBufferList().isLoaded(child))
467 theBufferList().releaseChild(this, child);
471 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
472 msg += emergencyWrite();
473 Alert::warning(_("Attempting to close changed document!"), msg);
476 // FIXME Do we really need to do this right before we delete d?
477 // clear references to children in macro tables
478 d->children_positions.clear();
479 d->position_to_children.clear();
481 if (!d->temppath.destroyDirectory()) {
482 Alert::warning(_("Could not remove temporary directory"),
483 bformat(_("Could not remove the temporary directory %1$s"),
484 from_utf8(d->temppath.absFileName())));
493 Buffer * Buffer::cloneFromMaster() const
496 cloned_buffers.push_back(new CloneList());
497 CloneList * clones = cloned_buffers.back();
499 masterBuffer()->cloneWithChildren(bufmap, clones);
501 // make sure we got cloned
502 BufferMap::const_iterator bit = bufmap.find(this);
503 LASSERT(bit != bufmap.end(), return 0);
504 Buffer * cloned_buffer = bit->second;
506 return cloned_buffer;
510 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
512 // have we already been cloned?
513 if (bufmap.find(this) != bufmap.end())
516 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
517 bufmap[this] = buffer_clone;
518 clones->insert(buffer_clone);
519 buffer_clone->d->clone_list_ = clones;
520 buffer_clone->d->macro_lock = true;
521 buffer_clone->d->children_positions.clear();
522 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
523 // math macro caches need to be rethought and simplified.
524 // I am not sure wether we should handle Buffer cloning here or in BufferList.
525 // Right now BufferList knows nothing about buffer clones.
526 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
527 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
528 for (; it != end; ++it) {
529 DocIterator dit = it->first.clone(buffer_clone);
530 dit.setBuffer(buffer_clone);
531 Buffer * child = const_cast<Buffer *>(it->second.second);
533 child->cloneWithChildren(bufmap, clones);
534 BufferMap::iterator const bit = bufmap.find(child);
535 LASSERT(bit != bufmap.end(), continue);
536 Buffer * child_clone = bit->second;
538 Inset * inset = dit.nextInset();
539 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
540 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
541 inset_inc->setChildBuffer(child_clone);
542 child_clone->d->setParent(buffer_clone);
543 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
544 buffer_clone->setChild(dit, child_clone);
546 buffer_clone->d->macro_lock = false;
551 Buffer * Buffer::cloneBufferOnly() const {
552 cloned_buffers.push_back(new CloneList());
553 CloneList * clones = cloned_buffers.back();
554 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
555 clones->insert(buffer_clone);
556 buffer_clone->d->clone_list_ = clones;
557 // we won't be cloning the children
558 buffer_clone->d->children_positions.clear();
563 bool Buffer::isClone() const
565 return d->cloned_buffer_;
569 void Buffer::changed(bool update_metrics) const
572 d->wa_->redrawAll(update_metrics);
576 frontend::WorkAreaManager & Buffer::workAreaManager() const
578 LASSERT(d->wa_, /**/);
583 Text & Buffer::text() const
585 return d->inset->text();
589 Inset & Buffer::inset() const
595 BufferParams & Buffer::params()
601 BufferParams const & Buffer::params() const
607 ParagraphList & Buffer::paragraphs()
609 return text().paragraphs();
613 ParagraphList const & Buffer::paragraphs() const
615 return text().paragraphs();
619 LyXVC & Buffer::lyxvc()
625 LyXVC const & Buffer::lyxvc() const
631 string const Buffer::temppath() const
633 return d->temppath.absFileName();
637 TexRow & Buffer::texrow()
643 TexRow const & Buffer::texrow() const
649 TocBackend & Buffer::tocBackend() const
651 return d->toc_backend;
655 Undo & Buffer::undo()
661 void Buffer::setChild(DocIterator const & dit, Buffer * child)
663 d->children_positions[child] = dit;
667 string Buffer::latexName(bool const no_path) const
669 FileName latex_name =
670 makeLatexName(d->exportFileName());
671 return no_path ? latex_name.onlyFileName()
672 : latex_name.absFileName();
676 FileName Buffer::Impl::exportFileName() const
678 docstring const branch_suffix =
679 params.branchlist().getFileNameSuffix();
680 if (branch_suffix.empty())
683 string const name = filename.onlyFileNameWithoutExt()
684 + to_utf8(branch_suffix);
685 FileName res(filename.onlyPath().absFileName() + "/" + name);
686 res.changeExtension(filename.extension());
692 string Buffer::logName(LogType * type) const
694 string const filename = latexName(false);
696 if (filename.empty()) {
702 string const path = temppath();
704 FileName const fname(addName(temppath(),
705 onlyFileName(changeExtension(filename,
708 // FIXME: how do we know this is the name of the build log?
709 FileName const bname(
710 addName(path, onlyFileName(
711 changeExtension(filename,
712 formats.extension(params().bufferFormat()) + ".out"))));
714 // Also consider the master buffer log file
715 FileName masterfname = fname;
717 if (masterBuffer() != this) {
718 string const mlogfile = masterBuffer()->logName(&mtype);
719 masterfname = FileName(mlogfile);
722 // If no Latex log or Build log is newer, show Build log
723 if (bname.exists() &&
724 ((!fname.exists() && !masterfname.exists())
725 || (fname.lastModified() < bname.lastModified()
726 && masterfname.lastModified() < bname.lastModified()))) {
727 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
730 return bname.absFileName();
731 // If we have a newer master file log or only a master log, show this
732 } else if (fname != masterfname
733 && (!fname.exists() && (masterfname.exists()
734 || fname.lastModified() < masterfname.lastModified()))) {
735 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
738 return masterfname.absFileName();
740 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
743 return fname.absFileName();
747 void Buffer::setReadonly(bool const flag)
749 if (d->read_only != flag) {
756 void Buffer::setFileName(FileName const & fname)
759 setReadonly(d->filename.isReadOnly());
765 int Buffer::readHeader(Lexer & lex)
767 int unknown_tokens = 0;
769 int begin_header_line = -1;
771 // Initialize parameters that may be/go lacking in header:
772 params().branchlist().clear();
773 params().preamble.erase();
774 params().options.erase();
775 params().master.erase();
776 params().float_placement.erase();
777 params().paperwidth.erase();
778 params().paperheight.erase();
779 params().leftmargin.erase();
780 params().rightmargin.erase();
781 params().topmargin.erase();
782 params().bottommargin.erase();
783 params().headheight.erase();
784 params().headsep.erase();
785 params().footskip.erase();
786 params().columnsep.erase();
787 params().fonts_cjk.erase();
788 params().listings_params.clear();
789 params().clearLayoutModules();
790 params().clearRemovedModules();
791 params().clearIncludedChildren();
792 params().pdfoptions().clear();
793 params().indiceslist().clear();
794 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
795 params().isbackgroundcolor = false;
796 params().fontcolor = RGBColor(0, 0, 0);
797 params().isfontcolor = false;
798 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
799 params().boxbgcolor = RGBColor(0xFF, 0, 0);
800 params().html_latex_start.clear();
801 params().html_latex_end.clear();
802 params().html_math_img_scale = 1.0;
803 params().output_sync_macro.erase();
804 params().local_layout.clear();
806 for (int i = 0; i < 4; ++i) {
807 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
808 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
811 ErrorList & errorList = d->errorLists["Parse"];
820 if (token == "\\end_header")
824 if (token == "\\begin_header") {
825 begin_header_line = line;
829 LYXERR(Debug::PARSER, "Handling document header token: `"
832 string unknown = params().readToken(lex, token, d->filename.onlyPath());
833 if (!unknown.empty()) {
834 if (unknown[0] != '\\' && token == "\\textclass") {
835 Alert::warning(_("Unknown document class"),
836 bformat(_("Using the default document class, because the "
837 "class %1$s is unknown."), from_utf8(unknown)));
840 docstring const s = bformat(_("Unknown token: "
844 errorList.push_back(ErrorItem(_("Document header error"),
849 if (begin_header_line) {
850 docstring const s = _("\\begin_header is missing");
851 errorList.push_back(ErrorItem(_("Document header error"),
855 params().makeDocumentClass();
857 return unknown_tokens;
862 // changed to be public and have one parameter
863 // Returns true if "\end_document" is not read (Asger)
864 bool Buffer::readDocument(Lexer & lex)
866 ErrorList & errorList = d->errorLists["Parse"];
869 // remove dummy empty par
870 paragraphs().clear();
872 if (!lex.checkFor("\\begin_document")) {
873 docstring const s = _("\\begin_document is missing");
874 errorList.push_back(ErrorItem(_("Document header error"),
880 if (params().outputChanges) {
881 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
882 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
883 LaTeXFeatures::isAvailable("xcolor");
885 if (!dvipost && !xcolorulem) {
886 Alert::warning(_("Changes not shown in LaTeX output"),
887 _("Changes will not be highlighted in LaTeX output, "
888 "because neither dvipost nor xcolor/ulem are installed.\n"
889 "Please install these packages or redefine "
890 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
891 } else if (!xcolorulem) {
892 Alert::warning(_("Changes not shown in LaTeX output"),
893 _("Changes will not be highlighted in LaTeX output "
894 "when using pdflatex, because xcolor and ulem are not installed.\n"
895 "Please install both packages or redefine "
896 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
900 if (!params().master.empty()) {
901 FileName const master_file = makeAbsPath(params().master,
902 onlyPath(absFileName()));
903 if (isLyXFileName(master_file.absFileName())) {
905 checkAndLoadLyXFile(master_file, true);
907 // necessary e.g. after a reload
908 // to re-register the child (bug 5873)
909 // FIXME: clean up updateMacros (here, only
910 // child registering is needed).
911 master->updateMacros();
912 // set master as master buffer, but only
913 // if we are a real child
914 if (master->isChild(this))
916 // if the master is not fully loaded
917 // it is probably just loading this
918 // child. No warning needed then.
919 else if (master->isFullyLoaded())
920 LYXERR0("The master '"
922 << "' assigned to this document ("
924 << ") does not include "
925 "this document. Ignoring the master assignment.");
930 // assure we have a default index
931 params().indiceslist().addDefault(B_("Index"));
934 bool const res = text().read(lex, errorList, d->inset);
936 // inform parent buffer about local macros
938 Buffer const * pbuf = parent();
939 UserMacroSet::const_iterator cit = usermacros.begin();
940 UserMacroSet::const_iterator end = usermacros.end();
941 for (; cit != end; ++cit)
942 pbuf->usermacros.insert(*cit);
946 updateMacroInstances(InternalUpdate);
951 bool Buffer::readString(string const & s)
953 params().compressed = false;
958 FileName const fn = FileName::tempName("Buffer_readString");
961 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
962 if (ret_plf != ReadSuccess)
965 if (file_format != LYX_FORMAT) {
966 // We need to call lyx2lyx, so write the input to a file
967 ofstream os(fn.toFilesystemEncoding().c_str());
971 return readFile(fn) == ReadSuccess;
974 if (readDocument(lex))
980 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
984 if (!lex.setFile(fname)) {
985 Alert::error(_("File Not Found"),
986 bformat(_("Unable to open file `%1$s'."),
987 from_utf8(fn.absFileName())));
988 return ReadFileNotFound;
992 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
993 if (ret_plf != ReadSuccess)
996 if (file_format != LYX_FORMAT) {
998 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
999 if (ret_clf != ReadSuccess)
1001 return readFile(tmpFile);
1004 // FIXME: InsetInfo needs to know whether the file is under VCS
1005 // during the parse process, so this has to be done before.
1006 lyxvc().file_found_hook(d->filename);
1008 if (readDocument(lex)) {
1009 Alert::error(_("Document format failure"),
1010 bformat(_("%1$s ended unexpectedly, which means"
1011 " that it is probably corrupted."),
1012 from_utf8(fn.absFileName())));
1013 return ReadDocumentFailure;
1016 d->file_fully_loaded = true;
1017 d->read_only = !d->filename.isWritable();
1018 params().compressed = formats.isZippedFile(d->filename);
1024 bool Buffer::isFullyLoaded() const
1026 return d->file_fully_loaded;
1030 void Buffer::setFullyLoaded(bool value)
1032 d->file_fully_loaded = value;
1036 PreviewLoader * Buffer::loader() const
1038 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1040 if (!d->preview_loader_)
1041 d->preview_loader_ = new PreviewLoader(*this);
1042 return d->preview_loader_;
1046 void Buffer::removePreviews() const
1048 delete d->preview_loader_;
1049 d->preview_loader_ = 0;
1053 void Buffer::updatePreviews() const
1055 PreviewLoader * ploader = loader();
1059 InsetIterator it = inset_iterator_begin(*d->inset);
1060 InsetIterator const end = inset_iterator_end(*d->inset);
1061 for (; it != end; ++it)
1062 it->addPreview(it, *ploader);
1064 ploader->startLoading();
1068 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1069 FileName const & fn, int & file_format) const
1071 if(!lex.checkFor("\\lyxformat")) {
1072 Alert::error(_("Document format failure"),
1073 bformat(_("%1$s is not a readable LyX document."),
1074 from_utf8(fn.absFileName())));
1075 return ReadNoLyXFormat;
1081 // LyX formats 217 and earlier were written as 2.17. This corresponds
1082 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1083 // these cases. See also: www.lyx.org/trac/changeset/1313.
1084 size_t dot = tmp_format.find_first_of(".,");
1085 if (dot != string::npos)
1086 tmp_format.erase(dot, 1);
1088 file_format = convert<int>(tmp_format);
1093 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1094 FileName & tmpfile, int from_format)
1096 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1097 if(tmpfile.empty()) {
1098 Alert::error(_("Conversion failed"),
1099 bformat(_("%1$s is from a different"
1100 " version of LyX, but a temporary"
1101 " file for converting it could"
1102 " not be created."),
1103 from_utf8(fn.absFileName())));
1104 return LyX2LyXNoTempFile;
1107 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1108 if (lyx2lyx.empty()) {
1109 Alert::error(_("Conversion script not found"),
1110 bformat(_("%1$s is from a different"
1111 " version of LyX, but the"
1112 " conversion script lyx2lyx"
1113 " could not be found."),
1114 from_utf8(fn.absFileName())));
1115 return LyX2LyXNotFound;
1119 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1120 ostringstream command;
1121 command << os::python()
1122 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1123 << " -t " << convert<string>(LYX_FORMAT)
1124 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1125 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1126 string const command_str = command.str();
1128 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1130 cmd_ret const ret = runCommand(command_str);
1131 if (ret.first != 0) {
1132 if (from_format < LYX_FORMAT) {
1133 Alert::error(_("Conversion script failed"),
1134 bformat(_("%1$s is from an older version"
1135 " of LyX and the lyx2lyx script"
1136 " failed to convert it."),
1137 from_utf8(fn.absFileName())));
1138 return LyX2LyXOlderFormat;
1140 Alert::error(_("Conversion script failed"),
1141 bformat(_("%1$s is from a newer version"
1142 " of LyX and the lyx2lyx script"
1143 " failed to convert it."),
1144 from_utf8(fn.absFileName())));
1145 return LyX2LyXNewerFormat;
1152 // Should probably be moved to somewhere else: BufferView? GuiView?
1153 bool Buffer::save() const
1155 docstring const file = makeDisplayPath(absFileName(), 20);
1156 d->filename.refresh();
1158 // check the read-only status before moving the file as a backup
1159 if (d->filename.exists()) {
1160 bool const read_only = !d->filename.isWritable();
1162 Alert::warning(_("File is read-only"),
1163 bformat(_("The file %1$s cannot be written because it "
1164 "is marked as read-only."), file));
1169 // ask if the disk file has been externally modified (use checksum method)
1170 if (fileName().exists() && isExternallyModified(checksum_method)) {
1172 bformat(_("Document %1$s has been externally modified. "
1173 "Are you sure you want to overwrite this file?"), file);
1174 int const ret = Alert::prompt(_("Overwrite modified file?"),
1175 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1180 // We don't need autosaves in the immediate future. (Asger)
1181 resetAutosaveTimers();
1183 FileName backupName;
1184 bool madeBackup = false;
1186 // make a backup if the file already exists
1187 if (lyxrc.make_backup && fileName().exists()) {
1188 backupName = FileName(absFileName() + '~');
1189 if (!lyxrc.backupdir_path.empty()) {
1190 string const mangledName =
1191 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1192 backupName = FileName(addName(lyxrc.backupdir_path,
1196 // Except file is symlink do not copy because of #6587.
1197 // Hard links have bad luck.
1198 if (fileName().isSymLink())
1199 madeBackup = fileName().copyTo(backupName);
1201 madeBackup = fileName().moveTo(backupName);
1204 Alert::error(_("Backup failure"),
1205 bformat(_("Cannot create backup file %1$s.\n"
1206 "Please check whether the directory exists and is writable."),
1207 from_utf8(backupName.absFileName())));
1208 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1212 if (writeFile(d->filename)) {
1216 // Saving failed, so backup is not backup
1218 backupName.moveTo(d->filename);
1224 bool Buffer::writeFile(FileName const & fname) const
1226 // FIXME Do we need to do these here? I don't think writing
1227 // the LyX file depends upon it. (RGH)
1229 // updateMacroInstances();
1231 if (d->read_only && fname == d->filename)
1234 bool retval = false;
1236 docstring const str = bformat(_("Saving document %1$s..."),
1237 makeDisplayPath(fname.absFileName()));
1240 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1242 if (params().compressed) {
1243 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1244 retval = ofs && write(ofs);
1246 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1247 retval = ofs && write(ofs);
1251 message(str + _(" could not write file!"));
1256 // removeAutosaveFile();
1259 message(str + _(" done."));
1265 docstring Buffer::emergencyWrite()
1267 // No need to save if the buffer has not changed.
1271 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1273 docstring user_message = bformat(
1274 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1276 // We try to save three places:
1277 // 1) Same place as document. Unless it is an unnamed doc.
1279 string s = absFileName();
1282 if (writeFile(FileName(s))) {
1284 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1285 return user_message;
1287 user_message += " " + _("Save failed! Trying again...\n");
1291 // 2) In HOME directory.
1292 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1294 lyxerr << ' ' << s << endl;
1295 if (writeFile(FileName(s))) {
1297 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1298 return user_message;
1301 user_message += " " + _("Save failed! Trying yet again...\n");
1303 // 3) In "/tmp" directory.
1304 // MakeAbsPath to prepend the current
1305 // drive letter on OS/2
1306 s = addName(package().temp_dir().absFileName(), absFileName());
1308 lyxerr << ' ' << s << endl;
1309 if (writeFile(FileName(s))) {
1311 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1312 return user_message;
1315 user_message += " " + _("Save failed! Bummer. Document is lost.");
1318 return user_message;
1322 bool Buffer::write(ostream & ofs) const
1325 // Use the standard "C" locale for file output.
1326 ofs.imbue(locale::classic());
1329 // The top of the file should not be written by params().
1331 // write out a comment in the top of the file
1332 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1333 << " created this file. For more info see http://www.lyx.org/\n"
1334 << "\\lyxformat " << LYX_FORMAT << "\n"
1335 << "\\begin_document\n";
1337 /// For each author, set 'used' to true if there is a change
1338 /// by this author in the document; otherwise set it to 'false'.
1339 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1340 AuthorList::Authors::const_iterator a_end = params().authors().end();
1341 for (; a_it != a_end; ++a_it)
1342 a_it->setUsed(false);
1344 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1345 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1346 for ( ; it != end; ++it)
1347 it->checkAuthors(params().authors());
1349 // now write out the buffer parameters.
1350 ofs << "\\begin_header\n";
1351 params().writeFile(ofs);
1352 ofs << "\\end_header\n";
1355 ofs << "\n\\begin_body\n";
1357 ofs << "\n\\end_body\n";
1359 // Write marker that shows file is complete
1360 ofs << "\\end_document" << endl;
1362 // Shouldn't really be needed....
1365 // how to check if close went ok?
1366 // Following is an attempt... (BE 20001011)
1368 // good() returns false if any error occured, including some
1369 // formatting error.
1370 // bad() returns true if something bad happened in the buffer,
1371 // which should include file system full errors.
1376 lyxerr << "File was not closed properly." << endl;
1383 bool Buffer::makeLaTeXFile(FileName const & fname,
1384 string const & original_path,
1385 OutputParams const & runparams_in,
1386 OutputWhat output) const
1388 OutputParams runparams = runparams_in;
1390 // This is necessary for LuaTeX/XeTeX with tex fonts.
1391 // See FIXME in BufferParams::encoding()
1392 if (runparams.isFullUnicode())
1393 runparams.encoding = encodings.fromLyXName("utf8-plain");
1395 string const encoding = runparams.encoding->iconvName();
1396 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1399 try { ofs.reset(encoding); }
1400 catch (iconv_codecvt_facet_exception const & e) {
1401 lyxerr << "Caught iconv exception: " << e.what() << endl;
1402 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1403 "verify that the support software for your encoding (%1$s) is "
1404 "properly installed"), from_ascii(encoding)));
1407 if (!openFileWrite(ofs, fname))
1410 //TexStream ts(ofs.rdbuf(), &texrow());
1411 ErrorList & errorList = d->errorLists["Export"];
1413 bool failed_export = false;
1414 otexstream os(ofs, d->texrow);
1416 // make sure we are ready to export
1417 // this needs to be done before we validate
1418 // FIXME Do we need to do this all the time? I.e., in children
1419 // of a master we are exporting?
1421 updateMacroInstances(OutputUpdate);
1424 os.texrow().reset();
1425 writeLaTeXSource(os, original_path, runparams, output);
1427 catch (EncodingException const & e) {
1428 odocstringstream ods;
1429 ods.put(e.failed_char);
1431 oss << "0x" << hex << e.failed_char << dec;
1432 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1433 " (code point %2$s)"),
1434 ods.str(), from_utf8(oss.str()));
1435 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1436 "representable in the chosen encoding.\n"
1437 "Changing the document encoding to utf8 could help."),
1438 e.par_id, e.pos, e.pos + 1));
1439 failed_export = true;
1441 catch (iconv_codecvt_facet_exception const & e) {
1442 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1443 _(e.what()), -1, 0, 0));
1444 failed_export = true;
1446 catch (exception const & e) {
1447 errorList.push_back(ErrorItem(_("conversion failed"),
1448 _(e.what()), -1, 0, 0));
1449 failed_export = true;
1452 lyxerr << "Caught some really weird exception..." << endl;
1458 failed_export = true;
1459 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1463 return !failed_export;
1467 void Buffer::writeLaTeXSource(otexstream & os,
1468 string const & original_path,
1469 OutputParams const & runparams_in,
1470 OutputWhat output) const
1472 // The child documents, if any, shall be already loaded at this point.
1474 OutputParams runparams = runparams_in;
1476 // If we are compiling a file standalone, even if this is the
1477 // child of some other buffer, let's cut the link here, so the
1478 // file is really independent and no concurring settings from
1479 // the master (e.g. branch state) interfere (see #8100).
1480 if (!runparams.is_child)
1481 d->ignore_parent = true;
1483 // Classify the unicode characters appearing in math insets
1484 Encodings::initUnicodeMath(*this);
1486 // validate the buffer.
1487 LYXERR(Debug::LATEX, " Validating buffer...");
1488 LaTeXFeatures features(*this, params(), runparams);
1490 runparams.use_polyglossia = features.usePolyglossia();
1491 LYXERR(Debug::LATEX, " Buffer validation done.");
1493 bool const output_preamble =
1494 output == FullSource || output == OnlyPreamble;
1495 bool const output_body =
1496 output == FullSource || output == OnlyBody;
1498 // The starting paragraph of the coming rows is the
1499 // first paragraph of the document. (Asger)
1500 if (output_preamble && runparams.nice) {
1501 os << "%% LyX " << lyx_version << " created this file. "
1502 "For more info, see http://www.lyx.org/.\n"
1503 "%% Do not edit unless you really know what "
1506 LYXERR(Debug::INFO, "lyx document header finished");
1508 // There are a few differences between nice LaTeX and usual files:
1509 // usual files have \batchmode and special input@path to allow
1510 // inclusion of figures specified by an explicitly relative path
1511 // (i.e., a path starting with './' or '../') with either \input or
1512 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1513 // input@path is set when the actual parameter original_path is set.
1514 // This is done for usual tex-file, but not for nice-latex-file.
1515 // (Matthias 250696)
1516 // Note that input@path is only needed for something the user does
1517 // in the preamble, included .tex files or ERT, files included by
1518 // LyX work without it.
1519 if (output_preamble) {
1520 if (!runparams.nice) {
1521 // code for usual, NOT nice-latex-file
1522 os << "\\batchmode\n"; // changed from \nonstopmode
1524 if (!original_path.empty()) {
1526 // We don't know the encoding of inputpath
1527 docstring const inputpath = from_utf8(original_path);
1528 docstring uncodable_glyphs;
1529 Encoding const * const enc = runparams.encoding;
1531 for (size_t n = 0; n < inputpath.size(); ++n) {
1532 if (!enc->encodable(inputpath[n])) {
1533 docstring const glyph(1, inputpath[n]);
1534 LYXERR0("Uncodable character '"
1536 << "' in input path!");
1537 uncodable_glyphs += glyph;
1542 // warn user if we found uncodable glyphs.
1543 if (!uncodable_glyphs.empty()) {
1544 frontend::Alert::warning(
1545 _("Uncodable character in file path"),
1547 _("The path of your document\n"
1549 "contains glyphs that are unknown "
1550 "in the current document encoding "
1551 "(namely %2$s). This may result in "
1552 "incomplete output, unless "
1553 "TEXINPUTS contains the document "
1554 "directory and you don't use "
1555 "explicitly relative paths (i.e., "
1556 "paths starting with './' or "
1557 "'../') in the preamble or in ERT."
1558 "\n\nIn case of problems, choose "
1559 "an appropriate document encoding\n"
1560 "(such as utf8) or change the "
1562 inputpath, uncodable_glyphs));
1565 support::latex_path(original_path);
1566 if (contains(docdir, '#')) {
1567 docdir = subst(docdir, "#", "\\#");
1568 os << "\\catcode`\\#=11"
1569 "\\def\\#{#}\\catcode`\\#=6\n";
1571 if (contains(docdir, '%')) {
1572 docdir = subst(docdir, "%", "\\%");
1573 os << "\\catcode`\\%=11"
1574 "\\def\\%{%}\\catcode`\\%=14\n";
1576 os << "\\makeatletter\n"
1577 << "\\def\\input@path{{"
1578 << docdir << "/}}\n"
1579 << "\\makeatother\n";
1583 // get parent macros (if this buffer has a parent) which will be
1584 // written at the document begin further down.
1585 MacroSet parentMacros;
1586 listParentMacros(parentMacros, features);
1588 // Write the preamble
1589 runparams.use_babel = params().writeLaTeX(os, features,
1590 d->filename.onlyPath());
1592 runparams.use_japanese = features.isRequired("japanese");
1595 // Restore the parenthood if needed
1596 if (!runparams.is_child)
1597 d->ignore_parent = false;
1602 os << "\\begin{document}\n";
1604 // output the parent macros
1605 MacroSet::iterator it = parentMacros.begin();
1606 MacroSet::iterator end = parentMacros.end();
1607 for (; it != end; ++it) {
1608 int num_lines = (*it)->write(os.os(), true);
1609 os.texrow().newlines(num_lines);
1612 } // output_preamble
1614 os.texrow().start(paragraphs().begin()->id(), 0);
1616 LYXERR(Debug::INFO, "preamble finished, now the body.");
1619 latexParagraphs(*this, text(), os, runparams);
1621 // Restore the parenthood if needed
1622 if (!runparams.is_child)
1623 d->ignore_parent = false;
1625 // add this just in case after all the paragraphs
1628 if (output_preamble) {
1629 os << "\\end{document}\n";
1630 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1632 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1634 runparams_in.encoding = runparams.encoding;
1636 // Just to be sure. (Asger)
1637 os.texrow().newline();
1639 //for (int i = 0; i<d->texrow.rows(); i++) {
1641 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1642 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1645 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1646 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1650 void Buffer::makeDocBookFile(FileName const & fname,
1651 OutputParams const & runparams,
1652 OutputWhat output) const
1654 LYXERR(Debug::LATEX, "makeDocBookFile...");
1657 if (!openFileWrite(ofs, fname))
1660 // make sure we are ready to export
1661 // this needs to be done before we validate
1663 updateMacroInstances(OutputUpdate);
1665 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1669 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1673 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1674 OutputParams const & runparams,
1675 OutputWhat output) const
1677 LaTeXFeatures features(*this, params(), runparams);
1682 DocumentClass const & tclass = params().documentClass();
1683 string const top_element = tclass.latexname();
1685 bool const output_preamble =
1686 output == FullSource || output == OnlyPreamble;
1687 bool const output_body =
1688 output == FullSource || output == OnlyBody;
1690 if (output_preamble) {
1691 if (runparams.flavor == OutputParams::XML)
1692 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1695 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1698 if (! tclass.class_header().empty())
1699 os << from_ascii(tclass.class_header());
1700 else if (runparams.flavor == OutputParams::XML)
1701 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1702 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1704 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1706 docstring preamble = from_utf8(params().preamble);
1707 if (runparams.flavor != OutputParams::XML ) {
1708 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1709 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1710 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1711 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1714 string const name = runparams.nice
1715 ? changeExtension(absFileName(), ".sgml") : fname;
1716 preamble += features.getIncludedFiles(name);
1717 preamble += features.getLyXSGMLEntities();
1719 if (!preamble.empty()) {
1720 os << "\n [ " << preamble << " ]";
1726 string top = top_element;
1728 if (runparams.flavor == OutputParams::XML)
1729 top += params().language->code();
1731 top += params().language->code().substr(0, 2);
1734 if (!params().options.empty()) {
1736 top += params().options;
1739 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1740 << " file was created by LyX " << lyx_version
1741 << "\n See http://www.lyx.org/ for more information -->\n";
1743 params().documentClass().counters().reset();
1745 sgml::openTag(os, top);
1747 docbookParagraphs(text(), *this, os, runparams);
1748 sgml::closeTag(os, top_element);
1753 void Buffer::makeLyXHTMLFile(FileName const & fname,
1754 OutputParams const & runparams) const
1756 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1759 if (!openFileWrite(ofs, fname))
1762 // make sure we are ready to export
1763 // this has to be done before we validate
1764 updateBuffer(UpdateMaster, OutputUpdate);
1765 updateMacroInstances(OutputUpdate);
1767 writeLyXHTMLSource(ofs, runparams, FullSource);
1771 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1775 void Buffer::writeLyXHTMLSource(odocstream & os,
1776 OutputParams const & runparams,
1777 OutputWhat output) const
1779 LaTeXFeatures features(*this, params(), runparams);
1781 d->bibinfo_.makeCitationLabels(*this);
1783 bool const output_preamble =
1784 output == FullSource || output == OnlyPreamble;
1785 bool const output_body =
1786 output == FullSource || output == OnlyBody || output == IncludedFile;
1788 if (output_preamble) {
1789 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1790 << "<!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"
1791 // FIXME Language should be set properly.
1792 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1794 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1795 // FIXME Presumably need to set this right
1796 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1798 docstring const & doctitle = features.htmlTitle();
1800 << (doctitle.empty() ?
1801 from_ascii("LyX Document") :
1802 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1805 docstring styles = features.getTClassHTMLPreamble();
1806 if (!styles.empty())
1807 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1809 styles = from_utf8(features.getPreambleSnippets());
1810 if (!styles.empty())
1811 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1813 // we will collect CSS information in a stream, and then output it
1814 // either here, as part of the header, or else in a separate file.
1815 odocstringstream css;
1816 styles = from_utf8(features.getCSSSnippets());
1817 if (!styles.empty())
1818 css << "/* LyX Provided Styles */\n" << styles << '\n';
1820 styles = features.getTClassHTMLStyles();
1821 if (!styles.empty())
1822 css << "/* Layout-provided Styles */\n" << styles << '\n';
1824 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1825 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1826 if (needfg || needbg) {
1827 css << "\nbody {\n";
1830 << from_ascii(X11hexname(params().fontcolor))
1833 css << " background-color: "
1834 << from_ascii(X11hexname(params().backgroundcolor))
1839 docstring const dstyles = css.str();
1840 if (!dstyles.empty()) {
1841 bool written = false;
1842 if (params().html_css_as_file) {
1843 // open a file for CSS info
1845 string const fcssname = addName(temppath(), "docstyle.css");
1846 FileName const fcssfile = FileName(fcssname);
1847 if (openFileWrite(ocss, fcssfile)) {
1851 // write link to header
1852 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1854 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1857 // we are here if the CSS is supposed to be written to the header
1858 // or if we failed to write it to an external file.
1860 os << "<style type='text/css'>\n"
1869 bool const output_body_tag = (output != IncludedFile);
1870 if (output_body_tag)
1873 params().documentClass().counters().reset();
1874 xhtmlParagraphs(text(), *this, xs, runparams);
1875 if (output_body_tag)
1879 if (output_preamble)
1884 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1885 // Other flags: -wall -v0 -x
1886 int Buffer::runChktex()
1890 // get LaTeX-Filename
1891 FileName const path(temppath());
1892 string const name = addName(path.absFileName(), latexName());
1893 string const org_path = filePath();
1895 PathChanger p(path); // path to LaTeX file
1896 message(_("Running chktex..."));
1898 // Generate the LaTeX file if neccessary
1899 OutputParams runparams(¶ms().encoding());
1900 runparams.flavor = OutputParams::LATEX;
1901 runparams.nice = false;
1902 runparams.linelen = lyxrc.plaintext_linelen;
1903 makeLaTeXFile(FileName(name), org_path, runparams);
1906 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1907 int const res = chktex.run(terr); // run chktex
1910 Alert::error(_("chktex failure"),
1911 _("Could not run chktex successfully."));
1912 } else if (res > 0) {
1913 ErrorList & errlist = d->errorLists["ChkTeX"];
1915 bufferErrors(terr, errlist);
1926 void Buffer::validate(LaTeXFeatures & features) const
1928 // Validate the buffer params, but not for included
1929 // files, since they also use the parent buffer's
1931 if (!features.runparams().is_child)
1932 params().validate(features);
1934 for_each(paragraphs().begin(), paragraphs().end(),
1935 bind(&Paragraph::validate, _1, ref(features)));
1937 if (lyxerr.debugging(Debug::LATEX)) {
1938 features.showStruct();
1943 void Buffer::getLabelList(vector<docstring> & list) const
1945 // If this is a child document, use the master's list instead.
1947 masterBuffer()->getLabelList(list);
1952 Toc & toc = d->toc_backend.toc("label");
1953 TocIterator toc_it = toc.begin();
1954 TocIterator end = toc.end();
1955 for (; toc_it != end; ++toc_it) {
1956 if (toc_it->depth() == 0)
1957 list.push_back(toc_it->str());
1962 void Buffer::updateBibfilesCache(UpdateScope scope) const
1964 // FIXME This is probably unnecssary, given where we call this.
1965 // If this is a child document, use the parent's cache instead.
1966 if (parent() && scope != UpdateChildOnly) {
1967 masterBuffer()->updateBibfilesCache();
1971 d->bibfiles_cache_.clear();
1972 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1973 if (it->lyxCode() == BIBTEX_CODE) {
1974 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1975 support::FileNameList const bibfiles = inset.getBibFiles();
1976 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1979 } else if (it->lyxCode() == INCLUDE_CODE) {
1980 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1981 Buffer const * const incbuf = inset.getChildBuffer();
1984 support::FileNameList const & bibfiles =
1985 incbuf->getBibfilesCache(UpdateChildOnly);
1986 if (!bibfiles.empty()) {
1987 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1993 d->bibfile_cache_valid_ = true;
1994 d->bibinfo_cache_valid_ = false;
1995 d->cite_labels_valid_ = false;
1999 void Buffer::invalidateBibinfoCache() const
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->invalidateBibinfoCache();
2010 void Buffer::invalidateBibfileCache() const
2012 d->bibfile_cache_valid_ = false;
2013 d->bibinfo_cache_valid_ = false;
2014 d->cite_labels_valid_ = false;
2015 // also invalidate the cache for the parent buffer
2016 Buffer const * const pbuf = d->parent();
2018 pbuf->invalidateBibfileCache();
2022 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2024 // FIXME This is probably unnecessary, given where we call this.
2025 // If this is a child document, use the master's cache instead.
2026 Buffer const * const pbuf = masterBuffer();
2027 if (pbuf != this && scope != UpdateChildOnly)
2028 return pbuf->getBibfilesCache();
2030 if (!d->bibfile_cache_valid_)
2031 this->updateBibfilesCache(scope);
2033 return d->bibfiles_cache_;
2037 BiblioInfo const & Buffer::masterBibInfo() const
2039 Buffer const * const tmp = masterBuffer();
2041 return tmp->masterBibInfo();
2046 void Buffer::checkIfBibInfoCacheIsValid() const
2048 // use the master's cache
2049 Buffer const * const tmp = masterBuffer();
2051 tmp->checkIfBibInfoCacheIsValid();
2055 // compare the cached timestamps with the actual ones.
2056 FileNameList const & bibfiles_cache = getBibfilesCache();
2057 FileNameList::const_iterator ei = bibfiles_cache.begin();
2058 FileNameList::const_iterator en = bibfiles_cache.end();
2059 for (; ei != en; ++ ei) {
2060 time_t lastw = ei->lastModified();
2061 time_t prevw = d->bibfile_status_[*ei];
2062 if (lastw != prevw) {
2063 d->bibinfo_cache_valid_ = false;
2064 d->cite_labels_valid_ = false;
2065 d->bibfile_status_[*ei] = lastw;
2071 void Buffer::reloadBibInfoCache() const
2073 // use the master's cache
2074 Buffer const * const tmp = masterBuffer();
2076 tmp->reloadBibInfoCache();
2080 checkIfBibInfoCacheIsValid();
2081 if (d->bibinfo_cache_valid_)
2084 d->bibinfo_.clear();
2086 d->bibinfo_cache_valid_ = true;
2090 void Buffer::collectBibKeys() const
2092 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2093 it->collectBibKeys(it);
2097 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2099 Buffer const * tmp = masterBuffer();
2100 BiblioInfo & masterbi = (tmp == this) ?
2101 d->bibinfo_ : tmp->d->bibinfo_;
2102 masterbi.mergeBiblioInfo(bi);
2106 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2108 Buffer const * tmp = masterBuffer();
2109 BiblioInfo & masterbi = (tmp == this) ?
2110 d->bibinfo_ : tmp->d->bibinfo_;
2115 bool Buffer::citeLabelsValid() const
2117 return masterBuffer()->d->cite_labels_valid_;
2121 void Buffer::removeBiblioTempFiles() const
2123 // We remove files that contain LaTeX commands specific to the
2124 // particular bibliographic style being used, in order to avoid
2125 // LaTeX errors when we switch style.
2126 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2127 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2128 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2129 aux_file.removeFile();
2130 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2131 bbl_file.removeFile();
2132 // Also for the parent buffer
2133 Buffer const * const pbuf = parent();
2135 pbuf->removeBiblioTempFiles();
2139 bool Buffer::isDepClean(string const & name) const
2141 DepClean::const_iterator const it = d->dep_clean.find(name);
2142 if (it == d->dep_clean.end())
2148 void Buffer::markDepClean(string const & name)
2150 d->dep_clean[name] = true;
2154 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2157 // FIXME? if there is an Buffer LFUN that can be dispatched even
2158 // if internal, put a switch '(cmd.action)' here.
2164 switch (cmd.action()) {
2166 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2167 flag.setOnOff(isReadonly());
2170 // FIXME: There is need for a command-line import.
2171 //case LFUN_BUFFER_IMPORT:
2173 case LFUN_BUFFER_AUTO_SAVE:
2176 case LFUN_BUFFER_EXPORT_CUSTOM:
2177 // FIXME: Nothing to check here?
2180 case LFUN_BUFFER_EXPORT: {
2181 docstring const arg = cmd.argument();
2182 if (arg == "custom") {
2186 string format = to_utf8(arg);
2187 size_t pos = format.find(' ');
2188 if (pos != string::npos)
2189 format = format.substr(0, pos);
2190 enable = params().isExportable(format);
2192 flag.message(bformat(
2193 _("Don't know how to export to format: %1$s"), arg));
2197 case LFUN_BUFFER_CHKTEX:
2198 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2201 case LFUN_BUILD_PROGRAM:
2202 enable = params().isExportable("program");
2205 case LFUN_BRANCH_ADD:
2206 case LFUN_BRANCHES_RENAME:
2207 case LFUN_BUFFER_PRINT:
2208 // if no Buffer is present, then of course we won't be called!
2211 case LFUN_BUFFER_LANGUAGE:
2212 enable = !isReadonly();
2218 flag.setEnabled(enable);
2223 void Buffer::dispatch(string const & command, DispatchResult & result)
2225 return dispatch(lyxaction.lookupFunc(command), result);
2229 // NOTE We can end up here even if we have no GUI, because we are called
2230 // by LyX::exec to handled command-line requests. So we may need to check
2231 // whether we have a GUI or not. The boolean use_gui holds this information.
2232 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2235 // FIXME? if there is an Buffer LFUN that can be dispatched even
2236 // if internal, put a switch '(cmd.action())' here.
2237 dr.dispatched(false);
2240 string const argument = to_utf8(func.argument());
2241 // We'll set this back to false if need be.
2242 bool dispatched = true;
2243 undo().beginUndoGroup();
2245 switch (func.action()) {
2246 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2247 if (lyxvc().inUse())
2248 lyxvc().toggleReadOnly();
2250 setReadonly(!isReadonly());
2253 case LFUN_BUFFER_EXPORT: {
2254 ExportStatus const status = doExport(argument, false);
2255 dr.setError(status != ExportSuccess);
2256 if (status != ExportSuccess)
2257 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2262 case LFUN_BUILD_PROGRAM:
2263 doExport("program", true);
2266 case LFUN_BUFFER_CHKTEX:
2270 case LFUN_BUFFER_EXPORT_CUSTOM: {
2272 string command = split(argument, format_name, ' ');
2273 Format const * format = formats.getFormat(format_name);
2275 lyxerr << "Format \"" << format_name
2276 << "\" not recognized!"
2281 // The name of the file created by the conversion process
2284 // Output to filename
2285 if (format->name() == "lyx") {
2286 string const latexname = latexName(false);
2287 filename = changeExtension(latexname,
2288 format->extension());
2289 filename = addName(temppath(), filename);
2291 if (!writeFile(FileName(filename)))
2295 doExport(format_name, true, filename);
2298 // Substitute $$FName for filename
2299 if (!contains(command, "$$FName"))
2300 command = "( " + command + " ) < $$FName";
2301 command = subst(command, "$$FName", filename);
2303 // Execute the command in the background
2305 call.startscript(Systemcall::DontWait, command, filePath());
2309 // FIXME: There is need for a command-line import.
2311 case LFUN_BUFFER_IMPORT:
2316 case LFUN_BUFFER_AUTO_SAVE:
2318 resetAutosaveTimers();
2321 case LFUN_BRANCH_ADD: {
2322 docstring branch_name = func.argument();
2323 if (branch_name.empty()) {
2327 BranchList & branch_list = params().branchlist();
2328 vector<docstring> const branches =
2329 getVectorFromString(branch_name, branch_list.separator());
2331 for (vector<docstring>::const_iterator it = branches.begin();
2332 it != branches.end(); ++it) {
2334 Branch * branch = branch_list.find(branch_name);
2336 LYXERR0("Branch " << branch_name << " already exists.");
2340 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2342 branch_list.add(branch_name);
2343 branch = branch_list.find(branch_name);
2344 string const x11hexname = X11hexname(branch->color());
2345 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2346 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2348 dr.screenUpdate(Update::Force);
2356 case LFUN_BRANCHES_RENAME: {
2357 if (func.argument().empty())
2360 docstring const oldname = from_utf8(func.getArg(0));
2361 docstring const newname = from_utf8(func.getArg(1));
2362 InsetIterator it = inset_iterator_begin(inset());
2363 InsetIterator const end = inset_iterator_end(inset());
2364 bool success = false;
2365 for (; it != end; ++it) {
2366 if (it->lyxCode() == BRANCH_CODE) {
2367 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2368 if (ins.branch() == oldname) {
2369 undo().recordUndo(CursorData(it));
2370 ins.rename(newname);
2375 if (it->lyxCode() == INCLUDE_CODE) {
2376 // get buffer of external file
2377 InsetInclude const & ins =
2378 static_cast<InsetInclude const &>(*it);
2379 Buffer * child = ins.getChildBuffer();
2382 child->dispatch(func, dr);
2387 dr.screenUpdate(Update::Force);
2388 dr.forceBufferUpdate();
2393 case LFUN_BUFFER_PRINT: {
2394 // we'll assume there's a problem until we succeed
2396 string target = func.getArg(0);
2397 string target_name = func.getArg(1);
2398 string command = func.getArg(2);
2401 || target_name.empty()
2402 || command.empty()) {
2403 LYXERR0("Unable to parse " << func.argument());
2404 docstring const msg =
2405 bformat(_("Unable to parse \"%1$s\""), func.argument());
2409 if (target != "printer" && target != "file") {
2410 LYXERR0("Unrecognized target \"" << target << '"');
2411 docstring const msg =
2412 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2417 if (!doExport("dvi", true)) {
2418 showPrintError(absFileName());
2419 dr.setMessage(_("Error exporting to DVI."));
2423 // Push directory path.
2424 string const path = temppath();
2425 // Prevent the compiler from optimizing away p
2429 // there are three cases here:
2430 // 1. we print to a file
2431 // 2. we print directly to a printer
2432 // 3. we print using a spool command (print to file first)
2435 string const dviname = changeExtension(latexName(true), "dvi");
2437 if (target == "printer") {
2438 if (!lyxrc.print_spool_command.empty()) {
2439 // case 3: print using a spool
2440 string const psname = changeExtension(dviname,".ps");
2441 command += ' ' + lyxrc.print_to_file
2444 + quoteName(dviname);
2446 string command2 = lyxrc.print_spool_command + ' ';
2447 if (target_name != "default") {
2448 command2 += lyxrc.print_spool_printerprefix
2452 command2 += quoteName(psname);
2454 // If successful, then spool command
2455 res = one.startscript(Systemcall::Wait, command,
2459 // If there's no GUI, we have to wait on this command. Otherwise,
2460 // LyX deletes the temporary directory, and with it the spooled
2461 // file, before it can be printed!!
2462 Systemcall::Starttype stype = use_gui ?
2463 Systemcall::DontWait : Systemcall::Wait;
2464 res = one.startscript(stype, command2,
2468 // case 2: print directly to a printer
2469 if (target_name != "default")
2470 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2472 Systemcall::Starttype stype = use_gui ?
2473 Systemcall::DontWait : Systemcall::Wait;
2474 res = one.startscript(stype, command +
2475 quoteName(dviname), filePath());
2479 // case 1: print to a file
2480 FileName const filename(makeAbsPath(target_name, filePath()));
2481 FileName const dvifile(makeAbsPath(dviname, path));
2482 if (filename.exists()) {
2483 docstring text = bformat(
2484 _("The file %1$s already exists.\n\n"
2485 "Do you want to overwrite that file?"),
2486 makeDisplayPath(filename.absFileName()));
2487 if (Alert::prompt(_("Overwrite file?"),
2488 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2491 command += ' ' + lyxrc.print_to_file
2492 + quoteName(filename.toFilesystemEncoding())
2494 + quoteName(dvifile.toFilesystemEncoding());
2496 Systemcall::Starttype stype = use_gui ?
2497 Systemcall::DontWait : Systemcall::Wait;
2498 res = one.startscript(stype, command, filePath());
2504 dr.setMessage(_("Error running external commands."));
2505 showPrintError(absFileName());
2514 dr.dispatched(dispatched);
2515 undo().endUndoGroup();
2519 void Buffer::changeLanguage(Language const * from, Language const * to)
2521 LASSERT(from, /**/);
2524 for_each(par_iterator_begin(),
2526 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2530 bool Buffer::isMultiLingual() const
2532 ParConstIterator end = par_iterator_end();
2533 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2534 if (it->isMultiLingual(params()))
2541 std::set<Language const *> Buffer::getLanguages() const
2543 std::set<Language const *> languages;
2544 getLanguages(languages);
2549 void Buffer::getLanguages(std::set<Language const *> & languages) const
2551 ParConstIterator end = par_iterator_end();
2552 // add the buffer language, even if it's not actively used
2553 languages.insert(language());
2554 // iterate over the paragraphs
2555 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2556 it->getLanguages(languages);
2558 ListOfBuffers clist = getDescendents();
2559 ListOfBuffers::const_iterator cit = clist.begin();
2560 ListOfBuffers::const_iterator const cen = clist.end();
2561 for (; cit != cen; ++cit)
2562 (*cit)->getLanguages(languages);
2566 DocIterator Buffer::getParFromID(int const id) const
2568 Buffer * buf = const_cast<Buffer *>(this);
2570 // John says this is called with id == -1 from undo
2571 lyxerr << "getParFromID(), id: " << id << endl;
2572 return doc_iterator_end(buf);
2575 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2576 if (it.paragraph().id() == id)
2579 return doc_iterator_end(buf);
2583 bool Buffer::hasParWithID(int const id) const
2585 return !getParFromID(id).atEnd();
2589 ParIterator Buffer::par_iterator_begin()
2591 return ParIterator(doc_iterator_begin(this));
2595 ParIterator Buffer::par_iterator_end()
2597 return ParIterator(doc_iterator_end(this));
2601 ParConstIterator Buffer::par_iterator_begin() const
2603 return ParConstIterator(doc_iterator_begin(this));
2607 ParConstIterator Buffer::par_iterator_end() const
2609 return ParConstIterator(doc_iterator_end(this));
2613 Language const * Buffer::language() const
2615 return params().language;
2619 docstring const Buffer::B_(string const & l10n) const
2621 return params().B_(l10n);
2625 bool Buffer::isClean() const
2627 return d->lyx_clean;
2631 bool Buffer::isExternallyModified(CheckMethod method) const
2633 LASSERT(d->filename.exists(), /**/);
2634 // if method == timestamp, check timestamp before checksum
2635 return (method == checksum_method
2636 || d->timestamp_ != d->filename.lastModified())
2637 && d->checksum_ != d->filename.checksum();
2641 void Buffer::saveCheckSum() const
2643 FileName const & file = d->filename;
2646 if (file.exists()) {
2647 d->timestamp_ = file.lastModified();
2648 d->checksum_ = file.checksum();
2650 // in the case of save to a new file.
2657 void Buffer::markClean() const
2659 if (!d->lyx_clean) {
2660 d->lyx_clean = true;
2663 // if the .lyx file has been saved, we don't need an
2665 d->bak_clean = true;
2666 d->undo_.markDirty();
2670 void Buffer::setUnnamed(bool flag)
2676 bool Buffer::isUnnamed() const
2683 /// Don't check unnamed, here: isInternal() is used in
2684 /// newBuffer(), where the unnamed flag has not been set by anyone
2685 /// yet. Also, for an internal buffer, there should be no need for
2686 /// retrieving fileName() nor for checking if it is unnamed or not.
2687 bool Buffer::isInternal() const
2689 return d->internal_buffer;
2693 void Buffer::setInternal(bool flag)
2695 d->internal_buffer = flag;
2699 void Buffer::markDirty()
2702 d->lyx_clean = false;
2705 d->bak_clean = false;
2707 DepClean::iterator it = d->dep_clean.begin();
2708 DepClean::const_iterator const end = d->dep_clean.end();
2710 for (; it != end; ++it)
2715 FileName Buffer::fileName() const
2721 string Buffer::absFileName() const
2723 return d->filename.absFileName();
2727 string Buffer::filePath() const
2729 int last = d->filename.onlyPath().absFileName().length() - 1;
2731 return d->filename.onlyPath().absFileName()[last] == '/'
2732 ? d->filename.onlyPath().absFileName()
2733 : d->filename.onlyPath().absFileName() + "/";
2737 bool Buffer::isReadonly() const
2739 return d->read_only;
2743 void Buffer::setParent(Buffer const * buffer)
2745 // Avoids recursive include.
2746 d->setParent(buffer == this ? 0 : buffer);
2751 Buffer const * Buffer::parent() const
2757 ListOfBuffers Buffer::allRelatives() const
2759 ListOfBuffers lb = masterBuffer()->getDescendents();
2760 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2765 Buffer const * Buffer::masterBuffer() const
2767 // FIXME Should be make sure we are not in some kind
2768 // of recursive include? A -> B -> A will crash this.
2769 Buffer const * const pbuf = d->parent();
2773 return pbuf->masterBuffer();
2777 bool Buffer::isChild(Buffer * child) const
2779 return d->children_positions.find(child) != d->children_positions.end();
2783 DocIterator Buffer::firstChildPosition(Buffer const * child)
2785 Impl::BufferPositionMap::iterator it;
2786 it = d->children_positions.find(child);
2787 if (it == d->children_positions.end())
2788 return DocIterator(this);
2793 bool Buffer::hasChildren() const
2795 return !d->children_positions.empty();
2799 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2801 // loop over children
2802 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2803 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2804 for (; it != end; ++it) {
2805 Buffer * child = const_cast<Buffer *>(it->first);
2807 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2808 if (bit != clist.end())
2810 clist.push_back(child);
2812 // there might be grandchildren
2813 child->collectChildren(clist, true);
2818 ListOfBuffers Buffer::getChildren() const
2821 collectChildren(v, false);
2822 // Make sure we have not included ourselves.
2823 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2824 if (bit != v.end()) {
2825 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2832 ListOfBuffers Buffer::getDescendents() const
2835 collectChildren(v, true);
2836 // Make sure we have not included ourselves.
2837 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2838 if (bit != v.end()) {
2839 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2846 template<typename M>
2847 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2852 typename M::const_iterator it = m.lower_bound(x);
2853 if (it == m.begin())
2861 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2862 DocIterator const & pos) const
2864 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2866 // if paragraphs have no macro context set, pos will be empty
2870 // we haven't found anything yet
2871 DocIterator bestPos = owner_->par_iterator_begin();
2872 MacroData const * bestData = 0;
2874 // find macro definitions for name
2875 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2876 if (nameIt != macros.end()) {
2877 // find last definition in front of pos or at pos itself
2878 PositionScopeMacroMap::const_iterator it
2879 = greatest_below(nameIt->second, pos);
2880 if (it != nameIt->second.end()) {
2882 // scope ends behind pos?
2883 if (pos < it->second.first) {
2884 // Looks good, remember this. If there
2885 // is no external macro behind this,
2886 // we found the right one already.
2887 bestPos = it->first;
2888 bestData = &it->second.second;
2892 // try previous macro if there is one
2893 if (it == nameIt->second.begin())
2900 // find macros in included files
2901 PositionScopeBufferMap::const_iterator it
2902 = greatest_below(position_to_children, pos);
2903 if (it == position_to_children.end())
2904 // no children before
2908 // do we know something better (i.e. later) already?
2909 if (it->first < bestPos )
2912 // scope ends behind pos?
2913 if (pos < it->second.first
2914 && (cloned_buffer_ ||
2915 theBufferList().isLoaded(it->second.second))) {
2916 // look for macro in external file
2918 MacroData const * data
2919 = it->second.second->getMacro(name, false);
2922 bestPos = it->first;
2928 // try previous file if there is one
2929 if (it == position_to_children.begin())
2934 // return the best macro we have found
2939 MacroData const * Buffer::getMacro(docstring const & name,
2940 DocIterator const & pos, bool global) const
2945 // query buffer macros
2946 MacroData const * data = d->getBufferMacro(name, pos);
2950 // If there is a master buffer, query that
2951 Buffer const * const pbuf = d->parent();
2953 d->macro_lock = true;
2954 MacroData const * macro = pbuf->getMacro(
2955 name, *this, false);
2956 d->macro_lock = false;
2962 data = MacroTable::globalMacros().get(name);
2971 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2973 // set scope end behind the last paragraph
2974 DocIterator scope = par_iterator_begin();
2975 scope.pit() = scope.lastpit() + 1;
2977 return getMacro(name, scope, global);
2981 MacroData const * Buffer::getMacro(docstring const & name,
2982 Buffer const & child, bool global) const
2984 // look where the child buffer is included first
2985 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2986 if (it == d->children_positions.end())
2989 // check for macros at the inclusion position
2990 return getMacro(name, it->second, global);
2994 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2996 pit_type const lastpit = it.lastpit();
2998 // look for macros in each paragraph
2999 while (it.pit() <= lastpit) {
3000 Paragraph & par = it.paragraph();
3002 // iterate over the insets of the current paragraph
3003 InsetList const & insets = par.insetList();
3004 InsetList::const_iterator iit = insets.begin();
3005 InsetList::const_iterator end = insets.end();
3006 for (; iit != end; ++iit) {
3007 it.pos() = iit->pos;
3009 // is it a nested text inset?
3010 if (iit->inset->asInsetText()) {
3011 // Inset needs its own scope?
3012 InsetText const * itext = iit->inset->asInsetText();
3013 bool newScope = itext->isMacroScope();
3015 // scope which ends just behind the inset
3016 DocIterator insetScope = it;
3019 // collect macros in inset
3020 it.push_back(CursorSlice(*iit->inset));
3021 updateMacros(it, newScope ? insetScope : scope);
3026 if (iit->inset->asInsetTabular()) {
3027 CursorSlice slice(*iit->inset);
3028 size_t const numcells = slice.nargs();
3029 for (; slice.idx() < numcells; slice.forwardIdx()) {
3030 it.push_back(slice);
3031 updateMacros(it, scope);
3037 // is it an external file?
3038 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3039 // get buffer of external file
3040 InsetInclude const & inset =
3041 static_cast<InsetInclude const &>(*iit->inset);
3043 Buffer * child = inset.getChildBuffer();
3048 // register its position, but only when it is
3049 // included first in the buffer
3050 if (children_positions.find(child) ==
3051 children_positions.end())
3052 children_positions[child] = it;
3054 // register child with its scope
3055 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3059 InsetMath * im = iit->inset->asInsetMath();
3060 if (doing_export && im) {
3061 InsetMathHull * hull = im->asHullInset();
3063 hull->recordLocation(it);
3066 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3070 MathMacroTemplate & macroTemplate =
3071 *iit->inset->asInsetMath()->asMacroTemplate();
3072 MacroContext mc(owner_, it);
3073 macroTemplate.updateToContext(mc);
3076 bool valid = macroTemplate.validMacro();
3077 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3078 // then the BufferView's cursor will be invalid in
3079 // some cases which leads to crashes.
3084 // FIXME (Abdel), I don't understandt why we pass 'it' here
3085 // instead of 'macroTemplate' defined above... is this correct?
3086 macros[macroTemplate.name()][it] =
3087 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3097 void Buffer::updateMacros() const
3102 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3104 // start with empty table
3106 d->children_positions.clear();
3107 d->position_to_children.clear();
3109 // Iterate over buffer, starting with first paragraph
3110 // The scope must be bigger than any lookup DocIterator
3111 // later. For the global lookup, lastpit+1 is used, hence
3112 // we use lastpit+2 here.
3113 DocIterator it = par_iterator_begin();
3114 DocIterator outerScope = it;
3115 outerScope.pit() = outerScope.lastpit() + 2;
3116 d->updateMacros(it, outerScope);
3120 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3122 InsetIterator it = inset_iterator_begin(inset());
3123 InsetIterator const end = inset_iterator_end(inset());
3124 for (; it != end; ++it) {
3125 if (it->lyxCode() == BRANCH_CODE) {
3126 InsetBranch & br = static_cast<InsetBranch &>(*it);
3127 docstring const name = br.branch();
3128 if (!from_master && !params().branchlist().find(name))
3129 result.push_back(name);
3130 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3131 result.push_back(name);
3134 if (it->lyxCode() == INCLUDE_CODE) {
3135 // get buffer of external file
3136 InsetInclude const & ins =
3137 static_cast<InsetInclude const &>(*it);
3138 Buffer * child = ins.getChildBuffer();
3141 child->getUsedBranches(result, true);
3144 // remove duplicates
3149 void Buffer::updateMacroInstances(UpdateType utype) const
3151 LYXERR(Debug::MACROS, "updateMacroInstances for "
3152 << d->filename.onlyFileName());
3153 DocIterator it = doc_iterator_begin(this);
3155 DocIterator const end = doc_iterator_end(this);
3156 for (; it != end; it.forwardInset()) {
3157 // look for MathData cells in InsetMathNest insets
3158 InsetMath * minset = it.nextInset()->asInsetMath();
3162 // update macro in all cells of the InsetMathNest
3163 DocIterator::idx_type n = minset->nargs();
3164 MacroContext mc = MacroContext(this, it);
3165 for (DocIterator::idx_type i = 0; i < n; ++i) {
3166 MathData & data = minset->cell(i);
3167 data.updateMacros(0, mc, utype);
3173 void Buffer::listMacroNames(MacroNameSet & macros) const
3178 d->macro_lock = true;
3180 // loop over macro names
3181 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3182 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3183 for (; nameIt != nameEnd; ++nameIt)
3184 macros.insert(nameIt->first);
3186 // loop over children
3187 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3188 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3189 for (; it != end; ++it)
3190 it->first->listMacroNames(macros);
3193 Buffer const * const pbuf = d->parent();
3195 pbuf->listMacroNames(macros);
3197 d->macro_lock = false;
3201 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3203 Buffer const * const pbuf = d->parent();
3208 pbuf->listMacroNames(names);
3211 MacroNameSet::iterator it = names.begin();
3212 MacroNameSet::iterator end = names.end();
3213 for (; it != end; ++it) {
3215 MacroData const * data =
3216 pbuf->getMacro(*it, *this, false);
3218 macros.insert(data);
3220 // we cannot access the original MathMacroTemplate anymore
3221 // here to calls validate method. So we do its work here manually.
3222 // FIXME: somehow make the template accessible here.
3223 if (data->optionals() > 0)
3224 features.require("xargs");
3230 Buffer::References & Buffer::references(docstring const & label)
3233 return const_cast<Buffer *>(masterBuffer())->references(label);
3235 RefCache::iterator it = d->ref_cache_.find(label);
3236 if (it != d->ref_cache_.end())
3237 return it->second.second;
3239 static InsetLabel const * dummy_il = 0;
3240 static References const dummy_refs;
3241 it = d->ref_cache_.insert(
3242 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3243 return it->second.second;
3247 Buffer::References const & Buffer::references(docstring const & label) const
3249 return const_cast<Buffer *>(this)->references(label);
3253 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3255 masterBuffer()->d->ref_cache_[label].first = il;
3259 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3261 return masterBuffer()->d->ref_cache_[label].first;
3265 void Buffer::clearReferenceCache() const
3268 d->ref_cache_.clear();
3272 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3275 //FIXME: This does not work for child documents yet.
3276 LASSERT(code == CITE_CODE, /**/);
3278 reloadBibInfoCache();
3280 // Check if the label 'from' appears more than once
3281 BiblioInfo const & keys = masterBibInfo();
3282 BiblioInfo::const_iterator bit = keys.begin();
3283 BiblioInfo::const_iterator bend = keys.end();
3284 vector<docstring> labels;
3286 for (; bit != bend; ++bit)
3288 labels.push_back(bit->first);
3290 if (count(labels.begin(), labels.end(), from) > 1)
3293 string const paramName = "key";
3294 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3295 if (it->lyxCode() == code) {
3296 InsetCommand * inset = it->asInsetCommand();
3299 docstring const oldValue = inset->getParam(paramName);
3300 if (oldValue == from)
3301 inset->setParam(paramName, to);
3307 void Buffer::getSourceCode(odocstream & os, string const format,
3308 pit_type par_begin, pit_type par_end,
3309 OutputWhat output, bool master) const
3311 OutputParams runparams(¶ms().encoding());
3312 runparams.nice = true;
3313 runparams.flavor = params().getOutputFlavor(format);
3314 runparams.linelen = lyxrc.plaintext_linelen;
3315 // No side effect of file copying and image conversion
3316 runparams.dryrun = true;
3318 if (output == CurrentParagraph) {
3319 runparams.par_begin = par_begin;
3320 runparams.par_end = par_end;
3321 if (par_begin + 1 == par_end) {
3323 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3327 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3328 convert<docstring>(par_begin),
3329 convert<docstring>(par_end - 1))
3332 // output paragraphs
3333 if (runparams.flavor == OutputParams::LYX) {
3334 Paragraph const & par = text().paragraphs()[par_begin];
3336 depth_type dt = par.getDepth();
3337 par.write(ods, params(), dt);
3338 os << from_utf8(ods.str());
3339 } else if (runparams.flavor == OutputParams::HTML) {
3341 setMathFlavor(runparams);
3342 xhtmlParagraphs(text(), *this, xs, runparams);
3343 } else if (runparams.flavor == OutputParams::TEXT) {
3345 // FIXME Handles only one paragraph, unlike the others.
3346 // Probably should have some routine with a signature like them.
3347 writePlaintextParagraph(*this,
3348 text().paragraphs()[par_begin], os, runparams, dummy);
3349 } else if (params().isDocBook()) {
3350 docbookParagraphs(text(), *this, os, runparams);
3352 // If we are previewing a paragraph, even if this is the
3353 // child of some other buffer, let's cut the link here,
3354 // so that no concurring settings from the master
3355 // (e.g. branch state) interfere (see #8101).
3357 d->ignore_parent = true;
3358 // We need to validate the Buffer params' features here
3359 // in order to know if we should output polyglossia
3360 // macros (instead of babel macros)
3361 LaTeXFeatures features(*this, params(), runparams);
3362 params().validate(features);
3363 runparams.use_polyglossia = features.usePolyglossia();
3368 // latex or literate
3369 otexstream ots(os, texrow);
3372 latexParagraphs(*this, text(), ots, runparams);
3374 // Restore the parenthood
3376 d->ignore_parent = false;
3380 if (output == FullSource)
3381 os << _("Preview source code");
3382 else if (output == OnlyPreamble)
3383 os << _("Preview preamble");
3384 else if (output == OnlyBody)
3385 os << _("Preview body");
3387 if (runparams.flavor == OutputParams::LYX) {
3389 if (output == FullSource)
3391 else if (output == OnlyPreamble)
3392 params().writeFile(ods);
3393 else if (output == OnlyBody)
3395 os << from_utf8(ods.str());
3396 } else if (runparams.flavor == OutputParams::HTML) {
3397 writeLyXHTMLSource(os, runparams, output);
3398 } else if (runparams.flavor == OutputParams::TEXT) {
3399 if (output == OnlyPreamble) {
3400 os << "% "<< _("Plain text does not have a preamble.");
3402 writePlaintextFile(*this, os, runparams);
3403 } else if (params().isDocBook()) {
3404 writeDocBookSource(os, absFileName(), runparams, output);
3406 // latex or literate
3408 d->texrow.newline();
3409 d->texrow.newline();
3410 otexstream ots(os, d->texrow);
3412 runparams.is_child = true;
3413 writeLaTeXSource(ots, string(), runparams, output);
3419 ErrorList & Buffer::errorList(string const & type) const
3421 return d->errorLists[type];
3425 void Buffer::updateTocItem(std::string const & type,
3426 DocIterator const & dit) const
3429 d->gui_->updateTocItem(type, dit);
3433 void Buffer::structureChanged() const
3436 d->gui_->structureChanged();
3440 void Buffer::errors(string const & err, bool from_master) const
3443 d->gui_->errors(err, from_master);
3447 void Buffer::message(docstring const & msg) const
3450 d->gui_->message(msg);
3454 void Buffer::setBusy(bool on) const
3457 d->gui_->setBusy(on);
3461 void Buffer::updateTitles() const
3464 d->wa_->updateTitles();
3468 void Buffer::resetAutosaveTimers() const
3471 d->gui_->resetAutosaveTimers();
3475 bool Buffer::hasGuiDelegate() const
3481 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3490 class AutoSaveBuffer : public ForkedProcess {
3493 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3494 : buffer_(buffer), fname_(fname) {}
3496 virtual shared_ptr<ForkedProcess> clone() const
3498 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3503 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3504 from_utf8(fname_.absFileName())));
3505 return run(DontWait);
3509 virtual int generateChild();
3511 Buffer const & buffer_;
3516 int AutoSaveBuffer::generateChild()
3518 #if defined(__APPLE__)
3519 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3520 * We should use something else like threads.
3522 * Since I do not know how to determine at run time what is the OS X
3523 * version, I just disable forking altogether for now (JMarc)
3525 pid_t const pid = -1;
3527 // tmp_ret will be located (usually) in /tmp
3528 // will that be a problem?
3529 // Note that this calls ForkedCalls::fork(), so it's
3530 // ok cross-platform.
3531 pid_t const pid = fork();
3532 // If you want to debug the autosave
3533 // you should set pid to -1, and comment out the fork.
3534 if (pid != 0 && pid != -1)
3538 // pid = -1 signifies that lyx was unable
3539 // to fork. But we will do the save
3541 bool failed = false;
3542 FileName const tmp_ret = FileName::tempName("lyxauto");
3543 if (!tmp_ret.empty()) {
3544 buffer_.writeFile(tmp_ret);
3545 // assume successful write of tmp_ret
3546 if (!tmp_ret.moveTo(fname_))
3552 // failed to write/rename tmp_ret so try writing direct
3553 if (!buffer_.writeFile(fname_)) {
3554 // It is dangerous to do this in the child,
3555 // but safe in the parent, so...
3556 if (pid == -1) // emit message signal.
3557 buffer_.message(_("Autosave failed!"));
3561 if (pid == 0) // we are the child so...
3570 FileName Buffer::getEmergencyFileName() const
3572 return FileName(d->filename.absFileName() + ".emergency");
3576 FileName Buffer::getAutosaveFileName() const
3578 // if the document is unnamed try to save in the backup dir, else
3579 // in the default document path, and as a last try in the filePath,
3580 // which will most often be the temporary directory
3583 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3584 : lyxrc.backupdir_path;
3585 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3588 string const fname = "#" + d->filename.onlyFileName() + "#";
3590 return makeAbsPath(fname, fpath);
3594 void Buffer::removeAutosaveFile() const
3596 FileName const f = getAutosaveFileName();
3602 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3604 FileName const newauto = getAutosaveFileName();
3606 if (newauto != oldauto && oldauto.exists())
3607 if (!oldauto.moveTo(newauto))
3608 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3612 bool Buffer::autoSave() const
3614 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3615 if (buf->d->bak_clean || isReadonly())
3618 message(_("Autosaving current document..."));
3619 buf->d->bak_clean = true;
3621 FileName const fname = getAutosaveFileName();
3622 if (d->cloned_buffer_) {
3623 // If this buffer is cloned, we assume that
3624 // we are running in a separate thread already.
3625 FileName const tmp_ret = FileName::tempName("lyxauto");
3626 if (!tmp_ret.empty()) {
3628 // assume successful write of tmp_ret
3629 if (tmp_ret.moveTo(fname))
3632 // failed to write/rename tmp_ret so try writing direct
3633 return writeFile(fname);
3635 /// This function is deprecated as the frontend needs to take care
3636 /// of cloning the buffer and autosaving it in another thread. It
3637 /// is still here to allow (QT_VERSION < 0x040400).
3638 AutoSaveBuffer autosave(*this, fname);
3645 // helper class, to guarantee this gets reset properly
3646 class Buffer::MarkAsExporting {
3648 MarkAsExporting(Buffer const * buf) : buf_(buf)
3650 LASSERT(buf_, /* */);
3651 buf_->setExportStatus(true);
3655 buf_->setExportStatus(false);
3658 Buffer const * const buf_;
3663 void Buffer::setExportStatus(bool e) const
3665 d->doing_export = e;
3666 ListOfBuffers clist = getDescendents();
3667 ListOfBuffers::const_iterator cit = clist.begin();
3668 ListOfBuffers::const_iterator const cen = clist.end();
3669 for (; cit != cen; ++cit)
3670 (*cit)->d->doing_export = e;
3674 bool Buffer::isExporting() const
3676 return d->doing_export;
3680 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3684 return doExport(target, put_in_tempdir, result_file);
3687 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3688 string & result_file) const
3690 bool const update_unincluded =
3691 params().maintain_unincluded_children
3692 && !params().getIncludedChildren().empty();
3694 // (1) export with all included children (omit \includeonly)
3695 if (update_unincluded) {
3696 ExportStatus const status =
3697 doExport(target, put_in_tempdir, true, result_file);
3698 if (status != ExportSuccess)
3701 // (2) export with included children only
3702 return doExport(target, put_in_tempdir, false, result_file);
3706 void Buffer::setMathFlavor(OutputParams & op) const
3708 switch (params().html_math_output) {
3709 case BufferParams::MathML:
3710 op.math_flavor = OutputParams::MathAsMathML;
3712 case BufferParams::HTML:
3713 op.math_flavor = OutputParams::MathAsHTML;
3715 case BufferParams::Images:
3716 op.math_flavor = OutputParams::MathAsImages;
3718 case BufferParams::LaTeX:
3719 op.math_flavor = OutputParams::MathAsLaTeX;
3725 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3726 bool includeall, string & result_file) const
3728 LYXERR(Debug::FILES, "target=" << target);
3729 OutputParams runparams(¶ms().encoding());
3730 string format = target;
3731 string dest_filename;
3732 size_t pos = target.find(' ');
3733 if (pos != string::npos) {
3734 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3735 format = target.substr(0, pos);
3736 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3737 FileName(dest_filename).onlyPath().createPath();
3738 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3740 MarkAsExporting exporting(this);
3741 string backend_format;
3742 runparams.flavor = OutputParams::LATEX;
3743 runparams.linelen = lyxrc.plaintext_linelen;
3744 runparams.includeall = includeall;
3745 vector<string> backs = params().backends();
3746 Converters converters = theConverters();
3747 bool need_nice_file = false;
3748 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3749 // Get shortest path to format
3750 converters.buildGraph();
3751 Graph::EdgePath path;
3752 for (vector<string>::const_iterator it = backs.begin();
3753 it != backs.end(); ++it) {
3754 Graph::EdgePath p = converters.getPath(*it, format);
3755 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3756 backend_format = *it;
3761 if (!put_in_tempdir) {
3762 // Only show this alert if this is an export to a non-temporary
3763 // file (not for previewing).
3764 Alert::error(_("Couldn't export file"), bformat(
3765 _("No information for exporting the format %1$s."),
3766 formats.prettyName(format)));
3768 return ExportNoPathToFormat;
3770 runparams.flavor = converters.getFlavor(path, this);
3771 Graph::EdgePath::const_iterator it = path.begin();
3772 Graph::EdgePath::const_iterator en = path.end();
3773 for (; it != en; ++it)
3774 if (theConverters().get(*it).nice) {
3775 need_nice_file = true;
3780 backend_format = format;
3781 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3782 // FIXME: Don't hardcode format names here, but use a flag
3783 if (backend_format == "pdflatex")
3784 runparams.flavor = OutputParams::PDFLATEX;
3785 else if (backend_format == "luatex")
3786 runparams.flavor = OutputParams::LUATEX;
3787 else if (backend_format == "dviluatex")
3788 runparams.flavor = OutputParams::DVILUATEX;
3789 else if (backend_format == "xetex")
3790 runparams.flavor = OutputParams::XETEX;
3793 string filename = latexName(false);
3794 filename = addName(temppath(), filename);
3795 filename = changeExtension(filename,
3796 formats.extension(backend_format));
3797 LYXERR(Debug::FILES, "filename=" << filename);
3799 // Plain text backend
3800 if (backend_format == "text") {
3801 runparams.flavor = OutputParams::TEXT;
3802 writePlaintextFile(*this, FileName(filename), runparams);
3805 else if (backend_format == "xhtml") {
3806 runparams.flavor = OutputParams::HTML;
3807 setMathFlavor(runparams);
3808 makeLyXHTMLFile(FileName(filename), runparams);
3809 } else if (backend_format == "lyx")
3810 writeFile(FileName(filename));
3812 else if (params().isDocBook()) {
3813 runparams.nice = !put_in_tempdir;
3814 makeDocBookFile(FileName(filename), runparams);
3817 else if (backend_format == format || need_nice_file) {
3818 runparams.nice = true;
3819 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3820 if (d->cloned_buffer_)
3821 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3824 } else if (!lyxrc.tex_allows_spaces
3825 && contains(filePath(), ' ')) {
3826 Alert::error(_("File name error"),
3827 _("The directory path to the document cannot contain spaces."));
3828 return ExportTexPathHasSpaces;
3830 runparams.nice = false;
3831 bool const success = makeLaTeXFile(
3832 FileName(filename), filePath(), runparams);
3833 if (d->cloned_buffer_)
3834 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3839 string const error_type = (format == "program")
3840 ? "Build" : params().bufferFormat();
3841 ErrorList & error_list = d->errorLists[error_type];
3842 string const ext = formats.extension(format);
3843 FileName const tmp_result_file(changeExtension(filename, ext));
3844 bool const success = converters.convert(this, FileName(filename),
3845 tmp_result_file, FileName(absFileName()), backend_format, format,
3848 // Emit the signal to show the error list or copy it back to the
3849 // cloned Buffer so that it can be emitted afterwards.
3850 if (format != backend_format) {
3851 if (d->cloned_buffer_) {
3852 d->cloned_buffer_->d->errorLists[error_type] =
3853 d->errorLists[error_type];
3856 // also to the children, in case of master-buffer-view
3857 ListOfBuffers clist = getDescendents();
3858 ListOfBuffers::const_iterator cit = clist.begin();
3859 ListOfBuffers::const_iterator const cen = clist.end();
3860 for (; cit != cen; ++cit) {
3861 if (d->cloned_buffer_) {
3862 // Enable reverse search by copying back the
3863 // texrow object to the cloned buffer.
3864 // FIXME: this is not thread safe.
3865 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3866 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3867 (*cit)->d->errorLists[error_type];
3869 (*cit)->errors(error_type, true);
3873 if (d->cloned_buffer_) {
3874 // Enable reverse dvi or pdf to work by copying back the texrow
3875 // object to the cloned buffer.
3876 // FIXME: There is a possibility of concurrent access to texrow
3877 // here from the main GUI thread that should be securized.
3878 d->cloned_buffer_->d->texrow = d->texrow;
3879 string const error_type = params().bufferFormat();
3880 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3884 return ExportConverterError;
3886 if (put_in_tempdir) {
3887 result_file = tmp_result_file.absFileName();
3888 return ExportSuccess;
3891 if (dest_filename.empty())
3892 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3894 result_file = dest_filename;
3895 // We need to copy referenced files (e. g. included graphics
3896 // if format == "dvi") to the result dir.
3897 vector<ExportedFile> const files =
3898 runparams.exportdata->externalFiles(format);
3899 string const dest = runparams.export_folder.empty() ?
3900 onlyPath(result_file) : runparams.export_folder;
3901 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3902 : force_overwrite == ALL_FILES;
3903 CopyStatus status = use_force ? FORCE : SUCCESS;
3905 vector<ExportedFile>::const_iterator it = files.begin();
3906 vector<ExportedFile>::const_iterator const en = files.end();
3907 for (; it != en && status != CANCEL; ++it) {
3908 string const fmt = formats.getFormatFromFile(it->sourceName);
3909 string fixedName = it->exportName;
3910 if (!runparams.export_folder.empty()) {
3911 // Relative pathnames starting with ../ will be sanitized
3912 // if exporting to a different folder
3913 while (fixedName.substr(0, 3) == "../")
3914 fixedName = fixedName.substr(3, fixedName.length() - 3);
3916 FileName fixedFileName = makeAbsPath(fixedName, dest);
3917 fixedFileName.onlyPath().createPath();
3918 status = copyFile(fmt, it->sourceName,
3920 it->exportName, status == FORCE,
3921 runparams.export_folder.empty());
3924 if (status == CANCEL) {
3925 message(_("Document export cancelled."));
3926 return ExportCancel;
3929 if (tmp_result_file.exists()) {
3930 // Finally copy the main file
3931 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3932 : force_overwrite != NO_FILES;
3933 if (status == SUCCESS && use_force)
3935 status = copyFile(format, tmp_result_file,
3936 FileName(result_file), result_file,
3938 if (status == CANCEL) {
3939 message(_("Document export cancelled."));
3940 return ExportCancel;
3942 message(bformat(_("Document exported as %1$s "
3944 formats.prettyName(format),
3945 makeDisplayPath(result_file)));
3948 // This must be a dummy converter like fax (bug 1888)
3949 message(bformat(_("Document exported as %1$s"),
3950 formats.prettyName(format)));
3953 return ExportSuccess;
3957 Buffer::ExportStatus Buffer::preview(string const & format) const
3959 bool const update_unincluded =
3960 params().maintain_unincluded_children
3961 && !params().getIncludedChildren().empty();
3962 return preview(format, update_unincluded);
3965 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3967 MarkAsExporting exporting(this);
3969 // (1) export with all included children (omit \includeonly)
3971 ExportStatus const status = doExport(format, true, true, result_file);
3972 if (status != ExportSuccess)
3975 // (2) export with included children only
3976 ExportStatus const status = doExport(format, true, false, result_file);
3977 if (status != ExportSuccess)
3979 if (!formats.view(*this, FileName(result_file), format))
3980 return PreviewError;
3981 return PreviewSuccess;
3985 Buffer::ReadStatus Buffer::extractFromVC()
3987 bool const found = LyXVC::file_not_found_hook(d->filename);
3989 return ReadFileNotFound;
3990 if (!d->filename.isReadableFile())
3996 Buffer::ReadStatus Buffer::loadEmergency()
3998 FileName const emergencyFile = getEmergencyFileName();
3999 if (!emergencyFile.exists()
4000 || emergencyFile.lastModified() <= d->filename.lastModified())
4001 return ReadFileNotFound;
4003 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4004 docstring const text = bformat(_("An emergency save of the document "
4005 "%1$s exists.\n\nRecover emergency save?"), file);
4007 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4008 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4014 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4015 bool const success = (ret_llf == ReadSuccess);
4018 Alert::warning(_("File is read-only"),
4019 bformat(_("An emergency file is successfully loaded, "
4020 "but the original file %1$s is marked read-only. "
4021 "Please make sure to save the document as a different "
4022 "file."), from_utf8(d->filename.absFileName())));
4025 str = _("Document was successfully recovered.");
4027 str = _("Document was NOT successfully recovered.");
4028 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4029 makeDisplayPath(emergencyFile.absFileName()));
4031 int const del_emerg =
4032 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4033 _("&Remove"), _("&Keep"));
4034 if (del_emerg == 0) {
4035 emergencyFile.removeFile();
4037 Alert::warning(_("Emergency file deleted"),
4038 _("Do not forget to save your file now!"), true);
4040 return success ? ReadSuccess : ReadEmergencyFailure;
4043 int const del_emerg =
4044 Alert::prompt(_("Delete emergency file?"),
4045 _("Remove emergency file now?"), 1, 1,
4046 _("&Remove"), _("&Keep"));
4048 emergencyFile.removeFile();
4049 return ReadOriginal;
4059 Buffer::ReadStatus Buffer::loadAutosave()
4061 // Now check if autosave file is newer.
4062 FileName const autosaveFile = getAutosaveFileName();
4063 if (!autosaveFile.exists()
4064 || autosaveFile.lastModified() <= d->filename.lastModified())
4065 return ReadFileNotFound;
4067 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4068 docstring const text = bformat(_("The backup of the document %1$s "
4069 "is newer.\n\nLoad the backup instead?"), file);
4070 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4071 _("&Load backup"), _("Load &original"), _("&Cancel"));
4076 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4077 // the file is not saved if we load the autosave file.
4078 if (ret_llf == ReadSuccess) {
4080 Alert::warning(_("File is read-only"),
4081 bformat(_("A backup file is successfully loaded, "
4082 "but the original file %1$s is marked read-only. "
4083 "Please make sure to save the document as a "
4085 from_utf8(d->filename.absFileName())));
4090 return ReadAutosaveFailure;
4093 // Here we delete the autosave
4094 autosaveFile.removeFile();
4095 return ReadOriginal;
4103 Buffer::ReadStatus Buffer::loadLyXFile()
4105 if (!d->filename.isReadableFile()) {
4106 ReadStatus const ret_rvc = extractFromVC();
4107 if (ret_rvc != ReadSuccess)
4111 ReadStatus const ret_re = loadEmergency();
4112 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4115 ReadStatus const ret_ra = loadAutosave();
4116 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4119 return loadThisLyXFile(d->filename);
4123 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4125 return readFile(fn);
4129 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4131 TeXErrors::Errors::const_iterator it = terr.begin();
4132 TeXErrors::Errors::const_iterator end = terr.end();
4133 ListOfBuffers clist = getDescendents();
4134 ListOfBuffers::const_iterator cen = clist.end();
4136 for (; it != end; ++it) {
4139 int errorRow = it->error_in_line;
4140 Buffer const * buf = 0;
4142 if (it->child_name.empty())
4143 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4145 // The error occurred in a child
4146 ListOfBuffers::const_iterator cit = clist.begin();
4147 for (; cit != cen; ++cit) {
4148 string const child_name =
4149 DocFileName(changeExtension(
4150 (*cit)->absFileName(), "tex")).
4152 if (it->child_name != child_name)
4154 (*cit)->d->texrow.getIdFromRow(errorRow,
4155 id_start, pos_start);
4156 if (id_start != -1) {
4157 buf = d->cloned_buffer_
4158 ? (*cit)->d->cloned_buffer_->d->owner_
4159 : (*cit)->d->owner_;
4170 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4171 } while (found && id_start == id_end && pos_start == pos_end);
4173 if (id_start != id_end) {
4174 // Next registered position is outside the inset where
4175 // the error occurred, so signal end-of-paragraph
4179 errorList.push_back(ErrorItem(it->error_desc,
4180 it->error_text, id_start, pos_start, pos_end, buf));
4185 void Buffer::setBuffersForInsets() const
4187 inset().setBuffer(const_cast<Buffer &>(*this));
4191 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4193 // Use the master text class also for child documents
4194 Buffer const * const master = masterBuffer();
4195 DocumentClass const & textclass = master->params().documentClass();
4197 // do this only if we are the top-level Buffer
4199 reloadBibInfoCache();
4201 // keep the buffers to be children in this set. If the call from the
4202 // master comes back we can see which of them were actually seen (i.e.
4203 // via an InsetInclude). The remaining ones in the set need still be updated.
4204 static std::set<Buffer const *> bufToUpdate;
4205 if (scope == UpdateMaster) {
4206 // If this is a child document start with the master
4207 if (master != this) {
4208 bufToUpdate.insert(this);
4209 master->updateBuffer(UpdateMaster, utype);
4210 // Do this here in case the master has no gui associated with it. Then,
4211 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4212 if (!master->d->gui_)
4215 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4216 if (bufToUpdate.find(this) == bufToUpdate.end())
4220 // start over the counters in the master
4221 textclass.counters().reset();
4224 // update will be done below for this buffer
4225 bufToUpdate.erase(this);
4227 // update all caches
4228 clearReferenceCache();
4231 Buffer & cbuf = const_cast<Buffer &>(*this);
4233 LASSERT(!text().paragraphs().empty(), /**/);
4236 ParIterator parit = cbuf.par_iterator_begin();
4237 updateBuffer(parit, utype);
4240 // TocBackend update will be done later.
4243 d->bibinfo_cache_valid_ = true;
4244 d->cite_labels_valid_ = true;
4245 cbuf.tocBackend().update();
4246 if (scope == UpdateMaster)
4247 cbuf.structureChanged();
4251 static depth_type getDepth(DocIterator const & it)
4253 depth_type depth = 0;
4254 for (size_t i = 0 ; i < it.depth() ; ++i)
4255 if (!it[i].inset().inMathed())
4256 depth += it[i].paragraph().getDepth() + 1;
4257 // remove 1 since the outer inset does not count
4261 static depth_type getItemDepth(ParIterator const & it)
4263 Paragraph const & par = *it;
4264 LabelType const labeltype = par.layout().labeltype;
4266 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4269 // this will hold the lowest depth encountered up to now.
4270 depth_type min_depth = getDepth(it);
4271 ParIterator prev_it = it;
4274 --prev_it.top().pit();
4276 // start of nested inset: go to outer par
4278 if (prev_it.empty()) {
4279 // start of document: nothing to do
4284 // We search for the first paragraph with same label
4285 // that is not more deeply nested.
4286 Paragraph & prev_par = *prev_it;
4287 depth_type const prev_depth = getDepth(prev_it);
4288 if (labeltype == prev_par.layout().labeltype) {
4289 if (prev_depth < min_depth)
4290 return prev_par.itemdepth + 1;
4291 if (prev_depth == min_depth)
4292 return prev_par.itemdepth;
4294 min_depth = min(min_depth, prev_depth);
4295 // small optimization: if we are at depth 0, we won't
4296 // find anything else
4297 if (prev_depth == 0)
4303 static bool needEnumCounterReset(ParIterator const & it)
4305 Paragraph const & par = *it;
4306 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4307 depth_type const cur_depth = par.getDepth();
4308 ParIterator prev_it = it;
4309 while (prev_it.pit()) {
4310 --prev_it.top().pit();
4311 Paragraph const & prev_par = *prev_it;
4312 if (prev_par.getDepth() <= cur_depth)
4313 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4315 // start of nested inset: reset
4320 // set the label of a paragraph. This includes the counters.
4321 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4323 BufferParams const & bp = owner_->masterBuffer()->params();
4324 DocumentClass const & textclass = bp.documentClass();
4325 Paragraph & par = it.paragraph();
4326 Layout const & layout = par.layout();
4327 Counters & counters = textclass.counters();
4329 if (par.params().startOfAppendix()) {
4330 // We want to reset the counter corresponding to toplevel sectioning
4331 Layout const & lay = textclass.getTOCLayout();
4332 docstring const cnt = lay.counter;
4334 counters.reset(cnt);
4335 counters.appendix(true);
4337 par.params().appendix(counters.appendix());
4339 // Compute the item depth of the paragraph
4340 par.itemdepth = getItemDepth(it);
4342 if (layout.margintype == MARGIN_MANUAL) {
4343 if (par.params().labelWidthString().empty())
4344 par.params().labelWidthString(par.expandLabel(layout, bp));
4345 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4346 // we do not need to do anything here, since the empty case is
4347 // handled during export.
4349 par.params().labelWidthString(docstring());
4352 switch(layout.labeltype) {
4354 if (layout.toclevel <= bp.secnumdepth
4355 && (layout.latextype != LATEX_ENVIRONMENT
4356 || it.text()->isFirstInSequence(it.pit()))) {
4357 if (counters.hasCounter(layout.counter))
4358 counters.step(layout.counter, utype);
4359 par.params().labelString(par.expandLabel(layout, bp));
4361 par.params().labelString(docstring());
4364 case LABEL_ITEMIZE: {
4365 // At some point of time we should do something more
4366 // clever here, like:
4367 // par.params().labelString(
4368 // bp.user_defined_bullet(par.itemdepth).getText());
4369 // for now, use a simple hardcoded label
4370 docstring itemlabel;
4371 switch (par.itemdepth) {
4373 itemlabel = char_type(0x2022);
4376 itemlabel = char_type(0x2013);
4379 itemlabel = char_type(0x2217);
4382 itemlabel = char_type(0x2219); // or 0x00b7
4385 par.params().labelString(itemlabel);
4389 case LABEL_ENUMERATE: {
4390 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4392 switch (par.itemdepth) {
4401 enumcounter += "iv";
4404 // not a valid enumdepth...
4408 // Maybe we have to reset the enumeration counter.
4409 if (needEnumCounterReset(it))
4410 counters.reset(enumcounter);
4411 counters.step(enumcounter, utype);
4413 string const & lang = par.getParLanguage(bp)->code();
4414 par.params().labelString(counters.theCounter(enumcounter, lang));
4419 case LABEL_SENSITIVE: {
4420 string const & type = counters.current_float();
4421 docstring full_label;
4423 full_label = owner_->B_("Senseless!!! ");
4425 docstring name = owner_->B_(textclass.floats().getType(type).name());
4426 if (counters.hasCounter(from_utf8(type))) {
4427 string const & lang = par.getParLanguage(bp)->code();
4428 counters.step(from_utf8(type), utype);
4429 full_label = bformat(from_ascii("%1$s %2$s:"),
4431 counters.theCounter(from_utf8(type), lang));
4433 full_label = bformat(from_ascii("%1$s #:"), name);
4435 par.params().labelString(full_label);
4439 case LABEL_NO_LABEL:
4440 par.params().labelString(docstring());
4444 case LABEL_TOP_ENVIRONMENT:
4445 case LABEL_CENTERED_TOP_ENVIRONMENT:
4448 par.params().labelString(par.expandLabel(layout, bp));
4454 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4456 LASSERT(parit.pit() == 0, /**/);
4458 // Set the position of the text in the buffer to be able
4459 // to resolve macros in it.
4460 parit.text()->setMacrocontextPosition(parit);
4462 depth_type maxdepth = 0;
4463 pit_type const lastpit = parit.lastpit();
4464 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4465 // reduce depth if necessary
4466 if (parit->params().depth() > maxdepth) {
4467 /** FIXME: this function is const, but
4468 * nevertheless it modifies the buffer. To be
4469 * cleaner, one should modify the buffer in
4470 * another function, which is actually
4471 * non-const. This would however be costly in
4472 * terms of code duplication.
4474 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4475 parit->params().depth(maxdepth);
4477 maxdepth = parit->getMaxDepthAfter();
4479 if (utype == OutputUpdate) {
4480 // track the active counters
4481 // we have to do this for the master buffer, since the local
4482 // buffer isn't tracking anything.
4483 masterBuffer()->params().documentClass().counters().
4484 setActiveLayout(parit->layout());
4487 // set the counter for this paragraph
4488 d->setLabel(parit, utype);
4491 InsetList::const_iterator iit = parit->insetList().begin();
4492 InsetList::const_iterator end = parit->insetList().end();
4493 for (; iit != end; ++iit) {
4494 parit.pos() = iit->pos;
4495 iit->inset->updateBuffer(parit, utype);
4501 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4502 WordLangTuple & word_lang, docstring_list & suggestions) const
4506 suggestions.clear();
4507 word_lang = WordLangTuple();
4508 bool const to_end = to.empty();
4509 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4510 // OK, we start from here.
4511 for (; from != end; from.forwardPos()) {
4512 // We are only interested in text so remove the math CursorSlice.
4513 while (from.inMathed()) {
4517 // If from is at the end of the document (which is possible
4518 // when leaving the mathed) LyX will crash later otherwise.
4519 if (from.atEnd() || (!to_end && from >= end))
4522 from.paragraph().spellCheck();
4523 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4524 if (SpellChecker::misspelled(res)) {
4529 // Do not increase progress when from == to, otherwise the word
4530 // count will be wrong.
4540 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4542 bool inword = false;
4547 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4548 if (!dit.inTexted()) {
4553 Paragraph const & par = dit.paragraph();
4554 pos_type const pos = dit.pos();
4556 // Copied and adapted from isWordSeparator() in Paragraph
4557 if (pos == dit.lastpos()) {
4560 Inset const * ins = par.getInset(pos);
4561 if (ins && skipNoOutput && !ins->producesOutput()) {
4564 // stop if end of range was skipped
4565 if (!to.atEnd() && dit >= to)
4568 } else if (!par.isDeleted(pos)) {
4569 if (par.isWordSeparator(pos))
4575 if (ins && ins->isLetter())
4577 else if (ins && ins->isSpace())
4580 char_type const c = par.getChar(pos);
4581 if (isPrintableNonspace(c))
4583 else if (isSpace(c))
4593 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4595 d->updateStatistics(from, to, skipNoOutput);
4599 int Buffer::wordCount() const
4601 return d->wordCount();
4605 int Buffer::charCount(bool with_blanks) const
4607 return d->charCount(with_blanks);
4611 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4614 // c.f. bug http://www.lyx.org/trac/ticket/6587
4615 removeAutosaveFile();
4616 // e.g., read-only status could have changed due to version control
4617 d->filename.refresh();
4618 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4620 // clear parent. this will get reset if need be.
4622 ReadStatus const status = loadLyXFile();
4623 if (status == ReadSuccess) {
4628 message(bformat(_("Document %1$s reloaded."), disp_fn));
4632 message(bformat(_("Could not reload document %1$s."), disp_fn));
4642 bool Buffer::saveAs(FileName const & fn)
4644 FileName const old_name = fileName();
4645 FileName const old_auto = getAutosaveFileName();
4646 bool const old_unnamed = isUnnamed();
4653 // bring the autosave file with us, just in case.
4654 moveAutosaveFile(old_auto);
4655 // validate version control data and
4656 // correct buffer title
4657 lyxvc().file_found_hook(fileName());
4659 // the file has now been saved to the new location.
4660 // we need to check that the locations of child buffers
4662 checkChildBuffers();
4663 checkMasterBuffer();
4667 // reset the old filename and unnamed state
4668 setFileName(old_name);
4669 setUnnamed(old_unnamed);
4675 // FIXME We could do better here, but it is complicated. What would be
4676 // nice is to offer either (a) to save the child buffer to an appropriate
4677 // location, so that it would "move with the master", or else (b) to update
4678 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4679 // complicated, because the code for this lives in GuiView.
4680 void Buffer::checkChildBuffers()
4682 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4683 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4684 for (; it != en; ++it) {
4685 DocIterator dit = it->second;
4686 Buffer * cbuf = const_cast<Buffer *>(it->first);
4687 if (!cbuf || !theBufferList().isLoaded(cbuf))
4689 Inset * inset = dit.nextInset();
4690 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4691 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4692 docstring const & incfile = inset_inc->getParam("filename");
4693 string oldloc = cbuf->absFileName();
4694 string newloc = makeAbsPath(to_utf8(incfile),
4695 onlyPath(absFileName())).absFileName();
4696 if (oldloc == newloc)
4698 // the location of the child file is incorrect.
4699 Alert::warning(_("Included File Invalid"),
4700 bformat(_("Saving this document to a new location has made the file:\n"
4702 "inaccessible. You will need to update the included filename."),
4703 from_utf8(oldloc)));
4705 inset_inc->setChildBuffer(0);
4707 // invalidate cache of children
4708 d->children_positions.clear();
4709 d->position_to_children.clear();
4713 // If a child has been saved under a different name/path, it might have been
4714 // orphaned. Therefore the master needs to be reset (bug 8161).
4715 void Buffer::checkMasterBuffer()
4717 Buffer const * const master = masterBuffer();
4721 // necessary to re-register the child (bug 5873)
4722 // FIXME: clean up updateMacros (here, only
4723 // child registering is needed).
4724 master->updateMacros();
4725 // (re)set master as master buffer, but only
4726 // if we are a real child
4727 if (master->isChild(this))