Search code examples
javascriptrestructuredtext

how to get the indent of a searched item in javascript?


Let's assume I have the following .rst file:


.. raw:: html

   <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
   <!-- prettier-ignore-start -->
   <!-- markdownlint-disable -->
   <table>
    <tr>
     <td align="center"><a href = "https://12rambau.github.io/web-resume/"><img src="https://avatars.githubusercontent.com/u/12596392?v=4" width="100px;" alt=""/><br /><sub><b>Rambaud Pierrick</b></sub></a></td>
    </tr>
   </table>
   
   <!-- markdownlint-restore -->
   <!-- prettier-ignore-end -->

   <!-- ALL-CONTRIBUTORS-LIST:END -->

That will display a table in my documentation. I'd like to automatically populate it with a JS bot, but the problem of reST is that indentation matters.

To get the point where I should start writing, I use:

const tagToLookFor = `<!-- ALL-CONTRIBUTORS-LIST:`
const startOfOpeningTagIndex = previousContent.indexOf(`${tagToLookFor}START`,)

Is there a way to also get the indentation of this tag in the file ?


Solution

  • I found an easy to proceed:

    First I count the number of spaces before the first character:

    const startIndent = Math.max(
        0,
        previousContent.lastIndexOf(
            '\n', 
            startOfOpeningTagIndex
        )
    );
    
    const nbSpaces = startOfOpeningTagIndex 
        - Math.min(startOfOpeningTagIndex, startIndent);
    

    And then for whatever I write down, I'll ad the appropriate number of spaces:

    newContent.replace('\n', '\n' + ' '.repeat(nbSpaces))