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