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"
16 #include "OutputParams.h"
18 #include "support/strfwd.h"
19 #include "support/types.h"
54 class ParConstIterator;
64 class GuiBufferDelegate;
65 class WorkAreaManager;
79 typedef std::list<Buffer *> ListOfBuffers;
80 /// a list of Buffers we cloned
81 typedef std::set<Buffer *> CloneList;
84 /** The buffer object.
85 * This is the buffer object. It contains all the information about
86 * a document loaded into LyX.
87 * The buffer object owns the Text (wrapped in an InsetText), which
88 * contains the individual paragraphs of the document.
91 * I am not sure if the class is complete or
92 * minimal, probably not.
93 * \author Lars Gullik Bjønnes
96 class MarkAsExporting;
100 /// What type of log will \c getLogName() return?
102 latexlog, ///< LaTeX log
103 buildlog ///< Literate build log
106 /// Result of \c readFile()
116 ReadEmergencyFailure,
133 ExportNoPathToFormat,
134 ExportTexPathHasSpaces,
135 ExportConverterError,
137 // Implies ExportSuccess.
139 // The exported file exists but there was an error when opening
144 /// Method to check if a file is externally modified, used by
145 /// isExternallyModified()
147 * timestamp is fast but inaccurate. For example, the granularity
148 * of timestamp on a FAT filesystem is 2 seconds. Also, various operations
149 * may touch the timestamp of a file even when its content is unchanged.
151 * checksum is accurate but slow, which can be a problem when it is
152 * frequently used, or used for a large file on a slow (network) file
155 * FIXME: replace this method with support/FileMonitor.
158 checksum_method, ///< Use file checksum
159 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
169 explicit Buffer(std::string const & file, bool readonly = false,
170 Buffer const * cloned_buffer = 0);
175 /// Clones the entire structure of which this Buffer is part, starting
176 /// with the master and cloning all the children, too.
177 Buffer * cloneFromMaster() const;
178 /// Just clones this single Buffer. For autosave.
179 Buffer * cloneBufferOnly() const;
181 bool isClone() const;
183 /** High-level interface to buffer functionality.
184 This function parses a command string and executes it.
186 void dispatch(std::string const & command, DispatchResult & result);
188 /// Maybe we know the function already by number...
189 void dispatch(FuncRequest const & func, DispatchResult & result);
191 /// Can this function be exectued?
192 /// \return true if we made a decision
193 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
196 DocIterator getParFromID(int id) const;
197 /// do we have a paragraph with this id?
198 bool hasParWithID(int id) const;
201 frontend::WorkAreaManager & workAreaManager() const;
204 Takes care of auto-save files and backup file if requested.
205 Returns \c true if the save is successful, \c false otherwise.
208 /// Renames and saves the buffer
209 bool saveAs(support::FileName const & fn);
211 /// Write document to stream. Returns \c false if unsuccessful.
212 bool write(std::ostream &) const;
213 /// Write file. Returns \c false if unsuccessful.
214 bool writeFile(support::FileName const &) const;
216 /// \name Functions involved in reading files/strings.
218 /// Loads the LyX file into the buffer. This function
219 /// tries to extract the file from version control if it
220 /// cannot be found. If it can be found, it will try to
221 /// read an emergency save file or an autosave file.
222 /// \sa loadThisLyXFile
223 ReadStatus loadLyXFile();
224 /// Loads the LyX file \c fn into the buffer. If you want
225 /// to check for files in a version control container,
226 /// emergency or autosave files, one should use \c loadLyXFile.
228 ReadStatus loadThisLyXFile(support::FileName const & fn);
229 /// import a new document from a string
230 bool importString(std::string const &, docstring const &, ErrorList &);
231 /// import a new file
232 bool importFile(std::string const &, support::FileName const &, ErrorList &);
233 /// read a new document from a string
234 bool readString(std::string const &);
235 /// Reloads the LyX file
237 //FIXME: The following function should be private
239 /// read the header, returns number of unknown tokens
240 int readHeader(Lexer & lex);
242 double fontScalingFactor() const;
246 typedef std::map<Buffer const *, Buffer *> BufferMap;
248 void cloneWithChildren(BufferMap &, CloneList *) const;
249 /// save timestamp and checksum of the given file.
250 void saveCheckSum() const;
252 ReadStatus readFile(support::FileName const & fn);
253 /// Reads a file without header.
254 /// \param par if != 0 insert the file.
255 /// \return \c true if file is not completely read.
256 bool readDocument(Lexer &);
257 /// Try to extract the file from a version control container
258 /// before reading if the file cannot be found.
259 /// \sa LyXVC::file_not_found_hook
260 ReadStatus extractFromVC();
261 /// Reads the first tag of a LyX File and
262 /// returns the file format number.
263 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
264 int & file_format) const;
265 /// Convert the LyX file to the LYX_FORMAT using
266 /// the lyx2lyx script and returns the filename
267 /// of the temporary file to be read
268 ReadStatus convertLyXFormat(support::FileName const & fn,
269 support::FileName & tmpfile, int from_format);
270 /// get appropriate name for backing up files from older versions
271 std::string getBackupName() const;
275 /// \name Functions involved in autosave and emergency files.
277 /// Save an autosave file to #filename.lyx#
278 bool autoSave() const;
279 /// save emergency file
280 /// \return a status message towards the user.
281 docstring emergencyWrite();
283 //FIXME:The following function should be private
286 void removeAutosaveFile() const;
289 /// Try to load an autosave file associated to \c fn.
290 ReadStatus loadAutosave();
291 /// Try to load an emergency file associated to \c fn.
292 ReadStatus loadEmergency();
293 /// Get the filename of the emergency file associated with the Buffer
294 support::FileName getEmergencyFileName() const;
295 /// Get the filename of the autosave file associated with the Buffer
296 support::FileName getAutosaveFileName() const;
298 void moveAutosaveFile(support::FileName const & old) const;
302 /// Fill in the ErrorList with the TeXErrors
303 void bufferErrors(TeXErrors const &, ErrorList &) const;
313 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
314 bool makeLaTeXFile(support::FileName const & filename,
315 std::string const & original_path,
316 OutputParams const &,
317 OutputWhat output = FullSource) const;
318 /** Export the buffer to LaTeX.
319 If \p os is a file stream, and params().inputenc is "auto" or
320 "default", and the buffer contains text in different languages
321 with more than one encoding, then this method will change the
322 encoding associated to \p os. Therefore you must not call this
323 method with a string stream if the output is supposed to go to a
326 otexstream os(ofs, texrow);
327 ofs.open("test.tex");
328 writeLaTeXSource(os, ...);
330 \endcode is NOT equivalent to \code
331 odocstringstream oss;
332 otexstream os(oss, texrow);
333 writeLaTeXSource(os, ...);
335 ofs.open("test.tex");
340 void writeLaTeXSource(otexstream & os,
341 std::string const & original_path,
342 OutputParams const &,
343 OutputWhat output = FullSource) const;
345 void makeDocBookFile(support::FileName const & filename,
346 OutputParams const & runparams_in,
347 OutputWhat output = FullSource) const;
349 void writeDocBookSource(odocstream & os, std::string const & filename,
350 OutputParams const & runparams_in,
351 OutputWhat output = FullSource) const;
353 void makeLyXHTMLFile(support::FileName const & filename,
354 OutputParams const & runparams_in) const;
356 void writeLyXHTMLSource(odocstream & os,
357 OutputParams const & runparams_in,
358 OutputWhat output = FullSource) const;
359 /// returns the main language for the buffer (document)
360 Language const * language() const;
361 /// get l10n translated to the buffers language
362 docstring const B_(std::string const & l10n) const;
366 /// return true if the main lyx file does not need saving
367 bool isClean() const;
369 bool isDepClean(std::string const & name) const;
371 /// whether or not disk file has been externally modified
372 bool isExternallyModified(CheckMethod method) const;
374 /// mark the main lyx file as not needing saving
375 void markClean() const;
378 void markDepClean(std::string const & name);
381 void setUnnamed(bool flag = true);
383 /// Whether or not a filename has been assigned to this buffer
384 bool isUnnamed() const;
386 /// Whether or not this buffer is internal.
388 /// An internal buffer does not contain a real document, but some auxiliary text segment.
389 /// It is not associated with a filename, it is never saved, thus it does not need to be
390 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
391 bool isInternal() const;
393 void setInternal(bool flag);
395 /// Mark this buffer as dirty.
398 /// Returns the buffer's filename. It is always an absolute path.
399 support::FileName fileName() const;
401 /// Returns the buffer's filename. It is always an absolute path.
402 std::string absFileName() const;
404 /// Returns the path where the buffer lives.
405 /// It is always an absolute path.
406 std::string filePath() const;
408 /** Returns the path where the document was last saved.
409 * It may be different from filePath() if the document was later
410 * manually moved to a different location.
411 * It is always an absolute path.
413 std::string originFilePath() const;
415 /** Returns the path where a local layout file lives.
416 * An empty string is returned for standard system and user layouts.
417 * If possible, it is always relative to the buffer path.
419 std::string layoutPos() const;
421 /** Set the path to a local layout file.
422 * This must be an absolute path but, if possible, it is always
423 * stored as relative to the buffer path.
425 void setLayoutPos(std::string const & path);
427 /** A transformed version of the file name, adequate for LaTeX.
428 \param no_path optional if \c true then the path is stripped.
430 std::string latexName(bool no_path = true) const;
432 /// Get the name and type of the log.
433 std::string logName(LogType * type = 0) const;
435 /// Set document's parent Buffer.
436 void setParent(Buffer const *);
437 Buffer const * parent() const;
439 /** Get the document's master (or \c this if this is not a
442 Buffer const * masterBuffer() const;
444 /// \return true if \p child is a child of this \c Buffer.
445 bool isChild(Buffer * child) const;
447 /// \return true if this \c Buffer has children
448 bool hasChildren() const;
450 /// \return a list of the direct children of this Buffer.
451 /// this list has no duplicates and is in the order in which
452 /// the children appear.
453 ListOfBuffers getChildren() const;
455 /// \return a list of all descendents of this Buffer (children,
456 /// grandchildren, etc). this list has no duplicates and is in
457 /// the order in which the children appear.
458 ListOfBuffers getDescendents() const;
460 /// Collect all relative buffers, in the order in which they appear.
461 /// I.e., the "root" Buffer is first, then its first child, then any
462 /// of its children, etc. However, there are no duplicates in this
464 /// This is "stable", too, in the sense that it returns the same
465 /// thing from whichever Buffer it is called.
466 ListOfBuffers allRelatives() const;
468 /// Is buffer read-only?
469 bool isReadonly() const;
471 /// Set buffer read-only flag
472 void setReadonly(bool flag = true);
474 /** Validate a buffer for LaTeX.
475 This validates the buffer, and returns a struct for use by
476 #makeLaTeX# and others. Its main use is to figure out what
477 commands and packages need to be included in the LaTeX file.
478 It (should) also check that the needed constructs are there
479 (i.e. that the \refs points to coresponding \labels). It
480 should perhaps inset "error" insets to help the user correct
483 void validate(LaTeXFeatures &) const;
485 /// Reference information is cached in the Buffer, so we do not
486 /// have to check or read things over and over.
488 /// There are two caches.
490 /// One is a cache of the BibTeX files from which reference info is
491 /// being gathered. This cache is PER BUFFER, and the cache for the
492 /// master essentially includes the cache for its children. This gets
493 /// invalidated when an InsetBibtex is created, deleted, or modified.
495 /// The other is a cache of the reference information itself. This
496 /// exists only in the master buffer, and when it needs to be updated,
497 /// the children add their information to the master's cache.
499 /// Calling this method invalidates the cache and so requires a
501 void invalidateBibinfoCache() const;
502 /// This invalidates the cache of files we need to check.
503 void invalidateBibfileCache() 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 /// collect bibliography info from the various insets in this buffer.
513 void collectBibKeys() const;
514 /// add some BiblioInfo to our cache
515 void addBiblioInfo(BiblioInfo const & bi) const;
516 /// add a single piece of bibliography info to our cache
517 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
519 void makeCitationLabels() const;
521 bool citeLabelsValid() const;
523 void getLabelList(std::vector<docstring> &) const;
525 /// This removes the .aux and .bbl files from the temp dir.
526 void removeBiblioTempFiles() const;
529 void changeLanguage(Language const * from, Language const * to);
532 bool isMultiLingual() const;
534 std::set<Language const *> getLanguages() const;
537 BufferParams & params();
538 BufferParams const & params() const;
540 BufferParams const & masterParams() const;
542 /** The list of paragraphs.
543 This is a linked list of paragraph, this list holds the
544 whole contents of the document.
546 ParagraphList & paragraphs();
547 ParagraphList const & paragraphs() const;
549 /// LyX version control object.
551 LyXVC const & lyxvc() const;
553 /// Where to put temporary files.
554 std::string const temppath() const;
556 /// Used when typesetting to place errorboxes.
557 TexRow const & texrow() const;
561 ParIterator par_iterator_begin();
563 ParConstIterator par_iterator_begin() const;
565 ParIterator par_iterator_end();
567 ParConstIterator par_iterator_end() const;
569 // Position of the child buffer where it appears first in the master.
570 DocIterator firstChildPosition(Buffer const * child);
572 /** \returns true only when the file is fully loaded.
573 * Used to prevent the premature generation of previews
574 * and by the citation inset.
576 bool isFullyLoaded() const;
577 /// Set by buffer_funcs' newFile.
578 void setFullyLoaded(bool);
580 /// FIXME: Needed by RenderPreview.
581 graphics::PreviewLoader * loader() const;
582 /// Update the LaTeX preview snippets associated with this buffer
583 void updatePreviews() const;
584 /// Remove any previewed LaTeX snippets associated with this buffer
585 void removePreviews() const;
587 /// Our main text (inside the top InsetText)
590 /// Our top InsetText
591 Inset & inset() const;
596 /// Collect macro definitions in paragraphs
597 void updateMacros() const;
598 /// Iterate through the whole buffer and try to resolve macros
599 void updateMacroInstances(UpdateType) const;
601 /// List macro names of this buffer, the parent and the children
602 void listMacroNames(MacroNameSet & macros) const;
603 /// Collect macros of the parent and its children in front of this buffer.
604 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
606 /// Return macro defined before pos (or in the master buffer)
607 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
608 /// Return macro defined anywhere in the buffer (or in the master buffer)
609 MacroData const * getMacro(docstring const & name, bool global = true) const;
610 /// Return macro defined before the inclusion of the child
611 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
613 /// Collect user macro names at loading time
614 typedef std::set<docstring> UserMacroSet;
615 mutable UserMacroSet usermacros;
617 /// Replace the inset contents for insets which InsetCode is equal
618 /// to the passed \p inset_code.
619 void changeRefsIfUnique(docstring const & from, docstring const & to);
621 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
622 /// including preamble
623 /// returns NULL if Id to Row conversion is unsupported
624 std::auto_ptr<TexRow> getSourceCode(odocstream & os,
625 std::string const & format, pit_type par_begin,
626 pit_type par_end, OutputWhat output, bool master) const;
628 /// Access to error list.
629 /// This method is used only for GUI visualisation of Buffer related
630 /// errors (like parsing or LateX compilation). This method is const
631 /// because modifying the returned ErrorList does not touch the document
633 ErrorList & errorList(std::string const & type) const;
636 /// This is useful only for screen visualisation of the Buffer. This
637 /// method is const because modifying this backend does not touch
638 /// the document contents.
639 TocBackend & tocBackend() const;
644 /// This function is called when the buffer is changed.
645 void changed(bool update_metrics) const;
647 void setChild(DocIterator const & dit, Buffer * child);
649 void updateTocItem(std::string const &, DocIterator const &) const;
650 /// This function is called when the buffer structure is changed.
651 void structureChanged() const;
652 /// This function is called when some parsing error shows up.
653 void errors(std::string const & err, bool from_master = false) const;
654 /// This function is called when the buffer busy status change.
655 void setBusy(bool on) const;
656 /// Update window titles of all users.
657 void updateTitles() const;
658 /// Reset autosave timers for all users.
659 void resetAutosaveTimers() const;
661 void message(docstring const & msg) const;
664 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
666 bool hasGuiDelegate() const;
669 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
670 /// Export buffer to format \p format and open the result in a suitable viewer.
671 /// Note: This has nothing to do with preview of graphics or math formulas.
672 ExportStatus preview(std::string const & format) const;
673 /// true if there was a previous preview this session of this buffer and
674 /// there was an error on the previous preview of this buffer.
675 bool lastPreviewError() const;
679 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
680 std::string & result_file) const;
681 /// target is a format name optionally followed by a space
682 /// and a destination file-name
683 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
684 bool includeall, std::string & result_file) const;
686 ExportStatus preview(std::string const & format, bool includeall = false) const;
688 void setMathFlavor(OutputParams & op) const;
692 bool isExporting() const;
695 typedef std::vector<std::pair<Inset *, ParIterator> > References;
697 References const & references(docstring const & label) const;
699 void addReference(docstring const & label, Inset * inset, ParIterator it);
701 void clearReferenceCache() const;
703 void setInsetLabel(docstring const & label, InsetLabel const * il);
705 InsetLabel const * insetLabel(docstring const & label) const;
707 /// return a list of all used branches (also in children)
708 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
710 /// sets the buffer_ member for every inset in this buffer.
711 // FIXME This really shouldn't be needed, but at the moment it's not
712 // clear how to do it just for the individual pieces we need.
713 void setBuffersForInsets() const;
714 /// Updates screen labels and some other information associated with
715 /// insets and paragraphs. Actually, it's more like a general "recurse
716 /// through the Buffer" routine, that visits all the insets and paragraphs.
717 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
718 /// \param scope: whether to start with the master document or just
720 /// \param output: whether we are preparing for output.
721 void updateBuffer(UpdateScope scope, UpdateType utype) const;
723 void updateBuffer(ParIterator & parit, UpdateType utype) const;
725 /// Spellcheck starting from \p from.
726 /// \p from initial position, will then points to the next misspelled
728 /// \p to will points to the end of the next misspelled word.
729 /// \p word_lang will contain the found misspelled word.
730 /// \return progress if a new word was found.
731 int spellCheck(DocIterator & from, DocIterator & to,
732 WordLangTuple & word_lang, docstring_list & suggestions) const;
734 void checkChildBuffers();
736 void checkMasterBuffer();
738 /// If the document is being saved to a new location and the named file
739 /// exists at the old location, return its updated path relative to the
740 /// new buffer path if possible, otherwise return its absolute path.
741 /// In all other cases, this is a no-op and name is returned unchanged.
742 /// If a non-empty ext is given, the existence of name.ext is checked
743 /// but the returned path will not contain this extension.
744 /// Similarly, when loading a document that was moved from the location
745 /// where it was saved, return the correct path relative to the new
747 std::string includedFilePath(std::string const & name,
748 std::string const & ext = empty_string()) const;
750 /// compute statistics between \p from and \p to
751 /// \p from initial position
752 /// \p to points to the end position
753 /// \p skipNoOutput if notes etc. should be ignored
754 void updateStatistics(DocIterator & from, DocIterator & to,
755 bool skipNoOutput = true) const;
756 /// statistics accessor functions
757 int wordCount() const;
758 int charCount(bool with_blanks) const;
761 friend class MarkAsExporting;
762 /// mark the buffer as busy exporting something, or not
763 void setExportStatus(bool e) const;
766 References & getReferenceCache(docstring const & label);
767 /// Change name of buffer. Updates "read-only" flag.
768 void setFileName(support::FileName const & fname);
770 void getLanguages(std::set<Language const *> &) const;
771 /// Checks whether any of the referenced bibfiles have changed since the
772 /// last time we loaded the cache. Note that this does NOT update the
773 /// cached information.
774 void checkIfBibInfoCacheIsValid() const;
775 /// Update the list of all bibfiles in use (including bibfiles
776 /// of loaded child documents).
777 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
778 /// Return the list with all bibfiles in use (including bibfiles
779 /// of loaded child documents).
780 support::FileNameList const &
781 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
783 void collectChildren(ListOfBuffers & children, bool grand_children) const;
786 Buffer(Buffer const &);
787 void operator=(Buffer const &);
789 /// Use the Pimpl idiom to hide the internals.
791 /// The pointer never changes although *pimpl_'s contents may.
796 /// Helper class, to guarantee that the export status
797 /// gets reset properly. To use, simply create a local variable:
798 /// MarkAsExporting mex(bufptr);
799 /// and leave the rest to us.
800 class MarkAsExporting {
802 MarkAsExporting(Buffer const * buf) : buf_(buf)
804 buf_->setExportStatus(true);
808 buf_->setExportStatus(false);
811 Buffer const * const buf_;