@@ -372,6 +372,25 @@ async function listFilesRecursive(relativeDir: string) {
372372 return files
373373}
374374
375+ async function listMarkdownFilesInSameDirectory ( markdownPath : string ) {
376+ const directory = posix . dirname ( markdownPath )
377+ const relativeDir = directory === '.' ? '' : directory
378+ const { fullPath } = resolveDataPath ( relativeDir )
379+ const entries = await readdir ( fullPath , { withFileTypes : true } )
380+
381+ return entries
382+ . filter ( entry => entry . isFile ( ) )
383+ . map ( ( entry ) => {
384+ const filePath = relativeDir ? `${ relativeDir } /${ entry . name } ` : entry . name
385+ return {
386+ filePath,
387+ extension : posix . extname ( entry . name ) . toLowerCase ( )
388+ }
389+ } )
390+ . filter ( entry => entry . extension === '.md' || entry . extension === '.markdown' )
391+ . map ( entry => entry . filePath )
392+ }
393+
375394async function removeEmptyDirectoriesRecursive ( relativeDir : string ) {
376395 const { fullPath } = resolveDataPath ( relativeDir )
377396 const entries = await readdir ( fullPath , { withFileTypes : true } )
@@ -398,10 +417,38 @@ async function cleanupOrphanMediaForMarkdown(markdownPath: string, content: stri
398417 return
399418 }
400419
420+ // Build a complete reference set from all markdown files in the same directory.
421+ // This prevents deleting shared media when one file is saved after switching
422+ // from another file that still references images in the same `.media` folder.
423+ const markdownFiles = await listMarkdownFilesInSameDirectory ( markdownPath )
424+ const allMarkdownFiles = markdownFiles . includes ( markdownPath )
425+ ? markdownFiles
426+ : [ ...markdownFiles , markdownPath ]
427+
428+ const markdownContents = new Map < string , string > ( )
429+ for ( const filePath of allMarkdownFiles ) {
430+ if ( filePath === markdownPath ) {
431+ // Use the newest editor content for the currently saved file.
432+ markdownContents . set ( filePath , content )
433+ continue
434+ }
435+
436+ const { fullPath : markdownFullPath } = resolveDataPath ( filePath )
437+ try {
438+ markdownContents . set ( filePath , await readFile ( markdownFullPath , 'utf8' ) )
439+ } catch {
440+ // Ignore transient read errors while cleaning up.
441+ }
442+ }
443+
401444 const existingFiles = await listFilesRecursive ( mediaDir )
402445
403446 for ( const filePath of existingFiles ) {
404- if ( ! isMediaFileReferencedInContent ( markdownPath , filePath , content ) ) {
447+ const isReferenced = Array . from ( markdownContents . entries ( ) ) . some ( ( [ markdownFilePath , markdownContent ] ) => {
448+ return isMediaFileReferencedInContent ( markdownFilePath , filePath , markdownContent )
449+ } )
450+
451+ if ( ! isReferenced ) {
405452 const { fullPath } = resolveDataPath ( filePath )
406453 await rm ( fullPath , { force : true } )
407454 }
0 commit comments