4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
15 #include "OutputEnums.h"
17 #include "support/unique_ptr.h"
18 #include "support/strfwd.h"
19 #include "support/types.h"
20 #include "support/FileNameList.h"
56 class ParConstIterator;
66 class GuiBufferDelegate;
67 class WorkAreaManager;
68 } // namespace frontend
73 class FileNamePairList;
74 } // namespace support
79 } // namespace graphics
83 typedef std::list<Buffer *> ListOfBuffers;
84 /// a list of Buffers we cloned
85 typedef std::set<Buffer *> CloneList;
88 /** The buffer object.
89 * This is the buffer object. It contains all the information about
90 * a document loaded into LyX.
91 * The buffer object owns the Text (wrapped in an InsetText), which
92 * contains the individual paragraphs of the document.
95 * I am not sure if the class is complete or
96 * minimal, probably not.
97 * \author Lars Gullik Bjønnes
100 class MarkAsExporting;
104 /// What type of log will \c getLogName() return?
106 latexlog, ///< LaTeX log
107 buildlog ///< Literate build log
110 /// Result of \c readFile()
120 ReadEmergencyFailure,
138 ExportNoPathToFormat,
139 ExportTexPathHasSpaces,
140 ExportConverterError,
142 // Implies ExportSuccess.
144 // The exported file exists but there was an error when opening
156 explicit Buffer(std::string const & file, bool readonly = false,
157 Buffer const * cloned_buffer = 0);
162 /// Clones the entire structure of which this Buffer is part,
163 /// cloning all the children, too.
164 Buffer * cloneWithChildren() const;
165 /// Just clones this single Buffer. For autosave.
166 Buffer * cloneBufferOnly() const;
168 bool isClone() const;
170 /** High-level interface to buffer functionality.
171 This function parses a command string and executes it.
173 void dispatch(std::string const & command, DispatchResult & result);
175 /// Maybe we know the function already by number...
176 void dispatch(FuncRequest const & func, DispatchResult & result);
178 /// Can this function be exectued?
179 /// \return true if we made a decision
180 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
183 DocIterator getParFromID(int id) const;
184 /// do we have a paragraph with this id?
185 bool hasParWithID(int id) const;
188 frontend::WorkAreaManager & workAreaManager() const;
191 Takes care of auto-save files and backup file if requested.
192 Returns \c true if the save is successful, \c false otherwise.
195 /// Renames and saves the buffer
196 bool saveAs(support::FileName const & fn);
198 /// Write document to stream. Returns \c false if unsuccessful.
199 bool write(std::ostream &) const;
200 /// Write file. Returns \c false if unsuccessful.
201 bool writeFile(support::FileName const &) const;
203 /// \name Functions involved in reading files/strings.
205 /// Loads the LyX file into the buffer. This function
206 /// tries to extract the file from version control if it
207 /// cannot be found. If it can be found, it will try to
208 /// read an emergency save file or an autosave file.
209 /// \sa loadThisLyXFile
210 ReadStatus loadLyXFile();
211 /// Loads the LyX file \c fn into the buffer. If you want
212 /// to check for files in a version control container,
213 /// emergency or autosave files, one should use \c loadLyXFile.
215 ReadStatus loadThisLyXFile(support::FileName const & fn);
216 /// import a new document from a string
217 bool importString(std::string const &, docstring const &, ErrorList &);
218 /// import a new file
219 bool importFile(std::string const &, support::FileName const &, ErrorList &);
220 /// read a new document from a string
221 bool readString(std::string const &);
222 /// Reloads the LyX file
224 //FIXME: The following function should be private
226 /// read the header, returns number of unknown tokens
227 int readHeader(Lexer & lex);
229 double fontScalingFactor() const;
233 typedef std::map<Buffer const *, Buffer *> BufferMap;
235 void cloneWithChildren(BufferMap &, CloneList *) const;
236 /// save checksum of the given file.
237 void saveCheckSum() const;
239 ReadStatus readFile(support::FileName const & fn);
240 /// Reads a file without header.
241 /// \param par if != 0 insert the file.
242 /// \return \c true if file is not completely read.
243 bool readDocument(Lexer &);
244 /// Try to extract the file from a version control container
245 /// before reading if the file cannot be found.
246 /// \sa LyXVC::file_not_found_hook
247 ReadStatus extractFromVC();
248 /// Reads the first tag of a LyX File and
249 /// returns the file format number.
250 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
251 int & file_format) const;
252 /// Convert the LyX file to the LYX_FORMAT using
253 /// the lyx2lyx script and returns the filename
254 /// of the temporary file to be read
255 ReadStatus convertLyXFormat(support::FileName const & fn,
256 support::FileName & tmpfile, int from_format);
257 /// get appropriate name for backing up files from older versions
258 support::FileName getBackupName() const;
262 /// \name Functions involved in autosave and emergency files.
264 /// Save an autosave file to #filename.lyx#
265 bool autoSave() const;
266 /// save emergency file
267 /// \return a status message towards the user.
268 docstring emergencyWrite();
270 //FIXME:The following function should be private
273 void removeAutosaveFile() const;
276 /// Try to load an autosave file associated to \c fn.
277 ReadStatus loadAutosave();
278 /// Try to load an emergency file associated to \c fn.
279 ReadStatus loadEmergency();
280 /// Get the filename of the emergency file associated with the Buffer
281 support::FileName getEmergencyFileName() const;
282 /// Get the filename of the autosave file associated with the Buffer
283 support::FileName getAutosaveFileName() const;
285 void moveAutosaveFile(support::FileName const & old) const;
289 /// Fill in the ErrorList with the TeXErrors
290 void bufferErrors(TeXErrors const &, ErrorList &) const;
300 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
301 ExportStatus makeLaTeXFile(support::FileName const & filename,
302 std::string const & original_path,
303 OutputParams const &,
304 OutputWhat output = FullSource) const;
305 /** Export the buffer to LaTeX.
306 If \p os is a file stream, and params().inputenc is "auto" or
307 "default", and the buffer contains text in different languages
308 with more than one encoding, then this method will change the
309 encoding associated to \p os. Therefore you must not call this
310 method with a string stream if the output is supposed to go to a
314 ofs.open("test.tex");
315 writeLaTeXSource(os, ...);
317 \endcode is NOT equivalent to \code
318 odocstringstream oss;
320 writeLaTeXSource(os, ...);
322 ofs.open("test.tex");
327 ExportStatus writeLaTeXSource(otexstream & os,
328 std::string const & original_path,
329 OutputParams const &,
330 OutputWhat output = FullSource) const;
332 ExportStatus makeDocBookFile(support::FileName const & filename,
333 OutputParams const & runparams_in,
334 OutputWhat output = FullSource) const;
336 ExportStatus writeDocBookSource(odocstream & os, std::string const & filename,
337 OutputParams const & runparams_in,
338 OutputWhat output = FullSource) const;
340 ExportStatus makeLyXHTMLFile(support::FileName const & filename,
341 OutputParams const & runparams_in) const;
343 ExportStatus writeLyXHTMLSource(odocstream & os,
344 OutputParams const & runparams_in,
345 OutputWhat output = FullSource) const;
346 /// returns the main language for the buffer (document)
347 Language const * language() const;
348 /// get l10n translated to the buffers language
349 docstring const B_(std::string const & l10n) const;
353 /// return true if the main lyx file does not need saving
354 bool isClean() const;
356 bool isDepClean(std::string const & name) const;
358 /// Whether or not disk file has been externally modified. Uses a checksum
359 /// which is accurate but slow, which can be a problem when it is frequently
360 /// used, or used for a large file on a slow (network) file system.
361 bool isChecksumModified() const;
363 /// Flag set by the FileSystemWatcher.
364 /// Fast but (not so) inaccurate, can be cleared by the user.
365 bool notifiesExternalModification() const;
366 void clearExternalModification() const;
368 /// mark the main lyx file as not needing saving
369 void markClean() const;
372 void markDepClean(std::string const & name);
375 void setUnnamed(bool flag = true);
377 /// Whether or not a filename has been assigned to this buffer
378 bool isUnnamed() const;
380 /// Whether or not this buffer is internal.
382 /// An internal buffer does not contain a real document, but some auxiliary text segment.
383 /// It is not associated with a filename, it is never saved, thus it does not need to be
384 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
385 bool isInternal() const;
387 void setInternal(bool flag);
389 /// Mark this buffer as dirty.
392 /// Returns the buffer's filename. It is always an absolute path.
393 support::FileName fileName() const;
395 /// Returns the buffer's filename. It is always an absolute path.
396 std::string absFileName() const;
398 /// Returns the path where the buffer lives.
399 /// It is always an absolute path.
400 std::string filePath() const;
402 /** Contructs a file name of a referenced file (child doc, included graphics etc).
403 * Absolute names are returned as is. If the name is relative, it is
404 * interpreted relative to filePath() if the file exists, otherwise
405 * relative to the original path where the document was last saved.
406 * The original path may be different from filePath() if the document was
407 * later manually moved to a different location.
409 support::DocFileName getReferencedFileName(std::string const & fn) const;
411 /// Format a file name for LaTeX output (absolute or relative or filename only,
412 /// depending on file and context)
413 std::string const prepareFileNameForLaTeX(std::string const &,
414 std::string const &, bool nice) const;
416 /** Returns a vector of bibliography (*.bib) file paths suitable for the
417 * output in the respective BibTeX/Biblatex macro
419 std::vector<docstring> const prepareBibFilePaths(OutputParams const &,
420 support::FileNamePairList const bibfilelist,
421 bool const extension = true) const;
423 /** Returns the path where a local layout file lives.
424 * An empty string is returned for standard system and user layouts.
425 * If possible, it is always relative to the buffer path.
427 std::string layoutPos() const;
429 /** Set the path to a local layout file.
430 * This must be an absolute path but, if possible, it is always
431 * stored as relative to the buffer path.
433 void setLayoutPos(std::string const & path);
435 /** A transformed version of the file name, adequate for LaTeX.
436 \param no_path optional if \c true then the path is stripped.
438 std::string latexName(bool no_path = true) const;
440 /// Get the name and type of the log.
441 std::string logName(LogType * type = 0) const;
443 /// Set document's parent Buffer.
444 void setParent(Buffer const *);
445 Buffer const * parent() const;
447 /** Get the document's master (or \c this if this is not a
450 Buffer const * masterBuffer() const;
452 /// \return true if \p child is a child of this \c Buffer.
453 bool isChild(Buffer * child) const;
455 /// \return true if this \c Buffer has children
456 bool hasChildren() const;
458 /// \return a list of the direct children of this Buffer.
459 /// this list has no duplicates and is in the order in which
460 /// the children appear.
461 ListOfBuffers getChildren() const;
463 /// \return a list of all descendents of this Buffer (children,
464 /// grandchildren, etc). this list has no duplicates and is in
465 /// the order in which the children appear.
466 ListOfBuffers getDescendents() const;
468 /// Collect all relative buffers, in the order in which they appear.
469 /// I.e., the "root" Buffer is first, then its first child, then any
470 /// of its children, etc. However, there are no duplicates in this
472 /// This is "stable", too, in the sense that it returns the same
473 /// thing from whichever Buffer it is called.
474 ListOfBuffers allRelatives() const;
476 /// Is buffer read-only? True if it has either the read-only flag or the
477 /// externally modified flag.
478 bool isReadonly() const;
480 /// Does the buffer have the read-only flag?
481 bool hasReadonlyFlag() const;
483 /// Set buffer read-only flag
484 void setReadonly(bool flag = true);
486 /** Validate a buffer for LaTeX.
487 This validates the buffer, and returns a struct for use by
488 #makeLaTeX# and others. Its main use is to figure out what
489 commands and packages need to be included in the LaTeX file.
490 It (should) also check that the needed constructs are there
491 (i.e. that the \refs points to coresponding \labels). It
492 should perhaps inset "error" insets to help the user correct
495 void validate(LaTeXFeatures &) const;
497 /// Bibliography information is cached in the Buffer, so we do not
498 /// have to check or read things over and over.
499 /// The cache exists only in the master buffer. When it is updated,
500 /// the children add their information to the master's cache.
501 /// Calling this method invalidates the cache and so requires a
503 void invalidateBibinfoCache() const;
504 /// Updates the cached bibliography information, checking first to see
505 /// whether the cache is valid. If so, we do nothing. If not, then we
506 /// reload all the BibTeX info.
507 /// Note that this operates on the master document.
508 void reloadBibInfoCache() const;
509 /// \return the bibliography information for this buffer's master,
510 /// or just for it, if it isn't a child.
511 BiblioInfo const & masterBibInfo() const;
512 /// \return this buffer's bibliography information
513 BiblioInfo const & bibInfo() const;
514 /// collect bibliography info from the various insets in this buffer.
515 void collectBibKeys(support::FileNameList &) const;
516 /// add some BiblioInfo to our cache
517 void addBiblioInfo(BiblioInfo const & bi) const;
518 /// add a single piece of bibliography info to our cache
519 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
521 void makeCitationLabels() const;
523 void invalidateCiteLabels() const;
525 bool citeLabelsValid() const;
527 void getLabelList(std::vector<docstring> &) const;
529 /// This removes the .aux and .bbl files from the temp dir.
530 void removeBiblioTempFiles() const;
533 void changeLanguage(Language const * from, Language const * to);
536 bool isMultiLingual() const;
538 std::set<Language const *> getLanguages() const;
541 BufferParams & params();
542 BufferParams const & params() const;
544 BufferParams const & masterParams() const;
546 /** The list of paragraphs.
547 This is a linked list of paragraph, this list holds the
548 whole contents of the document.
550 ParagraphList & paragraphs();
551 ParagraphList const & paragraphs() const;
553 /// LyX version control object.
555 LyXVC const & lyxvc() const;
557 /// Where to put temporary files.
558 std::string const temppath() const;
560 /// Used when typesetting to place errorboxes.
561 TexRow const & texrow() const;
565 ParIterator par_iterator_begin();
567 ParConstIterator par_iterator_begin() const;
569 ParIterator par_iterator_end();
571 ParConstIterator par_iterator_end() const;
573 // Position of the child buffer where it appears first in the master.
574 DocIterator firstChildPosition(Buffer const * child);
576 /** \returns true only when the file is fully loaded.
577 * Used to prevent the premature generation of previews
578 * and by the citation inset.
580 bool isFullyLoaded() const;
581 /// Set by buffer_funcs' newFile.
582 void setFullyLoaded(bool);
584 /// FIXME: Needed by RenderPreview.
585 graphics::PreviewLoader * loader() const;
586 /// Update the LaTeX preview snippets associated with this buffer
587 void updatePreviews() const;
588 /// Remove any previewed LaTeX snippets associated with this buffer
589 void removePreviews() const;
591 graphics::Cache & graphicsCache() const;
593 /// Our main text (inside the top InsetText)
596 /// Our top InsetText
597 Inset & inset() const;
602 /// Collect macro definitions in paragraphs
603 void updateMacros() const;
604 /// Iterate through the whole buffer and try to resolve macros
605 void updateMacroInstances(UpdateType) const;
607 /// List macro names of this buffer, the parent and the children
608 void listMacroNames(MacroNameSet & macros) const;
609 /// Collect macros of the parent and its children in front of this buffer.
610 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
612 /// Return macro defined before pos (or in the master buffer)
613 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
614 /// Return macro defined anywhere in the buffer (or in the master buffer)
615 MacroData const * getMacro(docstring const & name, bool global = true) const;
616 /// Return macro defined before the inclusion of the child
617 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
619 /// Collect user macro names at loading time
620 typedef std::set<docstring> UserMacroSet;
621 mutable UserMacroSet usermacros;
623 /// Replace the inset contents for insets which InsetCode is equal
624 /// to the passed \p inset_code.
625 void changeRefsIfUnique(docstring const & from, docstring const & to);
627 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
628 /// including preamble
629 /// returns nullptr if Id to Row conversion is unsupported
630 unique_ptr<TexRow> getSourceCode(odocstream & os,
631 std::string const & format, pit_type par_begin,
632 pit_type par_end, OutputWhat output, bool master) const;
634 /// Access to error list.
635 /// This method is used only for GUI visualisation of Buffer related
636 /// errors (like parsing or LateX compilation). This method is const
637 /// because modifying the returned ErrorList does not touch the document
639 ErrorList & errorList(std::string const & type) const;
642 /// This is useful only for screen visualisation of the Buffer. This
643 /// method is const because modifying this backend does not touch
644 /// the document contents.
645 TocBackend & tocBackend() const;
650 /// This function is called when the buffer is changed.
651 void changed(bool update_metrics) const;
653 void setChild(DocIterator const & dit, Buffer * child);
655 void updateTocItem(std::string const &, DocIterator const &) const;
656 /// This function is called when the buffer structure is changed.
657 void structureChanged() const;
658 /// This function is called when some parsing error shows up.
659 void errors(std::string const & err, bool from_master = false) const;
660 /// This function is called when the buffer busy status change.
661 void setBusy(bool on) const;
662 /// Update window titles of all users.
663 void updateTitles() const;
664 /// Reset autosave timers for all users.
665 void resetAutosaveTimers() const;
667 void message(docstring const & msg) const;
670 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
672 bool hasGuiDelegate() const;
675 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
676 /// Export buffer to format \p format and open the result in a suitable viewer.
677 /// Note: This has nothing to do with preview of graphics or math formulas.
678 ExportStatus preview(std::string const & format) const;
679 /// true if there was a previous preview this session of this buffer and
680 /// there was an error on the previous preview of this buffer.
681 bool lastPreviewError() const;
685 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
686 std::string & result_file) const;
687 /// target is a format name optionally followed by a space
688 /// and a destination file-name
689 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
690 bool includeall, std::string & result_file) const;
692 ExportStatus preview(std::string const & format, bool includeall) const;
694 void setMathFlavor(OutputParams & op) const;
698 bool isExporting() const;
701 typedef std::vector<std::pair<Inset *, ParIterator> > References;
703 References const & references(docstring const & label) const;
705 void addReference(docstring const & label, Inset * inset, ParIterator it);
707 void clearReferenceCache() const;
709 void setInsetLabel(docstring const & label, InsetLabel const * il);
711 InsetLabel const * insetLabel(docstring const & label) const;
713 /// return a list of all used branches (also in children)
714 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
716 /// Updates screen labels and some other information associated with
717 /// insets and paragraphs. Actually, it's more like a general "recurse
718 /// through the Buffer" routine, that visits all the insets and paragraphs.
719 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
720 /// \param scope: whether to start with the master document or just
722 /// \param output: whether we are preparing for output.
723 void updateBuffer(UpdateScope scope, UpdateType utype) const;
725 void updateBuffer(ParIterator & parit, UpdateType utype) const;
727 /// Spellcheck starting from \p from.
728 /// \p from initial position, will then points to the next misspelled
730 /// \p to will points to the end of the next misspelled word.
731 /// \p word_lang will contain the found misspelled word.
732 /// \return progress if a new word was found.
733 int spellCheck(DocIterator & from, DocIterator & to,
734 WordLangTuple & word_lang, docstring_list & suggestions) const;
736 void checkChildBuffers();
738 void checkMasterBuffer();
740 /// If the document is being saved to a new location and the named file
741 /// exists at the old location, return its updated path relative to the
742 /// new buffer path if possible, otherwise return its absolute path.
743 /// In all other cases, this is a no-op and name is returned unchanged.
744 /// If a non-empty ext is given, the existence of name.ext is checked
745 /// but the returned path will not contain this extension.
746 /// Similarly, when loading a document that was moved from the location
747 /// where it was saved, return the correct path relative to the new
749 std::string includedFilePath(std::string const & name,
750 std::string const & ext = empty_string()) const;
752 /// compute statistics between \p from and \p to
753 /// \p from initial position
754 /// \p to points to the end position
755 /// \p skipNoOutput if notes etc. should be ignored
756 void updateStatistics(DocIterator & from, DocIterator & to,
757 bool skipNoOutput = true) const;
758 /// statistics accessor functions
759 int wordCount() const;
760 int charCount(bool with_blanks) const;
762 // this is const because it does not modify the buffer's real contents,
763 // only the mutable flag.
764 void setChangesPresent(bool) const;
765 bool areChangesPresent() const;
766 void updateChangesPresent() const;
768 void registerBibfiles(support::FileNamePairList const & bf) const;
771 friend class MarkAsExporting;
772 /// mark the buffer as busy exporting something, or not
773 void setExportStatus(bool e) const;
776 References & getReferenceCache(docstring const & label);
777 /// Change name of buffer. Updates "read-only" flag.
778 void setFileName(support::FileName const & fname);
780 void getLanguages(std::set<Language const *> &) const;
781 /// Checks whether any of the referenced bibfiles have changed since the
782 /// last time we loaded the cache. Note that this does NOT update the
783 /// cached information.
784 void checkIfBibInfoCacheIsValid() const;
785 /// Return the list with all bibfiles in use (including bibfiles
786 /// of loaded child documents).
787 support::FileNamePairList const &
788 getBibfiles(UpdateScope scope = UpdateMaster) const;
790 void collectChildren(ListOfBuffers & children, bool grand_children) const;
793 Buffer(Buffer const &);
794 void operator=(Buffer const &);
796 /// Use the Pimpl idiom to hide the internals.
798 /// The pointer never changes although *pimpl_'s contents may.
803 /// Helper class, to guarantee that the export status
804 /// gets reset properly. To use, simply create a local variable:
805 /// MarkAsExporting mex(bufptr);
806 /// and leave the rest to us.
807 class MarkAsExporting {
809 MarkAsExporting(Buffer const * buf) : buf_(buf)
811 buf_->setExportStatus(true);
815 buf_->setExportStatus(false);
818 Buffer const * const buf_;