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 "insets/InsetCode.h"
20 #include "support/strfwd.h"
21 #include "support/types.h"
56 class ParConstIterator;
66 class GuiBufferDelegate;
67 class WorkAreaManager;
81 typedef std::list<Buffer *> ListOfBuffers;
82 /// a list of Buffers we cloned
83 typedef std::set<Buffer *> CloneList;
86 /** The buffer object.
87 * This is the buffer object. It contains all the informations about
88 * a document loaded into LyX.
89 * The buffer object owns the Text (wrapped in an InsetText), which
90 * contains the individual paragraphs of the document.
93 * I am not sure if the class is complete or
94 * minimal, probably not.
95 * \author Lars Gullik Bjønnes
99 /// What type of log will \c getLogName() return?
101 latexlog, ///< LaTeX log
102 buildlog ///< Literate build log
105 /// Result of \c readFile()
115 ReadEmergencyFailure,
132 ExportNoPathToFormat,
133 ExportTexPathHasSpaces,
134 ExportConverterError,
140 /// Method to check if a file is externally modified, used by
141 /// isExternallyModified()
143 * timestamp is fast but inaccurate. For example, the granularity
144 * of timestamp on a FAT filesystem is 2 second. Also, various operations
145 * may touch the timestamp of a file even when its content is unchanged.
147 * checksum is accurate but slow, which can be a problem when it is
148 * frequently used, or used for a large file on a slow (network) file
151 * FIXME: replace this method with support/FileMonitor.
154 checksum_method, ///< Use file checksum
155 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
165 explicit Buffer(std::string const & file, bool readonly = false,
166 Buffer const * cloned_buffer = 0);
172 Buffer * clone() const;
174 bool isClone() const;
176 /** High-level interface to buffer functionality.
177 This function parses a command string and executes it.
179 void dispatch(std::string const & command, DispatchResult & result);
181 /// Maybe we know the function already by number...
182 void dispatch(FuncRequest const & func, DispatchResult & result);
184 /// Can this function be exectued?
185 /// \return true if we made a decision
186 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
189 DocIterator getParFromID(int id) const;
190 /// do we have a paragraph with this id?
191 bool hasParWithID(int id) const;
194 frontend::WorkAreaManager & workAreaManager() const;
197 Takes care of auto-save files and backup file if requested.
198 Returns \c true if the save is successful, \c false otherwise.
201 /// Renames and saves the buffer
202 bool saveAs(support::FileName const & fn);
204 /// Write document to stream. Returns \c false if unsuccessful.
205 bool write(std::ostream &) const;
206 /// Write file. Returns \c false if unsuccessful.
207 bool writeFile(support::FileName const &) const;
209 /// \name Functions involved in reading files/strings.
211 /// Loads the LyX file into the buffer. This function
212 /// tries to extract the file from version control if it
213 /// cannot be found. If it can be found, it will try to
214 /// read an emergency save file or an autosave file.
215 /// \sa loadThisLyXFile
216 ReadStatus loadLyXFile();
217 /// Loads the LyX file \c fn into the buffer. If you want
218 /// to check for files in a version control container,
219 /// emergency or autosave files, one should use \c loadLyXFile.
221 ReadStatus loadThisLyXFile(support::FileName const & fn);
222 /// read a new document from a string
223 bool readString(std::string const &);
224 /// Reloads the LyX file
226 //FIXME: The following function should be private
228 /// read the header, returns number of unknown tokens
229 int readHeader(Lexer & lex);
233 typedef std::map<Buffer const *, Buffer *> BufferMap;
235 void clone(BufferMap &, CloneList *) const;
236 /// save timestamp and 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. This is only
246 /// implemented for RCS.
247 /// \sa LyXVC::file_not_found_hook
248 ReadStatus extractFromVC();
249 /// Reads the first tag of a LyX File and
250 /// returns the file format number.
251 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
252 int & file_format) const;
253 /// Convert the LyX file to the LYX_FORMAT using
254 /// the lyx2lyx script and returns the filename
255 /// of the temporary file to be read
256 ReadStatus convertLyXFormat(support::FileName const & fn,
257 support::FileName & tmpfile, int from_format);
261 /// \name Functions involved in autosave and emergency files.
263 /// Save an autosave file to #filename.lyx#
264 bool autoSave() const;
265 /// save emergency file
266 /// \return a status message towards the user.
267 docstring emergencyWrite();
269 //FIXME:The following function should be private
272 void removeAutosaveFile() const;
275 /// Try to load an autosave file associated to \c fn.
276 ReadStatus loadAutosave();
277 /// Try to load an emergency file associated to \c fn.
278 ReadStatus loadEmergency();
279 /// Get the filename of the emergency file associated with the Buffer
280 support::FileName getEmergencyFileName() const;
281 /// Get the filename of the autosave file associated with the Buffer
282 support::FileName getAutosaveFileName() const;
284 void moveAutosaveFile(support::FileName const & old) const;
288 /// Fill in the ErrorList with the TeXErrors
289 void bufferErrors(TeXErrors const &, ErrorList &) const;
298 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
299 bool makeLaTeXFile(support::FileName const & filename,
300 std::string const & original_path,
301 OutputParams const &,
302 OutputWhat output = FullSource) const;
303 /** Export the buffer to LaTeX.
304 If \p os is a file stream, and params().inputenc is "auto" or
305 "default", and the buffer contains text in different languages
306 with more than one encoding, then this method will change the
307 encoding associated to \p os. Therefore you must not call this
308 method with a string stream if the output is supposed to go to a
311 otexstream os(ofs, texrow);
312 ofs.open("test.tex");
313 writeLaTeXSource(os, ...);
315 \endcode is NOT equivalent to \code
316 odocstringstream oss;
317 otexstream os(oss, texrow);
318 writeLaTeXSource(os, ...);
320 ofs.open("test.tex");
325 void writeLaTeXSource(otexstream & os,
326 std::string const & original_path,
327 OutputParams const &,
328 OutputWhat output = FullSource) const;
330 void makeDocBookFile(support::FileName const & filename,
331 OutputParams const & runparams_in,
332 OutputWhat output = FullSource) const;
334 void writeDocBookSource(odocstream & os, std::string const & filename,
335 OutputParams const & runparams_in,
336 OutputWhat output = FullSource) const;
338 void makeLyXHTMLFile(support::FileName const & filename,
339 OutputParams const & runparams_in) const;
341 void writeLyXHTMLSource(odocstream & os,
342 OutputParams const & runparams_in,
343 OutputWhat output = FullSource) const;
344 /// returns the main language for the buffer (document)
345 Language const * language() const;
346 /// get l10n translated to the buffers language
347 docstring const B_(std::string const & l10n) const;
351 /// return true if the main lyx file does not need saving
352 bool isClean() const;
354 bool isDepClean(std::string const & name) const;
356 /// whether or not disk file has been externally modified
357 bool isExternallyModified(CheckMethod method) const;
359 /// mark the main lyx file as not needing saving
360 void markClean() const;
363 void markDepClean(std::string const & name);
366 void setUnnamed(bool flag = true);
368 /// Whether or not a filename has been assigned to this buffer
369 bool isUnnamed() const;
371 /// Whether or not this buffer is internal.
373 /// An internal buffer does not contain a real document, but some auxiliary text segment.
374 /// It is not associated with a filename, it is never saved, thus it does not need to be
375 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
376 bool isInternal() const;
378 /// Mark this buffer as dirty.
381 /// Returns the buffer's filename. It is always an absolute path.
382 support::FileName fileName() const;
384 /// Returns the buffer's filename. It is always an absolute path.
385 std::string absFileName() const;
387 /// Returns the the path where the buffer lives.
388 /// It is always an absolute path.
389 std::string filePath() const;
391 /** A transformed version of the file name, adequate for LaTeX.
392 \param no_path optional if \c true then the path is stripped.
394 std::string latexName(bool no_path = true) const;
396 /// Get the name and type of the log.
397 std::string logName(LogType * type = 0) const;
399 /// Set document's parent Buffer.
400 void setParent(Buffer const *);
401 Buffer const * parent() const;
403 /** Get the document's master (or \c this if this is not a
406 Buffer const * masterBuffer() const;
408 /// \return true if \p child is a child of this \c Buffer.
409 bool isChild(Buffer * child) const;
411 /// \return true if this \c Buffer has children
412 bool hasChildren() const;
414 /// \return a list of the direct children of this Buffer.
415 /// this list has no duplicates and is in the order in which
416 /// the children appear.
417 ListOfBuffers getChildren() const;
419 /// \return a list of all descendents of this Buffer (children,
420 /// grandchildren, etc). this list has no duplicates and is in
421 /// the order in which the children appear.
422 ListOfBuffers getDescendents() const;
424 /// Collect all relative buffers, in the order in which they appear.
425 /// I.e., the "root" Buffer is first, then its first child, then any
426 /// of its children, etc. However, there are no duplicates in this
428 /// This is "stable", too, in the sense that it returns the same
429 /// thing from whichever Buffer it is called.
430 ListOfBuffers allRelatives() const;
432 /// Is buffer read-only?
433 bool isReadonly() const;
435 /// Set buffer read-only flag
436 void setReadonly(bool flag = true);
438 /** Validate a buffer for LaTeX.
439 This validates the buffer, and returns a struct for use by
440 #makeLaTeX# and others. Its main use is to figure out what
441 commands and packages need to be included in the LaTeX file.
442 It (should) also check that the needed constructs are there
443 (i.e. that the \refs points to coresponding \labels). It
444 should perhaps inset "error" insets to help the user correct
447 void validate(LaTeXFeatures &) const;
449 /// Reference information is cached in the Buffer, so we do not
450 /// have to check or read things over and over.
452 /// There are two caches.
454 /// One is a cache of the BibTeX files from which reference info is
455 /// being gathered. This cache is PER BUFFER, and the cache for the
456 /// master essentially includes the cache for its children. This gets
457 /// invalidated when an InsetBibtex is created, deleted, or modified.
459 /// The other is a cache of the reference information itself. This
460 /// exists only in the master buffer, and when it needs to be updated,
461 /// the children add their information to the master's cache.
463 /// Calling this method invalidates the cache and so requires a
465 void invalidateBibinfoCache() const;
466 /// This invalidates the cache of files we need to check.
467 void invalidateBibfileCache() const;
468 /// Updates the cached bibliography information, checking first to see
469 /// whether the cache is valid. If so, we do nothing. If not, then we
470 /// reload all the BibTeX info.
471 /// Note that this operates on the master document.
472 void reloadBibInfoCache() const;
473 /// \return the bibliography information for this buffer's master,
474 /// or just for it, if it isn't a child.
475 BiblioInfo const & masterBibInfo() const;
476 /// collect bibliography info from the various insets in this buffer.
477 void collectBibKeys() const;
478 /// add some BiblioInfo to our cache
479 void addBiblioInfo(BiblioInfo const & bi) const;
480 /// add a single piece of bibliography info to our cache
481 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
483 bool citeLabelsValid() const;
485 void getLabelList(std::vector<docstring> &) const;
488 void changeLanguage(Language const * from, Language const * to);
491 bool isMultiLingual() const;
493 std::set<Language const *> getLanguages() const;
496 BufferParams & params();
497 BufferParams const & params() const;
499 /** The list of paragraphs.
500 This is a linked list of paragraph, this list holds the
501 whole contents of the document.
503 ParagraphList & paragraphs();
504 ParagraphList const & paragraphs() const;
506 /// LyX version control object.
508 LyXVC const & lyxvc() const;
510 /// Where to put temporary files.
511 std::string const temppath() const;
513 /// Used when typesetting to place errorboxes.
514 TexRow const & texrow() const;
518 ParIterator par_iterator_begin();
520 ParConstIterator par_iterator_begin() const;
522 ParIterator par_iterator_end();
524 ParConstIterator par_iterator_end() const;
526 // Position of the child buffer where it appears first in the master.
527 DocIterator firstChildPosition(Buffer const * child);
529 /** \returns true only when the file is fully loaded.
530 * Used to prevent the premature generation of previews
531 * and by the citation inset.
533 bool isFullyLoaded() const;
534 /// Set by buffer_funcs' newFile.
535 void setFullyLoaded(bool);
537 /// FIXME: Needed by RenderPreview.
538 graphics::PreviewLoader * loader() const;
539 /// Update the LaTeX preview snippets associated with this buffer
540 void updatePreviews() const;
541 /// Remove any previewed LaTeX snippets associated with this buffer
542 void removePreviews() const;
544 /// Our main text (inside the top InsetText)
547 /// Our top InsetText
548 Inset & inset() const;
553 /// Collect macro definitions in paragraphs
554 void updateMacros() const;
555 /// Iterate through the whole buffer and try to resolve macros
556 void updateMacroInstances(UpdateType) const;
558 /// List macro names of this buffer, the parent and the children
559 void listMacroNames(MacroNameSet & macros) const;
560 /// Collect macros of the parent and its children in front of this buffer.
561 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
563 /// Return macro defined before pos (or in the master buffer)
564 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
565 /// Return macro defined anywhere in the buffer (or in the master buffer)
566 MacroData const * getMacro(docstring const & name, bool global = true) const;
567 /// Return macro defined before the inclusion of the child
568 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
570 /// Collect user macro names at loading time
571 typedef std::set<docstring> UserMacroSet;
572 mutable UserMacroSet usermacros;
574 /// Replace the inset contents for insets which InsetCode is equal
575 /// to the passed \p inset_code.
576 void changeRefsIfUnique(docstring const & from, docstring const & to,
579 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
580 /// including preamble
581 void getSourceCode(odocstream & os, std::string const format,
582 pit_type par_begin, pit_type par_end, OutputWhat output) const;
584 /// Access to error list.
585 /// This method is used only for GUI visualisation of Buffer related
586 /// errors (like parsing or LateX compilation). This method is const
587 /// because modifying the returned ErrorList does not touch the document
589 ErrorList & errorList(std::string const & type) const;
592 /// This is useful only for screen visualisation of the Buffer. This
593 /// method is const because modifying this backend does not touch
594 /// the document contents.
595 TocBackend & tocBackend() const;
600 /// This function is called when the buffer is changed.
601 void changed(bool update_metrics) const;
603 void setChild(DocIterator const & dit, Buffer * child);
605 void updateTocItem(std::string const &, DocIterator const &) const;
606 /// This function is called when the buffer structure is changed.
607 void structureChanged() const;
608 /// This function is called when some parsing error shows up.
609 void errors(std::string const & err, bool from_master = false) const;
610 /// This function is called when the buffer busy status change.
611 void setBusy(bool on) const;
612 /// Update window titles of all users.
613 void updateTitles() const;
614 /// Reset autosave timers for all users.
615 void resetAutosaveTimers() const;
617 void message(docstring const & msg) const;
620 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
622 bool hasGuiDelegate() const;
625 ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
627 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
628 std::string & result_file) const;
630 ExportStatus preview(std::string const & format) const;
633 /// target is a format name optionally followed by a space
634 /// and a destination file-name
635 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
636 bool includeall, std::string & result_file) const;
638 ExportStatus doExport(std::string const & target, bool put_in_tempdir,
639 bool includeall) const;
641 ExportStatus preview(std::string const & format, bool includeall = false) const;
645 bool isExporting() const;
648 typedef std::vector<std::pair<Inset *, ParIterator> > References;
649 References & references(docstring const & label);
650 References const & references(docstring const & label) const;
651 void clearReferenceCache() const;
652 void setInsetLabel(docstring const & label, InsetLabel const * il);
653 InsetLabel const * insetLabel(docstring const & label) const;
655 /// return a list of all used branches (also in children)
656 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
658 /// sets the buffer_ member for every inset in this buffer.
659 // FIXME This really shouldn't be needed, but at the moment it's not
660 // clear how to do it just for the individual pieces we need.
661 void setBuffersForInsets() const;
662 /// Updates screen labels and some other information associated with
663 /// insets and paragraphs. Actually, it's more like a general "recurse
664 /// through the Buffer" routine, that visits all the insets and paragraphs.
665 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
666 /// \param scope: whether to start with the master document or just
668 /// \param output: whether we are preparing for output.
669 void updateBuffer(UpdateScope scope, UpdateType utype) const;
671 void updateBuffer(ParIterator & parit, UpdateType utype) const;
673 /// Spellcheck starting from \p from.
674 /// \p from initial position, will then points to the next misspelled
676 /// \p to will points to the end of the next misspelled word.
677 /// \p word_lang will contain the found misspelled word.
678 /// \return progress if a new word was found.
679 int spellCheck(DocIterator & from, DocIterator & to,
680 WordLangTuple & word_lang, docstring_list & suggestions) const;
682 void checkChildBuffers();
685 class MarkAsExporting;
686 friend class MarkAsExporting;
687 /// mark the buffer as busy exporting something, or not
688 void setExportStatus(bool e) const;
690 /// Change name of buffer. Updates "read-only" flag.
691 void setFileName(support::FileName const & fname);
693 void getLanguages(std::set<Language const *> &) const;
694 /// Checks whether any of the referenced bibfiles have changed since the
695 /// last time we loaded the cache. Note that this does NOT update the
696 /// cached information.
697 void checkIfBibInfoCacheIsValid() const;
698 /// Update the list of all bibfiles in use (including bibfiles
699 /// of loaded child documents).
700 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
701 /// Return the list with all bibfiles in use (including bibfiles
702 /// of loaded child documents).
703 support::FileNameList const &
704 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
706 void collectChildren(ListOfBuffers & children, bool grand_children) const;
709 Buffer(Buffer const &);
710 void operator=(Buffer const &);
712 /// Use the Pimpl idiom to hide the internals.
714 /// The pointer never changes although *pimpl_'s contents may.