# Placing \section, \subsection in the right margin of an RTL document

Rather than the default placing of \section and \subsection on their own line, I'd like to place them on the right margin (in a Right To Left document).

My current usage looks like this:

\documentclass{article}

\usepackage{polyglossia}
\setdefaultlanguage[calendar=hebrew, numerals=arabic]{hebrew}
\setotherlanguage{english}
\newfontfamily\hebrewfont{David CLM}

\begin{document}
\section{}
\subsection*{א}
אבג
\subsection*{ב}
דהו
\end{document}

Which gives:

Instead, I want to achieve this:

It is not exactly clear in the image but the bold text should be on the right margin.

Ideally I would like each \subsection to also include the current \section when it's printed, but if there is a \section without any \subsections, then only the \section should be displayed.

-

The titlesec package is brilliant for doing all sorts of fancy headings. It plays well with bidi provided that you load titlesec first (so in this case that means before polyglossia). So a partial answer is

\usepackage{titlesec}
\usepackage{polyglossia}
\setdefaultlanguage[calendar=hebrew, numerals=arabic]{hebrew}
\setotherlanguage{english}
\newfontfamily\hebrewfont{New Peninim MT} % I don't have David!

\titleformat{\subsection}[leftmargin]{\bfseries}{\thesection}%
{0.6em}{}
\titlespacing*{\subsection}{2em}{0.5ex}{1em}

which, when used with non-starred subsections, gives

Some notes:

1. For RTL documents leftmargin means, er, the right margin.

2. This relies on your decision to include subsection numbers manually as subsection titles. I attempted to provide a solution which avoids this but discovered, as you may have, that \renewcommand{\thesubsection}{\hebrewnumeral{\arabic{subsection}}} causes an error for no immediately apparent reason... so I guess all I can point out is that you will have to adjust manually if you rearrange your subsections.

3. The final part of your question (if I understand it correctly - you want to suppress a separate section number unless there are no subsections to display it?) is more difficult, for the reason that LaTeX doesn't know when it typesets a section title whether or not it will contain any subsections. So you will need to use information written to the auxiliary files on previous compilation runs. I can't see a straightforward way of using the information already written to the .aux file - although it's certainly there - so you might need to write this information out yourself and then read it back in on the next run when deciding whether or not to set the section number. Sorry if this all sounds very complicated - it's really more fiddly than difficult. I don't have time to implement a solution along these lines myself at the moment but will try to return to this answer in the next few days if none has appeared by then!