En script, obtiene el párrafo anterior a la selección actual

Hice un script que pasa por todos los cambios registrados:

var allChanges =app.activeDocument.stories.everyItem().changes.everyItem().getElements();
var nChanges = allChanges.length;

for (var i = nChanges-1; i >= 0; i--) {
    if (allChanges[i].changeType == ChangeTypes.INSERTED_TEXT) {
        /*Do stuff to inserted text*/
    } else if(allChanges[i].changeType == ChangeTypes.DELETED_TEXT) {
        /*Do stuff to deleted text*/
    }
    /*What I need help with would go here*/
}

Ahora quiero hacer una tabla de contenido de los artículos que contienen modificaciones. Para eso tendré que cambiar el estilo de párrafo del primer título anterior (marcado por el estilo de párrafo "Título") a "Título con cambios".

Soy completamente nuevo en el mundo de las secuencias de comandos para InDesign, pero tengo buenos conceptos básicos de JavaScript.

Creo que la forma de hacer esto sería ir en un ciclo while seleccionando el párrafo actual (que contiene la modificación) y verificar si tiene el estilo "Título" aplicado y, de ser así, aplicar el estilo "Título con cambios" en su lugar y finalizar el ciclo . De lo contrario, si el párrafo actual tiene aplicado el estilo "Título con cambios", finalice el ciclo while. De lo contrario, retroceda un párrafo y verifique la misma condición hasta.

Simplemente no sé cómo escribir el guión en sí o si es posible.

¡Gracias por su ayuda!

Respuestas (1)

Necesitaba una función para seleccionar el párrafo anterior como este:

function getPreviousPara(text){  
  return text.parent.characters.item(text.paragraphs[0].index-1).paragraphs[0];  
}

Luego, necesito recorrer y encontrar el párrafo anterior antes de manipular el cambio, ya que tengo que aceptar los cambios que se realizan allChanges[i] == nulldespués de aceptarlos.

Luego, necesito guardar la historia que contiene el cambio activo como var changeStory = allChanges[i].parent;. Luego manipulé los cambios, apliqué el estilo de carácter correspondiente y acepté el texto agregado y rechacé el texto eliminado. Luego recorro el var everyStyleRange = changeStory.textStyleRanges;aspecto del rango que contiene el estilo de carácter aplicado a cualquier modificación, o el estilo de Título modificado. Cuando lo encuentre, obtenga var currentPara = everyStyleRange[i].paragraphs[0];y verifique su nombre de estilo de párrafo. si coincide Title, aplique el Title modif. Si coincide Title modif, finaliza el bucle, de lo contrario, currentPara = getPreviousPara(currentPara);y repite.

Actualización: agregué comentarios para que quede claro el funcionamiento del script.

/*Function to select the previous paragraph*/
function getPreviousPara(text){
    var nextPara = text.parent.characters.item(text.paragraphs[0].index-1).paragraphs[0];
    return nextPara
}

/*Global variables declaration*/
var myDoc = app.activeDocument;
var allChanges =myDoc.stories.everyItem().changes.everyItem().getElements();
var nChanges = allChanges.length;

/*Loop through all changes*/
for (var i = 0; i <= nChanges-1; i++) {
    /*Get story containing change*/
    var changeStory =  allChanges[i].parent;

    /*Apply character style to Added text and Deleted text*/
    if (allChanges[i].changeType == ChangeTypes.INSERTED_TEXT) {
        var cName = "Added";
        var mCstyle = app.activeDocument.characterStyles.item(cName);
        allChanges[i].characters.everyItem().applyCharacterStyle(mCstyle);
        allChanges[i].accept();
    } else if(allChanges[i].changeType == ChangeTypes.DELETED_TEXT) {
        var cName = "Deleted";
        var mCstyle = app.activeDocument.characterStyles.item(cName);
        var changeParent = allChanges[i].parent;
        allChanges[i].characters.everyItem().applyCharacterStyle(mCstyle);
        allChanges[i].reject();
    }

    /*Get the textStyleRanges of the story*/
    var everyStyleRange = changeStory.textStyleRanges;
    nItems = everyStyleRange.length;

    /*1st while loop variables declaration*/
    var found = 0;
    var i = 0;

    /*Loop through all textStyleRanges*/
    while(found==0 && i<=nItems-1){

        /*Look for a style range that has the Deleted or Added character style or the Title modif style*/
        if (everyStyleRange[i].appliedCharacterStyle.name == "Deleted" || everyStyleRange[i].appliedCharacterStyle.name == "Added" || everyStyleRange[i].appliedCharacterStyle.name == "Title modif"){

            /*When found, kill the loop*/
            found = 1;

            /*2nd while loop variables declaration*/
            var currentPara = everyStyleRange[i].paragraphs[0];
            var corrected = 0;
            var maxLoopLimit = 0;

            /*Loop through all paragraphs of the story going backward from the found style range*/
            while(corrected==0 && maxLoopLimit < changeStory.paragraphs.length){
                maxLoopLimit++;

                /*Get the paragraph style name*/
                var currentParaStyleName= currentPara.appliedParagraphStyle.name;

                /*Look for the Title paragraph style applied*/
                if(currentParaStyleName == "Title"){

                    /*Title found, apply new paragraph style and kill 2nd while loop*/
                    currentPara.appliedParagraphStyle = currentParaStyleName+" modif";
                    corrected++; 
                }
                else if(currentParaStyleName == "Title modif"){

                    /*Title already changed, kill 2nd while loop*/
                    corrected++;
                }
                else{

                    /*Get previous paragraph and start loop again, acts as counter*/
                     currentPara = getPreviousPara(currentPara);
                }

            /*2nd while loop end*/
            }

        /*if end*/
        }

        /*If no modification were found in the story, alert the user that an error occured*/
        if(i>=nItems){alert("No changes character style was found so no Title change occured")}

        /*increment 1st loop counter*/
        i++;

    /*1st loop end*/
    }
}

Cosas pesadas para un codificador novato, ¡mucha investigación y pruebas!