]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
9a2d4844adb04b4f349460a32b5a406c7650a5dd
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
17
18 #include "insets/InsetCode.h"
19
20 #include "support/strfwd.h"
21 #include "support/types.h"
22
23 #include <map>
24 #include <list>
25 #include <set>
26 #include <string>
27 #include <vector>
28
29
30 namespace lyx {
31
32 class BiblioInfo;
33 class BibTeXInfo;
34 class BufferParams;
35 class DispatchResult;
36 class DocIterator;
37 class docstring_list;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetLabel;
43 class InsetRef;
44 class Font;
45 class Format;
46 class Lexer;
47 class Text;
48 class LyXVC;
49 class LaTeXFeatures;
50 class Language;
51 class MacroData;
52 class MacroNameSet;
53 class MacroSet;
54 class OutputParams;
55 class Paragraph;
56 class ParConstIterator;
57 class ParIterator;
58 class ParagraphList;
59 class TeXErrors;
60 class TexRow;
61 class TocBackend;
62 class Undo;
63 class WordLangTuple;
64
65 namespace frontend {
66 class GuiBufferDelegate;
67 class WorkAreaManager;
68 }
69
70 namespace support {
71 class FileName;
72 class FileNameList;
73 }
74
75 namespace graphics {
76 class PreviewLoader;
77 }
78
79
80 class Buffer;
81 typedef std::list<Buffer *> ListOfBuffers;
82 /// a list of Buffers we cloned
83 typedef std::set<Buffer *> CloneList;
84
85
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.
91  *
92  *
93  * I am not sure if the class is complete or
94  * minimal, probably not.
95  * \author Lars Gullik Bjønnes
96  */
97 class Buffer {
98 public:
99         /// What type of log will \c getLogName() return?
100         enum LogType {
101                 latexlog, ///< LaTeX log
102                 buildlog  ///< Literate build log
103         };
104
105         /// Result of \c readFile()
106         enum ReadStatus {
107                 ReadSuccess,
108                 ReadCancel,
109                 // failures
110                 ReadFailure,
111                 ReadWrongVersion,
112                 ReadFileNotFound,
113                 ReadVCError,
114                 ReadAutosaveFailure,
115                 ReadEmergencyFailure,
116                 ReadNoLyXFormat,
117                 ReadDocumentFailure,
118                 // lyx2lyx
119                 LyX2LyXNoTempFile,
120                 LyX2LyXNotFound,
121                 LyX2LyXOlderFormat,
122                 LyX2LyXNewerFormat,
123                 // other
124                 ReadOriginal
125         };
126
127         enum ExportStatus {
128                 // export
129                 ExportSuccess,
130                 ExportCancel,
131                 ExportError,
132                 ExportNoPathToFormat,
133                 ExportTexPathHasSpaces,
134                 ExportConverterError,
135                 // preview
136                 PreviewSuccess,
137                 PreviewError
138         };
139
140         /// Method to check if a file is externally modified, used by
141         /// isExternallyModified()
142         /**
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.
146          *
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
149          * system.
150          *
151          * FIXME: replace this method with support/FileMonitor.
152          */
153         enum CheckMethod {
154                 checksum_method, ///< Use file checksum
155                 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
156         };
157
158         ///
159         enum UpdateScope {
160                 UpdateMaster,
161                 UpdateChildOnly
162         };
163
164         /// Constructor
165         explicit Buffer(std::string const & file, bool readonly = false,
166                 Buffer const * cloned_buffer = 0);
167
168         /// Destructor
169         ~Buffer();
170
171         /// Clones the entire structure of which this Buffer is part, starting
172         /// with the master and cloning all the children, too.
173         Buffer * cloneFromMaster() const;
174         /// Just clones this single Buffer. For autosave.
175         Buffer * cloneBufferOnly() const;
176         ///
177         bool isClone() const;
178
179         /** High-level interface to buffer functionality.
180             This function parses a command string and executes it.
181         */
182         void dispatch(std::string const & command, DispatchResult & result);
183
184         /// Maybe we know the function already by number...
185         void dispatch(FuncRequest const & func, DispatchResult & result);
186
187         /// Can this function be exectued?
188         /// \return true if we made a decision
189         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
190
191         ///
192         DocIterator getParFromID(int id) const;
193         /// do we have a paragraph with this id?
194         bool hasParWithID(int id) const;
195
196         ///
197         frontend::WorkAreaManager & workAreaManager() const;
198
199         /** Save file.
200             Takes care of auto-save files and backup file if requested.
201             Returns \c true if the save is successful, \c false otherwise.
202         */
203         bool save() const;
204         /// Renames and saves the buffer
205         bool saveAs(support::FileName const & fn);
206
207         /// Write document to stream. Returns \c false if unsuccessful.
208         bool write(std::ostream &) const;
209         /// Write file. Returns \c false if unsuccessful.
210         bool writeFile(support::FileName const &) const;
211
212         /// \name Functions involved in reading files/strings.
213         //@{
214         /// Loads the LyX file into the buffer. This function
215         /// tries to extract the file from version control if it
216         /// cannot be found. If it can be found, it will try to
217         /// read an emergency save file or an autosave file.
218         /// \sa loadThisLyXFile
219         ReadStatus loadLyXFile();
220         /// Loads the LyX file \c fn into the buffer. If you want
221         /// to check for files in a version control container,
222         /// emergency or autosave files, one should use \c loadLyXFile.
223         /// /sa loadLyXFile
224         ReadStatus loadThisLyXFile(support::FileName const & fn);
225         /// read a new document from a string
226         bool readString(std::string const &);
227         /// Reloads the LyX file
228         ReadStatus reload();
229 //FIXME: The following function should be private
230 //private:
231         /// read the header, returns number of unknown tokens
232         int readHeader(Lexer & lex);
233
234 private:
235         ///
236         typedef std::map<Buffer const *, Buffer *> BufferMap;
237         ///
238         void cloneWithChildren(BufferMap &, CloneList *) const;
239         /// save timestamp and checksum of the given file.
240         void saveCheckSum() const;
241         /// read a new file
242         ReadStatus readFile(support::FileName const & fn);
243         /// Reads a file without header.
244         /// \param par if != 0 insert the file.
245         /// \return \c true if file is not completely read.
246         bool readDocument(Lexer &);
247         /// Try to extract the file from a version control container
248         /// before reading if the file cannot be found. This is only
249         /// implemented for RCS.
250         /// \sa LyXVC::file_not_found_hook
251         ReadStatus extractFromVC();
252         /// Reads the first tag of a LyX File and
253         /// returns the file format number.
254         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
255                 int & file_format) const;
256         /// Convert the LyX file to the LYX_FORMAT using
257         /// the lyx2lyx script and returns the filename
258         /// of the temporary file to be read
259         ReadStatus convertLyXFormat(support::FileName const & fn,
260                 support::FileName & tmpfile, int from_format);
261         //@}
262
263 public:
264         /// \name Functions involved in autosave and emergency files.
265         //@{
266         /// Save an autosave file to #filename.lyx#
267         bool autoSave() const;
268         /// save emergency file
269         /// \return a status message towards the user.
270         docstring emergencyWrite();
271
272 //FIXME:The following function should be private
273 //private:
274         ///
275         void removeAutosaveFile() const;
276
277 private:
278         /// Try to load an autosave file associated to \c fn.
279         ReadStatus loadAutosave();
280         /// Try to load an emergency file associated to \c fn.
281         ReadStatus loadEmergency();
282         /// Get the filename of the emergency file associated with the Buffer
283         support::FileName getEmergencyFileName() const;
284         /// Get the filename of the autosave file associated with the Buffer
285         support::FileName getAutosaveFileName() const;
286         ///
287         void moveAutosaveFile(support::FileName const & old) const;
288         //@}
289
290 public:
291         /// Fill in the ErrorList with the TeXErrors
292         void bufferErrors(TeXErrors const &, ErrorList &) const;
293
294         enum OutputWhat {
295                 FullSource,
296                 OnlyBody,
297                 OnlyPreamble,
298                 CurrentParagraph
299         };
300
301         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
302         bool makeLaTeXFile(support::FileName const & filename,
303                            std::string const & original_path,
304                            OutputParams const &,
305                            OutputWhat output = FullSource) const;
306         /** Export the buffer to LaTeX.
307             If \p os is a file stream, and params().inputenc is "auto" or
308             "default", and the buffer contains text in different languages
309             with more than one encoding, then this method will change the
310             encoding associated to \p os. Therefore you must not call this
311             method with a string stream if the output is supposed to go to a
312             file. \code
313             ofdocstream ofs;
314             otexstream os(ofs, texrow);
315             ofs.open("test.tex");
316             writeLaTeXSource(os, ...);
317             ofs.close();
318             \endcode is NOT equivalent to \code
319             odocstringstream oss;
320             otexstream os(oss, texrow);
321             writeLaTeXSource(os, ...);
322             ofdocstream ofs;
323             ofs.open("test.tex");
324             ofs << oss.str();
325             ofs.close();
326             \endcode
327          */
328         void writeLaTeXSource(otexstream & os,
329                            std::string const & original_path,
330                            OutputParams const &,
331                            OutputWhat output = FullSource) const;
332         ///
333         void makeDocBookFile(support::FileName const & filename,
334                              OutputParams const & runparams_in,
335                              OutputWhat output = FullSource) const;
336         ///
337         void writeDocBookSource(odocstream & os, std::string const & filename,
338                              OutputParams const & runparams_in,
339                              OutputWhat output = FullSource) const;
340         ///
341         void makeLyXHTMLFile(support::FileName const & filename,
342                              OutputParams const & runparams_in) const;
343         ///
344         void writeLyXHTMLSource(odocstream & os,
345                              OutputParams const & runparams_in,
346                              OutputWhat output = FullSource) const;
347         /// returns the main language for the buffer (document)
348         Language const * language() const;
349         /// get l10n translated to the buffers language
350         docstring const B_(std::string const & l10n) const;
351
352         ///
353         int runChktex();
354         /// return true if the main lyx file does not need saving
355         bool isClean() const;
356         ///
357         bool isDepClean(std::string const & name) const;
358
359         /// whether or not disk file has been externally modified
360         bool isExternallyModified(CheckMethod method) const;
361
362         /// mark the main lyx file as not needing saving
363         void markClean() const;
364
365         ///
366         void markDepClean(std::string const & name);
367
368         ///
369         void setUnnamed(bool flag = true);
370
371         /// Whether or not a filename has been assigned to this buffer
372         bool isUnnamed() const;
373
374         /// Whether or not this buffer is internal.
375         ///
376         /// An internal buffer does not contain a real document, but some auxiliary text segment.
377         /// It is not associated with a filename, it is never saved, thus it does not need to be
378         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
379         bool isInternal() const;
380
381         /// Mark this buffer as dirty.
382         void markDirty();
383
384         /// Returns the buffer's filename. It is always an absolute path.
385         support::FileName fileName() const;
386
387         /// Returns the buffer's filename. It is always an absolute path.
388         std::string absFileName() const;
389
390         /// Returns the the path where the buffer lives.
391         /// It is always an absolute path.
392         std::string filePath() const;
393
394         /** A transformed version of the file name, adequate for LaTeX.
395             \param no_path optional if \c true then the path is stripped.
396         */
397         std::string latexName(bool no_path = true) const;
398
399         /// Get the name and type of the log.
400         std::string logName(LogType * type = 0) const;
401
402         /// Set document's parent Buffer.
403         void setParent(Buffer const *);
404         Buffer const * parent() const;
405
406         /** Get the document's master (or \c this if this is not a
407             child document)
408          */
409         Buffer const * masterBuffer() const;
410
411         /// \return true if \p child is a child of this \c Buffer.
412         bool isChild(Buffer * child) const;
413
414         /// \return true if this \c Buffer has children
415         bool hasChildren() const;
416
417         /// \return a list of the direct children of this Buffer.
418         /// this list has no duplicates and is in the order in which
419         /// the children appear.
420         ListOfBuffers getChildren() const;
421
422         /// \return a list of all descendents of this Buffer (children,
423         /// grandchildren, etc). this list has no duplicates and is in
424         /// the order in which the children appear.
425         ListOfBuffers getDescendents() const;
426
427         /// Collect all relative buffers, in the order in which they appear.
428         /// I.e., the "root" Buffer is first, then its first child, then any
429         /// of its children, etc. However, there are no duplicates in this
430         /// list.
431         /// This is "stable", too, in the sense that it returns the same
432         /// thing from whichever Buffer it is called.
433         ListOfBuffers allRelatives() const;
434
435         /// Is buffer read-only?
436         bool isReadonly() const;
437
438         /// Set buffer read-only flag
439         void setReadonly(bool flag = true);
440
441         /** Validate a buffer for LaTeX.
442             This validates the buffer, and returns a struct for use by
443             #makeLaTeX# and others. Its main use is to figure out what
444             commands and packages need to be included in the LaTeX file.
445             It (should) also check that the needed constructs are there
446             (i.e. that the \refs points to coresponding \labels). It
447             should perhaps inset "error" insets to help the user correct
448             obvious mistakes.
449         */
450         void validate(LaTeXFeatures &) const;
451
452         /// Reference information is cached in the Buffer, so we do not
453         /// have to check or read things over and over.
454         ///
455         /// There are two caches.
456         ///
457         /// One is a cache of the BibTeX files from which reference info is
458         /// being gathered. This cache is PER BUFFER, and the cache for the
459         /// master essentially includes the cache for its children. This gets
460         /// invalidated when an InsetBibtex is created, deleted, or modified.
461         ///
462         /// The other is a cache of the reference information itself. This
463         /// exists only in the master buffer, and when it needs to be updated,
464         /// the children add their information to the master's cache.
465
466         /// Calling this method invalidates the cache and so requires a
467         /// re-read.
468         void invalidateBibinfoCache() const;
469         /// This invalidates the cache of files we need to check.
470         void invalidateBibfileCache() const;
471         /// Updates the cached bibliography information, checking first to see
472         /// whether the cache is valid. If so, we do nothing. If not, then we
473         /// reload all the BibTeX info.
474         /// Note that this operates on the master document.
475         void reloadBibInfoCache() const;
476         /// \return the bibliography information for this buffer's master,
477         /// or just for it, if it isn't a child.
478         BiblioInfo const & masterBibInfo() const;
479         /// collect bibliography info from the various insets in this buffer.
480         void collectBibKeys() const;
481         /// add some BiblioInfo to our cache
482         void addBiblioInfo(BiblioInfo const & bi) const;
483         /// add a single piece of bibliography info to our cache
484         void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
485         ///
486         bool citeLabelsValid() const;
487         ///
488         void getLabelList(std::vector<docstring> &) const;
489
490         /// This removes the .aux and .bbl files from the temp dir.
491         void removeBiblioTempFiles() const;
492
493         ///
494         void changeLanguage(Language const * from, Language const * to);
495
496         ///
497         bool isMultiLingual() const;
498         ///
499         std::set<Language const *> getLanguages() const;
500
501         ///
502         BufferParams & params();
503         BufferParams const & params() const;
504
505         /** The list of paragraphs.
506             This is a linked list of paragraph, this list holds the
507             whole contents of the document.
508          */
509         ParagraphList & paragraphs();
510         ParagraphList const & paragraphs() const;
511
512         /// LyX version control object.
513         LyXVC & lyxvc();
514         LyXVC const & lyxvc() const;
515
516         /// Where to put temporary files.
517         std::string const temppath() const;
518
519         /// Used when typesetting to place errorboxes.
520         TexRow const & texrow() const;
521         TexRow & texrow();
522
523         ///
524         ParIterator par_iterator_begin();
525         ///
526         ParConstIterator par_iterator_begin() const;
527         ///
528         ParIterator par_iterator_end();
529         ///
530         ParConstIterator par_iterator_end() const;
531
532         // Position of the child buffer where it appears first in the master.
533         DocIterator firstChildPosition(Buffer const * child);
534
535         /** \returns true only when the file is fully loaded.
536          *  Used to prevent the premature generation of previews
537          *  and by the citation inset.
538          */
539         bool isFullyLoaded() const;
540         /// Set by buffer_funcs' newFile.
541         void setFullyLoaded(bool);
542
543         /// FIXME: Needed by RenderPreview.
544         graphics::PreviewLoader * loader() const;
545         /// Update the LaTeX preview snippets associated with this buffer
546         void updatePreviews() const;
547         /// Remove any previewed LaTeX snippets associated with this buffer
548         void removePreviews() const;
549
550         /// Our main text (inside the top InsetText)
551         Text & text() const;
552
553         /// Our top InsetText
554         Inset & inset() const;
555
556         //
557         // Macro handling
558         //
559         /// Collect macro definitions in paragraphs
560         void updateMacros() const;
561         /// Iterate through the whole buffer and try to resolve macros
562         void updateMacroInstances(UpdateType) const;
563
564         /// List macro names of this buffer, the parent and the children
565         void listMacroNames(MacroNameSet & macros) const;
566         /// Collect macros of the parent and its children in front of this buffer.
567         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
568
569         /// Return macro defined before pos (or in the master buffer)
570         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
571         /// Return macro defined anywhere in the buffer (or in the master buffer)
572         MacroData const * getMacro(docstring const & name, bool global = true) const;
573         /// Return macro defined before the inclusion of the child
574         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
575
576         /// Collect user macro names at loading time
577         typedef std::set<docstring> UserMacroSet;
578         mutable UserMacroSet usermacros;
579
580         /// Replace the inset contents for insets which InsetCode is equal
581         /// to the passed \p inset_code.
582         void changeRefsIfUnique(docstring const & from, docstring const & to,
583                 InsetCode code);
584
585         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
586         /// including preamble
587         void getSourceCode(odocstream & os, std::string const format,
588                            pit_type par_begin, pit_type par_end, OutputWhat output) const;
589
590         /// Access to error list.
591         /// This method is used only for GUI visualisation of Buffer related
592         /// errors (like parsing or LateX compilation). This method is const
593         /// because modifying the returned ErrorList does not touch the document
594         /// contents.
595         ErrorList & errorList(std::string const & type) const;
596
597         /// The Toc backend.
598         /// This is useful only for screen visualisation of the Buffer. This
599         /// method is const because modifying this backend does not touch
600         /// the document contents.
601         TocBackend & tocBackend() const;
602
603         ///
604         Undo & undo();
605
606         /// This function is called when the buffer is changed.
607         void changed(bool update_metrics) const;
608         ///
609         void setChild(DocIterator const & dit, Buffer * child);
610         ///
611         void updateTocItem(std::string const &, DocIterator const &) const;
612         /// This function is called when the buffer structure is changed.
613         void structureChanged() const;
614         /// This function is called when some parsing error shows up.
615         void errors(std::string const & err, bool from_master = false) const;
616         /// This function is called when the buffer busy status change.
617         void setBusy(bool on) const;
618         /// Update window titles of all users.
619         void updateTitles() const;
620         /// Reset autosave timers for all users.
621         void resetAutosaveTimers() const;
622         ///
623         void message(docstring const & msg) const;
624
625         ///
626         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
627         ///
628         bool hasGuiDelegate() const;
629
630         ///
631         ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
632         ///
633         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
634                 std::string & result_file) const;
635         ///
636         ExportStatus preview(std::string const & format) const;
637
638 private:
639         /// target is a format name optionally followed by a space
640         /// and a destination file-name
641         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
642                 bool includeall, std::string & result_file) const;
643         ///
644         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
645                 bool includeall) const;
646         ///
647         ExportStatus preview(std::string const & format, bool includeall = false) const;
648         ///
649         void setMathFlavor(OutputParams & op) const;
650
651 public:
652         ///
653         bool isExporting() const;
654
655         ///
656         typedef std::vector<std::pair<Inset *, ParIterator> > References;
657         References & references(docstring const & label);
658         References const & references(docstring const & label) const;
659         void clearReferenceCache() const;
660         void setInsetLabel(docstring const & label, InsetLabel const * il);
661         InsetLabel const * insetLabel(docstring const & label) const;
662
663         /// return a list of all used branches (also in children)
664         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
665
666         /// sets the buffer_ member for every inset in this buffer.
667         // FIXME This really shouldn't be needed, but at the moment it's not
668         // clear how to do it just for the individual pieces we need.
669         void setBuffersForInsets() const;
670         /// Updates screen labels and some other information associated with
671         /// insets and paragraphs. Actually, it's more like a general "recurse
672         /// through the Buffer" routine, that visits all the insets and paragraphs.
673         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
674         /// \param scope: whether to start with the master document or just
675         /// do this one.
676         /// \param output: whether we are preparing for output.
677         void updateBuffer(UpdateScope scope, UpdateType utype) const;
678         ///
679         void updateBuffer(ParIterator & parit, UpdateType utype) const;
680
681         /// Spellcheck starting from \p from.
682         /// \p from initial position, will then points to the next misspelled
683         ///    word.
684         /// \p to will points to the end of the next misspelled word.
685         /// \p word_lang will contain the found misspelled word.
686         /// \return progress if a new word was found.
687         int spellCheck(DocIterator & from, DocIterator & to,
688                 WordLangTuple & word_lang, docstring_list & suggestions) const;
689         ///
690         void checkChildBuffers();
691
692 private:
693         class MarkAsExporting;
694         friend class MarkAsExporting;
695         /// mark the buffer as busy exporting something, or not
696         void setExportStatus(bool e) const;
697
698         /// Change name of buffer. Updates "read-only" flag.
699         void setFileName(support::FileName const & fname);
700         ///
701         void getLanguages(std::set<Language const *> &) const;
702         /// Checks whether any of the referenced bibfiles have changed since the
703         /// last time we loaded the cache. Note that this does NOT update the
704         /// cached information.
705         void checkIfBibInfoCacheIsValid() const;
706         /// Update the list of all bibfiles in use (including bibfiles
707         /// of loaded child documents).
708         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
709         /// Return the list with all bibfiles in use (including bibfiles
710         /// of loaded child documents).
711         support::FileNameList const &
712                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
713         ///
714         void collectChildren(ListOfBuffers & children, bool grand_children) const;
715
716         /// noncopyable
717         Buffer(Buffer const &);
718         void operator=(Buffer const &);
719
720         /// Use the Pimpl idiom to hide the internals.
721         class Impl;
722         /// The pointer never changes although *pimpl_'s contents may.
723         Impl * const d;
724 };
725
726
727 } // namespace lyx
728
729 #endif