@@ -202,6 +202,10 @@ async function main() {
202202 const mdContent = fs . readFileSync ( mdFile , 'utf8' ) ;
203203 const links = findImageLinks ( mdContent ) ;
204204 let newContent = mdContent ;
205+
206+ // Collect all changes first, then apply them in reverse order to avoid index shifting
207+ const changes = [ ] ;
208+
205209 for ( const linkObj of links ) {
206210 const { link, path : imgPath , index } = linkObj ;
207211 let caseType = null ;
@@ -234,7 +238,12 @@ async function main() {
234238 if ( fs . existsSync ( imgFsPath ) ) {
235239 // Use root-relative path for markdown
236240 const relImgPath = action . startsWith ( '/' ) ? action : '/' + action ;
237- newContent = newContent . replace ( link , link . replace ( imgPath , relImgPath ) ) ;
241+ const newLink = link . replace ( imgPath , relImgPath ) ;
242+ changes . push ( {
243+ originalLink : link ,
244+ newLink : newLink ,
245+ index : index
246+ } ) ;
238247 console . log ( `${ colors . green } Automatically updated image link in file with: ${ action } ${ colors . reset } ` ) ;
239248 } else {
240249 console . log ( colors . red , 'Suggested image does not exist:' , imgFsPath , colors . reset ) ;
@@ -275,10 +284,14 @@ async function main() {
275284 openImage ( imgFsPath ) ;
276285 const confirm = await promptUser ( 'Use this image? [y/N]: ' ) ;
277286 if ( confirm . toLowerCase ( ) === 'y' ) {
278- // Update the markdown content
279287 // Use root-relative path for markdown
280288 const relImgPath = action . startsWith ( '/' ) ? action : '/' + action ;
281- newContent = newContent . replace ( link , link . replace ( imgPath , relImgPath ) ) ;
289+ const newLink = link . replace ( imgPath , relImgPath ) ;
290+ changes . push ( {
291+ originalLink : link ,
292+ newLink : newLink ,
293+ index : index
294+ } ) ;
282295 console . log ( 'Updated image link in file.' ) ;
283296 break ;
284297 } else {
@@ -287,6 +300,13 @@ async function main() {
287300 }
288301 }
289302 }
303+
304+ // Apply all changes in reverse order to avoid index shifting
305+ changes . sort ( ( a , b ) => b . index - a . index ) ;
306+ for ( const change of changes ) {
307+ newContent = newContent . replace ( change . originalLink , change . newLink ) ;
308+ }
309+
290310 if ( newContent !== mdContent ) {
291311 fs . writeFileSync ( mdFile , newContent , 'utf8' ) ;
292312 console . log ( 'File updated:' , mdFile ) ;
0 commit comments