# Heading number in margin using titlesec and/or komascript

Using titlesec and/or komascript how do I format all headings so the number is left aligned in the margin, the title to the right, with a horizontal rule underneath it all (from margin to text width edge).

What's left of my hair is about to come out :(

 _____________________________
|                             |
| 3.1  Section Title          |
| -------------------------   |
|      Text width paragraph   |
|      Blah blah blah blah    |
|                             |

>-<  >------------------<
|                |
-- Margin        Text

-
have you seen Theorem Name/Numbering in Margin or How can I align section titles and list environments in the left margin? you should be able to adapt it to include titlerule which will give you the horizontal line... –  cmhughes Feb 14 '13 at 22:41
@cmhughes yes (and many more similar answers), but I haven't found anything that does left alignment and horizontal rule. I'm still working on it, just hoping a guru will through me a bone. –  h0tw1r3 Feb 14 '13 at 22:46

Here's one possibility using titlesec:

\documentclass{article}
\usepackage[calcwidth]{titlesec}
\usepackage{lipsum}

\newlength\mylen
\setlength\mylen{\dimexpr\oddsidemargin+1in+\hoffset\relax}

\titleformat{\section}
{\normalfont\Large\bfseries}
{\llap{\hspace*{-\mylen}\thesection\hfill}}{0em}{}
[{\makebox[\linewidth][l]{%
\hspace*{-\mylen}\rule{\dimexpr\textwidth+\mylen\relax}{1pt}}}]

\begin{document}

\section{A Test Section with a Short Title}
\lipsum[4]
\section{A Test Section with a Long Title Spanning More than One Line}
\lipsum[4]

\end{document}


Of course, you can adjust the value for \mylen to get the desired positioning for the numbers; for example, using

\setlength\mylen{\dimexpr\oddsidemargin+\hoffset\relax}


you get

-

Caveat: margin box size for number is not dynamic.

\documentclass[10pt,twoside,letterpaper,openright]{scrbook}
\usepackage{lipsum}
\usepackage{titlesec}
\titleformat{\section}[block]%
{\normalfont\scshape\filright}%
{\makebox[2em][l]{\thesection}}%
{1em}
{}[\titlerule]
\titlespacing{\section}{-3em}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}
\begin{document}
\chapter{Lorem Ipsem}
\section{Lorem Ipsum}
\lipsum[1]
\section{Lorem Ipsum}
\lipsum[1]
\end{document}

-
Also consider using \titlespacing*{...} if you wish to prevent the paragraph following the section from being indented. –  davidg Dec 13 '13 at 5:22