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 "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
60 #include "texstream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/PreviewLoader.h"
84 #include "frontends/alert.h"
85 #include "frontends/Delegates.h"
86 #include "frontends/WorkAreaManager.h"
88 #include "support/lassert.h"
89 #include "support/convert.h"
90 #include "support/debug.h"
91 #include "support/docstring_list.h"
92 #include "support/ExceptionMessage.h"
93 #include "support/FileName.h"
94 #include "support/FileNameList.h"
95 #include "support/filetools.h"
96 #include "support/ForkedCalls.h"
97 #include "support/gettext.h"
98 #include "support/gzstream.h"
99 #include "support/lstrings.h"
100 #include "support/lyxalgo.h"
101 #include "support/mutex.h"
102 #include "support/os.h"
103 #include "support/Package.h"
104 #include "support/PathChanger.h"
105 #include "support/Systemcall.h"
106 #include "support/TempFile.h"
107 #include "support/textutils.h"
108 #include "support/types.h"
110 #include "support/bind.h"
122 using namespace lyx::support;
123 using namespace lyx::graphics;
127 namespace Alert = frontend::Alert;
128 namespace os = support::os;
132 int const LYX_FORMAT = LYX_FORMAT_LYX;
134 typedef map<string, bool> DepClean;
135 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
140 // A storehouse for the cloned buffers.
141 list<CloneList *> cloned_buffers;
147 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
151 delete preview_loader_;
159 /// search for macro in local (buffer) table or in children
160 MacroData const * getBufferMacro(docstring const & name,
161 DocIterator const & pos) const;
163 /// Update macro table starting with position of it \param it in some
165 void updateMacros(DocIterator & it, DocIterator & scope);
167 void setLabel(ParIterator & it, UpdateType utype) const;
169 /** If we have branches that use the file suffix
170 feature, return the file name with suffix appended.
172 support::FileName exportFileName() const;
179 mutable TexRow texrow;
181 /// need to regenerate .tex?
185 mutable bool lyx_clean;
187 /// is autosave needed?
188 mutable bool bak_clean;
190 /// is this an unnamed file (New...)?
193 /// is this an internal bufffer?
194 bool internal_buffer;
199 /// name of the file the buffer is associated with.
202 /** Set to true only when the file is fully loaded.
203 * Used to prevent the premature generation of previews
204 * and by the citation inset.
206 bool file_fully_loaded;
208 /// original format of loaded file
211 /// if the file was originally loaded from an older format, do
212 /// we need to back it up still?
213 bool need_format_backup;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
224 ScopeMacro(DocIterator const & s, MacroData const & m)
225 : scope(s), macro(m) {}
229 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231 /// map from the macro name to the position map,
232 /// which maps the macro definition position to the scope and the MacroData.
233 NamePositionScopeMacroMap macros;
234 /// This seem to change the way Buffer::getMacro() works
235 mutable bool macro_lock;
237 /// positions of child buffers in the buffer
238 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
240 ScopeBuffer() : buffer(0) {}
241 ScopeBuffer(DocIterator const & s, Buffer const * b)
242 : scope(s), buffer(b) {}
244 Buffer const * buffer;
246 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247 /// position of children buffers in this buffer
248 BufferPositionMap children_positions;
249 /// map from children inclusion positions to their scope and their buffer
250 PositionScopeBufferMap position_to_children;
252 /// Contains the old buffer filePath() while saving-as, or the
253 /// directory where the document was last saved while loading.
256 /** Keeps track of the path of local layout files.
257 * If possible, it is always relative to the buffer path.
258 * Empty for layouts in system or user directory.
260 string layout_position;
262 /// Container for all sort of Buffer dependant errors.
263 map<string, ErrorList> errorLists;
265 /// timestamp and checksum used to test if the file has been externally
266 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
268 unsigned long checksum_;
271 frontend::WorkAreaManager * wa_;
273 frontend::GuiBufferDelegate * gui_;
278 /// A cache for the bibfiles (including bibfiles of loaded child
279 /// documents), needed for appropriate update of natbib labels.
280 mutable support::FileNameList bibfiles_cache_;
282 // FIXME The caching mechanism could be improved. At present, we have a
283 // cache for each Buffer, that caches all the bibliography info for that
284 // Buffer. A more efficient solution would be to have a global cache per
285 // file, and then to construct the Buffer's bibinfo from that.
286 /// A cache for bibliography info
287 mutable BiblioInfo bibinfo_;
288 /// whether the bibinfo cache is valid
289 mutable bool bibinfo_cache_valid_;
290 /// whether the bibfile cache is valid
291 mutable bool bibfile_cache_valid_;
292 /// Cache of timestamps of .bib files
293 map<FileName, time_t> bibfile_status_;
294 /// Indicates whether the bibinfo has changed since the last time
295 /// we ran updateBuffer(), i.e., whether citation labels may need
297 mutable bool cite_labels_valid_;
299 /// These two hold the file name and format, written to by
300 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
301 FileName preview_file_;
302 string preview_format_;
303 /// If there was an error when previewing, on the next preview we do
304 /// a fresh compile (e.g. in case the user installed a package that
308 mutable RefCache ref_cache_;
310 /// our Text that should be wrapped in an InsetText
314 PreviewLoader * preview_loader_;
316 /// This is here to force the test to be done whenever parent_buffer
318 Buffer const * parent() const
320 // ignore_parent temporarily "orphans" a buffer
321 // (e.g. if a child is compiled standalone)
324 // if parent_buffer is not loaded, then it has been unloaded,
325 // which means that parent_buffer is an invalid pointer. So we
326 // set it to null in that case.
327 // however, the BufferList doesn't know about cloned buffers, so
328 // they will always be regarded as unloaded. in that case, we hope
330 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
332 return parent_buffer;
336 void setParent(Buffer const * pb)
338 if (parent_buffer == pb)
341 if (!cloned_buffer_ && parent_buffer && pb)
342 LYXERR0("Warning: a buffer should not have two parents!");
344 if (!cloned_buffer_ && parent_buffer) {
345 parent_buffer->invalidateBibfileCache();
346 parent_buffer->invalidateBibinfoCache();
350 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
351 /// This one is useful for preview detached in a thread.
352 Buffer const * cloned_buffer_;
354 CloneList * clone_list_;
355 /// are we in the process of exporting this buffer?
356 mutable bool doing_export;
358 /// compute statistics
359 /// \p from initial position
360 /// \p to points to the end position
361 void updateStatistics(DocIterator & from, DocIterator & to,
362 bool skipNoOutput = true);
363 /// statistics accessor functions
364 int wordCount() const
368 int charCount(bool with_blanks) const
371 + (with_blanks ? blank_count_ : 0);
374 // does the buffer contain tracked changes? (if so, we automatically
375 // display the review toolbar, for instance)
376 mutable bool tracked_changes_present_;
379 /// So we can force access via the accessors.
380 mutable Buffer const * parent_buffer;
389 /// Creates the per buffer temporary directory
390 static FileName createBufferTmpDir()
392 // FIXME This would be the ideal application for a TempDir class (like
393 // TempFile but for directories)
398 Mutex::Locker locker(&mutex);
399 counter = convert<string>(count++);
401 // We are in our own directory. Why bother to mangle name?
402 // In fact I wrote this code to circumvent a problematic behaviour
403 // (bug?) of EMX mkstemp().
404 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
407 if (!tmpfl.createDirectory(0777)) {
408 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
409 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
410 from_utf8(tmpfl.absFileName())));
416 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
417 Buffer const * cloned_buffer)
418 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
419 internal_buffer(false), read_only(readonly_), filename(file),
420 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
421 ignore_parent(false), toc_backend(owner), macro_lock(false), timestamp_(0),
422 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
423 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
424 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer), clone_list_(0),
425 doing_export(false), parent_buffer(0),
426 word_count_(0), char_count_(0), blank_count_(0)
428 if (!cloned_buffer_) {
429 temppath = createBufferTmpDir();
430 lyxvc.setBuffer(owner_);
432 wa_ = new frontend::WorkAreaManager;
435 temppath = cloned_buffer_->d->temppath;
436 file_fully_loaded = true;
437 params = cloned_buffer_->d->params;
438 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
439 bibinfo_ = cloned_buffer_->d->bibinfo_;
440 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
441 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
442 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
443 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
444 unnamed = cloned_buffer_->d->unnamed;
445 internal_buffer = cloned_buffer_->d->internal_buffer;
446 layout_position = cloned_buffer_->d->layout_position;
447 preview_file_ = cloned_buffer_->d->preview_file_;
448 preview_format_ = cloned_buffer_->d->preview_format_;
449 preview_error_ = cloned_buffer_->d->preview_error_;
450 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
454 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
455 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
457 LYXERR(Debug::INFO, "Buffer::Buffer()");
459 d->inset = new InsetText(*cloned_buffer->d->inset);
460 d->inset->setBuffer(*this);
461 // FIXME: optimize this loop somewhat, maybe by creating a new
462 // general recursive Inset::setId().
463 DocIterator it = doc_iterator_begin(this);
464 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
465 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
466 it.paragraph().setId(cloned_it.paragraph().id());
468 d->inset = new InsetText(this);
469 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
475 LYXERR(Debug::INFO, "Buffer::~Buffer()");
476 // here the buffer should take care that it is
477 // saved properly, before it goes into the void.
479 // GuiView already destroyed
483 // No need to do additional cleanups for internal buffer.
489 // this is in case of recursive includes: we won't try to delete
490 // ourselves as a child.
491 d->clone_list_->erase(this);
492 // loop over children
493 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
494 Impl::BufferPositionMap::iterator end = d->children_positions.end();
495 for (; it != end; ++it) {
496 Buffer * child = const_cast<Buffer *>(it->first);
497 if (d->clone_list_->erase(child))
500 // if we're the master buffer, then we should get rid of the list
503 // If this is not empty, we have leaked something. Worse, one of the
504 // children still has a reference to this list. But we will try to
505 // continue, rather than shut down.
506 LATTEST(d->clone_list_->empty());
507 list<CloneList *>::iterator it =
508 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
509 if (it == cloned_buffers.end()) {
510 // We will leak in this case, but it is safe to continue.
513 cloned_buffers.erase(it);
514 delete d->clone_list_;
516 // FIXME Do we really need to do this right before we delete d?
517 // clear references to children in macro tables
518 d->children_positions.clear();
519 d->position_to_children.clear();
521 // loop over children
522 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
523 Impl::BufferPositionMap::iterator end = d->children_positions.end();
524 for (; it != end; ++it) {
525 Buffer * child = const_cast<Buffer *>(it->first);
526 if (theBufferList().isLoaded(child)) {
527 if (theBufferList().isOthersChild(this, child))
530 theBufferList().release(child);
535 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
536 msg += emergencyWrite();
537 Alert::warning(_("Attempting to close changed document!"), msg);
540 // FIXME Do we really need to do this right before we delete d?
541 // clear references to children in macro tables
542 d->children_positions.clear();
543 d->position_to_children.clear();
545 if (!d->temppath.destroyDirectory()) {
546 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
547 from_utf8(d->temppath.absFileName())));
556 Buffer * Buffer::cloneFromMaster() const
559 cloned_buffers.push_back(new CloneList);
560 CloneList * clones = cloned_buffers.back();
562 masterBuffer()->cloneWithChildren(bufmap, clones);
564 // make sure we got cloned
565 BufferMap::const_iterator bit = bufmap.find(this);
566 LASSERT(bit != bufmap.end(), return 0);
567 Buffer * cloned_buffer = bit->second;
569 return cloned_buffer;
573 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
575 // have we already been cloned?
576 if (bufmap.find(this) != bufmap.end())
579 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
581 // The clone needs its own DocumentClass, since running updateBuffer() will
582 // modify it, and we would otherwise be sharing it with the original Buffer.
583 buffer_clone->params().makeDocumentClass(true);
585 cap::switchBetweenClasses(
586 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
587 static_cast<InsetText &>(buffer_clone->inset()), el);
589 bufmap[this] = buffer_clone;
590 clones->insert(buffer_clone);
591 buffer_clone->d->clone_list_ = clones;
592 buffer_clone->d->macro_lock = true;
593 buffer_clone->d->children_positions.clear();
595 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
596 // math macro caches need to be rethought and simplified.
597 // I am not sure wether we should handle Buffer cloning here or in BufferList.
598 // Right now BufferList knows nothing about buffer clones.
599 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
600 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
601 for (; it != end; ++it) {
602 DocIterator dit = it->first.clone(buffer_clone);
603 dit.setBuffer(buffer_clone);
604 Buffer * child = const_cast<Buffer *>(it->second.buffer);
606 child->cloneWithChildren(bufmap, clones);
607 BufferMap::iterator const bit = bufmap.find(child);
608 LASSERT(bit != bufmap.end(), continue);
609 Buffer * child_clone = bit->second;
611 Inset * inset = dit.nextInset();
612 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
613 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
614 inset_inc->setChildBuffer(child_clone);
615 child_clone->d->setParent(buffer_clone);
616 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
617 buffer_clone->setChild(dit, child_clone);
619 buffer_clone->d->macro_lock = false;
624 Buffer * Buffer::cloneBufferOnly() const {
625 cloned_buffers.push_back(new CloneList);
626 CloneList * clones = cloned_buffers.back();
627 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
629 // The clone needs its own DocumentClass, since running updateBuffer() will
630 // modify it, and we would otherwise be sharing it with the original Buffer.
631 buffer_clone->params().makeDocumentClass(true);
633 cap::switchBetweenClasses(
634 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
635 static_cast<InsetText &>(buffer_clone->inset()), el);
637 clones->insert(buffer_clone);
638 buffer_clone->d->clone_list_ = clones;
640 // we won't be cloning the children
641 buffer_clone->d->children_positions.clear();
646 bool Buffer::isClone() const
648 return d->cloned_buffer_;
652 void Buffer::changed(bool update_metrics) const
655 d->wa_->redrawAll(update_metrics);
659 frontend::WorkAreaManager & Buffer::workAreaManager() const
666 Text & Buffer::text() const
668 return d->inset->text();
672 Inset & Buffer::inset() const
678 BufferParams & Buffer::params()
684 BufferParams const & Buffer::params() const
690 BufferParams const & Buffer::masterParams() const
692 if (masterBuffer() == this)
695 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
696 // Copy child authors to the params. We need those pointers.
697 AuthorList const & child_authors = params().authors();
698 AuthorList::Authors::const_iterator it = child_authors.begin();
699 for (; it != child_authors.end(); ++it)
700 mparams.authors().record(*it);
705 double Buffer::fontScalingFactor() const
707 return isExporting() ? 75.0 * params().html_math_img_scale
708 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
712 ParagraphList & Buffer::paragraphs()
714 return text().paragraphs();
718 ParagraphList const & Buffer::paragraphs() const
720 return text().paragraphs();
724 LyXVC & Buffer::lyxvc()
730 LyXVC const & Buffer::lyxvc() const
736 string const Buffer::temppath() const
738 return d->temppath.absFileName();
742 TexRow & Buffer::texrow()
748 TexRow const & Buffer::texrow() const
754 TocBackend & Buffer::tocBackend() const
756 return d->toc_backend;
760 Undo & Buffer::undo()
766 void Buffer::setChild(DocIterator const & dit, Buffer * child)
768 d->children_positions[child] = dit;
772 string Buffer::latexName(bool const no_path) const
774 FileName latex_name =
775 makeLatexName(d->exportFileName());
776 return no_path ? latex_name.onlyFileName()
777 : latex_name.absFileName();
781 FileName Buffer::Impl::exportFileName() const
783 docstring const branch_suffix =
784 params.branchlist().getFileNameSuffix();
785 if (branch_suffix.empty())
788 string const name = filename.onlyFileNameWithoutExt()
789 + to_utf8(branch_suffix);
790 FileName res(filename.onlyPath().absFileName() + "/" + name);
791 res.changeExtension(filename.extension());
797 string Buffer::logName(LogType * type) const
799 string const filename = latexName(false);
801 if (filename.empty()) {
807 string const path = temppath();
809 FileName const fname(addName(temppath(),
810 onlyFileName(changeExtension(filename,
813 // FIXME: how do we know this is the name of the build log?
814 FileName const bname(
815 addName(path, onlyFileName(
816 changeExtension(filename,
817 formats.extension(params().bufferFormat()) + ".out"))));
819 // Also consider the master buffer log file
820 FileName masterfname = fname;
821 LogType mtype = latexlog;
822 if (masterBuffer() != this) {
823 string const mlogfile = masterBuffer()->logName(&mtype);
824 masterfname = FileName(mlogfile);
827 // If no Latex log or Build log is newer, show Build log
828 if (bname.exists() &&
829 ((!fname.exists() && !masterfname.exists())
830 || (fname.lastModified() < bname.lastModified()
831 && masterfname.lastModified() < bname.lastModified()))) {
832 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
835 return bname.absFileName();
836 // If we have a newer master file log or only a master log, show this
837 } else if (fname != masterfname
838 && (!fname.exists() && (masterfname.exists()
839 || fname.lastModified() < masterfname.lastModified()))) {
840 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
843 return masterfname.absFileName();
845 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
848 return fname.absFileName();
852 void Buffer::setReadonly(bool const flag)
854 if (d->read_only != flag) {
861 void Buffer::setFileName(FileName const & fname)
863 bool const changed = fname != d->filename;
866 lyxvc().file_found_hook(fname);
867 setReadonly(d->filename.isReadOnly());
873 int Buffer::readHeader(Lexer & lex)
875 int unknown_tokens = 0;
877 int begin_header_line = -1;
879 // Initialize parameters that may be/go lacking in header:
880 params().branchlist().clear();
881 params().preamble.erase();
882 params().options.erase();
883 params().master.erase();
884 params().float_placement.erase();
885 params().paperwidth.erase();
886 params().paperheight.erase();
887 params().leftmargin.erase();
888 params().rightmargin.erase();
889 params().topmargin.erase();
890 params().bottommargin.erase();
891 params().headheight.erase();
892 params().headsep.erase();
893 params().footskip.erase();
894 params().columnsep.erase();
895 params().fonts_cjk.erase();
896 params().listings_params.clear();
897 params().clearLayoutModules();
898 params().clearRemovedModules();
899 params().clearIncludedChildren();
900 params().pdfoptions().clear();
901 params().indiceslist().clear();
902 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
903 params().isbackgroundcolor = false;
904 params().fontcolor = RGBColor(0, 0, 0);
905 params().isfontcolor = false;
906 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
907 params().boxbgcolor = RGBColor(0xFF, 0, 0);
908 params().html_latex_start.clear();
909 params().html_latex_end.clear();
910 params().html_math_img_scale = 1.0;
911 params().output_sync_macro.erase();
912 params().setLocalLayout(docstring(), false);
913 params().setLocalLayout(docstring(), true);
915 for (int i = 0; i < 4; ++i) {
916 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
917 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
920 ErrorList & errorList = d->errorLists["Parse"];
929 if (token == "\\end_header")
933 if (token == "\\begin_header") {
934 begin_header_line = line;
938 LYXERR(Debug::PARSER, "Handling document header token: `"
941 string const result =
942 params().readToken(lex, token, d->filename.onlyPath());
943 if (!result.empty()) {
944 if (token == "\\textclass") {
945 d->layout_position = result;
948 docstring const s = bformat(_("Unknown token: "
952 errorList.push_back(ErrorItem(_("Document header error"), s));
956 if (begin_header_line) {
957 docstring const s = _("\\begin_header is missing");
958 errorList.push_back(ErrorItem(_("Document header error"), s));
961 params().makeDocumentClass();
963 return unknown_tokens;
968 // changed to be public and have one parameter
969 // Returns true if "\end_document" is not read (Asger)
970 bool Buffer::readDocument(Lexer & lex)
972 ErrorList & errorList = d->errorLists["Parse"];
975 // remove dummy empty par
976 paragraphs().clear();
978 if (!lex.checkFor("\\begin_document")) {
979 docstring const s = _("\\begin_document is missing");
980 errorList.push_back(ErrorItem(_("Document header error"), s));
985 if (params().output_changes) {
986 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
987 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
988 LaTeXFeatures::isAvailable("xcolor");
990 if (!dvipost && !xcolorulem) {
991 Alert::warning(_("Changes not shown in LaTeX output"),
992 _("Changes will not be highlighted in LaTeX output, "
993 "because neither dvipost nor xcolor/ulem are installed.\n"
994 "Please install these packages or redefine "
995 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
996 } else if (!xcolorulem) {
997 Alert::warning(_("Changes not shown in LaTeX output"),
998 _("Changes will not be highlighted in LaTeX output "
999 "when using pdflatex, because xcolor and ulem are not installed.\n"
1000 "Please install both packages or redefine "
1001 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1005 if (!parent() && !params().master.empty()) {
1006 FileName const master_file = makeAbsPath(params().master,
1007 onlyPath(absFileName()));
1008 if (isLyXFileName(master_file.absFileName())) {
1010 checkAndLoadLyXFile(master_file, true);
1012 // necessary e.g. after a reload
1013 // to re-register the child (bug 5873)
1014 // FIXME: clean up updateMacros (here, only
1015 // child registering is needed).
1016 master->updateMacros();
1017 // set master as master buffer, but only
1018 // if we are a real child
1019 if (master->isChild(this))
1021 // if the master is not fully loaded
1022 // it is probably just loading this
1023 // child. No warning needed then.
1024 else if (master->isFullyLoaded())
1025 LYXERR0("The master '"
1027 << "' assigned to this document ("
1029 << ") does not include "
1030 "this document. Ignoring the master assignment.");
1035 // assure we have a default index
1036 params().indiceslist().addDefault(B_("Index"));
1039 if (FileName::isAbsolute(params().origin))
1040 d->old_position = params().origin;
1042 d->old_position = filePath();
1043 bool const res = text().read(lex, errorList, d->inset);
1044 d->old_position.clear();
1046 // inform parent buffer about local macros
1048 Buffer const * pbuf = parent();
1049 UserMacroSet::const_iterator cit = usermacros.begin();
1050 UserMacroSet::const_iterator end = usermacros.end();
1051 for (; cit != end; ++cit)
1052 pbuf->usermacros.insert(*cit);
1056 updateMacroInstances(InternalUpdate);
1061 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1063 Format const * fmt = formats.getFormat(format);
1066 // It is important to use the correct extension here, since some
1067 // converters create a wrong output file otherwise (e.g. html2latex)
1068 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1069 FileName const name(tempfile.name());
1070 ofdocstream os(name.toFilesystemEncoding().c_str());
1071 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1072 bool const success = !(os << contents).fail();
1075 bool converted = false;
1077 params().compressed = false;
1079 // remove dummy empty par
1080 paragraphs().clear();
1082 converted = importFile(format, name, errorList);
1091 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1093 if (!theConverters().isReachable(format, "lyx"))
1096 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1097 FileName const lyx(tempfile.name());
1098 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1099 return readFile(lyx) == ReadSuccess;
1105 bool Buffer::readString(string const & s)
1107 params().compressed = false;
1110 istringstream is(s);
1112 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1113 FileName const fn = tempfile.name();
1116 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1118 if (success && file_format != LYX_FORMAT) {
1119 // We need to call lyx2lyx, so write the input to a file
1120 ofstream os(fn.toFilesystemEncoding().c_str());
1123 // lyxvc in readFile
1124 if (readFile(fn) != ReadSuccess)
1128 if (readDocument(lex))
1134 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1138 if (!lex.setFile(fname)) {
1139 Alert::error(_("File Not Found"),
1140 bformat(_("Unable to open file `%1$s'."),
1141 from_utf8(fn.absFileName())));
1142 return ReadFileNotFound;
1146 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1147 if (ret_plf != ReadSuccess)
1150 if (file_format != LYX_FORMAT) {
1152 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1153 if (ret_clf != ReadSuccess)
1155 ret_clf = readFile(tmpFile);
1156 if (ret_clf == ReadSuccess) {
1157 d->file_format = file_format;
1158 d->need_format_backup = true;
1163 // FIXME: InsetInfo needs to know whether the file is under VCS
1164 // during the parse process, so this has to be done before.
1165 lyxvc().file_found_hook(d->filename);
1167 if (readDocument(lex)) {
1168 Alert::error(_("Document format failure"),
1169 bformat(_("%1$s ended unexpectedly, which means"
1170 " that it is probably corrupted."),
1171 from_utf8(fn.absFileName())));
1172 return ReadDocumentFailure;
1175 d->file_fully_loaded = true;
1176 d->read_only = !d->filename.isWritable();
1177 params().compressed = formats.isZippedFile(d->filename);
1183 bool Buffer::isFullyLoaded() const
1185 return d->file_fully_loaded;
1189 void Buffer::setFullyLoaded(bool value)
1191 d->file_fully_loaded = value;
1195 bool Buffer::lastPreviewError() const
1197 return d->preview_error_;
1201 PreviewLoader * Buffer::loader() const
1203 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1205 if (!d->preview_loader_)
1206 d->preview_loader_ = new PreviewLoader(*this);
1207 return d->preview_loader_;
1211 void Buffer::removePreviews() const
1213 delete d->preview_loader_;
1214 d->preview_loader_ = 0;
1218 void Buffer::updatePreviews() const
1220 PreviewLoader * ploader = loader();
1224 InsetIterator it = inset_iterator_begin(*d->inset);
1225 InsetIterator const end = inset_iterator_end(*d->inset);
1226 for (; it != end; ++it)
1227 it->addPreview(it, *ploader);
1229 ploader->startLoading();
1233 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1234 FileName const & fn, int & file_format) const
1236 if(!lex.checkFor("\\lyxformat")) {
1237 Alert::error(_("Document format failure"),
1238 bformat(_("%1$s is not a readable LyX document."),
1239 from_utf8(fn.absFileName())));
1240 return ReadNoLyXFormat;
1246 // LyX formats 217 and earlier were written as 2.17. This corresponds
1247 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1248 // these cases. See also: www.lyx.org/trac/changeset/1313.
1249 size_t dot = tmp_format.find_first_of(".,");
1250 if (dot != string::npos)
1251 tmp_format.erase(dot, 1);
1253 file_format = convert<int>(tmp_format);
1258 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1259 FileName & tmpfile, int from_format)
1261 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1262 tempfile.setAutoRemove(false);
1263 tmpfile = tempfile.name();
1264 if(tmpfile.empty()) {
1265 Alert::error(_("Conversion failed"),
1266 bformat(_("%1$s is from a different"
1267 " version of LyX, but a temporary"
1268 " file for converting it could"
1269 " not be created."),
1270 from_utf8(fn.absFileName())));
1271 return LyX2LyXNoTempFile;
1274 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1275 if (lyx2lyx.empty()) {
1276 Alert::error(_("Conversion script not found"),
1277 bformat(_("%1$s is from a different"
1278 " version of LyX, but the"
1279 " conversion script lyx2lyx"
1280 " could not be found."),
1281 from_utf8(fn.absFileName())));
1282 return LyX2LyXNotFound;
1286 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1287 ostringstream command;
1288 command << os::python()
1289 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1290 << " -t " << convert<string>(LYX_FORMAT)
1291 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1292 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1293 string const command_str = command.str();
1295 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1297 cmd_ret const ret = runCommand(command_str);
1298 if (ret.first != 0) {
1299 if (from_format < LYX_FORMAT) {
1300 Alert::error(_("Conversion script failed"),
1301 bformat(_("%1$s is from an older version"
1302 " of LyX and the lyx2lyx script"
1303 " failed to convert it."),
1304 from_utf8(fn.absFileName())));
1305 return LyX2LyXOlderFormat;
1307 Alert::error(_("Conversion script failed"),
1308 bformat(_("%1$s is from a newer version"
1309 " of LyX and the lyx2lyx script"
1310 " failed to convert it."),
1311 from_utf8(fn.absFileName())));
1312 return LyX2LyXNewerFormat;
1319 FileName Buffer::getBackupName() const {
1320 FileName const & fn = fileName();
1321 string const fname = fn.onlyFileNameWithoutExt();
1322 string const fext = fn.extension() + "~";
1323 string const fpath = lyxrc.backupdir_path.empty() ?
1324 fn.onlyPath().absFileName() :
1325 lyxrc.backupdir_path;
1326 string const fform = convert<string>(d->file_format);
1327 string const backname = fname + "-lyxformat-" + fform;
1328 FileName backup(addName(fpath, addExtension(backname, fext)));
1330 // limit recursion, just in case
1332 unsigned long orig_checksum = 0;
1333 while (backup.exists() && v < 100) {
1334 if (orig_checksum == 0)
1335 orig_checksum = fn.checksum();
1336 unsigned long new_checksum = backup.checksum();
1337 if (orig_checksum == new_checksum) {
1338 LYXERR(Debug::FILES, "Not backing up " << fn <<
1339 "since " << backup << "has the same checksum.");
1340 // a bit of a hack, but we have to check this anyway
1341 // below, and setting this is simpler than introducing
1342 // a special boolean for this purpose.
1346 string const newbackname = backname + "-" + convert<string>(v);
1347 backup.set(addName(fpath, addExtension(newbackname, fext)));
1350 return v < 100 ? backup : FileName();
1354 // Should probably be moved to somewhere else: BufferView? GuiView?
1355 bool Buffer::save() const
1357 docstring const file = makeDisplayPath(absFileName(), 20);
1358 d->filename.refresh();
1360 // check the read-only status before moving the file as a backup
1361 if (d->filename.exists()) {
1362 bool const read_only = !d->filename.isWritable();
1364 Alert::warning(_("File is read-only"),
1365 bformat(_("The file %1$s cannot be written because it "
1366 "is marked as read-only."), file));
1371 // ask if the disk file has been externally modified (use checksum method)
1372 if (fileName().exists() && isExternallyModified(checksum_method)) {
1374 bformat(_("Document %1$s has been externally modified. "
1375 "Are you sure you want to overwrite this file?"), file);
1376 int const ret = Alert::prompt(_("Overwrite modified file?"),
1377 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1382 // We don't need autosaves in the immediate future. (Asger)
1383 resetAutosaveTimers();
1385 // if the file does not yet exist, none of the backup activity
1386 // that follows is necessary
1387 if (!fileName().exists()) {
1388 if (!writeFile(fileName()))
1394 // we first write the file to a new name, then move it to its
1395 // proper location once that has been done successfully. that
1396 // way we preserve the original file if something goes wrong.
1397 string const justname = fileName().onlyFileNameWithoutExt();
1398 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1399 justname + "-XXXXXX.lyx");
1400 bool const symlink = fileName().isSymLink();
1402 tempfile->setAutoRemove(false);
1404 FileName savefile(tempfile->name());
1405 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1406 if (!writeFile(savefile))
1409 // we will set this to false if we fail
1410 bool made_backup = true;
1412 FileName backupName;
1413 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1415 if (d->need_format_backup)
1416 backupName = getBackupName();
1418 // If we for some reason failed to find a backup name in case of
1419 // a format change, this will still set one. It's the best we can
1421 if (backupName.empty()) {
1422 backupName.set(fileName().absFileName() + "~");
1423 if (!lyxrc.backupdir_path.empty()) {
1424 string const mangledName =
1425 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1426 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1430 LYXERR(Debug::FILES, "Backing up original file to " <<
1431 backupName.absFileName());
1432 // Except file is symlink do not copy because of #6587.
1433 // Hard links have bad luck.
1434 made_backup = symlink ?
1435 fileName().copyTo(backupName):
1436 fileName().moveTo(backupName);
1439 Alert::error(_("Backup failure"),
1440 bformat(_("Cannot create backup file %1$s.\n"
1441 "Please check whether the directory exists and is writable."),
1442 from_utf8(backupName.absFileName())));
1443 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1444 } else if (d->need_format_backup) {
1445 // the original file has been backed up successfully, so we
1446 // will not need to do that again
1447 d->need_format_backup = false;
1451 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1452 // Only do this if tempfile is not in autoremove mode
1455 // If we have no symlink, we can simply rename the temp file.
1456 // Otherwise, we need to copy it so the symlink stays intact.
1457 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1458 savefile.moveTo(fileName()))
1460 // saveCheckSum() was already called by writeFile(), but the
1461 // time stamp is invalidated by copying/moving
1464 if (d->file_format != LYX_FORMAT)
1465 // the file associated with this buffer is now in the current format
1466 d->file_format = LYX_FORMAT;
1469 // else we saved the file, but failed to move it to the right location.
1471 if (needBackup && made_backup && !symlink) {
1472 // the original file was moved to some new location, so it will look
1473 // to the user as if it was deleted. (see bug #9234.) we could try
1474 // to restore it, but that would basically mean trying to do again
1475 // what we just failed to do. better to leave things as they are.
1476 Alert::error(_("Write failure"),
1477 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1478 "But LyX could not move it to:\n %2$s.\n"
1479 "Your original file has been backed up to:\n %3$s"),
1480 from_utf8(savefile.absFileName()),
1481 from_utf8(fileName().absFileName()),
1482 from_utf8(backupName.absFileName())));
1484 // either we did not try to make a backup, or else we tried and failed,
1485 // or else the original file was a symlink, in which case it was copied,
1486 // not moved. so the original file is intact.
1487 Alert::error(_("Write failure"),
1488 bformat(_("Cannot move saved file to:\n %1$s.\n"
1489 "But the file has successfully been saved as:\n %2$s."),
1490 from_utf8(fileName().absFileName()),
1491 from_utf8(savefile.absFileName())));
1497 bool Buffer::writeFile(FileName const & fname) const
1499 if (d->read_only && fname == d->filename)
1502 bool retval = false;
1504 docstring const str = bformat(_("Saving document %1$s..."),
1505 makeDisplayPath(fname.absFileName()));
1508 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1510 if (params().compressed) {
1511 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1512 retval = ofs && write(ofs);
1514 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1515 retval = ofs && write(ofs);
1519 message(str + _(" could not write file!"));
1524 // removeAutosaveFile();
1527 message(str + _(" done."));
1533 docstring Buffer::emergencyWrite()
1535 // No need to save if the buffer has not changed.
1539 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1541 docstring user_message = bformat(
1542 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1544 // We try to save three places:
1545 // 1) Same place as document. Unless it is an unnamed doc.
1547 string s = absFileName();
1550 if (writeFile(FileName(s))) {
1552 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1553 return user_message;
1555 user_message += " " + _("Save failed! Trying again...\n");
1559 // 2) In HOME directory.
1560 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1562 lyxerr << ' ' << s << endl;
1563 if (writeFile(FileName(s))) {
1565 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1566 return user_message;
1569 user_message += " " + _("Save failed! Trying yet again...\n");
1571 // 3) In "/tmp" directory.
1572 // MakeAbsPath to prepend the current
1573 // drive letter on OS/2
1574 s = addName(package().temp_dir().absFileName(), absFileName());
1576 lyxerr << ' ' << s << endl;
1577 if (writeFile(FileName(s))) {
1579 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1580 return user_message;
1583 user_message += " " + _("Save failed! Bummer. Document is lost.");
1586 return user_message;
1590 bool Buffer::write(ostream & ofs) const
1593 // Use the standard "C" locale for file output.
1594 ofs.imbue(locale::classic());
1597 // The top of the file should not be written by params().
1599 // write out a comment in the top of the file
1600 // Important: Keep the version formatting in sync with lyx2lyx and
1601 // tex2lyx (bug 7951)
1602 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1603 << " created this file. For more info see http://www.lyx.org/\n"
1604 << "\\lyxformat " << LYX_FORMAT << "\n"
1605 << "\\begin_document\n";
1607 /// For each author, set 'used' to true if there is a change
1608 /// by this author in the document; otherwise set it to 'false'.
1609 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1610 AuthorList::Authors::const_iterator a_end = params().authors().end();
1611 for (; a_it != a_end; ++a_it)
1612 a_it->setUsed(false);
1614 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1615 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1616 for ( ; it != end; ++it)
1617 it->checkAuthors(params().authors());
1619 // now write out the buffer parameters.
1620 ofs << "\\begin_header\n";
1621 params().writeFile(ofs, this);
1622 ofs << "\\end_header\n";
1625 ofs << "\n\\begin_body\n";
1627 ofs << "\n\\end_body\n";
1629 // Write marker that shows file is complete
1630 ofs << "\\end_document" << endl;
1632 // Shouldn't really be needed....
1635 // how to check if close went ok?
1636 // Following is an attempt... (BE 20001011)
1638 // good() returns false if any error occurred, including some
1639 // formatting error.
1640 // bad() returns true if something bad happened in the buffer,
1641 // which should include file system full errors.
1646 lyxerr << "File was not closed properly." << endl;
1653 bool Buffer::makeLaTeXFile(FileName const & fname,
1654 string const & original_path,
1655 OutputParams const & runparams_in,
1656 OutputWhat output) const
1658 OutputParams runparams = runparams_in;
1660 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1661 // Check here, because the "flavor" is not known in BufferParams::encoding()
1662 // (power users can override this safety measure selecting "utf8-plain").
1663 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1664 && (runparams.encoding->name() != "utf8-plain"))
1665 runparams.encoding = encodings.fromLyXName("ascii");
1667 string const encoding = runparams.encoding->iconvName();
1668 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1671 try { ofs.reset(encoding); }
1672 catch (iconv_codecvt_facet_exception const & e) {
1673 lyxerr << "Caught iconv exception: " << e.what() << endl;
1674 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1675 "verify that the support software for your encoding (%1$s) is "
1676 "properly installed"), from_ascii(encoding)));
1679 if (!openFileWrite(ofs, fname))
1682 ErrorList & errorList = d->errorLists["Export"];
1684 bool failed_export = false;
1687 // make sure we are ready to export
1688 // this needs to be done before we validate
1689 // FIXME Do we need to do this all the time? I.e., in children
1690 // of a master we are exporting?
1692 updateMacroInstances(OutputUpdate);
1695 writeLaTeXSource(os, original_path, runparams, output);
1697 catch (EncodingException const & e) {
1698 docstring const failed(1, e.failed_char);
1700 oss << "0x" << hex << e.failed_char << dec;
1701 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1702 " (code point %2$s)"),
1703 failed, from_utf8(oss.str()));
1704 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1705 "representable in the chosen encoding.\n"
1706 "Changing the document encoding to utf8 could help."),
1707 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1708 failed_export = true;
1710 catch (iconv_codecvt_facet_exception const & e) {
1711 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1713 failed_export = true;
1715 catch (exception const & e) {
1716 errorList.push_back(ErrorItem(_("conversion failed"),
1718 failed_export = true;
1721 lyxerr << "Caught some really weird exception..." << endl;
1725 d->texrow = move(os.texrow());
1729 failed_export = true;
1730 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1733 if (runparams_in.silent)
1737 return !failed_export;
1741 void Buffer::writeLaTeXSource(otexstream & os,
1742 string const & original_path,
1743 OutputParams const & runparams_in,
1744 OutputWhat output) const
1746 // The child documents, if any, shall be already loaded at this point.
1748 OutputParams runparams = runparams_in;
1750 // XeTeX with TeX fonts is only safe with ASCII encoding,
1751 // Check here, because the "flavor" is not known in BufferParams::encoding()
1752 // (power users can override this safety measure selecting "utf8-plain").
1753 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1754 && (runparams.encoding->name() != "utf8-plain"))
1755 runparams.encoding = encodings.fromLyXName("ascii");
1756 // FIXME: when only the current paragraph is shown, this is ignored
1757 // (or not reached) and characters encodable in the current
1758 // encoding are not converted to ASCII-representation.
1760 // If we are compiling a file standalone, even if this is the
1761 // child of some other buffer, let's cut the link here, so the
1762 // file is really independent and no concurring settings from
1763 // the master (e.g. branch state) interfere (see #8100).
1764 if (!runparams.is_child)
1765 d->ignore_parent = true;
1767 // Classify the unicode characters appearing in math insets
1768 BufferEncodings::initUnicodeMath(*this);
1770 // validate the buffer.
1771 LYXERR(Debug::LATEX, " Validating buffer...");
1772 LaTeXFeatures features(*this, params(), runparams);
1774 // This is only set once per document (in master)
1775 if (!runparams.is_child)
1776 runparams.use_polyglossia = features.usePolyglossia();
1777 LYXERR(Debug::LATEX, " Buffer validation done.");
1779 bool const output_preamble =
1780 output == FullSource || output == OnlyPreamble;
1781 bool const output_body =
1782 output == FullSource || output == OnlyBody;
1784 // The starting paragraph of the coming rows is the
1785 // first paragraph of the document. (Asger)
1786 if (output_preamble && runparams.nice) {
1787 os << "%% LyX " << lyx_version << " created this file. "
1788 "For more info, see http://www.lyx.org/.\n"
1789 "%% Do not edit unless you really know what "
1792 LYXERR(Debug::INFO, "lyx document header finished");
1794 // There are a few differences between nice LaTeX and usual files:
1795 // usual files have \batchmode and special input@path to allow
1796 // inclusion of figures specified by an explicitly relative path
1797 // (i.e., a path starting with './' or '../') with either \input or
1798 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1799 // input@path is set when the actual parameter original_path is set.
1800 // This is done for usual tex-file, but not for nice-latex-file.
1801 // (Matthias 250696)
1802 // Note that input@path is only needed for something the user does
1803 // in the preamble, included .tex files or ERT, files included by
1804 // LyX work without it.
1805 if (output_preamble) {
1806 if (!runparams.nice) {
1807 // code for usual, NOT nice-latex-file
1808 os << "\\batchmode\n"; // changed from \nonstopmode
1810 if (!original_path.empty()) {
1812 // We don't know the encoding of inputpath
1813 docstring const inputpath = from_utf8(original_path);
1814 docstring uncodable_glyphs;
1815 Encoding const * const enc = runparams.encoding;
1817 for (size_t n = 0; n < inputpath.size(); ++n) {
1818 if (!enc->encodable(inputpath[n])) {
1819 docstring const glyph(1, inputpath[n]);
1820 LYXERR0("Uncodable character '"
1822 << "' in input path!");
1823 uncodable_glyphs += glyph;
1828 // warn user if we found uncodable glyphs.
1829 if (!uncodable_glyphs.empty()) {
1830 frontend::Alert::warning(
1831 _("Uncodable character in file path"),
1833 _("The path of your document\n"
1835 "contains glyphs that are unknown "
1836 "in the current document encoding "
1837 "(namely %2$s). This may result in "
1838 "incomplete output, unless "
1839 "TEXINPUTS contains the document "
1840 "directory and you don't use "
1841 "explicitly relative paths (i.e., "
1842 "paths starting with './' or "
1843 "'../') in the preamble or in ERT."
1844 "\n\nIn case of problems, choose "
1845 "an appropriate document encoding\n"
1846 "(such as utf8) or change the "
1848 inputpath, uncodable_glyphs));
1851 support::latex_path(original_path);
1852 if (contains(docdir, '#')) {
1853 docdir = subst(docdir, "#", "\\#");
1854 os << "\\catcode`\\#=11"
1855 "\\def\\#{#}\\catcode`\\#=6\n";
1857 if (contains(docdir, '%')) {
1858 docdir = subst(docdir, "%", "\\%");
1859 os << "\\catcode`\\%=11"
1860 "\\def\\%{%}\\catcode`\\%=14\n";
1862 os << "\\makeatletter\n"
1863 << "\\def\\input@path{{"
1865 << "\\makeatother\n";
1869 // get parent macros (if this buffer has a parent) which will be
1870 // written at the document begin further down.
1871 MacroSet parentMacros;
1872 listParentMacros(parentMacros, features);
1874 // Write the preamble
1875 runparams.use_babel = params().writeLaTeX(os, features,
1876 d->filename.onlyPath());
1878 // Japanese might be required only in some children of a document,
1879 // but once required, we must keep use_japanese true.
1880 runparams.use_japanese |= features.isRequired("japanese");
1883 // Restore the parenthood if needed
1884 if (!runparams.is_child)
1885 d->ignore_parent = false;
1890 // mark the beginning of the body to separate it from InPreamble insets
1891 os.texrow().start(TexRow::beginDocument());
1892 os << "\\begin{document}\n";
1894 // mark the start of a new paragraph by simulating a newline,
1895 // so that os.afterParbreak() returns true at document start
1898 // output the parent macros
1899 MacroSet::iterator it = parentMacros.begin();
1900 MacroSet::iterator end = parentMacros.end();
1901 for (; it != end; ++it) {
1902 int num_lines = (*it)->write(os.os(), true);
1903 os.texrow().newlines(num_lines);
1906 } // output_preamble
1908 LYXERR(Debug::INFO, "preamble finished, now the body.");
1911 latexParagraphs(*this, text(), os, runparams);
1913 // Restore the parenthood if needed
1914 if (!runparams.is_child)
1915 d->ignore_parent = false;
1917 // add this just in case after all the paragraphs
1920 if (output_preamble) {
1921 os << "\\end{document}\n";
1922 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1924 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1926 runparams_in.encoding = runparams.encoding;
1928 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1929 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1933 void Buffer::makeDocBookFile(FileName const & fname,
1934 OutputParams const & runparams,
1935 OutputWhat output) const
1937 LYXERR(Debug::LATEX, "makeDocBookFile...");
1940 if (!openFileWrite(ofs, fname))
1943 // make sure we are ready to export
1944 // this needs to be done before we validate
1946 updateMacroInstances(OutputUpdate);
1948 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1952 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1956 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1957 OutputParams const & runparams,
1958 OutputWhat output) const
1960 LaTeXFeatures features(*this, params(), runparams);
1965 DocumentClass const & tclass = params().documentClass();
1966 string const & top_element = tclass.latexname();
1968 bool const output_preamble =
1969 output == FullSource || output == OnlyPreamble;
1970 bool const output_body =
1971 output == FullSource || output == OnlyBody;
1973 if (output_preamble) {
1974 if (runparams.flavor == OutputParams::XML)
1975 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1978 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1981 if (! tclass.class_header().empty())
1982 os << from_ascii(tclass.class_header());
1983 else if (runparams.flavor == OutputParams::XML)
1984 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1985 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1987 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1989 docstring preamble = params().preamble;
1990 if (runparams.flavor != OutputParams::XML ) {
1991 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1992 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1993 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1994 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1997 string const name = runparams.nice
1998 ? changeExtension(absFileName(), ".sgml") : fname;
1999 preamble += features.getIncludedFiles(name);
2000 preamble += features.getLyXSGMLEntities();
2002 if (!preamble.empty()) {
2003 os << "\n [ " << preamble << " ]";
2009 string top = top_element;
2011 if (runparams.flavor == OutputParams::XML)
2012 top += params().language->code();
2014 top += params().language->code().substr(0, 2);
2017 if (!params().options.empty()) {
2019 top += params().options;
2022 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2023 << " file was created by LyX " << lyx_version
2024 << "\n See http://www.lyx.org/ for more information -->\n";
2026 params().documentClass().counters().reset();
2028 sgml::openTag(os, top);
2030 docbookParagraphs(text(), *this, os, runparams);
2031 sgml::closeTag(os, top_element);
2036 void Buffer::makeLyXHTMLFile(FileName const & fname,
2037 OutputParams const & runparams) const
2039 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2042 if (!openFileWrite(ofs, fname))
2045 // make sure we are ready to export
2046 // this has to be done before we validate
2047 updateBuffer(UpdateMaster, OutputUpdate);
2048 updateMacroInstances(OutputUpdate);
2050 writeLyXHTMLSource(ofs, runparams, FullSource);
2054 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2058 void Buffer::writeLyXHTMLSource(odocstream & os,
2059 OutputParams const & runparams,
2060 OutputWhat output) const
2062 LaTeXFeatures features(*this, params(), runparams);
2064 d->bibinfo_.makeCitationLabels(*this);
2066 bool const output_preamble =
2067 output == FullSource || output == OnlyPreamble;
2068 bool const output_body =
2069 output == FullSource || output == OnlyBody || output == IncludedFile;
2071 if (output_preamble) {
2072 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2073 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
2074 // FIXME Language should be set properly.
2075 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2077 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2078 // FIXME Presumably need to set this right
2079 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2081 docstring const & doctitle = features.htmlTitle();
2083 << (doctitle.empty() ?
2084 from_ascii("LyX Document") :
2085 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2088 docstring styles = features.getTClassHTMLPreamble();
2089 if (!styles.empty())
2090 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2092 styles = features.getPreambleSnippets().str;
2093 if (!styles.empty())
2094 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2096 // we will collect CSS information in a stream, and then output it
2097 // either here, as part of the header, or else in a separate file.
2098 odocstringstream css;
2099 styles = features.getCSSSnippets();
2100 if (!styles.empty())
2101 css << "/* LyX Provided Styles */\n" << styles << '\n';
2103 styles = features.getTClassHTMLStyles();
2104 if (!styles.empty())
2105 css << "/* Layout-provided Styles */\n" << styles << '\n';
2107 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2108 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2109 if (needfg || needbg) {
2110 css << "\nbody {\n";
2113 << from_ascii(X11hexname(params().fontcolor))
2116 css << " background-color: "
2117 << from_ascii(X11hexname(params().backgroundcolor))
2122 docstring const dstyles = css.str();
2123 if (!dstyles.empty()) {
2124 bool written = false;
2125 if (params().html_css_as_file) {
2126 // open a file for CSS info
2128 string const fcssname = addName(temppath(), "docstyle.css");
2129 FileName const fcssfile = FileName(fcssname);
2130 if (openFileWrite(ocss, fcssfile)) {
2134 // write link to header
2135 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2137 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2140 // we are here if the CSS is supposed to be written to the header
2141 // or if we failed to write it to an external file.
2143 os << "<style type='text/css'>\n"
2152 bool const output_body_tag = (output != IncludedFile);
2153 if (output_body_tag)
2154 os << "<body dir=\"auto\">\n";
2156 if (output != IncludedFile)
2157 // if we're an included file, the counters are in the master.
2158 params().documentClass().counters().reset();
2159 xhtmlParagraphs(text(), *this, xs, runparams);
2160 if (output_body_tag)
2164 if (output_preamble)
2169 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2170 // Other flags: -wall -v0 -x
2171 int Buffer::runChktex()
2175 // get LaTeX-Filename
2176 FileName const path(temppath());
2177 string const name = addName(path.absFileName(), latexName());
2178 string const org_path = filePath();
2180 PathChanger p(path); // path to LaTeX file
2181 message(_("Running chktex..."));
2183 // Generate the LaTeX file if neccessary
2184 OutputParams runparams(¶ms().encoding());
2185 runparams.flavor = OutputParams::LATEX;
2186 runparams.nice = false;
2187 runparams.linelen = lyxrc.plaintext_linelen;
2188 makeLaTeXFile(FileName(name), org_path, runparams);
2191 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2192 int const res = chktex.run(terr); // run chktex
2195 Alert::error(_("chktex failure"),
2196 _("Could not run chktex successfully."));
2198 ErrorList & errlist = d->errorLists["ChkTeX"];
2200 bufferErrors(terr, errlist);
2205 if (runparams.silent)
2206 d->errorLists["ChkTeX"].clear();
2214 void Buffer::validate(LaTeXFeatures & features) const
2216 // Validate the buffer params, but not for included
2217 // files, since they also use the parent buffer's
2219 if (!features.runparams().is_child)
2220 params().validate(features);
2222 for (Paragraph const & p : paragraphs())
2223 p.validate(features);
2225 if (lyxerr.debugging(Debug::LATEX)) {
2226 features.showStruct();
2231 void Buffer::getLabelList(vector<docstring> & list) const
2233 // If this is a child document, use the master's list instead.
2235 masterBuffer()->getLabelList(list);
2240 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2241 Toc::const_iterator toc_it = toc->begin();
2242 Toc::const_iterator end = toc->end();
2243 for (; toc_it != end; ++toc_it) {
2244 if (toc_it->depth() == 0)
2245 list.push_back(toc_it->str());
2250 void Buffer::updateBibfilesCache(UpdateScope scope) const
2252 // FIXME This is probably unnecssary, given where we call this.
2253 // If this is a child document, use the parent's cache instead.
2254 if (parent() && scope != UpdateChildOnly) {
2255 masterBuffer()->updateBibfilesCache();
2259 d->bibfiles_cache_.clear();
2260 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2261 if (it->lyxCode() == BIBTEX_CODE) {
2262 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2263 support::FileNameList const bibfiles = inset.getBibFiles();
2264 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2267 } else if (it->lyxCode() == INCLUDE_CODE) {
2268 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2269 Buffer const * const incbuf = inset.getChildBuffer();
2272 support::FileNameList const & bibfiles =
2273 incbuf->getBibfilesCache(UpdateChildOnly);
2274 if (!bibfiles.empty()) {
2275 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2281 d->bibfile_cache_valid_ = true;
2282 d->bibinfo_cache_valid_ = false;
2283 d->cite_labels_valid_ = false;
2287 void Buffer::invalidateBibinfoCache() const
2289 d->bibinfo_cache_valid_ = false;
2290 d->cite_labels_valid_ = false;
2291 // also invalidate the cache for the parent buffer
2292 Buffer const * const pbuf = d->parent();
2294 pbuf->invalidateBibinfoCache();
2298 void Buffer::invalidateBibfileCache() const
2300 d->bibfile_cache_valid_ = false;
2301 d->bibinfo_cache_valid_ = false;
2302 d->cite_labels_valid_ = false;
2303 // also invalidate the cache for the parent buffer
2304 Buffer const * const pbuf = d->parent();
2306 pbuf->invalidateBibfileCache();
2310 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2312 // FIXME This is probably unnecessary, given where we call this.
2313 // If this is a child document, use the master's cache instead.
2314 Buffer const * const pbuf = masterBuffer();
2315 if (pbuf != this && scope != UpdateChildOnly)
2316 return pbuf->getBibfilesCache();
2318 if (!d->bibfile_cache_valid_)
2319 this->updateBibfilesCache(scope);
2321 return d->bibfiles_cache_;
2325 BiblioInfo const & Buffer::masterBibInfo() const
2327 Buffer const * const tmp = masterBuffer();
2329 return tmp->masterBibInfo();
2334 void Buffer::checkIfBibInfoCacheIsValid() const
2336 // use the master's cache
2337 Buffer const * const tmp = masterBuffer();
2339 tmp->checkIfBibInfoCacheIsValid();
2343 // compare the cached timestamps with the actual ones.
2344 FileNameList const & bibfiles_cache = getBibfilesCache();
2345 FileNameList::const_iterator ei = bibfiles_cache.begin();
2346 FileNameList::const_iterator en = bibfiles_cache.end();
2347 for (; ei != en; ++ ei) {
2348 time_t lastw = ei->lastModified();
2349 time_t prevw = d->bibfile_status_[*ei];
2350 if (lastw != prevw) {
2351 d->bibinfo_cache_valid_ = false;
2352 d->cite_labels_valid_ = false;
2353 d->bibfile_status_[*ei] = lastw;
2359 void Buffer::reloadBibInfoCache() const
2361 // use the master's cache
2362 Buffer const * const tmp = masterBuffer();
2364 tmp->reloadBibInfoCache();
2368 checkIfBibInfoCacheIsValid();
2369 if (d->bibinfo_cache_valid_)
2372 d->bibinfo_.clear();
2374 d->bibinfo_cache_valid_ = true;
2378 void Buffer::collectBibKeys() const
2380 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2381 it->collectBibKeys(it);
2385 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2387 Buffer const * tmp = masterBuffer();
2388 BiblioInfo & masterbi = (tmp == this) ?
2389 d->bibinfo_ : tmp->d->bibinfo_;
2390 masterbi.mergeBiblioInfo(bi);
2394 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2396 Buffer const * tmp = masterBuffer();
2397 BiblioInfo & masterbi = (tmp == this) ?
2398 d->bibinfo_ : tmp->d->bibinfo_;
2403 void Buffer::makeCitationLabels() const
2405 Buffer const * const master = masterBuffer();
2406 return d->bibinfo_.makeCitationLabels(*master);
2410 bool Buffer::citeLabelsValid() const
2412 return masterBuffer()->d->cite_labels_valid_;
2416 void Buffer::removeBiblioTempFiles() const
2418 // We remove files that contain LaTeX commands specific to the
2419 // particular bibliographic style being used, in order to avoid
2420 // LaTeX errors when we switch style.
2421 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2422 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2423 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2424 aux_file.removeFile();
2425 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2426 bbl_file.removeFile();
2427 // Also for the parent buffer
2428 Buffer const * const pbuf = parent();
2430 pbuf->removeBiblioTempFiles();
2434 bool Buffer::isDepClean(string const & name) const
2436 DepClean::const_iterator const it = d->dep_clean.find(name);
2437 if (it == d->dep_clean.end())
2443 void Buffer::markDepClean(string const & name)
2445 d->dep_clean[name] = true;
2449 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2452 // FIXME? if there is an Buffer LFUN that can be dispatched even
2453 // if internal, put a switch '(cmd.action)' here.
2459 switch (cmd.action()) {
2461 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2462 flag.setOnOff(isReadonly());
2465 // FIXME: There is need for a command-line import.
2466 //case LFUN_BUFFER_IMPORT:
2468 case LFUN_BUFFER_AUTO_SAVE:
2471 case LFUN_BUFFER_EXPORT_CUSTOM:
2472 // FIXME: Nothing to check here?
2475 case LFUN_BUFFER_EXPORT: {
2476 docstring const arg = cmd.argument();
2477 if (arg == "custom") {
2481 string format = to_utf8(arg);
2482 size_t pos = format.find(' ');
2483 if (pos != string::npos)
2484 format = format.substr(0, pos);
2485 enable = params().isExportable(format, false);
2487 flag.message(bformat(
2488 _("Don't know how to export to format: %1$s"), arg));
2492 case LFUN_BUFFER_CHKTEX:
2493 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2496 case LFUN_BUILD_PROGRAM:
2497 enable = params().isExportable("program", false);
2500 case LFUN_BRANCH_ACTIVATE:
2501 case LFUN_BRANCH_DEACTIVATE:
2502 case LFUN_BRANCH_MASTER_ACTIVATE:
2503 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2504 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2505 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2506 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2507 : params().branchlist();
2508 docstring const branchName = cmd.argument();
2509 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2513 case LFUN_BRANCH_ADD:
2514 case LFUN_BRANCHES_RENAME:
2515 // if no Buffer is present, then of course we won't be called!
2518 case LFUN_BUFFER_LANGUAGE:
2519 enable = !isReadonly();
2522 case LFUN_BUFFER_VIEW_CACHE:
2523 (d->preview_file_).refresh();
2524 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2527 case LFUN_CHANGES_TRACK:
2528 flag.setEnabled(true);
2529 flag.setOnOff(params().track_changes);
2532 case LFUN_CHANGES_OUTPUT:
2533 flag.setEnabled(true);
2534 flag.setOnOff(params().output_changes);
2537 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2538 flag.setOnOff(params().compressed);
2542 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2543 flag.setOnOff(params().output_sync);
2550 flag.setEnabled(enable);
2555 void Buffer::dispatch(string const & command, DispatchResult & result)
2557 return dispatch(lyxaction.lookupFunc(command), result);
2561 // NOTE We can end up here even if we have no GUI, because we are called
2562 // by LyX::exec to handled command-line requests. So we may need to check
2563 // whether we have a GUI or not. The boolean use_gui holds this information.
2564 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2567 // FIXME? if there is an Buffer LFUN that can be dispatched even
2568 // if internal, put a switch '(cmd.action())' here.
2569 dr.dispatched(false);
2572 string const argument = to_utf8(func.argument());
2573 // We'll set this back to false if need be.
2574 bool dispatched = true;
2575 undo().beginUndoGroup();
2577 switch (func.action()) {
2578 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2579 if (lyxvc().inUse()) {
2580 string log = lyxvc().toggleReadOnly();
2585 setReadonly(!isReadonly());
2588 case LFUN_BUFFER_EXPORT: {
2589 ExportStatus const status = doExport(argument, false);
2590 dr.setError(status != ExportSuccess);
2591 if (status != ExportSuccess)
2592 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2597 case LFUN_BUILD_PROGRAM: {
2598 ExportStatus const status = doExport("program", true);
2599 dr.setError(status != ExportSuccess);
2600 if (status != ExportSuccess)
2601 dr.setMessage(_("Error generating literate programming code."));
2605 case LFUN_BUFFER_CHKTEX:
2609 case LFUN_BUFFER_EXPORT_CUSTOM: {
2611 string command = split(argument, format_name, ' ');
2612 Format const * format = formats.getFormat(format_name);
2614 lyxerr << "Format \"" << format_name
2615 << "\" not recognized!"
2620 // The name of the file created by the conversion process
2623 // Output to filename
2624 if (format->name() == "lyx") {
2625 string const latexname = latexName(false);
2626 filename = changeExtension(latexname,
2627 format->extension());
2628 filename = addName(temppath(), filename);
2630 if (!writeFile(FileName(filename)))
2634 doExport(format_name, true, filename);
2637 // Substitute $$FName for filename
2638 if (!contains(command, "$$FName"))
2639 command = "( " + command + " ) < $$FName";
2640 command = subst(command, "$$FName", filename);
2642 // Execute the command in the background
2644 call.startscript(Systemcall::DontWait, command,
2645 filePath(), layoutPos());
2649 // FIXME: There is need for a command-line import.
2651 case LFUN_BUFFER_IMPORT:
2656 case LFUN_BUFFER_AUTO_SAVE:
2658 resetAutosaveTimers();
2661 case LFUN_BRANCH_ACTIVATE:
2662 case LFUN_BRANCH_DEACTIVATE:
2663 case LFUN_BRANCH_MASTER_ACTIVATE:
2664 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2665 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2666 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2667 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2670 docstring const branch_name = func.argument();
2671 // the case without a branch name is handled elsewhere
2672 if (branch_name.empty()) {
2676 Branch * branch = buf->params().branchlist().find(branch_name);
2678 LYXERR0("Branch " << branch_name << " does not exist.");
2680 docstring const msg =
2681 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2685 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2686 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2687 if (branch->isSelected() != activate) {
2688 buf->undo().recordUndoBufferParams(CursorData());
2689 branch->setSelected(activate);
2691 dr.screenUpdate(Update::Force);
2692 dr.forceBufferUpdate();
2697 case LFUN_BRANCH_ADD: {
2698 docstring branch_name = func.argument();
2699 if (branch_name.empty()) {
2703 BranchList & branch_list = params().branchlist();
2704 vector<docstring> const branches =
2705 getVectorFromString(branch_name, branch_list.separator());
2707 for (vector<docstring>::const_iterator it = branches.begin();
2708 it != branches.end(); ++it) {
2710 Branch * branch = branch_list.find(branch_name);
2712 LYXERR0("Branch " << branch_name << " already exists.");
2716 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2718 undo().recordUndoBufferParams(CursorData());
2719 branch_list.add(branch_name);
2720 branch = branch_list.find(branch_name);
2721 string const x11hexname = X11hexname(branch->color());
2722 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2723 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2725 dr.screenUpdate(Update::Force);
2733 case LFUN_BRANCHES_RENAME: {
2734 if (func.argument().empty())
2737 docstring const oldname = from_utf8(func.getArg(0));
2738 docstring const newname = from_utf8(func.getArg(1));
2739 InsetIterator it = inset_iterator_begin(inset());
2740 InsetIterator const end = inset_iterator_end(inset());
2741 bool success = false;
2742 for (; it != end; ++it) {
2743 if (it->lyxCode() == BRANCH_CODE) {
2744 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2745 if (ins.branch() == oldname) {
2746 undo().recordUndo(CursorData(it));
2747 ins.rename(newname);
2752 if (it->lyxCode() == INCLUDE_CODE) {
2753 // get buffer of external file
2754 InsetInclude const & ins =
2755 static_cast<InsetInclude const &>(*it);
2756 Buffer * child = ins.getChildBuffer();
2759 child->dispatch(func, dr);
2764 dr.screenUpdate(Update::Force);
2765 dr.forceBufferUpdate();
2770 case LFUN_BUFFER_VIEW_CACHE:
2771 if (!formats.view(*this, d->preview_file_,
2772 d->preview_format_))
2773 dr.setMessage(_("Error viewing the output file."));
2776 case LFUN_CHANGES_TRACK:
2777 if (params().save_transient_properties)
2778 undo().recordUndoBufferParams(CursorData());
2779 params().track_changes = !params().track_changes;
2780 if (!params().track_changes)
2781 dr.forceChangesUpdate();
2784 case LFUN_CHANGES_OUTPUT:
2785 if (params().save_transient_properties)
2786 undo().recordUndoBufferParams(CursorData());
2787 params().output_changes = !params().output_changes;
2788 if (params().output_changes) {
2789 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2790 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2791 LaTeXFeatures::isAvailable("xcolor");
2793 if (!dvipost && !xcolorulem) {
2794 Alert::warning(_("Changes not shown in LaTeX output"),
2795 _("Changes will not be highlighted in LaTeX output, "
2796 "because neither dvipost nor xcolor/ulem are installed.\n"
2797 "Please install these packages or redefine "
2798 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2799 } else if (!xcolorulem) {
2800 Alert::warning(_("Changes not shown in LaTeX output"),
2801 _("Changes will not be highlighted in LaTeX output "
2802 "when using pdflatex, because xcolor and ulem are not installed.\n"
2803 "Please install both packages or redefine "
2804 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2809 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2810 // turn compression on/off
2811 undo().recordUndoBufferParams(CursorData());
2812 params().compressed = !params().compressed;
2815 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2816 undo().recordUndoBufferParams(CursorData());
2817 params().output_sync = !params().output_sync;
2824 dr.dispatched(dispatched);
2825 undo().endUndoGroup();
2829 void Buffer::changeLanguage(Language const * from, Language const * to)
2831 LASSERT(from, return);
2832 LASSERT(to, return);
2834 for_each(par_iterator_begin(),
2836 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2840 bool Buffer::isMultiLingual() const
2842 ParConstIterator end = par_iterator_end();
2843 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2844 if (it->isMultiLingual(params()))
2851 std::set<Language const *> Buffer::getLanguages() const
2853 std::set<Language const *> languages;
2854 getLanguages(languages);
2859 void Buffer::getLanguages(std::set<Language const *> & languages) const
2861 ParConstIterator end = par_iterator_end();
2862 // add the buffer language, even if it's not actively used
2863 languages.insert(language());
2864 // iterate over the paragraphs
2865 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2866 it->getLanguages(languages);
2868 ListOfBuffers clist = getDescendents();
2869 ListOfBuffers::const_iterator cit = clist.begin();
2870 ListOfBuffers::const_iterator const cen = clist.end();
2871 for (; cit != cen; ++cit)
2872 (*cit)->getLanguages(languages);
2876 DocIterator Buffer::getParFromID(int const id) const
2878 Buffer * buf = const_cast<Buffer *>(this);
2880 // This means non-existent
2881 return doc_iterator_end(buf);
2883 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2884 if (it.paragraph().id() == id)
2887 return doc_iterator_end(buf);
2891 bool Buffer::hasParWithID(int const id) const
2893 return !getParFromID(id).atEnd();
2897 ParIterator Buffer::par_iterator_begin()
2899 return ParIterator(doc_iterator_begin(this));
2903 ParIterator Buffer::par_iterator_end()
2905 return ParIterator(doc_iterator_end(this));
2909 ParConstIterator Buffer::par_iterator_begin() const
2911 return ParConstIterator(doc_iterator_begin(this));
2915 ParConstIterator Buffer::par_iterator_end() const
2917 return ParConstIterator(doc_iterator_end(this));
2921 Language const * Buffer::language() const
2923 return params().language;
2927 docstring const Buffer::B_(string const & l10n) const
2929 return params().B_(l10n);
2933 bool Buffer::isClean() const
2935 return d->lyx_clean;
2939 bool Buffer::isExternallyModified(CheckMethod method) const
2941 LASSERT(d->filename.exists(), return false);
2942 // if method == timestamp, check timestamp before checksum
2943 return (method == checksum_method
2944 || d->timestamp_ != d->filename.lastModified())
2945 && d->checksum_ != d->filename.checksum();
2949 void Buffer::saveCheckSum() const
2951 FileName const & file = d->filename;
2954 if (file.exists()) {
2955 d->timestamp_ = file.lastModified();
2956 d->checksum_ = file.checksum();
2958 // in the case of save to a new file.
2965 void Buffer::markClean() const
2967 if (!d->lyx_clean) {
2968 d->lyx_clean = true;
2971 // if the .lyx file has been saved, we don't need an
2973 d->bak_clean = true;
2974 d->undo_.markDirty();
2978 void Buffer::setUnnamed(bool flag)
2984 bool Buffer::isUnnamed() const
2991 /// Don't check unnamed, here: isInternal() is used in
2992 /// newBuffer(), where the unnamed flag has not been set by anyone
2993 /// yet. Also, for an internal buffer, there should be no need for
2994 /// retrieving fileName() nor for checking if it is unnamed or not.
2995 bool Buffer::isInternal() const
2997 return d->internal_buffer;
3001 void Buffer::setInternal(bool flag)
3003 d->internal_buffer = flag;
3007 void Buffer::markDirty()
3010 d->lyx_clean = false;
3013 d->bak_clean = false;
3015 DepClean::iterator it = d->dep_clean.begin();
3016 DepClean::const_iterator const end = d->dep_clean.end();
3018 for (; it != end; ++it)
3023 FileName Buffer::fileName() const
3029 string Buffer::absFileName() const
3031 return d->filename.absFileName();
3035 string Buffer::filePath() const
3037 string const abs = d->filename.onlyPath().absFileName();
3040 int last = abs.length() - 1;
3042 return abs[last] == '/' ? abs : abs + '/';
3046 DocFileName Buffer::getReferencedFileName(string const & fn) const
3049 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3050 result.set(fn, filePath());
3052 // filePath() ends with a path separator
3053 FileName const test(filePath() + fn);
3055 result.set(fn, filePath());
3057 result.set(fn, params().origin);
3064 string Buffer::layoutPos() const
3066 return d->layout_position;
3070 void Buffer::setLayoutPos(string const & path)
3073 d->layout_position.clear();
3077 LATTEST(FileName::isAbsolute(path));
3079 d->layout_position =
3080 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3082 if (d->layout_position.empty())
3083 d->layout_position = ".";
3087 bool Buffer::isReadonly() const
3089 return d->read_only;
3093 void Buffer::setParent(Buffer const * buffer)
3095 // Avoids recursive include.
3096 d->setParent(buffer == this ? 0 : buffer);
3101 Buffer const * Buffer::parent() const
3107 ListOfBuffers Buffer::allRelatives() const
3109 ListOfBuffers lb = masterBuffer()->getDescendents();
3110 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3115 Buffer const * Buffer::masterBuffer() const
3117 // FIXME Should be make sure we are not in some kind
3118 // of recursive include? A -> B -> A will crash this.
3119 Buffer const * const pbuf = d->parent();
3123 return pbuf->masterBuffer();
3127 bool Buffer::isChild(Buffer * child) const
3129 return d->children_positions.find(child) != d->children_positions.end();
3133 DocIterator Buffer::firstChildPosition(Buffer const * child)
3135 Impl::BufferPositionMap::iterator it;
3136 it = d->children_positions.find(child);
3137 if (it == d->children_positions.end())
3138 return DocIterator(this);
3143 bool Buffer::hasChildren() const
3145 return !d->children_positions.empty();
3149 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3151 // loop over children
3152 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3153 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3154 for (; it != end; ++it) {
3155 Buffer * child = const_cast<Buffer *>(it->first);
3157 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3158 if (bit != clist.end())
3160 clist.push_back(child);
3162 // there might be grandchildren
3163 child->collectChildren(clist, true);
3168 ListOfBuffers Buffer::getChildren() const
3171 collectChildren(v, false);
3172 // Make sure we have not included ourselves.
3173 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3174 if (bit != v.end()) {
3175 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3182 ListOfBuffers Buffer::getDescendents() const
3185 collectChildren(v, true);
3186 // Make sure we have not included ourselves.
3187 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3188 if (bit != v.end()) {
3189 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3196 template<typename M>
3197 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3202 typename M::const_iterator it = m.lower_bound(x);
3203 if (it == m.begin())
3211 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3212 DocIterator const & pos) const
3214 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3216 // if paragraphs have no macro context set, pos will be empty
3220 // we haven't found anything yet
3221 DocIterator bestPos = owner_->par_iterator_begin();
3222 MacroData const * bestData = 0;
3224 // find macro definitions for name
3225 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3226 if (nameIt != macros.end()) {
3227 // find last definition in front of pos or at pos itself
3228 PositionScopeMacroMap::const_iterator it
3229 = greatest_below(nameIt->second, pos);
3230 if (it != nameIt->second.end()) {
3232 // scope ends behind pos?
3233 if (pos < it->second.scope) {
3234 // Looks good, remember this. If there
3235 // is no external macro behind this,
3236 // we found the right one already.
3237 bestPos = it->first;
3238 bestData = &it->second.macro;
3242 // try previous macro if there is one
3243 if (it == nameIt->second.begin())
3250 // find macros in included files
3251 PositionScopeBufferMap::const_iterator it
3252 = greatest_below(position_to_children, pos);
3253 if (it == position_to_children.end())
3254 // no children before
3258 // do we know something better (i.e. later) already?
3259 if (it->first < bestPos )
3262 // scope ends behind pos?
3263 if (pos < it->second.scope
3264 && (cloned_buffer_ ||
3265 theBufferList().isLoaded(it->second.buffer))) {
3266 // look for macro in external file
3268 MacroData const * data
3269 = it->second.buffer->getMacro(name, false);
3272 bestPos = it->first;
3278 // try previous file if there is one
3279 if (it == position_to_children.begin())
3284 // return the best macro we have found
3289 MacroData const * Buffer::getMacro(docstring const & name,
3290 DocIterator const & pos, bool global) const
3295 // query buffer macros
3296 MacroData const * data = d->getBufferMacro(name, pos);
3300 // If there is a master buffer, query that
3301 Buffer const * const pbuf = d->parent();
3303 d->macro_lock = true;
3304 MacroData const * macro = pbuf->getMacro(
3305 name, *this, false);
3306 d->macro_lock = false;
3312 data = MacroTable::globalMacros().get(name);
3321 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3323 // set scope end behind the last paragraph
3324 DocIterator scope = par_iterator_begin();
3325 scope.pit() = scope.lastpit() + 1;
3327 return getMacro(name, scope, global);
3331 MacroData const * Buffer::getMacro(docstring const & name,
3332 Buffer const & child, bool global) const
3334 // look where the child buffer is included first
3335 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3336 if (it == d->children_positions.end())
3339 // check for macros at the inclusion position
3340 return getMacro(name, it->second, global);
3344 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3346 pit_type const lastpit = it.lastpit();
3348 // look for macros in each paragraph
3349 while (it.pit() <= lastpit) {
3350 Paragraph & par = it.paragraph();
3352 // iterate over the insets of the current paragraph
3353 InsetList const & insets = par.insetList();
3354 InsetList::const_iterator iit = insets.begin();
3355 InsetList::const_iterator end = insets.end();
3356 for (; iit != end; ++iit) {
3357 it.pos() = iit->pos;
3359 // is it a nested text inset?
3360 if (iit->inset->asInsetText()) {
3361 // Inset needs its own scope?
3362 InsetText const * itext = iit->inset->asInsetText();
3363 bool newScope = itext->isMacroScope();
3365 // scope which ends just behind the inset
3366 DocIterator insetScope = it;
3369 // collect macros in inset
3370 it.push_back(CursorSlice(*iit->inset));
3371 updateMacros(it, newScope ? insetScope : scope);
3376 if (iit->inset->asInsetTabular()) {
3377 CursorSlice slice(*iit->inset);
3378 size_t const numcells = slice.nargs();
3379 for (; slice.idx() < numcells; slice.forwardIdx()) {
3380 it.push_back(slice);
3381 updateMacros(it, scope);
3387 // is it an external file?
3388 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3389 // get buffer of external file
3390 InsetInclude const & inset =
3391 static_cast<InsetInclude const &>(*iit->inset);
3393 Buffer * child = inset.getChildBuffer();
3398 // register its position, but only when it is
3399 // included first in the buffer
3400 if (children_positions.find(child) ==
3401 children_positions.end())
3402 children_positions[child] = it;
3404 // register child with its scope
3405 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3409 InsetMath * im = iit->inset->asInsetMath();
3410 if (doing_export && im) {
3411 InsetMathHull * hull = im->asHullInset();
3413 hull->recordLocation(it);
3416 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3420 MathMacroTemplate & macroTemplate =
3421 *iit->inset->asInsetMath()->asMacroTemplate();
3422 MacroContext mc(owner_, it);
3423 macroTemplate.updateToContext(mc);
3426 bool valid = macroTemplate.validMacro();
3427 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3428 // then the BufferView's cursor will be invalid in
3429 // some cases which leads to crashes.
3434 // FIXME (Abdel), I don't understand why we pass 'it' here
3435 // instead of 'macroTemplate' defined above... is this correct?
3436 macros[macroTemplate.name()][it] =
3437 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3447 void Buffer::updateMacros() const
3452 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3454 // start with empty table
3456 d->children_positions.clear();
3457 d->position_to_children.clear();
3459 // Iterate over buffer, starting with first paragraph
3460 // The scope must be bigger than any lookup DocIterator
3461 // later. For the global lookup, lastpit+1 is used, hence
3462 // we use lastpit+2 here.
3463 DocIterator it = par_iterator_begin();
3464 DocIterator outerScope = it;
3465 outerScope.pit() = outerScope.lastpit() + 2;
3466 d->updateMacros(it, outerScope);
3470 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3472 InsetIterator it = inset_iterator_begin(inset());
3473 InsetIterator const end = inset_iterator_end(inset());
3474 for (; it != end; ++it) {
3475 if (it->lyxCode() == BRANCH_CODE) {
3476 InsetBranch & br = static_cast<InsetBranch &>(*it);
3477 docstring const name = br.branch();
3478 if (!from_master && !params().branchlist().find(name))
3479 result.push_back(name);
3480 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3481 result.push_back(name);
3484 if (it->lyxCode() == INCLUDE_CODE) {
3485 // get buffer of external file
3486 InsetInclude const & ins =
3487 static_cast<InsetInclude const &>(*it);
3488 Buffer * child = ins.getChildBuffer();
3491 child->getUsedBranches(result, true);
3494 // remove duplicates
3499 void Buffer::updateMacroInstances(UpdateType utype) const
3501 LYXERR(Debug::MACROS, "updateMacroInstances for "
3502 << d->filename.onlyFileName());
3503 DocIterator it = doc_iterator_begin(this);
3505 DocIterator const end = doc_iterator_end(this);
3506 for (; it != end; it.forwardInset()) {
3507 // look for MathData cells in InsetMathNest insets
3508 InsetMath * minset = it.nextInset()->asInsetMath();
3512 // update macro in all cells of the InsetMathNest
3513 DocIterator::idx_type n = minset->nargs();
3514 MacroContext mc = MacroContext(this, it);
3515 for (DocIterator::idx_type i = 0; i < n; ++i) {
3516 MathData & data = minset->cell(i);
3517 data.updateMacros(0, mc, utype);
3523 void Buffer::listMacroNames(MacroNameSet & macros) const
3528 d->macro_lock = true;
3530 // loop over macro names
3531 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3532 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3533 for (; nameIt != nameEnd; ++nameIt)
3534 macros.insert(nameIt->first);
3536 // loop over children
3537 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3538 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3539 for (; it != end; ++it)
3540 it->first->listMacroNames(macros);
3543 Buffer const * const pbuf = d->parent();
3545 pbuf->listMacroNames(macros);
3547 d->macro_lock = false;
3551 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3553 Buffer const * const pbuf = d->parent();
3558 pbuf->listMacroNames(names);
3561 MacroNameSet::iterator it = names.begin();
3562 MacroNameSet::iterator end = names.end();
3563 for (; it != end; ++it) {
3565 MacroData const * data =
3566 pbuf->getMacro(*it, *this, false);
3568 macros.insert(data);
3570 // we cannot access the original MathMacroTemplate anymore
3571 // here to calls validate method. So we do its work here manually.
3572 // FIXME: somehow make the template accessible here.
3573 if (data->optionals() > 0)
3574 features.require("xargs");
3580 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3583 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3585 RefCache::iterator it = d->ref_cache_.find(label);
3586 if (it != d->ref_cache_.end())
3587 return it->second.second;
3589 static InsetLabel const * dummy_il = 0;
3590 static References const dummy_refs = References();
3591 it = d->ref_cache_.insert(
3592 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3593 return it->second.second;
3597 Buffer::References const & Buffer::references(docstring const & label) const
3599 return const_cast<Buffer *>(this)->getReferenceCache(label);
3603 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3605 References & refs = getReferenceCache(label);
3606 refs.push_back(make_pair(inset, it));
3610 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3612 masterBuffer()->d->ref_cache_[label].first = il;
3616 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3618 return masterBuffer()->d->ref_cache_[label].first;
3622 void Buffer::clearReferenceCache() const
3625 d->ref_cache_.clear();
3629 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3631 //FIXME: This does not work for child documents yet.
3632 reloadBibInfoCache();
3634 // Check if the label 'from' appears more than once
3635 BiblioInfo const & keys = masterBibInfo();
3636 BiblioInfo::const_iterator bit = keys.begin();
3637 BiblioInfo::const_iterator bend = keys.end();
3638 vector<docstring> labels;
3640 for (; bit != bend; ++bit)
3642 labels.push_back(bit->first);
3644 if (count(labels.begin(), labels.end(), from) > 1)
3647 string const paramName = "key";
3648 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3649 if (it->lyxCode() != CITE_CODE)
3651 InsetCommand * inset = it->asInsetCommand();
3652 docstring const oldValue = inset->getParam(paramName);
3653 if (oldValue == from)
3654 inset->setParam(paramName, to);
3658 // returns NULL if id-to-row conversion is unsupported
3659 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3660 pit_type par_begin, pit_type par_end,
3661 OutputWhat output, bool master) const
3663 unique_ptr<TexRow> texrow;
3664 OutputParams runparams(¶ms().encoding());
3665 runparams.nice = true;
3666 runparams.flavor = params().getOutputFlavor(format);
3667 runparams.linelen = lyxrc.plaintext_linelen;
3668 // No side effect of file copying and image conversion
3669 runparams.dryrun = true;
3671 if (output == CurrentParagraph) {
3672 runparams.par_begin = par_begin;
3673 runparams.par_end = par_end;
3674 if (par_begin + 1 == par_end) {
3676 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3680 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3681 convert<docstring>(par_begin),
3682 convert<docstring>(par_end - 1))
3685 // output paragraphs
3686 if (runparams.flavor == OutputParams::LYX) {
3687 Paragraph const & par = text().paragraphs()[par_begin];
3689 depth_type dt = par.getDepth();
3690 par.write(ods, params(), dt);
3691 os << from_utf8(ods.str());
3692 } else if (runparams.flavor == OutputParams::HTML) {
3694 setMathFlavor(runparams);
3695 xhtmlParagraphs(text(), *this, xs, runparams);
3696 } else if (runparams.flavor == OutputParams::TEXT) {
3698 // FIXME Handles only one paragraph, unlike the others.
3699 // Probably should have some routine with a signature like them.
3700 writePlaintextParagraph(*this,
3701 text().paragraphs()[par_begin], os, runparams, dummy);
3702 } else if (params().isDocBook()) {
3703 docbookParagraphs(text(), *this, os, runparams);
3705 // If we are previewing a paragraph, even if this is the
3706 // child of some other buffer, let's cut the link here,
3707 // so that no concurring settings from the master
3708 // (e.g. branch state) interfere (see #8101).
3710 d->ignore_parent = true;
3711 // We need to validate the Buffer params' features here
3712 // in order to know if we should output polyglossia
3713 // macros (instead of babel macros)
3714 LaTeXFeatures features(*this, params(), runparams);
3715 params().validate(features);
3716 runparams.use_polyglossia = features.usePolyglossia();
3717 // latex or literate
3720 ots.texrow().newlines(2);
3722 latexParagraphs(*this, text(), ots, runparams);
3723 texrow = ots.releaseTexRow();
3725 // Restore the parenthood
3727 d->ignore_parent = false;
3731 if (output == FullSource)
3732 os << _("Preview source code");
3733 else if (output == OnlyPreamble)
3734 os << _("Preview preamble");
3735 else if (output == OnlyBody)
3736 os << _("Preview body");
3738 if (runparams.flavor == OutputParams::LYX) {
3740 if (output == FullSource)
3742 else if (output == OnlyPreamble)
3743 params().writeFile(ods, this);
3744 else if (output == OnlyBody)
3746 os << from_utf8(ods.str());
3747 } else if (runparams.flavor == OutputParams::HTML) {
3748 writeLyXHTMLSource(os, runparams, output);
3749 } else if (runparams.flavor == OutputParams::TEXT) {
3750 if (output == OnlyPreamble) {
3751 os << "% "<< _("Plain text does not have a preamble.");
3753 writePlaintextFile(*this, os, runparams);
3754 } else if (params().isDocBook()) {
3755 writeDocBookSource(os, absFileName(), runparams, output);
3757 // latex or literate
3760 ots.texrow().newlines(2);
3762 runparams.is_child = true;
3763 writeLaTeXSource(ots, string(), runparams, output);
3764 texrow = ots.releaseTexRow();
3771 ErrorList & Buffer::errorList(string const & type) const
3773 return d->errorLists[type];
3777 void Buffer::updateTocItem(std::string const & type,
3778 DocIterator const & dit) const
3781 d->gui_->updateTocItem(type, dit);
3785 void Buffer::structureChanged() const
3788 d->gui_->structureChanged();
3792 void Buffer::errors(string const & err, bool from_master) const
3795 d->gui_->errors(err, from_master);
3799 void Buffer::message(docstring const & msg) const
3802 d->gui_->message(msg);
3806 void Buffer::setBusy(bool on) const
3809 d->gui_->setBusy(on);
3813 void Buffer::updateTitles() const
3816 d->wa_->updateTitles();
3820 void Buffer::resetAutosaveTimers() const
3823 d->gui_->resetAutosaveTimers();
3827 bool Buffer::hasGuiDelegate() const
3833 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3842 class AutoSaveBuffer : public ForkedProcess {
3845 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3846 : buffer_(buffer), fname_(fname) {}
3848 virtual shared_ptr<ForkedProcess> clone() const
3850 return make_shared<AutoSaveBuffer>(*this);
3855 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3856 from_utf8(fname_.absFileName())));
3857 return run(DontWait);
3861 virtual int generateChild();
3863 Buffer const & buffer_;
3868 int AutoSaveBuffer::generateChild()
3870 #if defined(__APPLE__)
3871 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3872 * We should use something else like threads.
3874 * Since I do not know how to determine at run time what is the OS X
3875 * version, I just disable forking altogether for now (JMarc)
3877 pid_t const pid = -1;
3879 // tmp_ret will be located (usually) in /tmp
3880 // will that be a problem?
3881 // Note that this calls ForkedCalls::fork(), so it's
3882 // ok cross-platform.
3883 pid_t const pid = fork();
3884 // If you want to debug the autosave
3885 // you should set pid to -1, and comment out the fork.
3886 if (pid != 0 && pid != -1)
3890 // pid = -1 signifies that lyx was unable
3891 // to fork. But we will do the save
3893 bool failed = false;
3894 TempFile tempfile("lyxautoXXXXXX.lyx");
3895 tempfile.setAutoRemove(false);
3896 FileName const tmp_ret = tempfile.name();
3897 if (!tmp_ret.empty()) {
3898 if (!buffer_.writeFile(tmp_ret))
3900 else if (!tmp_ret.moveTo(fname_))
3906 // failed to write/rename tmp_ret so try writing direct
3907 if (!buffer_.writeFile(fname_)) {
3908 // It is dangerous to do this in the child,
3909 // but safe in the parent, so...
3910 if (pid == -1) // emit message signal.
3911 buffer_.message(_("Autosave failed!"));
3915 if (pid == 0) // we are the child so...
3924 FileName Buffer::getEmergencyFileName() const
3926 return FileName(d->filename.absFileName() + ".emergency");
3930 FileName Buffer::getAutosaveFileName() const
3932 // if the document is unnamed try to save in the backup dir, else
3933 // in the default document path, and as a last try in the filePath,
3934 // which will most often be the temporary directory
3937 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3938 : lyxrc.backupdir_path;
3939 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3942 string const fname = "#" + d->filename.onlyFileName() + "#";
3944 return makeAbsPath(fname, fpath);
3948 void Buffer::removeAutosaveFile() const
3950 FileName const f = getAutosaveFileName();
3956 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3958 FileName const newauto = getAutosaveFileName();
3960 if (newauto != oldauto && oldauto.exists())
3961 if (!oldauto.moveTo(newauto))
3962 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3966 bool Buffer::autoSave() const
3968 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3969 if (buf->d->bak_clean || isReadonly())
3972 message(_("Autosaving current document..."));
3973 buf->d->bak_clean = true;
3975 FileName const fname = getAutosaveFileName();
3976 LASSERT(d->cloned_buffer_, return false);
3978 // If this buffer is cloned, we assume that
3979 // we are running in a separate thread already.
3980 TempFile tempfile("lyxautoXXXXXX.lyx");
3981 tempfile.setAutoRemove(false);
3982 FileName const tmp_ret = tempfile.name();
3983 if (!tmp_ret.empty()) {
3985 // assume successful write of tmp_ret
3986 if (tmp_ret.moveTo(fname))
3989 // failed to write/rename tmp_ret so try writing direct
3990 return writeFile(fname);
3994 void Buffer::setExportStatus(bool e) const
3996 d->doing_export = e;
3997 ListOfBuffers clist = getDescendents();
3998 ListOfBuffers::const_iterator cit = clist.begin();
3999 ListOfBuffers::const_iterator const cen = clist.end();
4000 for (; cit != cen; ++cit)
4001 (*cit)->d->doing_export = e;
4005 bool Buffer::isExporting() const
4007 return d->doing_export;
4011 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4015 return doExport(target, put_in_tempdir, result_file);
4018 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4019 string & result_file) const
4021 bool const update_unincluded =
4022 params().maintain_unincluded_children
4023 && !params().getIncludedChildren().empty();
4025 // (1) export with all included children (omit \includeonly)
4026 if (update_unincluded) {
4027 ExportStatus const status =
4028 doExport(target, put_in_tempdir, true, result_file);
4029 if (status != ExportSuccess)
4032 // (2) export with included children only
4033 return doExport(target, put_in_tempdir, false, result_file);
4037 void Buffer::setMathFlavor(OutputParams & op) const
4039 switch (params().html_math_output) {
4040 case BufferParams::MathML:
4041 op.math_flavor = OutputParams::MathAsMathML;
4043 case BufferParams::HTML:
4044 op.math_flavor = OutputParams::MathAsHTML;
4046 case BufferParams::Images:
4047 op.math_flavor = OutputParams::MathAsImages;
4049 case BufferParams::LaTeX:
4050 op.math_flavor = OutputParams::MathAsLaTeX;
4056 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4057 bool includeall, string & result_file) const
4059 LYXERR(Debug::FILES, "target=" << target);
4060 OutputParams runparams(¶ms().encoding());
4061 string format = target;
4062 string dest_filename;
4063 size_t pos = target.find(' ');
4064 if (pos != string::npos) {
4065 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4066 format = target.substr(0, pos);
4067 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4068 FileName(dest_filename).onlyPath().createPath();
4069 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4071 MarkAsExporting exporting(this);
4072 string backend_format;
4073 runparams.flavor = OutputParams::LATEX;
4074 runparams.linelen = lyxrc.plaintext_linelen;
4075 runparams.includeall = includeall;
4076 vector<string> backs = params().backends();
4077 Converters converters = theConverters();
4078 bool need_nice_file = false;
4079 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4080 // Get shortest path to format
4081 converters.buildGraph();
4082 Graph::EdgePath path;
4083 for (vector<string>::const_iterator it = backs.begin();
4084 it != backs.end(); ++it) {
4085 Graph::EdgePath p = converters.getPath(*it, format);
4086 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4087 backend_format = *it;
4092 if (!put_in_tempdir) {
4093 // Only show this alert if this is an export to a non-temporary
4094 // file (not for previewing).
4095 Alert::error(_("Couldn't export file"), bformat(
4096 _("No information for exporting the format %1$s."),
4097 formats.prettyName(format)));
4099 return ExportNoPathToFormat;
4101 runparams.flavor = converters.getFlavor(path, this);
4102 Graph::EdgePath::const_iterator it = path.begin();
4103 Graph::EdgePath::const_iterator en = path.end();
4104 for (; it != en; ++it)
4105 if (theConverters().get(*it).nice()) {
4106 need_nice_file = true;
4111 backend_format = format;
4112 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4113 // FIXME: Don't hardcode format names here, but use a flag
4114 if (backend_format == "pdflatex")
4115 runparams.flavor = OutputParams::PDFLATEX;
4116 else if (backend_format == "luatex")
4117 runparams.flavor = OutputParams::LUATEX;
4118 else if (backend_format == "dviluatex")
4119 runparams.flavor = OutputParams::DVILUATEX;
4120 else if (backend_format == "xetex")
4121 runparams.flavor = OutputParams::XETEX;
4124 string filename = latexName(false);
4125 filename = addName(temppath(), filename);
4126 filename = changeExtension(filename,
4127 formats.extension(backend_format));
4128 LYXERR(Debug::FILES, "filename=" << filename);
4130 // Plain text backend
4131 if (backend_format == "text") {
4132 runparams.flavor = OutputParams::TEXT;
4133 writePlaintextFile(*this, FileName(filename), runparams);
4136 else if (backend_format == "xhtml") {
4137 runparams.flavor = OutputParams::HTML;
4138 setMathFlavor(runparams);
4139 makeLyXHTMLFile(FileName(filename), runparams);
4140 } else if (backend_format == "lyx")
4141 writeFile(FileName(filename));
4143 else if (params().isDocBook()) {
4144 runparams.nice = !put_in_tempdir;
4145 makeDocBookFile(FileName(filename), runparams);
4148 else if (backend_format == format || need_nice_file) {
4149 runparams.nice = true;
4150 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4151 if (d->cloned_buffer_)
4152 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4155 } else if (!lyxrc.tex_allows_spaces
4156 && contains(filePath(), ' ')) {
4157 Alert::error(_("File name error"),
4158 _("The directory path to the document cannot contain spaces."));
4159 return ExportTexPathHasSpaces;
4161 runparams.nice = false;
4162 bool const success = makeLaTeXFile(
4163 FileName(filename), filePath(), runparams);
4164 if (d->cloned_buffer_)
4165 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4170 string const error_type = (format == "program")
4171 ? "Build" : params().bufferFormat();
4172 ErrorList & error_list = d->errorLists[error_type];
4173 string const ext = formats.extension(format);
4174 FileName const tmp_result_file(changeExtension(filename, ext));
4175 bool const success = converters.convert(this, FileName(filename),
4176 tmp_result_file, FileName(absFileName()), backend_format, format,
4179 // Emit the signal to show the error list or copy it back to the
4180 // cloned Buffer so that it can be emitted afterwards.
4181 if (format != backend_format) {
4182 if (runparams.silent)
4184 else if (d->cloned_buffer_)
4185 d->cloned_buffer_->d->errorLists[error_type] =
4186 d->errorLists[error_type];
4189 // also to the children, in case of master-buffer-view
4190 ListOfBuffers clist = getDescendents();
4191 ListOfBuffers::const_iterator cit = clist.begin();
4192 ListOfBuffers::const_iterator const cen = clist.end();
4193 for (; cit != cen; ++cit) {
4194 if (runparams.silent)
4195 (*cit)->d->errorLists[error_type].clear();
4196 else if (d->cloned_buffer_) {
4197 // Enable reverse search by copying back the
4198 // texrow object to the cloned buffer.
4199 // FIXME: this is not thread safe.
4200 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4201 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4202 (*cit)->d->errorLists[error_type];
4204 (*cit)->errors(error_type, true);
4208 if (d->cloned_buffer_) {
4209 // Enable reverse dvi or pdf to work by copying back the texrow
4210 // object to the cloned buffer.
4211 // FIXME: There is a possibility of concurrent access to texrow
4212 // here from the main GUI thread that should be securized.
4213 d->cloned_buffer_->d->texrow = d->texrow;
4214 string const error_type = params().bufferFormat();
4215 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4219 if (put_in_tempdir) {
4220 result_file = tmp_result_file.absFileName();
4221 return success ? ExportSuccess : ExportConverterError;
4224 if (dest_filename.empty())
4225 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4227 result_file = dest_filename;
4228 // We need to copy referenced files (e. g. included graphics
4229 // if format == "dvi") to the result dir.
4230 vector<ExportedFile> const files =
4231 runparams.exportdata->externalFiles(format);
4232 string const dest = runparams.export_folder.empty() ?
4233 onlyPath(result_file) : runparams.export_folder;
4234 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4235 : force_overwrite == ALL_FILES;
4236 CopyStatus status = use_force ? FORCE : SUCCESS;
4238 vector<ExportedFile>::const_iterator it = files.begin();
4239 vector<ExportedFile>::const_iterator const en = files.end();
4240 for (; it != en && status != CANCEL; ++it) {
4241 string const fmt = formats.getFormatFromFile(it->sourceName);
4242 string fixedName = it->exportName;
4243 if (!runparams.export_folder.empty()) {
4244 // Relative pathnames starting with ../ will be sanitized
4245 // if exporting to a different folder
4246 while (fixedName.substr(0, 3) == "../")
4247 fixedName = fixedName.substr(3, fixedName.length() - 3);
4249 FileName fixedFileName = makeAbsPath(fixedName, dest);
4250 fixedFileName.onlyPath().createPath();
4251 status = copyFile(fmt, it->sourceName,
4253 it->exportName, status == FORCE,
4254 runparams.export_folder.empty());
4257 if (status == CANCEL) {
4258 message(_("Document export cancelled."));
4259 return ExportCancel;
4262 if (tmp_result_file.exists()) {
4263 // Finally copy the main file
4264 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4265 : force_overwrite != NO_FILES;
4266 if (status == SUCCESS && use_force)
4268 status = copyFile(format, tmp_result_file,
4269 FileName(result_file), result_file,
4271 if (status == CANCEL) {
4272 message(_("Document export cancelled."));
4273 return ExportCancel;
4275 message(bformat(_("Document exported as %1$s "
4277 formats.prettyName(format),
4278 makeDisplayPath(result_file)));
4281 // This must be a dummy converter like fax (bug 1888)
4282 message(bformat(_("Document exported as %1$s"),
4283 formats.prettyName(format)));
4286 return success ? ExportSuccess : ExportConverterError;
4290 Buffer::ExportStatus Buffer::preview(string const & format) const
4292 bool const update_unincluded =
4293 params().maintain_unincluded_children
4294 && !params().getIncludedChildren().empty();
4295 return preview(format, update_unincluded);
4299 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4301 MarkAsExporting exporting(this);
4303 // (1) export with all included children (omit \includeonly)
4305 ExportStatus const status = doExport(format, true, true, result_file);
4306 if (status != ExportSuccess)
4309 // (2) export with included children only
4310 ExportStatus const status = doExport(format, true, false, result_file);
4311 FileName const previewFile(result_file);
4313 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4314 theimpl->preview_file_ = previewFile;
4315 theimpl->preview_format_ = format;
4316 theimpl->preview_error_ = (status != ExportSuccess);
4318 if (status != ExportSuccess)
4321 if (previewFile.exists())
4322 return formats.view(*this, previewFile, format) ?
4323 PreviewSuccess : PreviewError;
4325 // Successful export but no output file?
4326 // Probably a bug in error detection.
4327 LATTEST(status != ExportSuccess);
4332 Buffer::ReadStatus Buffer::extractFromVC()
4334 bool const found = LyXVC::file_not_found_hook(d->filename);
4336 return ReadFileNotFound;
4337 if (!d->filename.isReadableFile())
4343 Buffer::ReadStatus Buffer::loadEmergency()
4345 FileName const emergencyFile = getEmergencyFileName();
4346 if (!emergencyFile.exists()
4347 || emergencyFile.lastModified() <= d->filename.lastModified())
4348 return ReadFileNotFound;
4350 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4351 docstring const text = bformat(_("An emergency save of the document "
4352 "%1$s exists.\n\nRecover emergency save?"), file);
4354 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4355 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4361 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4362 bool const success = (ret_llf == ReadSuccess);
4365 Alert::warning(_("File is read-only"),
4366 bformat(_("An emergency file is successfully loaded, "
4367 "but the original file %1$s is marked read-only. "
4368 "Please make sure to save the document as a different "
4369 "file."), from_utf8(d->filename.absFileName())));
4372 lyxvc().file_found_hook(d->filename);
4373 str = _("Document was successfully recovered.");
4375 str = _("Document was NOT successfully recovered.");
4376 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4377 makeDisplayPath(emergencyFile.absFileName()));
4379 int const del_emerg =
4380 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4381 _("&Remove"), _("&Keep"));
4382 if (del_emerg == 0) {
4383 emergencyFile.removeFile();
4385 Alert::warning(_("Emergency file deleted"),
4386 _("Do not forget to save your file now!"), true);
4388 return success ? ReadSuccess : ReadEmergencyFailure;
4391 int const del_emerg =
4392 Alert::prompt(_("Delete emergency file?"),
4393 _("Remove emergency file now?"), 1, 1,
4394 _("&Remove"), _("&Keep"));
4396 emergencyFile.removeFile();
4397 return ReadOriginal;
4407 Buffer::ReadStatus Buffer::loadAutosave()
4409 // Now check if autosave file is newer.
4410 FileName const autosaveFile = getAutosaveFileName();
4411 if (!autosaveFile.exists()
4412 || autosaveFile.lastModified() <= d->filename.lastModified())
4413 return ReadFileNotFound;
4415 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4416 docstring const text = bformat(_("The backup of the document %1$s "
4417 "is newer.\n\nLoad the backup instead?"), file);
4418 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4419 _("&Load backup"), _("Load &original"), _("&Cancel"));
4424 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4425 // the file is not saved if we load the autosave file.
4426 if (ret_llf == ReadSuccess) {
4428 Alert::warning(_("File is read-only"),
4429 bformat(_("A backup file is successfully loaded, "
4430 "but the original file %1$s is marked read-only. "
4431 "Please make sure to save the document as a "
4433 from_utf8(d->filename.absFileName())));
4436 lyxvc().file_found_hook(d->filename);
4439 return ReadAutosaveFailure;
4442 // Here we delete the autosave
4443 autosaveFile.removeFile();
4444 return ReadOriginal;
4452 Buffer::ReadStatus Buffer::loadLyXFile()
4454 if (!d->filename.isReadableFile()) {
4455 ReadStatus const ret_rvc = extractFromVC();
4456 if (ret_rvc != ReadSuccess)
4460 ReadStatus const ret_re = loadEmergency();
4461 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4464 ReadStatus const ret_ra = loadAutosave();
4465 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4468 return loadThisLyXFile(d->filename);
4472 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4474 return readFile(fn);
4478 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4480 for (auto const & err : terr) {
4481 TexRow::TextEntry start, end = TexRow::text_none;
4482 int errorRow = err.error_in_line;
4483 Buffer const * buf = 0;
4485 if (err.child_name.empty())
4486 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4488 // The error occurred in a child
4489 for (Buffer const * child : getDescendents()) {
4490 string const child_name =
4491 DocFileName(changeExtension(child->absFileName(), "tex")).
4493 if (err.child_name != child_name)
4495 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4496 if (!TexRow::isNone(start)) {
4497 buf = d->cloned_buffer_
4498 ? child->d->cloned_buffer_->d->owner_
4505 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4511 void Buffer::setBuffersForInsets() const
4513 inset().setBuffer(const_cast<Buffer &>(*this));
4517 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4519 LBUFERR(!text().paragraphs().empty());
4521 // Use the master text class also for child documents
4522 Buffer const * const master = masterBuffer();
4523 DocumentClass const & textclass = master->params().documentClass();
4525 // do this only if we are the top-level Buffer
4526 if (master == this) {
4527 textclass.counters().reset(from_ascii("bibitem"));
4528 reloadBibInfoCache();
4531 // keep the buffers to be children in this set. If the call from the
4532 // master comes back we can see which of them were actually seen (i.e.
4533 // via an InsetInclude). The remaining ones in the set need still be updated.
4534 static std::set<Buffer const *> bufToUpdate;
4535 if (scope == UpdateMaster) {
4536 // If this is a child document start with the master
4537 if (master != this) {
4538 bufToUpdate.insert(this);
4539 master->updateBuffer(UpdateMaster, utype);
4540 // If the master buffer has no gui associated with it, then the TocModel is
4541 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4542 // (bug 5699). The same happens if the master buffer is open in a different
4543 // window. This test catches both possibilities.
4544 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4545 // There remains a problem here: If there is another child open in yet a third
4546 // window, that TOC is not updated. So some more general solution is needed at
4548 if (master->d->gui_ != d->gui_)
4551 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4552 if (bufToUpdate.find(this) == bufToUpdate.end())
4556 // start over the counters in the master
4557 textclass.counters().reset();
4560 // update will be done below for this buffer
4561 bufToUpdate.erase(this);
4563 // update all caches
4564 clearReferenceCache();
4566 setChangesPresent(false);
4568 Buffer & cbuf = const_cast<Buffer &>(*this);
4571 ParIterator parit = cbuf.par_iterator_begin();
4572 updateBuffer(parit, utype);
4575 // TocBackend update will be done later.
4578 d->bibinfo_cache_valid_ = true;
4579 d->cite_labels_valid_ = true;
4581 cbuf.tocBackend().update(true, utype);
4582 if (scope == UpdateMaster)
4583 cbuf.structureChanged();
4587 static depth_type getDepth(DocIterator const & it)
4589 depth_type depth = 0;
4590 for (size_t i = 0 ; i < it.depth() ; ++i)
4591 if (!it[i].inset().inMathed())
4592 depth += it[i].paragraph().getDepth() + 1;
4593 // remove 1 since the outer inset does not count
4594 // we should have at least one non-math inset, so
4595 // depth should nevery be 0. but maybe it is worth
4596 // marking this, just in case.
4598 // coverity[INTEGER_OVERFLOW]
4602 static depth_type getItemDepth(ParIterator const & it)
4604 Paragraph const & par = *it;
4605 LabelType const labeltype = par.layout().labeltype;
4607 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4610 // this will hold the lowest depth encountered up to now.
4611 depth_type min_depth = getDepth(it);
4612 ParIterator prev_it = it;
4615 --prev_it.top().pit();
4617 // start of nested inset: go to outer par
4619 if (prev_it.empty()) {
4620 // start of document: nothing to do
4625 // We search for the first paragraph with same label
4626 // that is not more deeply nested.
4627 Paragraph & prev_par = *prev_it;
4628 depth_type const prev_depth = getDepth(prev_it);
4629 if (labeltype == prev_par.layout().labeltype) {
4630 if (prev_depth < min_depth)
4631 return prev_par.itemdepth + 1;
4632 if (prev_depth == min_depth)
4633 return prev_par.itemdepth;
4635 min_depth = min(min_depth, prev_depth);
4636 // small optimization: if we are at depth 0, we won't
4637 // find anything else
4638 if (prev_depth == 0)
4644 static bool needEnumCounterReset(ParIterator const & it)
4646 Paragraph const & par = *it;
4647 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4648 depth_type const cur_depth = par.getDepth();
4649 ParIterator prev_it = it;
4650 while (prev_it.pit()) {
4651 --prev_it.top().pit();
4652 Paragraph const & prev_par = *prev_it;
4653 if (prev_par.getDepth() <= cur_depth)
4654 return prev_par.layout().name() != par.layout().name();
4656 // start of nested inset: reset
4661 // set the label of a paragraph. This includes the counters.
4662 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4664 BufferParams const & bp = owner_->masterBuffer()->params();
4665 DocumentClass const & textclass = bp.documentClass();
4666 Paragraph & par = it.paragraph();
4667 Layout const & layout = par.layout();
4668 Counters & counters = textclass.counters();
4670 if (par.params().startOfAppendix()) {
4671 // We want to reset the counter corresponding to toplevel sectioning
4672 Layout const & lay = textclass.getTOCLayout();
4673 docstring const cnt = lay.counter;
4675 counters.reset(cnt);
4676 counters.appendix(true);
4678 par.params().appendix(counters.appendix());
4680 // Compute the item depth of the paragraph
4681 par.itemdepth = getItemDepth(it);
4683 if (layout.margintype == MARGIN_MANUAL) {
4684 if (par.params().labelWidthString().empty())
4685 par.params().labelWidthString(par.expandLabel(layout, bp));
4686 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4687 // we do not need to do anything here, since the empty case is
4688 // handled during export.
4690 par.params().labelWidthString(docstring());
4693 switch(layout.labeltype) {
4694 case LABEL_ITEMIZE: {
4695 // At some point of time we should do something more
4696 // clever here, like:
4697 // par.params().labelString(
4698 // bp.user_defined_bullet(par.itemdepth).getText());
4699 // for now, use a simple hardcoded label
4700 docstring itemlabel;
4701 switch (par.itemdepth) {
4703 itemlabel = char_type(0x2022);
4706 itemlabel = char_type(0x2013);
4709 itemlabel = char_type(0x2217);
4712 itemlabel = char_type(0x2219); // or 0x00b7
4715 par.params().labelString(itemlabel);
4719 case LABEL_ENUMERATE: {
4720 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4722 switch (par.itemdepth) {
4731 enumcounter += "iv";
4734 // not a valid enumdepth...
4738 // Increase the master counter?
4739 if (layout.stepmastercounter && needEnumCounterReset(it))
4740 counters.stepMaster(enumcounter, utype);
4742 // Maybe we have to reset the enumeration counter.
4743 if (!layout.resumecounter && needEnumCounterReset(it))
4744 counters.reset(enumcounter);
4745 counters.step(enumcounter, utype);
4747 string const & lang = par.getParLanguage(bp)->code();
4748 par.params().labelString(counters.theCounter(enumcounter, lang));
4753 case LABEL_SENSITIVE: {
4754 string const & type = counters.current_float();
4755 docstring full_label;
4757 full_label = owner_->B_("Senseless!!! ");
4759 docstring name = owner_->B_(textclass.floats().getType(type).name());
4760 if (counters.hasCounter(from_utf8(type))) {
4761 string const & lang = par.getParLanguage(bp)->code();
4762 counters.step(from_utf8(type), utype);
4763 full_label = bformat(from_ascii("%1$s %2$s:"),
4765 counters.theCounter(from_utf8(type), lang));
4767 full_label = bformat(from_ascii("%1$s #:"), name);
4769 par.params().labelString(full_label);
4773 case LABEL_NO_LABEL:
4774 par.params().labelString(docstring());
4778 case LABEL_CENTERED:
4779 case LABEL_STATIC: {
4780 docstring const & lcounter = layout.counter;
4781 if (!lcounter.empty()) {
4782 if (layout.toclevel <= bp.secnumdepth
4783 && (layout.latextype != LATEX_ENVIRONMENT
4784 || it.text()->isFirstInSequence(it.pit()))) {
4785 if (counters.hasCounter(lcounter))
4786 counters.step(lcounter, utype);
4787 par.params().labelString(par.expandLabel(layout, bp));
4789 par.params().labelString(docstring());
4791 par.params().labelString(par.expandLabel(layout, bp));
4797 par.params().labelString(par.expandLabel(layout, bp));
4802 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4804 // LASSERT: Is it safe to continue here, or should we just return?
4805 LASSERT(parit.pit() == 0, /**/);
4807 // Set the position of the text in the buffer to be able
4808 // to resolve macros in it.
4809 parit.text()->setMacrocontextPosition(parit);
4811 depth_type maxdepth = 0;
4812 pit_type const lastpit = parit.lastpit();
4813 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4814 // reduce depth if necessary
4815 if (parit->params().depth() > maxdepth) {
4816 /** FIXME: this function is const, but
4817 * nevertheless it modifies the buffer. To be
4818 * cleaner, one should modify the buffer in
4819 * another function, which is actually
4820 * non-const. This would however be costly in
4821 * terms of code duplication.
4823 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4824 parit->params().depth(maxdepth);
4826 maxdepth = parit->getMaxDepthAfter();
4828 if (utype == OutputUpdate) {
4829 // track the active counters
4830 // we have to do this for the master buffer, since the local
4831 // buffer isn't tracking anything.
4832 masterBuffer()->params().documentClass().counters().
4833 setActiveLayout(parit->layout());
4836 // set the counter for this paragraph
4837 d->setLabel(parit, utype);
4839 // update change-tracking flag
4840 parit->addChangesToBuffer(*this);
4843 InsetList::const_iterator iit = parit->insetList().begin();
4844 InsetList::const_iterator end = parit->insetList().end();
4845 for (; iit != end; ++iit) {
4846 parit.pos() = iit->pos;
4847 iit->inset->updateBuffer(parit, utype);
4853 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4854 WordLangTuple & word_lang, docstring_list & suggestions) const
4858 suggestions.clear();
4859 word_lang = WordLangTuple();
4860 bool const to_end = to.empty();
4861 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4862 // OK, we start from here.
4863 for (; from != end; from.forwardPos()) {
4864 // This skips all insets with spell check disabled.
4865 while (!from.allowSpellCheck()) {
4869 // If from is at the end of the document (which is possible
4870 // when "from" was changed above) LyX will crash later otherwise.
4871 if (from.atEnd() || (!to_end && from >= end))
4874 from.paragraph().spellCheck();
4875 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4876 if (SpellChecker::misspelled(res)) {
4880 // Do not increase progress when from == to, otherwise the word
4881 // count will be wrong.
4891 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4893 bool inword = false;
4898 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4899 if (!dit.inTexted()) {
4904 Paragraph const & par = dit.paragraph();
4905 pos_type const pos = dit.pos();
4907 // Copied and adapted from isWordSeparator() in Paragraph
4908 if (pos == dit.lastpos()) {
4911 Inset const * ins = par.getInset(pos);
4912 if (ins && skipNoOutput && !ins->producesOutput()) {
4915 // stop if end of range was skipped
4916 if (!to.atEnd() && dit >= to)
4919 } else if (!par.isDeleted(pos)) {
4920 if (par.isWordSeparator(pos))
4926 if (ins && ins->isLetter())
4928 else if (ins && ins->isSpace())
4931 char_type const c = par.getChar(pos);
4932 if (isPrintableNonspace(c))
4934 else if (isSpace(c))
4944 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4946 d->updateStatistics(from, to, skipNoOutput);
4950 int Buffer::wordCount() const
4952 return d->wordCount();
4956 int Buffer::charCount(bool with_blanks) const
4958 return d->charCount(with_blanks);
4962 Buffer::ReadStatus Buffer::reload()
4965 // c.f. bug http://www.lyx.org/trac/ticket/6587
4966 removeAutosaveFile();
4967 // e.g., read-only status could have changed due to version control
4968 d->filename.refresh();
4969 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4971 // clear parent. this will get reset if need be.
4973 ReadStatus const status = loadLyXFile();
4974 if (status == ReadSuccess) {
4979 message(bformat(_("Document %1$s reloaded."), disp_fn));
4982 message(bformat(_("Could not reload document %1$s."), disp_fn));
4992 bool Buffer::saveAs(FileName const & fn)
4994 FileName const old_name = fileName();
4995 FileName const old_auto = getAutosaveFileName();
4996 bool const old_unnamed = isUnnamed();
4997 bool success = true;
4998 d->old_position = filePath();
5005 // bring the autosave file with us, just in case.
5006 moveAutosaveFile(old_auto);
5007 // validate version control data and
5008 // correct buffer title
5009 lyxvc().file_found_hook(fileName());
5011 // the file has now been saved to the new location.
5012 // we need to check that the locations of child buffers
5014 checkChildBuffers();
5015 checkMasterBuffer();
5018 // reset the old filename and unnamed state
5019 setFileName(old_name);
5020 setUnnamed(old_unnamed);
5024 d->old_position.clear();
5029 void Buffer::checkChildBuffers()
5031 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5032 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5033 for (; it != en; ++it) {
5034 DocIterator dit = it->second;
5035 Buffer * cbuf = const_cast<Buffer *>(it->first);
5036 if (!cbuf || !theBufferList().isLoaded(cbuf))
5038 Inset * inset = dit.nextInset();
5039 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5040 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5041 docstring const & incfile = inset_inc->getParam("filename");
5042 string oldloc = cbuf->absFileName();
5043 string newloc = makeAbsPath(to_utf8(incfile),
5044 onlyPath(absFileName())).absFileName();
5045 if (oldloc == newloc)
5047 // the location of the child file is incorrect.
5049 inset_inc->setChildBuffer(0);
5051 // invalidate cache of children
5052 d->children_positions.clear();
5053 d->position_to_children.clear();
5057 // If a child has been saved under a different name/path, it might have been
5058 // orphaned. Therefore the master needs to be reset (bug 8161).
5059 void Buffer::checkMasterBuffer()
5061 Buffer const * const master = masterBuffer();
5065 // necessary to re-register the child (bug 5873)
5066 // FIXME: clean up updateMacros (here, only
5067 // child registering is needed).
5068 master->updateMacros();
5069 // (re)set master as master buffer, but only
5070 // if we are a real child
5071 if (master->isChild(this))
5078 string Buffer::includedFilePath(string const & name, string const & ext) const
5080 if (d->old_position.empty() ||
5081 equivalent(FileName(d->old_position), FileName(filePath())))
5084 bool isabsolute = FileName::isAbsolute(name);
5085 // both old_position and filePath() end with a path separator
5086 string absname = isabsolute ? name : d->old_position + name;
5088 // if old_position is set to origin, we need to do the equivalent of
5089 // getReferencedFileName() (see readDocument())
5090 if (!isabsolute && d->old_position == params().origin) {
5091 FileName const test(addExtension(filePath() + name, ext));
5093 absname = filePath() + name;
5096 if (!FileName(addExtension(absname, ext)).exists())
5100 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5102 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5103 from_utf8(filePath())));
5107 void Buffer::setChangesPresent(bool b) const
5109 d->tracked_changes_present_ = b;
5113 bool Buffer::areChangesPresent() const
5115 return d->tracked_changes_present_;
5119 void Buffer::updateChangesPresent() const
5121 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5122 setChangesPresent(false);
5123 ParConstIterator it = par_iterator_begin();
5124 ParConstIterator const end = par_iterator_end();
5125 for (; !areChangesPresent() && it != end; ++it)
5126 it->addChangesToBuffer(*this);