3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "DispatchResult.h"
29 #include "DocIterator.h"
31 #include "ErrorList.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "IndicesList.h"
37 #include "InsetIterator.h"
38 #include "InsetList.h"
40 #include "LaTeXFeatures.h"
44 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
120 using namespace lyx::support;
121 using namespace lyx::graphics;
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
153 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
157 delete preview_loader_;
165 /// search for macro in local (buffer) table or in children
166 MacroData const * getBufferMacro(docstring const & name,
167 DocIterator const & pos) const;
169 /// Update macro table starting with position of it \param it in some
171 void updateMacros(DocIterator & it, DocIterator & scope);
173 void setLabel(ParIterator & it, UpdateType utype) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this an unnamed file (New...)?
199 /// is this an internal bufffer?
200 bool internal_buffer;
205 /// name of the file the buffer is associated with.
208 /** Set to true only when the file is fully loaded.
209 * Used to prevent the premature generation of previews
210 * and by the citation inset.
212 bool file_fully_loaded;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
221 typedef pair<DocIterator, MacroData> ScopeMacro;
222 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
223 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
224 /// map from the macro name to the position map,
225 /// which maps the macro definition position to the scope and the MacroData.
226 NamePositionScopeMacroMap macros;
227 /// This seem to change the way Buffer::getMacro() works
228 mutable bool macro_lock;
230 /// positions of child buffers in the buffer
231 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
232 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Container for all sort of Buffer dependant errors.
240 map<string, ErrorList> errorLists;
242 /// timestamp and checksum used to test if the file has been externally
243 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245 unsigned long checksum_;
248 frontend::WorkAreaManager * wa_;
250 frontend::GuiBufferDelegate * gui_;
255 /// A cache for the bibfiles (including bibfiles of loaded child
256 /// documents), needed for appropriate update of natbib labels.
257 mutable support::FileNameList bibfiles_cache_;
259 // FIXME The caching mechanism could be improved. At present, we have a
260 // cache for each Buffer, that caches all the bibliography info for that
261 // Buffer. A more efficient solution would be to have a global cache per
262 // file, and then to construct the Buffer's bibinfo from that.
263 /// A cache for bibliography info
264 mutable BiblioInfo bibinfo_;
265 /// whether the bibinfo cache is valid
266 mutable bool bibinfo_cache_valid_;
267 /// whether the bibfile cache is valid
268 mutable bool bibfile_cache_valid_;
269 /// Cache of timestamps of .bib files
270 map<FileName, time_t> bibfile_status_;
271 /// Indicates whether the bibinfo has changed since the last time
272 /// we ran updateBuffer(), i.e., whether citation labels may need
274 mutable bool cite_labels_valid_;
276 mutable RefCache ref_cache_;
278 /// our Text that should be wrapped in an InsetText
282 PreviewLoader * preview_loader_;
284 /// This is here to force the test to be done whenever parent_buffer
286 Buffer const * parent() const {
287 // ignore_parent temporarily "orphans" a buffer
288 // (e.g. if a child is compiled standalone)
291 // if parent_buffer is not loaded, then it has been unloaded,
292 // which means that parent_buffer is an invalid pointer. So we
293 // set it to null in that case.
294 // however, the BufferList doesn't know about cloned buffers, so
295 // they will always be regarded as unloaded. in that case, we hope
297 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
299 return parent_buffer;
303 void setParent(Buffer const * pb) {
304 if (parent_buffer == pb)
307 if (!cloned_buffer_ && parent_buffer && pb)
308 LYXERR0("Warning: a buffer should not have two parents!");
310 if (!cloned_buffer_ && parent_buffer) {
311 parent_buffer->invalidateBibfileCache();
312 parent_buffer->invalidateBibinfoCache();
316 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
317 /// This one is useful for preview detached in a thread.
318 Buffer const * cloned_buffer_;
320 CloneList * clone_list_;
321 /// are we in the process of exporting this buffer?
322 mutable bool doing_export;
324 /// compute statistics
325 /// \p from initial position
326 /// \p to points to the end position
327 void updateStatistics(DocIterator & from, DocIterator & to,
328 bool skipNoOutput = true);
329 /// statistics accessor functions
330 int wordCount() const { return word_count_; }
331 int charCount(bool with_blanks) const {
333 + (with_blanks ? blank_count_ : 0);
337 /// So we can force access via the accessors.
338 mutable Buffer const * parent_buffer;
347 /// Creates the per buffer temporary directory
348 static FileName createBufferTmpDir()
351 // We are in our own directory. Why bother to mangle name?
352 // In fact I wrote this code to circumvent a problematic behaviour
353 // (bug?) of EMX mkstemp().
354 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
355 convert<string>(count++));
357 if (!tmpfl.createDirectory(0777)) {
358 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
359 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
360 from_utf8(tmpfl.absFileName())));
366 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
367 Buffer const * cloned_buffer)
368 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
369 internal_buffer(false), read_only(readonly_), filename(file),
370 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
371 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
372 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
373 cite_labels_valid_(false), preview_loader_(0),
374 cloned_buffer_(cloned_buffer), clone_list_(0),
375 doing_export(false), parent_buffer(0)
377 if (!cloned_buffer_) {
378 temppath = createBufferTmpDir();
379 lyxvc.setBuffer(owner_);
381 wa_ = new frontend::WorkAreaManager;
384 temppath = cloned_buffer_->d->temppath;
385 file_fully_loaded = true;
386 params = cloned_buffer_->d->params;
387 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
388 bibinfo_ = cloned_buffer_->d->bibinfo_;
389 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
390 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
391 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
392 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
393 unnamed = cloned_buffer_->d->unnamed;
394 internal_buffer = cloned_buffer_->d->internal_buffer;
398 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
399 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
401 LYXERR(Debug::INFO, "Buffer::Buffer()");
403 d->inset = new InsetText(*cloned_buffer->d->inset);
404 d->inset->setBuffer(*this);
405 // FIXME: optimize this loop somewhat, maybe by creating a new
406 // general recursive Inset::setId().
407 DocIterator it = doc_iterator_begin(this);
408 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
409 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
410 it.paragraph().setId(cloned_it.paragraph().id());
412 d->inset = new InsetText(this);
413 d->inset->setAutoBreakRows(true);
414 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
420 LYXERR(Debug::INFO, "Buffer::~Buffer()");
421 // here the buffer should take care that it is
422 // saved properly, before it goes into the void.
424 // GuiView already destroyed
428 // No need to do additional cleanups for internal buffer.
434 // this is in case of recursive includes: we won't try to delete
435 // ourselves as a child.
436 d->clone_list_->erase(this);
437 // loop over children
438 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
439 Impl::BufferPositionMap::iterator end = d->children_positions.end();
440 for (; it != end; ++it) {
441 Buffer * child = const_cast<Buffer *>(it->first);
442 if (d->clone_list_->erase(child))
445 // if we're the master buffer, then we should get rid of the list
448 // if this is not empty, we have leaked something. worse, one of the
449 // children still has a reference to this list.
450 LASSERT(d->clone_list_->empty(), /* */);
451 list<CloneList *>::iterator it =
452 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
453 LASSERT(it != cloned_buffers.end(), /* */);
454 cloned_buffers.erase(it);
455 delete d->clone_list_;
457 // FIXME Do we really need to do this right before we delete d?
458 // clear references to children in macro tables
459 d->children_positions.clear();
460 d->position_to_children.clear();
462 // loop over children
463 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
464 Impl::BufferPositionMap::iterator end = d->children_positions.end();
465 for (; it != end; ++it) {
466 Buffer * child = const_cast<Buffer *>(it->first);
467 if (theBufferList().isLoaded(child))
468 theBufferList().releaseChild(this, child);
472 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
473 msg += emergencyWrite();
474 Alert::warning(_("Attempting to close changed document!"), msg);
477 // FIXME Do we really need to do this right before we delete d?
478 // clear references to children in macro tables
479 d->children_positions.clear();
480 d->position_to_children.clear();
482 if (!d->temppath.destroyDirectory()) {
483 Alert::warning(_("Could not remove temporary directory"),
484 bformat(_("Could not remove the temporary directory %1$s"),
485 from_utf8(d->temppath.absFileName())));
494 Buffer * Buffer::cloneFromMaster() const
497 cloned_buffers.push_back(new CloneList());
498 CloneList * clones = cloned_buffers.back();
500 masterBuffer()->cloneWithChildren(bufmap, clones);
502 // make sure we got cloned
503 BufferMap::const_iterator bit = bufmap.find(this);
504 LASSERT(bit != bufmap.end(), return 0);
505 Buffer * cloned_buffer = bit->second;
507 return cloned_buffer;
511 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
513 // have we already been cloned?
514 if (bufmap.find(this) != bufmap.end())
517 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
518 bufmap[this] = buffer_clone;
519 clones->insert(buffer_clone);
520 buffer_clone->d->clone_list_ = clones;
521 buffer_clone->d->macro_lock = true;
522 buffer_clone->d->children_positions.clear();
523 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
524 // math macro caches need to be rethought and simplified.
525 // I am not sure wether we should handle Buffer cloning here or in BufferList.
526 // Right now BufferList knows nothing about buffer clones.
527 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
528 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
529 for (; it != end; ++it) {
530 DocIterator dit = it->first.clone(buffer_clone);
531 dit.setBuffer(buffer_clone);
532 Buffer * child = const_cast<Buffer *>(it->second.second);
534 child->cloneWithChildren(bufmap, clones);
535 BufferMap::iterator const bit = bufmap.find(child);
536 LASSERT(bit != bufmap.end(), continue);
537 Buffer * child_clone = bit->second;
539 Inset * inset = dit.nextInset();
540 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
541 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
542 inset_inc->setChildBuffer(child_clone);
543 child_clone->d->setParent(buffer_clone);
544 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
545 buffer_clone->setChild(dit, child_clone);
547 buffer_clone->d->macro_lock = false;
552 Buffer * Buffer::cloneBufferOnly() const {
553 cloned_buffers.push_back(new CloneList());
554 CloneList * clones = cloned_buffers.back();
555 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
556 clones->insert(buffer_clone);
557 buffer_clone->d->clone_list_ = clones;
558 // we won't be cloning the children
559 buffer_clone->d->children_positions.clear();
564 bool Buffer::isClone() const
566 return d->cloned_buffer_;
570 void Buffer::changed(bool update_metrics) const
573 d->wa_->redrawAll(update_metrics);
577 frontend::WorkAreaManager & Buffer::workAreaManager() const
579 LASSERT(d->wa_, /**/);
584 Text & Buffer::text() const
586 return d->inset->text();
590 Inset & Buffer::inset() const
596 BufferParams & Buffer::params()
602 BufferParams const & Buffer::params() const
608 ParagraphList & Buffer::paragraphs()
610 return text().paragraphs();
614 ParagraphList const & Buffer::paragraphs() const
616 return text().paragraphs();
620 LyXVC & Buffer::lyxvc()
626 LyXVC const & Buffer::lyxvc() const
632 string const Buffer::temppath() const
634 return d->temppath.absFileName();
638 TexRow & Buffer::texrow()
644 TexRow const & Buffer::texrow() const
650 TocBackend & Buffer::tocBackend() const
652 return d->toc_backend;
656 Undo & Buffer::undo()
662 void Buffer::setChild(DocIterator const & dit, Buffer * child)
664 d->children_positions[child] = dit;
668 string Buffer::latexName(bool const no_path) const
670 FileName latex_name =
671 makeLatexName(d->exportFileName());
672 return no_path ? latex_name.onlyFileName()
673 : latex_name.absFileName();
677 FileName Buffer::Impl::exportFileName() const
679 docstring const branch_suffix =
680 params.branchlist().getFileNameSuffix();
681 if (branch_suffix.empty())
684 string const name = filename.onlyFileNameWithoutExt()
685 + to_utf8(branch_suffix);
686 FileName res(filename.onlyPath().absFileName() + "/" + name);
687 res.changeExtension(filename.extension());
693 string Buffer::logName(LogType * type) const
695 string const filename = latexName(false);
697 if (filename.empty()) {
703 string const path = temppath();
705 FileName const fname(addName(temppath(),
706 onlyFileName(changeExtension(filename,
709 // FIXME: how do we know this is the name of the build log?
710 FileName const bname(
711 addName(path, onlyFileName(
712 changeExtension(filename,
713 formats.extension(params().bufferFormat()) + ".out"))));
715 // Also consider the master buffer log file
716 FileName masterfname = fname;
718 if (masterBuffer() != this) {
719 string const mlogfile = masterBuffer()->logName(&mtype);
720 masterfname = FileName(mlogfile);
723 // If no Latex log or Build log is newer, show Build log
724 if (bname.exists() &&
725 ((!fname.exists() && !masterfname.exists())
726 || (fname.lastModified() < bname.lastModified()
727 && masterfname.lastModified() < bname.lastModified()))) {
728 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
731 return bname.absFileName();
732 // If we have a newer master file log or only a master log, show this
733 } else if (fname != masterfname
734 && (!fname.exists() && (masterfname.exists()
735 || fname.lastModified() < masterfname.lastModified()))) {
736 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
739 return masterfname.absFileName();
741 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
744 return fname.absFileName();
748 void Buffer::setReadonly(bool const flag)
750 if (d->read_only != flag) {
757 void Buffer::setFileName(FileName const & fname)
760 setReadonly(d->filename.isReadOnly());
766 int Buffer::readHeader(Lexer & lex)
768 int unknown_tokens = 0;
770 int begin_header_line = -1;
772 // Initialize parameters that may be/go lacking in header:
773 params().branchlist().clear();
774 params().preamble.erase();
775 params().options.erase();
776 params().master.erase();
777 params().float_placement.erase();
778 params().paperwidth.erase();
779 params().paperheight.erase();
780 params().leftmargin.erase();
781 params().rightmargin.erase();
782 params().topmargin.erase();
783 params().bottommargin.erase();
784 params().headheight.erase();
785 params().headsep.erase();
786 params().footskip.erase();
787 params().columnsep.erase();
788 params().fonts_cjk.erase();
789 params().listings_params.clear();
790 params().clearLayoutModules();
791 params().clearRemovedModules();
792 params().clearIncludedChildren();
793 params().pdfoptions().clear();
794 params().indiceslist().clear();
795 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
796 params().isbackgroundcolor = false;
797 params().fontcolor = RGBColor(0, 0, 0);
798 params().isfontcolor = false;
799 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
800 params().boxbgcolor = RGBColor(0xFF, 0, 0);
801 params().html_latex_start.clear();
802 params().html_latex_end.clear();
803 params().html_math_img_scale = 1.0;
804 params().output_sync_macro.erase();
805 params().local_layout.clear();
807 for (int i = 0; i < 4; ++i) {
808 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
809 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
812 ErrorList & errorList = d->errorLists["Parse"];
821 if (token == "\\end_header")
825 if (token == "\\begin_header") {
826 begin_header_line = line;
830 LYXERR(Debug::PARSER, "Handling document header token: `"
833 string unknown = params().readToken(lex, token, d->filename.onlyPath());
834 if (!unknown.empty()) {
835 if (unknown[0] != '\\' && token == "\\textclass") {
836 Alert::warning(_("Unknown document class"),
837 bformat(_("Using the default document class, because the "
838 "class %1$s is unknown."), from_utf8(unknown)));
841 docstring const s = bformat(_("Unknown token: "
845 errorList.push_back(ErrorItem(_("Document header error"),
850 if (begin_header_line) {
851 docstring const s = _("\\begin_header is missing");
852 errorList.push_back(ErrorItem(_("Document header error"),
856 params().makeDocumentClass();
858 return unknown_tokens;
863 // changed to be public and have one parameter
864 // Returns true if "\end_document" is not read (Asger)
865 bool Buffer::readDocument(Lexer & lex)
867 ErrorList & errorList = d->errorLists["Parse"];
870 // remove dummy empty par
871 paragraphs().clear();
873 if (!lex.checkFor("\\begin_document")) {
874 docstring const s = _("\\begin_document is missing");
875 errorList.push_back(ErrorItem(_("Document header error"),
881 if (params().outputChanges) {
882 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
883 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
884 LaTeXFeatures::isAvailable("xcolor");
886 if (!dvipost && !xcolorulem) {
887 Alert::warning(_("Changes not shown in LaTeX output"),
888 _("Changes will not be highlighted in LaTeX output, "
889 "because neither dvipost nor xcolor/ulem are installed.\n"
890 "Please install these packages or redefine "
891 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
892 } else if (!xcolorulem) {
893 Alert::warning(_("Changes not shown in LaTeX output"),
894 _("Changes will not be highlighted in LaTeX output "
895 "when using pdflatex, because xcolor and ulem are not installed.\n"
896 "Please install both packages or redefine "
897 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
901 if (!params().master.empty()) {
902 FileName const master_file = makeAbsPath(params().master,
903 onlyPath(absFileName()));
904 if (isLyXFileName(master_file.absFileName())) {
906 checkAndLoadLyXFile(master_file, true);
908 // necessary e.g. after a reload
909 // to re-register the child (bug 5873)
910 // FIXME: clean up updateMacros (here, only
911 // child registering is needed).
912 master->updateMacros();
913 // set master as master buffer, but only
914 // if we are a real child
915 if (master->isChild(this))
917 // if the master is not fully loaded
918 // it is probably just loading this
919 // child. No warning needed then.
920 else if (master->isFullyLoaded())
921 LYXERR0("The master '"
923 << "' assigned to this document ("
925 << ") does not include "
926 "this document. Ignoring the master assignment.");
931 // assure we have a default index
932 params().indiceslist().addDefault(B_("Index"));
935 bool const res = text().read(lex, errorList, d->inset);
937 // inform parent buffer about local macros
939 Buffer const * pbuf = parent();
940 UserMacroSet::const_iterator cit = usermacros.begin();
941 UserMacroSet::const_iterator end = usermacros.end();
942 for (; cit != end; ++cit)
943 pbuf->usermacros.insert(*cit);
947 updateMacroInstances(InternalUpdate);
952 bool Buffer::readString(string const & s)
954 params().compressed = false;
959 FileName const fn = FileName::tempName("Buffer_readString");
962 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
963 if (ret_plf != ReadSuccess)
966 if (file_format != LYX_FORMAT) {
967 // We need to call lyx2lyx, so write the input to a file
968 ofstream os(fn.toFilesystemEncoding().c_str());
972 return readFile(fn) == ReadSuccess;
975 if (readDocument(lex))
981 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
985 if (!lex.setFile(fname)) {
986 Alert::error(_("File Not Found"),
987 bformat(_("Unable to open file `%1$s'."),
988 from_utf8(fn.absFileName())));
989 return ReadFileNotFound;
993 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
994 if (ret_plf != ReadSuccess)
997 if (file_format != LYX_FORMAT) {
999 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1000 if (ret_clf != ReadSuccess)
1002 return readFile(tmpFile);
1005 // FIXME: InsetInfo needs to know whether the file is under VCS
1006 // during the parse process, so this has to be done before.
1007 lyxvc().file_found_hook(d->filename);
1009 if (readDocument(lex)) {
1010 Alert::error(_("Document format failure"),
1011 bformat(_("%1$s ended unexpectedly, which means"
1012 " that it is probably corrupted."),
1013 from_utf8(fn.absFileName())));
1014 return ReadDocumentFailure;
1017 d->file_fully_loaded = true;
1018 d->read_only = !d->filename.isWritable();
1019 params().compressed = formats.isZippedFile(d->filename);
1025 bool Buffer::isFullyLoaded() const
1027 return d->file_fully_loaded;
1031 void Buffer::setFullyLoaded(bool value)
1033 d->file_fully_loaded = value;
1037 PreviewLoader * Buffer::loader() const
1039 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1041 if (!d->preview_loader_)
1042 d->preview_loader_ = new PreviewLoader(*this);
1043 return d->preview_loader_;
1047 void Buffer::removePreviews() const
1049 delete d->preview_loader_;
1050 d->preview_loader_ = 0;
1054 void Buffer::updatePreviews() const
1056 PreviewLoader * ploader = loader();
1060 InsetIterator it = inset_iterator_begin(*d->inset);
1061 InsetIterator const end = inset_iterator_end(*d->inset);
1062 for (; it != end; ++it)
1063 it->addPreview(it, *ploader);
1065 ploader->startLoading();
1069 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1070 FileName const & fn, int & file_format) const
1072 if(!lex.checkFor("\\lyxformat")) {
1073 Alert::error(_("Document format failure"),
1074 bformat(_("%1$s is not a readable LyX document."),
1075 from_utf8(fn.absFileName())));
1076 return ReadNoLyXFormat;
1082 // LyX formats 217 and earlier were written as 2.17. This corresponds
1083 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1084 // these cases. See also: www.lyx.org/trac/changeset/1313.
1085 size_t dot = tmp_format.find_first_of(".,");
1086 if (dot != string::npos)
1087 tmp_format.erase(dot, 1);
1089 file_format = convert<int>(tmp_format);
1094 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1095 FileName & tmpfile, int from_format)
1097 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1098 if(tmpfile.empty()) {
1099 Alert::error(_("Conversion failed"),
1100 bformat(_("%1$s is from a different"
1101 " version of LyX, but a temporary"
1102 " file for converting it could"
1103 " not be created."),
1104 from_utf8(fn.absFileName())));
1105 return LyX2LyXNoTempFile;
1108 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1109 if (lyx2lyx.empty()) {
1110 Alert::error(_("Conversion script not found"),
1111 bformat(_("%1$s is from a different"
1112 " version of LyX, but the"
1113 " conversion script lyx2lyx"
1114 " could not be found."),
1115 from_utf8(fn.absFileName())));
1116 return LyX2LyXNotFound;
1120 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1121 ostringstream command;
1122 command << os::python()
1123 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1124 << " -t " << convert<string>(LYX_FORMAT)
1125 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1126 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1127 string const command_str = command.str();
1129 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1131 cmd_ret const ret = runCommand(command_str);
1132 if (ret.first != 0) {
1133 if (from_format < LYX_FORMAT) {
1134 Alert::error(_("Conversion script failed"),
1135 bformat(_("%1$s is from an older version"
1136 " of LyX and the lyx2lyx script"
1137 " failed to convert it."),
1138 from_utf8(fn.absFileName())));
1139 return LyX2LyXOlderFormat;
1141 Alert::error(_("Conversion script failed"),
1142 bformat(_("%1$s is from a newer version"
1143 " of LyX and the lyx2lyx script"
1144 " failed to convert it."),
1145 from_utf8(fn.absFileName())));
1146 return LyX2LyXNewerFormat;
1153 // Should probably be moved to somewhere else: BufferView? GuiView?
1154 bool Buffer::save() const
1156 docstring const file = makeDisplayPath(absFileName(), 20);
1157 d->filename.refresh();
1159 // check the read-only status before moving the file as a backup
1160 if (d->filename.exists()) {
1161 bool const read_only = !d->filename.isWritable();
1163 Alert::warning(_("File is read-only"),
1164 bformat(_("The file %1$s cannot be written because it "
1165 "is marked as read-only."), file));
1170 // ask if the disk file has been externally modified (use checksum method)
1171 if (fileName().exists() && isExternallyModified(checksum_method)) {
1173 bformat(_("Document %1$s has been externally modified. "
1174 "Are you sure you want to overwrite this file?"), file);
1175 int const ret = Alert::prompt(_("Overwrite modified file?"),
1176 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1181 // We don't need autosaves in the immediate future. (Asger)
1182 resetAutosaveTimers();
1184 FileName backupName;
1185 bool madeBackup = false;
1187 // make a backup if the file already exists
1188 if (lyxrc.make_backup && fileName().exists()) {
1189 backupName = FileName(absFileName() + '~');
1190 if (!lyxrc.backupdir_path.empty()) {
1191 string const mangledName =
1192 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1193 backupName = FileName(addName(lyxrc.backupdir_path,
1197 // Except file is symlink do not copy because of #6587.
1198 // Hard links have bad luck.
1199 if (fileName().isSymLink())
1200 madeBackup = fileName().copyTo(backupName);
1202 madeBackup = fileName().moveTo(backupName);
1205 Alert::error(_("Backup failure"),
1206 bformat(_("Cannot create backup file %1$s.\n"
1207 "Please check whether the directory exists and is writable."),
1208 from_utf8(backupName.absFileName())));
1209 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1213 if (writeFile(d->filename)) {
1217 // Saving failed, so backup is not backup
1219 backupName.moveTo(d->filename);
1225 bool Buffer::writeFile(FileName const & fname) const
1227 // FIXME Do we need to do these here? I don't think writing
1228 // the LyX file depends upon it. (RGH)
1230 // updateMacroInstances();
1232 if (d->read_only && fname == d->filename)
1235 bool retval = false;
1237 docstring const str = bformat(_("Saving document %1$s..."),
1238 makeDisplayPath(fname.absFileName()));
1241 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1243 if (params().compressed) {
1244 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1245 retval = ofs && write(ofs);
1247 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1248 retval = ofs && write(ofs);
1252 message(str + _(" could not write file!"));
1257 // removeAutosaveFile();
1260 message(str + _(" done."));
1266 docstring Buffer::emergencyWrite()
1268 // No need to save if the buffer has not changed.
1272 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1274 docstring user_message = bformat(
1275 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1277 // We try to save three places:
1278 // 1) Same place as document. Unless it is an unnamed doc.
1280 string s = absFileName();
1283 if (writeFile(FileName(s))) {
1285 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1286 return user_message;
1288 user_message += " " + _("Save failed! Trying again...\n");
1292 // 2) In HOME directory.
1293 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1295 lyxerr << ' ' << s << endl;
1296 if (writeFile(FileName(s))) {
1298 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1299 return user_message;
1302 user_message += " " + _("Save failed! Trying yet again...\n");
1304 // 3) In "/tmp" directory.
1305 // MakeAbsPath to prepend the current
1306 // drive letter on OS/2
1307 s = addName(package().temp_dir().absFileName(), absFileName());
1309 lyxerr << ' ' << s << endl;
1310 if (writeFile(FileName(s))) {
1312 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1313 return user_message;
1316 user_message += " " + _("Save failed! Bummer. Document is lost.");
1319 return user_message;
1323 bool Buffer::write(ostream & ofs) const
1326 // Use the standard "C" locale for file output.
1327 ofs.imbue(locale::classic());
1330 // The top of the file should not be written by params().
1332 // write out a comment in the top of the file
1333 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1334 << " created this file. For more info see http://www.lyx.org/\n"
1335 << "\\lyxformat " << LYX_FORMAT << "\n"
1336 << "\\begin_document\n";
1338 /// For each author, set 'used' to true if there is a change
1339 /// by this author in the document; otherwise set it to 'false'.
1340 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1341 AuthorList::Authors::const_iterator a_end = params().authors().end();
1342 for (; a_it != a_end; ++a_it)
1343 a_it->setUsed(false);
1345 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1346 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1347 for ( ; it != end; ++it)
1348 it->checkAuthors(params().authors());
1350 // now write out the buffer parameters.
1351 ofs << "\\begin_header\n";
1352 params().writeFile(ofs);
1353 ofs << "\\end_header\n";
1356 ofs << "\n\\begin_body\n";
1358 ofs << "\n\\end_body\n";
1360 // Write marker that shows file is complete
1361 ofs << "\\end_document" << endl;
1363 // Shouldn't really be needed....
1366 // how to check if close went ok?
1367 // Following is an attempt... (BE 20001011)
1369 // good() returns false if any error occured, including some
1370 // formatting error.
1371 // bad() returns true if something bad happened in the buffer,
1372 // which should include file system full errors.
1377 lyxerr << "File was not closed properly." << endl;
1384 bool Buffer::makeLaTeXFile(FileName const & fname,
1385 string const & original_path,
1386 OutputParams const & runparams_in,
1387 OutputWhat output) const
1389 OutputParams runparams = runparams_in;
1391 // This is necessary for LuaTeX/XeTeX with tex fonts.
1392 // See FIXME in BufferParams::encoding()
1393 if (runparams.isFullUnicode())
1394 runparams.encoding = encodings.fromLyXName("utf8-plain");
1396 string const encoding = runparams.encoding->iconvName();
1397 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1400 try { ofs.reset(encoding); }
1401 catch (iconv_codecvt_facet_exception const & e) {
1402 lyxerr << "Caught iconv exception: " << e.what() << endl;
1403 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1404 "verify that the support software for your encoding (%1$s) is "
1405 "properly installed"), from_ascii(encoding)));
1408 if (!openFileWrite(ofs, fname))
1411 //TexStream ts(ofs.rdbuf(), &texrow());
1412 ErrorList & errorList = d->errorLists["Export"];
1414 bool failed_export = false;
1415 otexstream os(ofs, d->texrow);
1417 // make sure we are ready to export
1418 // this needs to be done before we validate
1419 // FIXME Do we need to do this all the time? I.e., in children
1420 // of a master we are exporting?
1422 updateMacroInstances(OutputUpdate);
1425 os.texrow().reset();
1426 writeLaTeXSource(os, original_path, runparams, output);
1428 catch (EncodingException const & e) {
1429 odocstringstream ods;
1430 ods.put(e.failed_char);
1432 oss << "0x" << hex << e.failed_char << dec;
1433 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1434 " (code point %2$s)"),
1435 ods.str(), from_utf8(oss.str()));
1436 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1437 "representable in the chosen encoding.\n"
1438 "Changing the document encoding to utf8 could help."),
1439 e.par_id, e.pos, e.pos + 1));
1440 failed_export = true;
1442 catch (iconv_codecvt_facet_exception const & e) {
1443 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1444 _(e.what()), -1, 0, 0));
1445 failed_export = true;
1447 catch (exception const & e) {
1448 errorList.push_back(ErrorItem(_("conversion failed"),
1449 _(e.what()), -1, 0, 0));
1450 failed_export = true;
1453 lyxerr << "Caught some really weird exception..." << endl;
1459 failed_export = true;
1460 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1464 return !failed_export;
1468 void Buffer::writeLaTeXSource(otexstream & os,
1469 string const & original_path,
1470 OutputParams const & runparams_in,
1471 OutputWhat output) const
1473 // The child documents, if any, shall be already loaded at this point.
1475 OutputParams runparams = runparams_in;
1477 // If we are compiling a file standalone, even if this is the
1478 // child of some other buffer, let's cut the link here, so the
1479 // file is really independent and no concurring settings from
1480 // the master (e.g. branch state) interfere (see #8100).
1481 if (!runparams.is_child)
1482 d->ignore_parent = true;
1484 // Classify the unicode characters appearing in math insets
1485 Encodings::initUnicodeMath(*this);
1487 // validate the buffer.
1488 LYXERR(Debug::LATEX, " Validating buffer...");
1489 LaTeXFeatures features(*this, params(), runparams);
1491 runparams.use_polyglossia = features.usePolyglossia();
1492 LYXERR(Debug::LATEX, " Buffer validation done.");
1494 bool const output_preamble =
1495 output == FullSource || output == OnlyPreamble;
1496 bool const output_body =
1497 output == FullSource || output == OnlyBody;
1499 // The starting paragraph of the coming rows is the
1500 // first paragraph of the document. (Asger)
1501 if (output_preamble && runparams.nice) {
1502 os << "%% LyX " << lyx_version << " created this file. "
1503 "For more info, see http://www.lyx.org/.\n"
1504 "%% Do not edit unless you really know what "
1507 LYXERR(Debug::INFO, "lyx document header finished");
1509 // There are a few differences between nice LaTeX and usual files:
1510 // usual files have \batchmode and special input@path to allow
1511 // inclusion of figures specified by an explicitly relative path
1512 // (i.e., a path starting with './' or '../') with either \input or
1513 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1514 // input@path is set when the actual parameter original_path is set.
1515 // This is done for usual tex-file, but not for nice-latex-file.
1516 // (Matthias 250696)
1517 // Note that input@path is only needed for something the user does
1518 // in the preamble, included .tex files or ERT, files included by
1519 // LyX work without it.
1520 if (output_preamble) {
1521 if (!runparams.nice) {
1522 // code for usual, NOT nice-latex-file
1523 os << "\\batchmode\n"; // changed from \nonstopmode
1525 if (!original_path.empty()) {
1527 // We don't know the encoding of inputpath
1528 docstring const inputpath = from_utf8(original_path);
1529 docstring uncodable_glyphs;
1530 Encoding const * const enc = runparams.encoding;
1532 for (size_t n = 0; n < inputpath.size(); ++n) {
1533 if (!enc->encodable(inputpath[n])) {
1534 docstring const glyph(1, inputpath[n]);
1535 LYXERR0("Uncodable character '"
1537 << "' in input path!");
1538 uncodable_glyphs += glyph;
1543 // warn user if we found uncodable glyphs.
1544 if (!uncodable_glyphs.empty()) {
1545 frontend::Alert::warning(
1546 _("Uncodable character in file path"),
1548 _("The path of your document\n"
1550 "contains glyphs that are unknown "
1551 "in the current document encoding "
1552 "(namely %2$s). This may result in "
1553 "incomplete output, unless "
1554 "TEXINPUTS contains the document "
1555 "directory and you don't use "
1556 "explicitly relative paths (i.e., "
1557 "paths starting with './' or "
1558 "'../') in the preamble or in ERT."
1559 "\n\nIn case of problems, choose "
1560 "an appropriate document encoding\n"
1561 "(such as utf8) or change the "
1563 inputpath, uncodable_glyphs));
1566 support::latex_path(original_path);
1567 if (contains(docdir, '#')) {
1568 docdir = subst(docdir, "#", "\\#");
1569 os << "\\catcode`\\#=11"
1570 "\\def\\#{#}\\catcode`\\#=6\n";
1572 if (contains(docdir, '%')) {
1573 docdir = subst(docdir, "%", "\\%");
1574 os << "\\catcode`\\%=11"
1575 "\\def\\%{%}\\catcode`\\%=14\n";
1577 os << "\\makeatletter\n"
1578 << "\\def\\input@path{{"
1579 << docdir << "/}}\n"
1580 << "\\makeatother\n";
1584 // get parent macros (if this buffer has a parent) which will be
1585 // written at the document begin further down.
1586 MacroSet parentMacros;
1587 listParentMacros(parentMacros, features);
1589 // Write the preamble
1590 runparams.use_babel = params().writeLaTeX(os, features,
1591 d->filename.onlyPath());
1593 runparams.use_japanese = features.isRequired("japanese");
1596 // Restore the parenthood if needed
1597 if (!runparams.is_child)
1598 d->ignore_parent = false;
1603 os << "\\begin{document}\n";
1605 // output the parent macros
1606 MacroSet::iterator it = parentMacros.begin();
1607 MacroSet::iterator end = parentMacros.end();
1608 for (; it != end; ++it) {
1609 int num_lines = (*it)->write(os.os(), true);
1610 os.texrow().newlines(num_lines);
1613 } // output_preamble
1615 os.texrow().start(paragraphs().begin()->id(), 0);
1617 LYXERR(Debug::INFO, "preamble finished, now the body.");
1620 latexParagraphs(*this, text(), os, runparams);
1622 // Restore the parenthood if needed
1623 if (!runparams.is_child)
1624 d->ignore_parent = false;
1626 // add this just in case after all the paragraphs
1629 if (output_preamble) {
1630 os << "\\end{document}\n";
1631 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1633 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1635 runparams_in.encoding = runparams.encoding;
1637 // Just to be sure. (Asger)
1638 os.texrow().newline();
1640 //for (int i = 0; i<d->texrow.rows(); i++) {
1642 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1643 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1646 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1647 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1651 void Buffer::makeDocBookFile(FileName const & fname,
1652 OutputParams const & runparams,
1653 OutputWhat output) const
1655 LYXERR(Debug::LATEX, "makeDocBookFile...");
1658 if (!openFileWrite(ofs, fname))
1661 // make sure we are ready to export
1662 // this needs to be done before we validate
1664 updateMacroInstances(OutputUpdate);
1666 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1670 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1674 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1675 OutputParams const & runparams,
1676 OutputWhat output) const
1678 LaTeXFeatures features(*this, params(), runparams);
1683 DocumentClass const & tclass = params().documentClass();
1684 string const top_element = tclass.latexname();
1686 bool const output_preamble =
1687 output == FullSource || output == OnlyPreamble;
1688 bool const output_body =
1689 output == FullSource || output == OnlyBody;
1691 if (output_preamble) {
1692 if (runparams.flavor == OutputParams::XML)
1693 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1696 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1699 if (! tclass.class_header().empty())
1700 os << from_ascii(tclass.class_header());
1701 else if (runparams.flavor == OutputParams::XML)
1702 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1703 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1705 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1707 docstring preamble = from_utf8(params().preamble);
1708 if (runparams.flavor != OutputParams::XML ) {
1709 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1710 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1711 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1712 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1715 string const name = runparams.nice
1716 ? changeExtension(absFileName(), ".sgml") : fname;
1717 preamble += features.getIncludedFiles(name);
1718 preamble += features.getLyXSGMLEntities();
1720 if (!preamble.empty()) {
1721 os << "\n [ " << preamble << " ]";
1727 string top = top_element;
1729 if (runparams.flavor == OutputParams::XML)
1730 top += params().language->code();
1732 top += params().language->code().substr(0, 2);
1735 if (!params().options.empty()) {
1737 top += params().options;
1740 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1741 << " file was created by LyX " << lyx_version
1742 << "\n See http://www.lyx.org/ for more information -->\n";
1744 params().documentClass().counters().reset();
1746 sgml::openTag(os, top);
1748 docbookParagraphs(text(), *this, os, runparams);
1749 sgml::closeTag(os, top_element);
1754 void Buffer::makeLyXHTMLFile(FileName const & fname,
1755 OutputParams const & runparams) const
1757 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1760 if (!openFileWrite(ofs, fname))
1763 // make sure we are ready to export
1764 // this has to be done before we validate
1765 updateBuffer(UpdateMaster, OutputUpdate);
1766 updateMacroInstances(OutputUpdate);
1768 writeLyXHTMLSource(ofs, runparams, FullSource);
1772 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1776 void Buffer::writeLyXHTMLSource(odocstream & os,
1777 OutputParams const & runparams,
1778 OutputWhat output) const
1780 LaTeXFeatures features(*this, params(), runparams);
1782 d->bibinfo_.makeCitationLabels(*this);
1784 bool const output_preamble =
1785 output == FullSource || output == OnlyPreamble;
1786 bool const output_body =
1787 output == FullSource || output == OnlyBody || output == IncludedFile;
1789 if (output_preamble) {
1790 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1791 << "<!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"
1792 // FIXME Language should be set properly.
1793 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1795 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1796 // FIXME Presumably need to set this right
1797 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1799 docstring const & doctitle = features.htmlTitle();
1801 << (doctitle.empty() ?
1802 from_ascii("LyX Document") :
1803 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1806 docstring styles = features.getTClassHTMLPreamble();
1807 if (!styles.empty())
1808 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1810 styles = from_utf8(features.getPreambleSnippets());
1811 if (!styles.empty())
1812 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1814 // we will collect CSS information in a stream, and then output it
1815 // either here, as part of the header, or else in a separate file.
1816 odocstringstream css;
1817 styles = from_utf8(features.getCSSSnippets());
1818 if (!styles.empty())
1819 css << "/* LyX Provided Styles */\n" << styles << '\n';
1821 styles = features.getTClassHTMLStyles();
1822 if (!styles.empty())
1823 css << "/* Layout-provided Styles */\n" << styles << '\n';
1825 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1826 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1827 if (needfg || needbg) {
1828 css << "\nbody {\n";
1831 << from_ascii(X11hexname(params().fontcolor))
1834 css << " background-color: "
1835 << from_ascii(X11hexname(params().backgroundcolor))
1840 docstring const dstyles = css.str();
1841 if (!dstyles.empty()) {
1842 bool written = false;
1843 if (params().html_css_as_file) {
1844 // open a file for CSS info
1846 string const fcssname = addName(temppath(), "docstyle.css");
1847 FileName const fcssfile = FileName(fcssname);
1848 if (openFileWrite(ocss, fcssfile)) {
1852 // write link to header
1853 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1855 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1858 // we are here if the CSS is supposed to be written to the header
1859 // or if we failed to write it to an external file.
1861 os << "<style type='text/css'>\n"
1870 bool const output_body_tag = (output != IncludedFile);
1871 if (output_body_tag)
1874 params().documentClass().counters().reset();
1875 xhtmlParagraphs(text(), *this, xs, runparams);
1876 if (output_body_tag)
1880 if (output_preamble)
1885 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1886 // Other flags: -wall -v0 -x
1887 int Buffer::runChktex()
1891 // get LaTeX-Filename
1892 FileName const path(temppath());
1893 string const name = addName(path.absFileName(), latexName());
1894 string const org_path = filePath();
1896 PathChanger p(path); // path to LaTeX file
1897 message(_("Running chktex..."));
1899 // Generate the LaTeX file if neccessary
1900 OutputParams runparams(¶ms().encoding());
1901 runparams.flavor = OutputParams::LATEX;
1902 runparams.nice = false;
1903 runparams.linelen = lyxrc.plaintext_linelen;
1904 makeLaTeXFile(FileName(name), org_path, runparams);
1907 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1908 int const res = chktex.run(terr); // run chktex
1911 Alert::error(_("chktex failure"),
1912 _("Could not run chktex successfully."));
1913 } else if (res > 0) {
1914 ErrorList & errlist = d->errorLists["ChkTeX"];
1916 bufferErrors(terr, errlist);
1927 void Buffer::validate(LaTeXFeatures & features) const
1929 // Validate the buffer params, but not for included
1930 // files, since they also use the parent buffer's
1932 if (!features.runparams().is_child)
1933 params().validate(features);
1935 for_each(paragraphs().begin(), paragraphs().end(),
1936 bind(&Paragraph::validate, _1, ref(features)));
1938 if (lyxerr.debugging(Debug::LATEX)) {
1939 features.showStruct();
1944 void Buffer::getLabelList(vector<docstring> & list) const
1946 // If this is a child document, use the master's list instead.
1948 masterBuffer()->getLabelList(list);
1953 Toc & toc = d->toc_backend.toc("label");
1954 TocIterator toc_it = toc.begin();
1955 TocIterator end = toc.end();
1956 for (; toc_it != end; ++toc_it) {
1957 if (toc_it->depth() == 0)
1958 list.push_back(toc_it->str());
1963 void Buffer::updateBibfilesCache(UpdateScope scope) const
1965 // FIXME This is probably unnecssary, given where we call this.
1966 // If this is a child document, use the parent's cache instead.
1967 if (parent() && scope != UpdateChildOnly) {
1968 masterBuffer()->updateBibfilesCache();
1972 d->bibfiles_cache_.clear();
1973 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1974 if (it->lyxCode() == BIBTEX_CODE) {
1975 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1976 support::FileNameList const bibfiles = inset.getBibFiles();
1977 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1980 } else if (it->lyxCode() == INCLUDE_CODE) {
1981 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1982 Buffer const * const incbuf = inset.getChildBuffer();
1985 support::FileNameList const & bibfiles =
1986 incbuf->getBibfilesCache(UpdateChildOnly);
1987 if (!bibfiles.empty()) {
1988 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1994 d->bibfile_cache_valid_ = true;
1995 d->bibinfo_cache_valid_ = false;
1996 d->cite_labels_valid_ = false;
2000 void Buffer::invalidateBibinfoCache() const
2002 d->bibinfo_cache_valid_ = false;
2003 d->cite_labels_valid_ = false;
2004 // also invalidate the cache for the parent buffer
2005 Buffer const * const pbuf = d->parent();
2007 pbuf->invalidateBibinfoCache();
2011 void Buffer::invalidateBibfileCache() const
2013 d->bibfile_cache_valid_ = false;
2014 d->bibinfo_cache_valid_ = false;
2015 d->cite_labels_valid_ = false;
2016 // also invalidate the cache for the parent buffer
2017 Buffer const * const pbuf = d->parent();
2019 pbuf->invalidateBibfileCache();
2023 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2025 // FIXME This is probably unnecessary, given where we call this.
2026 // If this is a child document, use the master's cache instead.
2027 Buffer const * const pbuf = masterBuffer();
2028 if (pbuf != this && scope != UpdateChildOnly)
2029 return pbuf->getBibfilesCache();
2031 if (!d->bibfile_cache_valid_)
2032 this->updateBibfilesCache(scope);
2034 return d->bibfiles_cache_;
2038 BiblioInfo const & Buffer::masterBibInfo() const
2040 Buffer const * const tmp = masterBuffer();
2042 return tmp->masterBibInfo();
2047 void Buffer::checkIfBibInfoCacheIsValid() const
2049 // use the master's cache
2050 Buffer const * const tmp = masterBuffer();
2052 tmp->checkIfBibInfoCacheIsValid();
2056 // compare the cached timestamps with the actual ones.
2057 FileNameList const & bibfiles_cache = getBibfilesCache();
2058 FileNameList::const_iterator ei = bibfiles_cache.begin();
2059 FileNameList::const_iterator en = bibfiles_cache.end();
2060 for (; ei != en; ++ ei) {
2061 time_t lastw = ei->lastModified();
2062 time_t prevw = d->bibfile_status_[*ei];
2063 if (lastw != prevw) {
2064 d->bibinfo_cache_valid_ = false;
2065 d->cite_labels_valid_ = false;
2066 d->bibfile_status_[*ei] = lastw;
2072 void Buffer::reloadBibInfoCache() const
2074 // use the master's cache
2075 Buffer const * const tmp = masterBuffer();
2077 tmp->reloadBibInfoCache();
2081 checkIfBibInfoCacheIsValid();
2082 if (d->bibinfo_cache_valid_)
2085 d->bibinfo_.clear();
2087 d->bibinfo_cache_valid_ = true;
2091 void Buffer::collectBibKeys() const
2093 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2094 it->collectBibKeys(it);
2098 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2100 Buffer const * tmp = masterBuffer();
2101 BiblioInfo & masterbi = (tmp == this) ?
2102 d->bibinfo_ : tmp->d->bibinfo_;
2103 masterbi.mergeBiblioInfo(bi);
2107 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2109 Buffer const * tmp = masterBuffer();
2110 BiblioInfo & masterbi = (tmp == this) ?
2111 d->bibinfo_ : tmp->d->bibinfo_;
2116 bool Buffer::citeLabelsValid() const
2118 return masterBuffer()->d->cite_labels_valid_;
2122 void Buffer::removeBiblioTempFiles() const
2124 // We remove files that contain LaTeX commands specific to the
2125 // particular bibliographic style being used, in order to avoid
2126 // LaTeX errors when we switch style.
2127 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2128 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2129 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2130 aux_file.removeFile();
2131 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2132 bbl_file.removeFile();
2133 // Also for the parent buffer
2134 Buffer const * const pbuf = parent();
2136 pbuf->removeBiblioTempFiles();
2140 bool Buffer::isDepClean(string const & name) const
2142 DepClean::const_iterator const it = d->dep_clean.find(name);
2143 if (it == d->dep_clean.end())
2149 void Buffer::markDepClean(string const & name)
2151 d->dep_clean[name] = true;
2155 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2158 // FIXME? if there is an Buffer LFUN that can be dispatched even
2159 // if internal, put a switch '(cmd.action)' here.
2165 switch (cmd.action()) {
2167 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2168 flag.setOnOff(isReadonly());
2171 // FIXME: There is need for a command-line import.
2172 //case LFUN_BUFFER_IMPORT:
2174 case LFUN_BUFFER_AUTO_SAVE:
2177 case LFUN_BUFFER_EXPORT_CUSTOM:
2178 // FIXME: Nothing to check here?
2181 case LFUN_BUFFER_EXPORT: {
2182 docstring const arg = cmd.argument();
2183 if (arg == "custom") {
2187 string format = to_utf8(arg);
2188 size_t pos = format.find(' ');
2189 if (pos != string::npos)
2190 format = format.substr(0, pos);
2191 enable = params().isExportable(format);
2193 flag.message(bformat(
2194 _("Don't know how to export to format: %1$s"), arg));
2198 case LFUN_BUFFER_CHKTEX:
2199 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2202 case LFUN_BUILD_PROGRAM:
2203 enable = params().isExportable("program");
2206 case LFUN_BRANCH_ADD:
2207 case LFUN_BRANCHES_RENAME:
2208 case LFUN_BUFFER_PRINT:
2209 // if no Buffer is present, then of course we won't be called!
2212 case LFUN_BUFFER_LANGUAGE:
2213 enable = !isReadonly();
2219 flag.setEnabled(enable);
2224 void Buffer::dispatch(string const & command, DispatchResult & result)
2226 return dispatch(lyxaction.lookupFunc(command), result);
2230 // NOTE We can end up here even if we have no GUI, because we are called
2231 // by LyX::exec to handled command-line requests. So we may need to check
2232 // whether we have a GUI or not. The boolean use_gui holds this information.
2233 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2236 // FIXME? if there is an Buffer LFUN that can be dispatched even
2237 // if internal, put a switch '(cmd.action())' here.
2238 dr.dispatched(false);
2241 string const argument = to_utf8(func.argument());
2242 // We'll set this back to false if need be.
2243 bool dispatched = true;
2244 undo().beginUndoGroup();
2246 switch (func.action()) {
2247 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2248 if (lyxvc().inUse())
2249 lyxvc().toggleReadOnly();
2251 setReadonly(!isReadonly());
2254 case LFUN_BUFFER_EXPORT: {
2255 ExportStatus const status = doExport(argument, false);
2256 dr.setError(status != ExportSuccess);
2257 if (status != ExportSuccess)
2258 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2263 case LFUN_BUILD_PROGRAM:
2264 doExport("program", true);
2267 case LFUN_BUFFER_CHKTEX:
2271 case LFUN_BUFFER_EXPORT_CUSTOM: {
2273 string command = split(argument, format_name, ' ');
2274 Format const * format = formats.getFormat(format_name);
2276 lyxerr << "Format \"" << format_name
2277 << "\" not recognized!"
2282 // The name of the file created by the conversion process
2285 // Output to filename
2286 if (format->name() == "lyx") {
2287 string const latexname = latexName(false);
2288 filename = changeExtension(latexname,
2289 format->extension());
2290 filename = addName(temppath(), filename);
2292 if (!writeFile(FileName(filename)))
2296 doExport(format_name, true, filename);
2299 // Substitute $$FName for filename
2300 if (!contains(command, "$$FName"))
2301 command = "( " + command + " ) < $$FName";
2302 command = subst(command, "$$FName", filename);
2304 // Execute the command in the background
2306 call.startscript(Systemcall::DontWait, command, filePath());
2310 // FIXME: There is need for a command-line import.
2312 case LFUN_BUFFER_IMPORT:
2317 case LFUN_BUFFER_AUTO_SAVE:
2319 resetAutosaveTimers();
2322 case LFUN_BRANCH_ADD: {
2323 docstring branch_name = func.argument();
2324 if (branch_name.empty()) {
2328 BranchList & branch_list = params().branchlist();
2329 vector<docstring> const branches =
2330 getVectorFromString(branch_name, branch_list.separator());
2332 for (vector<docstring>::const_iterator it = branches.begin();
2333 it != branches.end(); ++it) {
2335 Branch * branch = branch_list.find(branch_name);
2337 LYXERR0("Branch " << branch_name << " already exists.");
2341 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2343 branch_list.add(branch_name);
2344 branch = branch_list.find(branch_name);
2345 string const x11hexname = X11hexname(branch->color());
2346 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2347 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2349 dr.screenUpdate(Update::Force);
2357 case LFUN_BRANCHES_RENAME: {
2358 if (func.argument().empty())
2361 docstring const oldname = from_utf8(func.getArg(0));
2362 docstring const newname = from_utf8(func.getArg(1));
2363 InsetIterator it = inset_iterator_begin(inset());
2364 InsetIterator const end = inset_iterator_end(inset());
2365 bool success = false;
2366 for (; it != end; ++it) {
2367 if (it->lyxCode() == BRANCH_CODE) {
2368 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2369 if (ins.branch() == oldname) {
2370 undo().recordUndo(CursorData(it));
2371 ins.rename(newname);
2376 if (it->lyxCode() == INCLUDE_CODE) {
2377 // get buffer of external file
2378 InsetInclude const & ins =
2379 static_cast<InsetInclude const &>(*it);
2380 Buffer * child = ins.getChildBuffer();
2383 child->dispatch(func, dr);
2388 dr.screenUpdate(Update::Force);
2389 dr.forceBufferUpdate();
2394 case LFUN_BUFFER_PRINT: {
2395 // we'll assume there's a problem until we succeed
2397 string target = func.getArg(0);
2398 string target_name = func.getArg(1);
2399 string command = func.getArg(2);
2402 || target_name.empty()
2403 || command.empty()) {
2404 LYXERR0("Unable to parse " << func.argument());
2405 docstring const msg =
2406 bformat(_("Unable to parse \"%1$s\""), func.argument());
2410 if (target != "printer" && target != "file") {
2411 LYXERR0("Unrecognized target \"" << target << '"');
2412 docstring const msg =
2413 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2418 if (!doExport("dvi", true)) {
2419 showPrintError(absFileName());
2420 dr.setMessage(_("Error exporting to DVI."));
2424 // Push directory path.
2425 string const path = temppath();
2426 // Prevent the compiler from optimizing away p
2430 // there are three cases here:
2431 // 1. we print to a file
2432 // 2. we print directly to a printer
2433 // 3. we print using a spool command (print to file first)
2436 string const dviname = changeExtension(latexName(true), "dvi");
2438 if (target == "printer") {
2439 if (!lyxrc.print_spool_command.empty()) {
2440 // case 3: print using a spool
2441 string const psname = changeExtension(dviname,".ps");
2442 command += ' ' + lyxrc.print_to_file
2445 + quoteName(dviname);
2447 string command2 = lyxrc.print_spool_command + ' ';
2448 if (target_name != "default") {
2449 command2 += lyxrc.print_spool_printerprefix
2453 command2 += quoteName(psname);
2455 // If successful, then spool command
2456 res = one.startscript(Systemcall::Wait, command,
2460 // If there's no GUI, we have to wait on this command. Otherwise,
2461 // LyX deletes the temporary directory, and with it the spooled
2462 // file, before it can be printed!!
2463 Systemcall::Starttype stype = use_gui ?
2464 Systemcall::DontWait : Systemcall::Wait;
2465 res = one.startscript(stype, command2,
2469 // case 2: print directly to a printer
2470 if (target_name != "default")
2471 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2473 Systemcall::Starttype stype = use_gui ?
2474 Systemcall::DontWait : Systemcall::Wait;
2475 res = one.startscript(stype, command +
2476 quoteName(dviname), filePath());
2480 // case 1: print to a file
2481 FileName const filename(makeAbsPath(target_name, filePath()));
2482 FileName const dvifile(makeAbsPath(dviname, path));
2483 if (filename.exists()) {
2484 docstring text = bformat(
2485 _("The file %1$s already exists.\n\n"
2486 "Do you want to overwrite that file?"),
2487 makeDisplayPath(filename.absFileName()));
2488 if (Alert::prompt(_("Overwrite file?"),
2489 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2492 command += ' ' + lyxrc.print_to_file
2493 + quoteName(filename.toFilesystemEncoding())
2495 + quoteName(dvifile.toFilesystemEncoding());
2497 Systemcall::Starttype stype = use_gui ?
2498 Systemcall::DontWait : Systemcall::Wait;
2499 res = one.startscript(stype, command, filePath());
2505 dr.setMessage(_("Error running external commands."));
2506 showPrintError(absFileName());
2515 dr.dispatched(dispatched);
2516 undo().endUndoGroup();
2520 void Buffer::changeLanguage(Language const * from, Language const * to)
2522 LASSERT(from, /**/);
2525 for_each(par_iterator_begin(),
2527 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2531 bool Buffer::isMultiLingual() const
2533 ParConstIterator end = par_iterator_end();
2534 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2535 if (it->isMultiLingual(params()))
2542 std::set<Language const *> Buffer::getLanguages() const
2544 std::set<Language const *> languages;
2545 getLanguages(languages);
2550 void Buffer::getLanguages(std::set<Language const *> & languages) const
2552 ParConstIterator end = par_iterator_end();
2553 // add the buffer language, even if it's not actively used
2554 languages.insert(language());
2555 // iterate over the paragraphs
2556 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2557 it->getLanguages(languages);
2559 ListOfBuffers clist = getDescendents();
2560 ListOfBuffers::const_iterator cit = clist.begin();
2561 ListOfBuffers::const_iterator const cen = clist.end();
2562 for (; cit != cen; ++cit)
2563 (*cit)->getLanguages(languages);
2567 DocIterator Buffer::getParFromID(int const id) const
2569 Buffer * buf = const_cast<Buffer *>(this);
2571 // John says this is called with id == -1 from undo
2572 lyxerr << "getParFromID(), id: " << id << endl;
2573 return doc_iterator_end(buf);
2576 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2577 if (it.paragraph().id() == id)
2580 return doc_iterator_end(buf);
2584 bool Buffer::hasParWithID(int const id) const
2586 return !getParFromID(id).atEnd();
2590 ParIterator Buffer::par_iterator_begin()
2592 return ParIterator(doc_iterator_begin(this));
2596 ParIterator Buffer::par_iterator_end()
2598 return ParIterator(doc_iterator_end(this));
2602 ParConstIterator Buffer::par_iterator_begin() const
2604 return ParConstIterator(doc_iterator_begin(this));
2608 ParConstIterator Buffer::par_iterator_end() const
2610 return ParConstIterator(doc_iterator_end(this));
2614 Language const * Buffer::language() const
2616 return params().language;
2620 docstring const Buffer::B_(string const & l10n) const
2622 return params().B_(l10n);
2626 bool Buffer::isClean() const
2628 return d->lyx_clean;
2632 bool Buffer::isExternallyModified(CheckMethod method) const
2634 LASSERT(d->filename.exists(), /**/);
2635 // if method == timestamp, check timestamp before checksum
2636 return (method == checksum_method
2637 || d->timestamp_ != d->filename.lastModified())
2638 && d->checksum_ != d->filename.checksum();
2642 void Buffer::saveCheckSum() const
2644 FileName const & file = d->filename;
2647 if (file.exists()) {
2648 d->timestamp_ = file.lastModified();
2649 d->checksum_ = file.checksum();
2651 // in the case of save to a new file.
2658 void Buffer::markClean() const
2660 if (!d->lyx_clean) {
2661 d->lyx_clean = true;
2664 // if the .lyx file has been saved, we don't need an
2666 d->bak_clean = true;
2667 d->undo_.markDirty();
2671 void Buffer::setUnnamed(bool flag)
2677 bool Buffer::isUnnamed() const
2684 /// Don't check unnamed, here: isInternal() is used in
2685 /// newBuffer(), where the unnamed flag has not been set by anyone
2686 /// yet. Also, for an internal buffer, there should be no need for
2687 /// retrieving fileName() nor for checking if it is unnamed or not.
2688 bool Buffer::isInternal() const
2690 return d->internal_buffer;
2694 void Buffer::setInternal(bool flag)
2696 d->internal_buffer = flag;
2700 void Buffer::markDirty()
2703 d->lyx_clean = false;
2706 d->bak_clean = false;
2708 DepClean::iterator it = d->dep_clean.begin();
2709 DepClean::const_iterator const end = d->dep_clean.end();
2711 for (; it != end; ++it)
2716 FileName Buffer::fileName() const
2722 string Buffer::absFileName() const
2724 return d->filename.absFileName();
2728 string Buffer::filePath() const
2730 int last = d->filename.onlyPath().absFileName().length() - 1;
2732 return d->filename.onlyPath().absFileName()[last] == '/'
2733 ? d->filename.onlyPath().absFileName()
2734 : d->filename.onlyPath().absFileName() + "/";
2738 bool Buffer::isReadonly() const
2740 return d->read_only;
2744 void Buffer::setParent(Buffer const * buffer)
2746 // Avoids recursive include.
2747 d->setParent(buffer == this ? 0 : buffer);
2752 Buffer const * Buffer::parent() const
2758 ListOfBuffers Buffer::allRelatives() const
2760 ListOfBuffers lb = masterBuffer()->getDescendents();
2761 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2766 Buffer const * Buffer::masterBuffer() const
2768 // FIXME Should be make sure we are not in some kind
2769 // of recursive include? A -> B -> A will crash this.
2770 Buffer const * const pbuf = d->parent();
2774 return pbuf->masterBuffer();
2778 bool Buffer::isChild(Buffer * child) const
2780 return d->children_positions.find(child) != d->children_positions.end();
2784 DocIterator Buffer::firstChildPosition(Buffer const * child)
2786 Impl::BufferPositionMap::iterator it;
2787 it = d->children_positions.find(child);
2788 if (it == d->children_positions.end())
2789 return DocIterator(this);
2794 bool Buffer::hasChildren() const
2796 return !d->children_positions.empty();
2800 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2802 // loop over children
2803 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2804 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2805 for (; it != end; ++it) {
2806 Buffer * child = const_cast<Buffer *>(it->first);
2808 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2809 if (bit != clist.end())
2811 clist.push_back(child);
2813 // there might be grandchildren
2814 child->collectChildren(clist, true);
2819 ListOfBuffers Buffer::getChildren() const
2822 collectChildren(v, false);
2823 // Make sure we have not included ourselves.
2824 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2825 if (bit != v.end()) {
2826 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2833 ListOfBuffers Buffer::getDescendents() const
2836 collectChildren(v, true);
2837 // Make sure we have not included ourselves.
2838 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2839 if (bit != v.end()) {
2840 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2847 template<typename M>
2848 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2853 typename M::const_iterator it = m.lower_bound(x);
2854 if (it == m.begin())
2862 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2863 DocIterator const & pos) const
2865 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2867 // if paragraphs have no macro context set, pos will be empty
2871 // we haven't found anything yet
2872 DocIterator bestPos = owner_->par_iterator_begin();
2873 MacroData const * bestData = 0;
2875 // find macro definitions for name
2876 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2877 if (nameIt != macros.end()) {
2878 // find last definition in front of pos or at pos itself
2879 PositionScopeMacroMap::const_iterator it
2880 = greatest_below(nameIt->second, pos);
2881 if (it != nameIt->second.end()) {
2883 // scope ends behind pos?
2884 if (pos < it->second.first) {
2885 // Looks good, remember this. If there
2886 // is no external macro behind this,
2887 // we found the right one already.
2888 bestPos = it->first;
2889 bestData = &it->second.second;
2893 // try previous macro if there is one
2894 if (it == nameIt->second.begin())
2901 // find macros in included files
2902 PositionScopeBufferMap::const_iterator it
2903 = greatest_below(position_to_children, pos);
2904 if (it == position_to_children.end())
2905 // no children before
2909 // do we know something better (i.e. later) already?
2910 if (it->first < bestPos )
2913 // scope ends behind pos?
2914 if (pos < it->second.first
2915 && (cloned_buffer_ ||
2916 theBufferList().isLoaded(it->second.second))) {
2917 // look for macro in external file
2919 MacroData const * data
2920 = it->second.second->getMacro(name, false);
2923 bestPos = it->first;
2929 // try previous file if there is one
2930 if (it == position_to_children.begin())
2935 // return the best macro we have found
2940 MacroData const * Buffer::getMacro(docstring const & name,
2941 DocIterator const & pos, bool global) const
2946 // query buffer macros
2947 MacroData const * data = d->getBufferMacro(name, pos);
2951 // If there is a master buffer, query that
2952 Buffer const * const pbuf = d->parent();
2954 d->macro_lock = true;
2955 MacroData const * macro = pbuf->getMacro(
2956 name, *this, false);
2957 d->macro_lock = false;
2963 data = MacroTable::globalMacros().get(name);
2972 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2974 // set scope end behind the last paragraph
2975 DocIterator scope = par_iterator_begin();
2976 scope.pit() = scope.lastpit() + 1;
2978 return getMacro(name, scope, global);
2982 MacroData const * Buffer::getMacro(docstring const & name,
2983 Buffer const & child, bool global) const
2985 // look where the child buffer is included first
2986 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2987 if (it == d->children_positions.end())
2990 // check for macros at the inclusion position
2991 return getMacro(name, it->second, global);
2995 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2997 pit_type const lastpit = it.lastpit();
2999 // look for macros in each paragraph
3000 while (it.pit() <= lastpit) {
3001 Paragraph & par = it.paragraph();
3003 // iterate over the insets of the current paragraph
3004 InsetList const & insets = par.insetList();
3005 InsetList::const_iterator iit = insets.begin();
3006 InsetList::const_iterator end = insets.end();
3007 for (; iit != end; ++iit) {
3008 it.pos() = iit->pos;
3010 // is it a nested text inset?
3011 if (iit->inset->asInsetText()) {
3012 // Inset needs its own scope?
3013 InsetText const * itext = iit->inset->asInsetText();
3014 bool newScope = itext->isMacroScope();
3016 // scope which ends just behind the inset
3017 DocIterator insetScope = it;
3020 // collect macros in inset
3021 it.push_back(CursorSlice(*iit->inset));
3022 updateMacros(it, newScope ? insetScope : scope);
3027 if (iit->inset->asInsetTabular()) {
3028 CursorSlice slice(*iit->inset);
3029 size_t const numcells = slice.nargs();
3030 for (; slice.idx() < numcells; slice.forwardIdx()) {
3031 it.push_back(slice);
3032 updateMacros(it, scope);
3038 // is it an external file?
3039 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3040 // get buffer of external file
3041 InsetInclude const & inset =
3042 static_cast<InsetInclude const &>(*iit->inset);
3044 Buffer * child = inset.getChildBuffer();
3049 // register its position, but only when it is
3050 // included first in the buffer
3051 if (children_positions.find(child) ==
3052 children_positions.end())
3053 children_positions[child] = it;
3055 // register child with its scope
3056 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3060 InsetMath * im = iit->inset->asInsetMath();
3061 if (doing_export && im) {
3062 InsetMathHull * hull = im->asHullInset();
3064 hull->recordLocation(it);
3067 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3071 MathMacroTemplate & macroTemplate =
3072 *iit->inset->asInsetMath()->asMacroTemplate();
3073 MacroContext mc(owner_, it);
3074 macroTemplate.updateToContext(mc);
3077 bool valid = macroTemplate.validMacro();
3078 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3079 // then the BufferView's cursor will be invalid in
3080 // some cases which leads to crashes.
3085 // FIXME (Abdel), I don't understandt why we pass 'it' here
3086 // instead of 'macroTemplate' defined above... is this correct?
3087 macros[macroTemplate.name()][it] =
3088 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3098 void Buffer::updateMacros() const
3103 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3105 // start with empty table
3107 d->children_positions.clear();
3108 d->position_to_children.clear();
3110 // Iterate over buffer, starting with first paragraph
3111 // The scope must be bigger than any lookup DocIterator
3112 // later. For the global lookup, lastpit+1 is used, hence
3113 // we use lastpit+2 here.
3114 DocIterator it = par_iterator_begin();
3115 DocIterator outerScope = it;
3116 outerScope.pit() = outerScope.lastpit() + 2;
3117 d->updateMacros(it, outerScope);
3121 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3123 InsetIterator it = inset_iterator_begin(inset());
3124 InsetIterator const end = inset_iterator_end(inset());
3125 for (; it != end; ++it) {
3126 if (it->lyxCode() == BRANCH_CODE) {
3127 InsetBranch & br = static_cast<InsetBranch &>(*it);
3128 docstring const name = br.branch();
3129 if (!from_master && !params().branchlist().find(name))
3130 result.push_back(name);
3131 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3132 result.push_back(name);
3135 if (it->lyxCode() == INCLUDE_CODE) {
3136 // get buffer of external file
3137 InsetInclude const & ins =
3138 static_cast<InsetInclude const &>(*it);
3139 Buffer * child = ins.getChildBuffer();
3142 child->getUsedBranches(result, true);
3145 // remove duplicates
3150 void Buffer::updateMacroInstances(UpdateType utype) const
3152 LYXERR(Debug::MACROS, "updateMacroInstances for "
3153 << d->filename.onlyFileName());
3154 DocIterator it = doc_iterator_begin(this);
3156 DocIterator const end = doc_iterator_end(this);
3157 for (; it != end; it.forwardInset()) {
3158 // look for MathData cells in InsetMathNest insets
3159 InsetMath * minset = it.nextInset()->asInsetMath();
3163 // update macro in all cells of the InsetMathNest
3164 DocIterator::idx_type n = minset->nargs();
3165 MacroContext mc = MacroContext(this, it);
3166 for (DocIterator::idx_type i = 0; i < n; ++i) {
3167 MathData & data = minset->cell(i);
3168 data.updateMacros(0, mc, utype);
3174 void Buffer::listMacroNames(MacroNameSet & macros) const
3179 d->macro_lock = true;
3181 // loop over macro names
3182 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3183 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3184 for (; nameIt != nameEnd; ++nameIt)
3185 macros.insert(nameIt->first);
3187 // loop over children
3188 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3189 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3190 for (; it != end; ++it)
3191 it->first->listMacroNames(macros);
3194 Buffer const * const pbuf = d->parent();
3196 pbuf->listMacroNames(macros);
3198 d->macro_lock = false;
3202 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3204 Buffer const * const pbuf = d->parent();
3209 pbuf->listMacroNames(names);
3212 MacroNameSet::iterator it = names.begin();
3213 MacroNameSet::iterator end = names.end();
3214 for (; it != end; ++it) {
3216 MacroData const * data =
3217 pbuf->getMacro(*it, *this, false);
3219 macros.insert(data);
3221 // we cannot access the original MathMacroTemplate anymore
3222 // here to calls validate method. So we do its work here manually.
3223 // FIXME: somehow make the template accessible here.
3224 if (data->optionals() > 0)
3225 features.require("xargs");
3231 Buffer::References & Buffer::references(docstring const & label)
3234 return const_cast<Buffer *>(masterBuffer())->references(label);
3236 RefCache::iterator it = d->ref_cache_.find(label);
3237 if (it != d->ref_cache_.end())
3238 return it->second.second;
3240 static InsetLabel const * dummy_il = 0;
3241 static References const dummy_refs;
3242 it = d->ref_cache_.insert(
3243 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3244 return it->second.second;
3248 Buffer::References const & Buffer::references(docstring const & label) const
3250 return const_cast<Buffer *>(this)->references(label);
3254 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3256 masterBuffer()->d->ref_cache_[label].first = il;
3260 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3262 return masterBuffer()->d->ref_cache_[label].first;
3266 void Buffer::clearReferenceCache() const
3269 d->ref_cache_.clear();
3273 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3276 //FIXME: This does not work for child documents yet.
3277 LASSERT(code == CITE_CODE, /**/);
3279 reloadBibInfoCache();
3281 // Check if the label 'from' appears more than once
3282 BiblioInfo const & keys = masterBibInfo();
3283 BiblioInfo::const_iterator bit = keys.begin();
3284 BiblioInfo::const_iterator bend = keys.end();
3285 vector<docstring> labels;
3287 for (; bit != bend; ++bit)
3289 labels.push_back(bit->first);
3291 if (count(labels.begin(), labels.end(), from) > 1)
3294 string const paramName = "key";
3295 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3296 if (it->lyxCode() == code) {
3297 InsetCommand * inset = it->asInsetCommand();
3300 docstring const oldValue = inset->getParam(paramName);
3301 if (oldValue == from)
3302 inset->setParam(paramName, to);
3308 void Buffer::getSourceCode(odocstream & os, string const format,
3309 pit_type par_begin, pit_type par_end,
3310 OutputWhat output, bool master) const
3312 OutputParams runparams(¶ms().encoding());
3313 runparams.nice = true;
3314 runparams.flavor = params().getOutputFlavor(format);
3315 runparams.linelen = lyxrc.plaintext_linelen;
3316 // No side effect of file copying and image conversion
3317 runparams.dryrun = true;
3319 if (output == CurrentParagraph) {
3320 runparams.par_begin = par_begin;
3321 runparams.par_end = par_end;
3322 if (par_begin + 1 == par_end) {
3324 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3328 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3329 convert<docstring>(par_begin),
3330 convert<docstring>(par_end - 1))
3333 // output paragraphs
3334 if (runparams.flavor == OutputParams::LYX) {
3335 Paragraph const & par = text().paragraphs()[par_begin];
3337 depth_type dt = par.getDepth();
3338 par.write(ods, params(), dt);
3339 os << from_utf8(ods.str());
3340 } else if (runparams.flavor == OutputParams::HTML) {
3342 setMathFlavor(runparams);
3343 xhtmlParagraphs(text(), *this, xs, runparams);
3344 } else if (runparams.flavor == OutputParams::TEXT) {
3346 // FIXME Handles only one paragraph, unlike the others.
3347 // Probably should have some routine with a signature like them.
3348 writePlaintextParagraph(*this,
3349 text().paragraphs()[par_begin], os, runparams, dummy);
3350 } else if (params().isDocBook()) {
3351 docbookParagraphs(text(), *this, os, runparams);
3353 // If we are previewing a paragraph, even if this is the
3354 // child of some other buffer, let's cut the link here,
3355 // so that no concurring settings from the master
3356 // (e.g. branch state) interfere (see #8101).
3358 d->ignore_parent = true;
3359 // We need to validate the Buffer params' features here
3360 // in order to know if we should output polyglossia
3361 // macros (instead of babel macros)
3362 LaTeXFeatures features(*this, params(), runparams);
3363 params().validate(features);
3364 runparams.use_polyglossia = features.usePolyglossia();
3369 // latex or literate
3370 otexstream ots(os, texrow);
3373 latexParagraphs(*this, text(), ots, runparams);
3375 // Restore the parenthood
3377 d->ignore_parent = false;
3381 if (output == FullSource)
3382 os << _("Preview source code");
3383 else if (output == OnlyPreamble)
3384 os << _("Preview preamble");
3385 else if (output == OnlyBody)
3386 os << _("Preview body");
3388 if (runparams.flavor == OutputParams::LYX) {
3390 if (output == FullSource)
3392 else if (output == OnlyPreamble)
3393 params().writeFile(ods);
3394 else if (output == OnlyBody)
3396 os << from_utf8(ods.str());
3397 } else if (runparams.flavor == OutputParams::HTML) {
3398 writeLyXHTMLSource(os, runparams, output);
3399 } else if (runparams.flavor == OutputParams::TEXT) {
3400 if (output == OnlyPreamble) {
3401 os << "% "<< _("Plain text does not have a preamble.");
3403 writePlaintextFile(*this, os, runparams);
3404 } else if (params().isDocBook()) {
3405 writeDocBookSource(os, absFileName(), runparams, output);
3407 // latex or literate
3409 d->texrow.newline();
3410 d->texrow.newline();
3411 otexstream ots(os, d->texrow);
3413 runparams.is_child = true;
3414 writeLaTeXSource(ots, string(), runparams, output);
3420 ErrorList & Buffer::errorList(string const & type) const
3422 return d->errorLists[type];
3426 void Buffer::updateTocItem(std::string const & type,
3427 DocIterator const & dit) const
3430 d->gui_->updateTocItem(type, dit);
3434 void Buffer::structureChanged() const
3437 d->gui_->structureChanged();
3441 void Buffer::errors(string const & err, bool from_master) const
3444 d->gui_->errors(err, from_master);
3448 void Buffer::message(docstring const & msg) const
3451 d->gui_->message(msg);
3455 void Buffer::setBusy(bool on) const
3458 d->gui_->setBusy(on);
3462 void Buffer::updateTitles() const
3465 d->wa_->updateTitles();
3469 void Buffer::resetAutosaveTimers() const
3472 d->gui_->resetAutosaveTimers();
3476 bool Buffer::hasGuiDelegate() const
3482 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3491 class AutoSaveBuffer : public ForkedProcess {
3494 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3495 : buffer_(buffer), fname_(fname) {}
3497 virtual shared_ptr<ForkedProcess> clone() const
3499 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3504 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3505 from_utf8(fname_.absFileName())));
3506 return run(DontWait);
3510 virtual int generateChild();
3512 Buffer const & buffer_;
3517 int AutoSaveBuffer::generateChild()
3519 #if defined(__APPLE__)
3520 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3521 * We should use something else like threads.
3523 * Since I do not know how to determine at run time what is the OS X
3524 * version, I just disable forking altogether for now (JMarc)
3526 pid_t const pid = -1;
3528 // tmp_ret will be located (usually) in /tmp
3529 // will that be a problem?
3530 // Note that this calls ForkedCalls::fork(), so it's
3531 // ok cross-platform.
3532 pid_t const pid = fork();
3533 // If you want to debug the autosave
3534 // you should set pid to -1, and comment out the fork.
3535 if (pid != 0 && pid != -1)
3539 // pid = -1 signifies that lyx was unable
3540 // to fork. But we will do the save
3542 bool failed = false;
3543 FileName const tmp_ret = FileName::tempName("lyxauto");
3544 if (!tmp_ret.empty()) {
3545 buffer_.writeFile(tmp_ret);
3546 // assume successful write of tmp_ret
3547 if (!tmp_ret.moveTo(fname_))
3553 // failed to write/rename tmp_ret so try writing direct
3554 if (!buffer_.writeFile(fname_)) {
3555 // It is dangerous to do this in the child,
3556 // but safe in the parent, so...
3557 if (pid == -1) // emit message signal.
3558 buffer_.message(_("Autosave failed!"));
3562 if (pid == 0) // we are the child so...
3571 FileName Buffer::getEmergencyFileName() const
3573 return FileName(d->filename.absFileName() + ".emergency");
3577 FileName Buffer::getAutosaveFileName() const
3579 // if the document is unnamed try to save in the backup dir, else
3580 // in the default document path, and as a last try in the filePath,
3581 // which will most often be the temporary directory
3584 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3585 : lyxrc.backupdir_path;
3586 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3589 string const fname = "#" + d->filename.onlyFileName() + "#";
3591 return makeAbsPath(fname, fpath);
3595 void Buffer::removeAutosaveFile() const
3597 FileName const f = getAutosaveFileName();
3603 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3605 FileName const newauto = getAutosaveFileName();
3607 if (newauto != oldauto && oldauto.exists())
3608 if (!oldauto.moveTo(newauto))
3609 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3613 bool Buffer::autoSave() const
3615 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3616 if (buf->d->bak_clean || isReadonly())
3619 message(_("Autosaving current document..."));
3620 buf->d->bak_clean = true;
3622 FileName const fname = getAutosaveFileName();
3623 if (d->cloned_buffer_) {
3624 // If this buffer is cloned, we assume that
3625 // we are running in a separate thread already.
3626 FileName const tmp_ret = FileName::tempName("lyxauto");
3627 if (!tmp_ret.empty()) {
3629 // assume successful write of tmp_ret
3630 if (tmp_ret.moveTo(fname))
3633 // failed to write/rename tmp_ret so try writing direct
3634 return writeFile(fname);
3636 /// This function is deprecated as the frontend needs to take care
3637 /// of cloning the buffer and autosaving it in another thread. It
3638 /// is still here to allow (QT_VERSION < 0x040400).
3639 AutoSaveBuffer autosave(*this, fname);
3646 // helper class, to guarantee this gets reset properly
3647 class Buffer::MarkAsExporting {
3649 MarkAsExporting(Buffer const * buf) : buf_(buf)
3651 LASSERT(buf_, /* */);
3652 buf_->setExportStatus(true);
3656 buf_->setExportStatus(false);
3659 Buffer const * const buf_;
3664 void Buffer::setExportStatus(bool e) const
3666 d->doing_export = e;
3667 ListOfBuffers clist = getDescendents();
3668 ListOfBuffers::const_iterator cit = clist.begin();
3669 ListOfBuffers::const_iterator const cen = clist.end();
3670 for (; cit != cen; ++cit)
3671 (*cit)->d->doing_export = e;
3675 bool Buffer::isExporting() const
3677 return d->doing_export;
3681 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3685 return doExport(target, put_in_tempdir, result_file);
3688 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3689 string & result_file) const
3691 bool const update_unincluded =
3692 params().maintain_unincluded_children
3693 && !params().getIncludedChildren().empty();
3695 // (1) export with all included children (omit \includeonly)
3696 if (update_unincluded) {
3697 ExportStatus const status =
3698 doExport(target, put_in_tempdir, true, result_file);
3699 if (status != ExportSuccess)
3702 // (2) export with included children only
3703 return doExport(target, put_in_tempdir, false, result_file);
3707 void Buffer::setMathFlavor(OutputParams & op) const
3709 switch (params().html_math_output) {
3710 case BufferParams::MathML:
3711 op.math_flavor = OutputParams::MathAsMathML;
3713 case BufferParams::HTML:
3714 op.math_flavor = OutputParams::MathAsHTML;
3716 case BufferParams::Images:
3717 op.math_flavor = OutputParams::MathAsImages;
3719 case BufferParams::LaTeX:
3720 op.math_flavor = OutputParams::MathAsLaTeX;
3726 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3727 bool includeall, string & result_file) const
3729 LYXERR(Debug::FILES, "target=" << target);
3730 OutputParams runparams(¶ms().encoding());
3731 string format = target;
3732 string dest_filename;
3733 size_t pos = target.find(' ');
3734 if (pos != string::npos) {
3735 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3736 format = target.substr(0, pos);
3737 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3738 FileName(dest_filename).onlyPath().createPath();
3739 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3741 MarkAsExporting exporting(this);
3742 string backend_format;
3743 runparams.flavor = OutputParams::LATEX;
3744 runparams.linelen = lyxrc.plaintext_linelen;
3745 runparams.includeall = includeall;
3746 vector<string> backs = params().backends();
3747 Converters converters = theConverters();
3748 bool need_nice_file = false;
3749 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3750 // Get shortest path to format
3751 converters.buildGraph();
3752 Graph::EdgePath path;
3753 for (vector<string>::const_iterator it = backs.begin();
3754 it != backs.end(); ++it) {
3755 Graph::EdgePath p = converters.getPath(*it, format);
3756 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3757 backend_format = *it;
3762 if (!put_in_tempdir) {
3763 // Only show this alert if this is an export to a non-temporary
3764 // file (not for previewing).
3765 Alert::error(_("Couldn't export file"), bformat(
3766 _("No information for exporting the format %1$s."),
3767 formats.prettyName(format)));
3769 return ExportNoPathToFormat;
3771 runparams.flavor = converters.getFlavor(path, this);
3772 Graph::EdgePath::const_iterator it = path.begin();
3773 Graph::EdgePath::const_iterator en = path.end();
3774 for (; it != en; ++it)
3775 if (theConverters().get(*it).nice) {
3776 need_nice_file = true;
3781 backend_format = format;
3782 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3783 // FIXME: Don't hardcode format names here, but use a flag
3784 if (backend_format == "pdflatex")
3785 runparams.flavor = OutputParams::PDFLATEX;
3786 else if (backend_format == "luatex")
3787 runparams.flavor = OutputParams::LUATEX;
3788 else if (backend_format == "dviluatex")
3789 runparams.flavor = OutputParams::DVILUATEX;
3790 else if (backend_format == "xetex")
3791 runparams.flavor = OutputParams::XETEX;
3794 string filename = latexName(false);
3795 filename = addName(temppath(), filename);
3796 filename = changeExtension(filename,
3797 formats.extension(backend_format));
3798 LYXERR(Debug::FILES, "filename=" << filename);
3800 // Plain text backend
3801 if (backend_format == "text") {
3802 runparams.flavor = OutputParams::TEXT;
3803 writePlaintextFile(*this, FileName(filename), runparams);
3806 else if (backend_format == "xhtml") {
3807 runparams.flavor = OutputParams::HTML;
3808 setMathFlavor(runparams);
3809 makeLyXHTMLFile(FileName(filename), runparams);
3810 } else if (backend_format == "lyx")
3811 writeFile(FileName(filename));
3813 else if (params().isDocBook()) {
3814 runparams.nice = !put_in_tempdir;
3815 makeDocBookFile(FileName(filename), runparams);
3818 else if (backend_format == format || need_nice_file) {
3819 runparams.nice = true;
3820 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3821 if (d->cloned_buffer_)
3822 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3825 } else if (!lyxrc.tex_allows_spaces
3826 && contains(filePath(), ' ')) {
3827 Alert::error(_("File name error"),
3828 _("The directory path to the document cannot contain spaces."));
3829 return ExportTexPathHasSpaces;
3831 runparams.nice = false;
3832 bool const success = makeLaTeXFile(
3833 FileName(filename), filePath(), runparams);
3834 if (d->cloned_buffer_)
3835 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3840 string const error_type = (format == "program")
3841 ? "Build" : params().bufferFormat();
3842 ErrorList & error_list = d->errorLists[error_type];
3843 string const ext = formats.extension(format);
3844 FileName const tmp_result_file(changeExtension(filename, ext));
3845 bool const success = converters.convert(this, FileName(filename),
3846 tmp_result_file, FileName(absFileName()), backend_format, format,
3849 // Emit the signal to show the error list or copy it back to the
3850 // cloned Buffer so that it can be emitted afterwards.
3851 if (format != backend_format) {
3852 if (d->cloned_buffer_) {
3853 d->cloned_buffer_->d->errorLists[error_type] =
3854 d->errorLists[error_type];
3857 // also to the children, in case of master-buffer-view
3858 ListOfBuffers clist = getDescendents();
3859 ListOfBuffers::const_iterator cit = clist.begin();
3860 ListOfBuffers::const_iterator const cen = clist.end();
3861 for (; cit != cen; ++cit) {
3862 if (d->cloned_buffer_) {
3863 // Enable reverse search by copying back the
3864 // texrow object to the cloned buffer.
3865 // FIXME: this is not thread safe.
3866 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3867 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3868 (*cit)->d->errorLists[error_type];
3870 (*cit)->errors(error_type, true);
3874 if (d->cloned_buffer_) {
3875 // Enable reverse dvi or pdf to work by copying back the texrow
3876 // object to the cloned buffer.
3877 // FIXME: There is a possibility of concurrent access to texrow
3878 // here from the main GUI thread that should be securized.
3879 d->cloned_buffer_->d->texrow = d->texrow;
3880 string const error_type = params().bufferFormat();
3881 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3885 return ExportConverterError;
3887 if (put_in_tempdir) {
3888 result_file = tmp_result_file.absFileName();
3889 return ExportSuccess;
3892 if (dest_filename.empty())
3893 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3895 result_file = dest_filename;
3896 // We need to copy referenced files (e. g. included graphics
3897 // if format == "dvi") to the result dir.
3898 vector<ExportedFile> const files =
3899 runparams.exportdata->externalFiles(format);
3900 string const dest = runparams.export_folder.empty() ?
3901 onlyPath(result_file) : runparams.export_folder;
3902 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3903 : force_overwrite == ALL_FILES;
3904 CopyStatus status = use_force ? FORCE : SUCCESS;
3906 vector<ExportedFile>::const_iterator it = files.begin();
3907 vector<ExportedFile>::const_iterator const en = files.end();
3908 for (; it != en && status != CANCEL; ++it) {
3909 string const fmt = formats.getFormatFromFile(it->sourceName);
3910 string fixedName = it->exportName;
3911 if (!runparams.export_folder.empty()) {
3912 // Relative pathnames starting with ../ will be sanitized
3913 // if exporting to a different folder
3914 while (fixedName.substr(0, 3) == "../")
3915 fixedName = fixedName.substr(3, fixedName.length() - 3);
3917 FileName fixedFileName = makeAbsPath(fixedName, dest);
3918 fixedFileName.onlyPath().createPath();
3919 status = copyFile(fmt, it->sourceName,
3921 it->exportName, status == FORCE,
3922 runparams.export_folder.empty());
3925 if (status == CANCEL) {
3926 message(_("Document export cancelled."));
3927 return ExportCancel;
3930 if (tmp_result_file.exists()) {
3931 // Finally copy the main file
3932 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3933 : force_overwrite != NO_FILES;
3934 if (status == SUCCESS && use_force)
3936 status = copyFile(format, tmp_result_file,
3937 FileName(result_file), result_file,
3939 if (status == CANCEL) {
3940 message(_("Document export cancelled."));
3941 return ExportCancel;
3943 message(bformat(_("Document exported as %1$s "
3945 formats.prettyName(format),
3946 makeDisplayPath(result_file)));
3949 // This must be a dummy converter like fax (bug 1888)
3950 message(bformat(_("Document exported as %1$s"),
3951 formats.prettyName(format)));
3954 return ExportSuccess;
3958 Buffer::ExportStatus Buffer::preview(string const & format) const
3960 bool const update_unincluded =
3961 params().maintain_unincluded_children
3962 && !params().getIncludedChildren().empty();
3963 return preview(format, update_unincluded);
3966 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3968 MarkAsExporting exporting(this);
3970 // (1) export with all included children (omit \includeonly)
3972 ExportStatus const status = doExport(format, true, true, result_file);
3973 if (status != ExportSuccess)
3976 // (2) export with included children only
3977 ExportStatus const status = doExport(format, true, false, result_file);
3978 if (status != ExportSuccess)
3980 if (!formats.view(*this, FileName(result_file), format))
3981 return PreviewError;
3982 return PreviewSuccess;
3986 Buffer::ReadStatus Buffer::extractFromVC()
3988 bool const found = LyXVC::file_not_found_hook(d->filename);
3990 return ReadFileNotFound;
3991 if (!d->filename.isReadableFile())
3997 Buffer::ReadStatus Buffer::loadEmergency()
3999 FileName const emergencyFile = getEmergencyFileName();
4000 if (!emergencyFile.exists()
4001 || emergencyFile.lastModified() <= d->filename.lastModified())
4002 return ReadFileNotFound;
4004 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4005 docstring const text = bformat(_("An emergency save of the document "
4006 "%1$s exists.\n\nRecover emergency save?"), file);
4008 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4009 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4015 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4016 bool const success = (ret_llf == ReadSuccess);
4019 Alert::warning(_("File is read-only"),
4020 bformat(_("An emergency file is successfully loaded, "
4021 "but the original file %1$s is marked read-only. "
4022 "Please make sure to save the document as a different "
4023 "file."), from_utf8(d->filename.absFileName())));
4026 str = _("Document was successfully recovered.");
4028 str = _("Document was NOT successfully recovered.");
4029 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4030 makeDisplayPath(emergencyFile.absFileName()));
4032 int const del_emerg =
4033 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4034 _("&Remove"), _("&Keep"));
4035 if (del_emerg == 0) {
4036 emergencyFile.removeFile();
4038 Alert::warning(_("Emergency file deleted"),
4039 _("Do not forget to save your file now!"), true);
4041 return success ? ReadSuccess : ReadEmergencyFailure;
4044 int const del_emerg =
4045 Alert::prompt(_("Delete emergency file?"),
4046 _("Remove emergency file now?"), 1, 1,
4047 _("&Remove"), _("&Keep"));
4049 emergencyFile.removeFile();
4050 return ReadOriginal;
4060 Buffer::ReadStatus Buffer::loadAutosave()
4062 // Now check if autosave file is newer.
4063 FileName const autosaveFile = getAutosaveFileName();
4064 if (!autosaveFile.exists()
4065 || autosaveFile.lastModified() <= d->filename.lastModified())
4066 return ReadFileNotFound;
4068 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4069 docstring const text = bformat(_("The backup of the document %1$s "
4070 "is newer.\n\nLoad the backup instead?"), file);
4071 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4072 _("&Load backup"), _("Load &original"), _("&Cancel"));
4077 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4078 // the file is not saved if we load the autosave file.
4079 if (ret_llf == ReadSuccess) {
4081 Alert::warning(_("File is read-only"),
4082 bformat(_("A backup file is successfully loaded, "
4083 "but the original file %1$s is marked read-only. "
4084 "Please make sure to save the document as a "
4086 from_utf8(d->filename.absFileName())));
4091 return ReadAutosaveFailure;
4094 // Here we delete the autosave
4095 autosaveFile.removeFile();
4096 return ReadOriginal;
4104 Buffer::ReadStatus Buffer::loadLyXFile()
4106 if (!d->filename.isReadableFile()) {
4107 ReadStatus const ret_rvc = extractFromVC();
4108 if (ret_rvc != ReadSuccess)
4112 ReadStatus const ret_re = loadEmergency();
4113 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4116 ReadStatus const ret_ra = loadAutosave();
4117 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4120 return loadThisLyXFile(d->filename);
4124 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4126 return readFile(fn);
4130 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4132 TeXErrors::Errors::const_iterator it = terr.begin();
4133 TeXErrors::Errors::const_iterator end = terr.end();
4134 ListOfBuffers clist = getDescendents();
4135 ListOfBuffers::const_iterator cen = clist.end();
4137 for (; it != end; ++it) {
4140 int errorRow = it->error_in_line;
4141 Buffer const * buf = 0;
4143 if (it->child_name.empty())
4144 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4146 // The error occurred in a child
4147 ListOfBuffers::const_iterator cit = clist.begin();
4148 for (; cit != cen; ++cit) {
4149 string const child_name =
4150 DocFileName(changeExtension(
4151 (*cit)->absFileName(), "tex")).
4153 if (it->child_name != child_name)
4155 (*cit)->d->texrow.getIdFromRow(errorRow,
4156 id_start, pos_start);
4157 if (id_start != -1) {
4158 buf = d->cloned_buffer_
4159 ? (*cit)->d->cloned_buffer_->d->owner_
4160 : (*cit)->d->owner_;
4171 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4172 } while (found && id_start == id_end && pos_start == pos_end);
4174 if (id_start != id_end) {
4175 // Next registered position is outside the inset where
4176 // the error occurred, so signal end-of-paragraph
4180 errorList.push_back(ErrorItem(it->error_desc,
4181 it->error_text, id_start, pos_start, pos_end, buf));
4186 void Buffer::setBuffersForInsets() const
4188 inset().setBuffer(const_cast<Buffer &>(*this));
4192 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4194 // Use the master text class also for child documents
4195 Buffer const * const master = masterBuffer();
4196 DocumentClass const & textclass = master->params().documentClass();
4198 // do this only if we are the top-level Buffer
4200 reloadBibInfoCache();
4202 // keep the buffers to be children in this set. If the call from the
4203 // master comes back we can see which of them were actually seen (i.e.
4204 // via an InsetInclude). The remaining ones in the set need still be updated.
4205 static std::set<Buffer const *> bufToUpdate;
4206 if (scope == UpdateMaster) {
4207 // If this is a child document start with the master
4208 if (master != this) {
4209 bufToUpdate.insert(this);
4210 master->updateBuffer(UpdateMaster, utype);
4211 // Do this here in case the master has no gui associated with it. Then,
4212 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4213 if (!master->d->gui_)
4216 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4217 if (bufToUpdate.find(this) == bufToUpdate.end())
4221 // start over the counters in the master
4222 textclass.counters().reset();
4225 // update will be done below for this buffer
4226 bufToUpdate.erase(this);
4228 // update all caches
4229 clearReferenceCache();
4232 Buffer & cbuf = const_cast<Buffer &>(*this);
4234 LASSERT(!text().paragraphs().empty(), /**/);
4237 ParIterator parit = cbuf.par_iterator_begin();
4238 updateBuffer(parit, utype);
4241 // TocBackend update will be done later.
4244 d->bibinfo_cache_valid_ = true;
4245 d->cite_labels_valid_ = true;
4246 cbuf.tocBackend().update();
4247 if (scope == UpdateMaster)
4248 cbuf.structureChanged();
4252 static depth_type getDepth(DocIterator const & it)
4254 depth_type depth = 0;
4255 for (size_t i = 0 ; i < it.depth() ; ++i)
4256 if (!it[i].inset().inMathed())
4257 depth += it[i].paragraph().getDepth() + 1;
4258 // remove 1 since the outer inset does not count
4262 static depth_type getItemDepth(ParIterator const & it)
4264 Paragraph const & par = *it;
4265 LabelType const labeltype = par.layout().labeltype;
4267 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4270 // this will hold the lowest depth encountered up to now.
4271 depth_type min_depth = getDepth(it);
4272 ParIterator prev_it = it;
4275 --prev_it.top().pit();
4277 // start of nested inset: go to outer par
4279 if (prev_it.empty()) {
4280 // start of document: nothing to do
4285 // We search for the first paragraph with same label
4286 // that is not more deeply nested.
4287 Paragraph & prev_par = *prev_it;
4288 depth_type const prev_depth = getDepth(prev_it);
4289 if (labeltype == prev_par.layout().labeltype) {
4290 if (prev_depth < min_depth)
4291 return prev_par.itemdepth + 1;
4292 if (prev_depth == min_depth)
4293 return prev_par.itemdepth;
4295 min_depth = min(min_depth, prev_depth);
4296 // small optimization: if we are at depth 0, we won't
4297 // find anything else
4298 if (prev_depth == 0)
4304 static bool needEnumCounterReset(ParIterator const & it)
4306 Paragraph const & par = *it;
4307 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4308 depth_type const cur_depth = par.getDepth();
4309 ParIterator prev_it = it;
4310 while (prev_it.pit()) {
4311 --prev_it.top().pit();
4312 Paragraph const & prev_par = *prev_it;
4313 if (prev_par.getDepth() <= cur_depth)
4314 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4316 // start of nested inset: reset
4321 // set the label of a paragraph. This includes the counters.
4322 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4324 BufferParams const & bp = owner_->masterBuffer()->params();
4325 DocumentClass const & textclass = bp.documentClass();
4326 Paragraph & par = it.paragraph();
4327 Layout const & layout = par.layout();
4328 Counters & counters = textclass.counters();
4330 if (par.params().startOfAppendix()) {
4331 // We want to reset the counter corresponding to toplevel sectioning
4332 Layout const & lay = textclass.getTOCLayout();
4333 docstring const cnt = lay.counter;
4335 counters.reset(cnt);
4336 counters.appendix(true);
4338 par.params().appendix(counters.appendix());
4340 // Compute the item depth of the paragraph
4341 par.itemdepth = getItemDepth(it);
4343 if (layout.margintype == MARGIN_MANUAL) {
4344 if (par.params().labelWidthString().empty())
4345 par.params().labelWidthString(par.expandLabel(layout, bp));
4346 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4347 // we do not need to do anything here, since the empty case is
4348 // handled during export.
4350 par.params().labelWidthString(docstring());
4353 switch(layout.labeltype) {
4355 if (layout.toclevel <= bp.secnumdepth
4356 && (layout.latextype != LATEX_ENVIRONMENT
4357 || it.text()->isFirstInSequence(it.pit()))) {
4358 if (counters.hasCounter(layout.counter))
4359 counters.step(layout.counter, utype);
4360 par.params().labelString(par.expandLabel(layout, bp));
4362 par.params().labelString(docstring());
4365 case LABEL_ITEMIZE: {
4366 // At some point of time we should do something more
4367 // clever here, like:
4368 // par.params().labelString(
4369 // bp.user_defined_bullet(par.itemdepth).getText());
4370 // for now, use a simple hardcoded label
4371 docstring itemlabel;
4372 switch (par.itemdepth) {
4374 itemlabel = char_type(0x2022);
4377 itemlabel = char_type(0x2013);
4380 itemlabel = char_type(0x2217);
4383 itemlabel = char_type(0x2219); // or 0x00b7
4386 par.params().labelString(itemlabel);
4390 case LABEL_ENUMERATE: {
4391 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4393 switch (par.itemdepth) {
4402 enumcounter += "iv";
4405 // not a valid enumdepth...
4409 // Maybe we have to reset the enumeration counter.
4410 if (needEnumCounterReset(it))
4411 counters.reset(enumcounter);
4412 counters.step(enumcounter, utype);
4414 string const & lang = par.getParLanguage(bp)->code();
4415 par.params().labelString(counters.theCounter(enumcounter, lang));
4420 case LABEL_SENSITIVE: {
4421 string const & type = counters.current_float();
4422 docstring full_label;
4424 full_label = owner_->B_("Senseless!!! ");
4426 docstring name = owner_->B_(textclass.floats().getType(type).name());
4427 if (counters.hasCounter(from_utf8(type))) {
4428 string const & lang = par.getParLanguage(bp)->code();
4429 counters.step(from_utf8(type), utype);
4430 full_label = bformat(from_ascii("%1$s %2$s:"),
4432 counters.theCounter(from_utf8(type), lang));
4434 full_label = bformat(from_ascii("%1$s #:"), name);
4436 par.params().labelString(full_label);
4440 case LABEL_NO_LABEL:
4441 par.params().labelString(docstring());
4445 case LABEL_TOP_ENVIRONMENT:
4446 case LABEL_CENTERED_TOP_ENVIRONMENT:
4449 par.params().labelString(par.expandLabel(layout, bp));
4455 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4457 LASSERT(parit.pit() == 0, /**/);
4459 // Set the position of the text in the buffer to be able
4460 // to resolve macros in it.
4461 parit.text()->setMacrocontextPosition(parit);
4463 depth_type maxdepth = 0;
4464 pit_type const lastpit = parit.lastpit();
4465 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4466 // reduce depth if necessary
4467 if (parit->params().depth() > maxdepth) {
4468 /** FIXME: this function is const, but
4469 * nevertheless it modifies the buffer. To be
4470 * cleaner, one should modify the buffer in
4471 * another function, which is actually
4472 * non-const. This would however be costly in
4473 * terms of code duplication.
4475 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4476 parit->params().depth(maxdepth);
4478 maxdepth = parit->getMaxDepthAfter();
4480 if (utype == OutputUpdate) {
4481 // track the active counters
4482 // we have to do this for the master buffer, since the local
4483 // buffer isn't tracking anything.
4484 masterBuffer()->params().documentClass().counters().
4485 setActiveLayout(parit->layout());
4488 // set the counter for this paragraph
4489 d->setLabel(parit, utype);
4492 InsetList::const_iterator iit = parit->insetList().begin();
4493 InsetList::const_iterator end = parit->insetList().end();
4494 for (; iit != end; ++iit) {
4495 parit.pos() = iit->pos;
4496 iit->inset->updateBuffer(parit, utype);
4502 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4503 WordLangTuple & word_lang, docstring_list & suggestions) const
4507 suggestions.clear();
4508 word_lang = WordLangTuple();
4509 bool const to_end = to.empty();
4510 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4511 // OK, we start from here.
4512 for (; from != end; from.forwardPos()) {
4513 // We are only interested in text so remove the math CursorSlice.
4514 while (from.inMathed()) {
4518 // If from is at the end of the document (which is possible
4519 // when leaving the mathed) LyX will crash later otherwise.
4520 if (from.atEnd() || (!to_end && from >= end))
4523 from.paragraph().spellCheck();
4524 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4525 if (SpellChecker::misspelled(res)) {
4530 // Do not increase progress when from == to, otherwise the word
4531 // count will be wrong.
4541 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4543 bool inword = false;
4548 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4549 if (!dit.inTexted()) {
4554 Paragraph const & par = dit.paragraph();
4555 pos_type const pos = dit.pos();
4557 // Copied and adapted from isWordSeparator() in Paragraph
4558 if (pos == dit.lastpos()) {
4561 Inset const * ins = par.getInset(pos);
4562 if (ins && skipNoOutput && !ins->producesOutput()) {
4565 // stop if end of range was skipped
4566 if (!to.atEnd() && dit >= to)
4569 } else if (!par.isDeleted(pos)) {
4570 if (par.isWordSeparator(pos))
4576 if (ins && ins->isLetter())
4578 else if (ins && ins->isSpace())
4581 char_type const c = par.getChar(pos);
4582 if (isPrintableNonspace(c))
4584 else if (isSpace(c))
4594 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4596 d->updateStatistics(from, to, skipNoOutput);
4600 int Buffer::wordCount() const
4602 return d->wordCount();
4606 int Buffer::charCount(bool with_blanks) const
4608 return d->charCount(with_blanks);
4612 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4615 // c.f. bug http://www.lyx.org/trac/ticket/6587
4616 removeAutosaveFile();
4617 // e.g., read-only status could have changed due to version control
4618 d->filename.refresh();
4619 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4621 // clear parent. this will get reset if need be.
4623 ReadStatus const status = loadLyXFile();
4624 if (status == ReadSuccess) {
4629 message(bformat(_("Document %1$s reloaded."), disp_fn));
4633 message(bformat(_("Could not reload document %1$s."), disp_fn));
4643 bool Buffer::saveAs(FileName const & fn)
4645 FileName const old_name = fileName();
4646 FileName const old_auto = getAutosaveFileName();
4647 bool const old_unnamed = isUnnamed();
4654 // bring the autosave file with us, just in case.
4655 moveAutosaveFile(old_auto);
4656 // validate version control data and
4657 // correct buffer title
4658 lyxvc().file_found_hook(fileName());
4660 // the file has now been saved to the new location.
4661 // we need to check that the locations of child buffers
4663 checkChildBuffers();
4664 checkMasterBuffer();
4668 // reset the old filename and unnamed state
4669 setFileName(old_name);
4670 setUnnamed(old_unnamed);
4676 // FIXME We could do better here, but it is complicated. What would be
4677 // nice is to offer either (a) to save the child buffer to an appropriate
4678 // location, so that it would "move with the master", or else (b) to update
4679 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4680 // complicated, because the code for this lives in GuiView.
4681 void Buffer::checkChildBuffers()
4683 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4684 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4685 for (; it != en; ++it) {
4686 DocIterator dit = it->second;
4687 Buffer * cbuf = const_cast<Buffer *>(it->first);
4688 if (!cbuf || !theBufferList().isLoaded(cbuf))
4690 Inset * inset = dit.nextInset();
4691 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4692 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4693 docstring const & incfile = inset_inc->getParam("filename");
4694 string oldloc = cbuf->absFileName();
4695 string newloc = makeAbsPath(to_utf8(incfile),
4696 onlyPath(absFileName())).absFileName();
4697 if (oldloc == newloc)
4699 // the location of the child file is incorrect.
4700 Alert::warning(_("Included File Invalid"),
4701 bformat(_("Saving this document to a new location has made the file:\n"
4703 "inaccessible. You will need to update the included filename."),
4704 from_utf8(oldloc)));
4706 inset_inc->setChildBuffer(0);
4708 // invalidate cache of children
4709 d->children_positions.clear();
4710 d->position_to_children.clear();
4714 // If a child has been saved under a different name/path, it might have been
4715 // orphaned. Therefore the master needs to be reset (bug 8161).
4716 void Buffer::checkMasterBuffer()
4718 Buffer const * const master = masterBuffer();
4722 // necessary to re-register the child (bug 5873)
4723 // FIXME: clean up updateMacros (here, only
4724 // child registering is needed).
4725 master->updateMacros();
4726 // (re)set master as master buffer, but only
4727 // if we are a real child
4728 if (master->isChild(this))