I am reading an actuarial textbook (Nonlife Actuarial Models Theory, Methods and Evaluation by Yiu-Kuen Tse) and I want to understand the author's calculation of the expected value of a loss variable $X_L$ (defined as $$X_L = \left\{\begin{array}{l} 0 , & X \leq d\\ X-d , & X >d \end{array}\right\}$$ for some deductible $d$ and where $X$ is a continuous variable). To calculate $\text{E}(X_L)$, the author shows $$\begin{align}\text{E}(X_L) &= \int_{0}^{\infty}{xf_{X_L}(x)dx}\\ &= \int_{d}^{\infty}{(x-d)f_{X}(x)dx}\\ &= -\int_{d}^{\infty} (x-d)dS_X(x)\\ &= -\left[(x-d)S_X(x)|_{d}^{\infty} - \int_{d}^{\infty} S_X(x)dx\right]\\ &=\int_{d}^{\infty} S_X(x)dx \end{align}$$
My question is about the justification for going from line 2 to 3 and then again from 3 to 4. From line 2 to 3, I understand we are using the equation $f_X(x) = -\frac{dS_X(x)}{dx} $ but how can we just substitute in the integral without having to change anything? Is this something related to line 3 being a Riemann–Stieltjes integral or something simpler?
For lines 3 to 4, from searching around, I found the accepted answer from this question Riemann-Stieltjes integral, integration by parts (Rudin) , so I was wondering are we making use of a similar theorem (I know below says to a constant and not to $\infty$) to get from lines 3 to 4 here? The theorem in question: $$\int_{a}^{b} g(x)df(x) = f(b)g(b) - f(a)g(a) - \int_{a}^{b} f(x)dg(x)$$.